language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <pcap/pcap.h> #include <time.h> #include <stdlib.h> #include <stdio.h> char buffer[1024] ; int index = 0 ; void getPacket( u_char *arg , const struct pcap_pkthdr * pkthdr , const u_char * packet ) { int* id = (int *)arg ; int i , j ; /* printf( "[+] id : %d\n" , ++(*id ) ) ; printf( " packet len : %d\n" , pkthdr -> len ) ; printf( " packet caplen : %d\n" , pkthdr -> caplen ) ; printf( " recieved time : %s" , ctime( (const time_t *) &pkthdr->ts.tv_sec ) ) ; printf( " bytes streams : \n" ) ; printf( " " ) ; for( i = 0 ; i < pkthdr->len ; i ++ ) { printf( " %02x" , packet[i] ) ; if( ( i + 1 ) % 16 == 0 ) { printf( " " ) ; for( j = i - 16 ; j <= i ; j ++ ) if( packet[j] >= 32 && packet[j] <= 126 ) putchar( packet[j] ) ; else putchar( '.' ) ; printf ( "\n " ) ; } else if( ( i + 1 ) % 4 == 0 ) printf( " |" ) ; } if( ( i + 1 ) % 16 != 0 ) { while( 1 ) { printf( " " ) ; if( ( i + 1 ) % 16 == 0 ) break ; if( ( i + 1 ) % 4 == 0 ) printf ( " " ) ; i ++ ; } printf( " " ) ; for( j = i - 16 ; j <= i && j < pkthdr->len ; j ++ ) if( packet[j] >= 32 && packet[j] <= 126 ) putchar( packet[j] ) ; else putchar( '.' ) ; } puts( "" ) ; */ // ethernet wrap /* printf( " Mac : %02x:%02x:%02x:%02x:%02x:%02x -> %02x:%02x:%02x:%02x:%02x:%02x\n" , packet[6] , packet[7] , packet[8] , packet[9] , packet[10] , packet[11] , packet[0] , packet[1] , packet[2] , packet[3] , packet[4] , packet[5] ) ; */ // include a ip header if( ( packet[12] & 8 && 1 ) && !( packet[13] | 0 || 0 ) ) { /* printf( " IP : %03d.%03d.%03d.%03d -> %03d.%03d.%03d.%03d \n" , packet[26] , packet[27] , packet[28] , packet[29] , packet[30] , packet[31] , packet[32] , packet[33] ) ; */ // include a tcp header if( packet[23] & 6 && 1 ) { /* printf( " TCP : %05d -> %05d \n" , packet[34]*256 + packet[35] , packet[36]*256 + packet[37] ) ; puts( " TCP FLAG : " ) ; printf( " URG , ACK , PSH , RST , SYN , FIN\n %-6d%-6d%-6d%-6d%-6d%-6d\n" , packet[47] & 32 && 1 , packet[47] & 16 && 1, packet[47] & 8 && 1 , packet[47] & 4 && 1, packet[47] & 2 && 1, packet[47] & 1 && 1 ) ; */ // include something for telnet if( ( packet[34]==0 && packet[35]==23 ) || ( packet[36]==0 && packet[37]==23 ) ) { printf( " TELNET : " ) ; if( pkthdr->len > 54 ) { for( i = 54 ; i < pkthdr->len ; i ++ ) { putchar( packet[i] ) ; } if( ( packet[47] & 8 && 1 ) && packet[54] < 128 ) { for( i = 54 ; i < pkthdr->len ; i ++ ) buffer[index++] = packet[i] ; } } if( packet[47] & 1 && 1 ) { puts( "TCP-FIN" ) ; buffer[index++] = '\0' ; printf( "[*] buffer : \n %s" , buffer ) ; } puts( "" ) ; }//end of telnet }//end of tcp }// end of ip } int main( ) { char errBuf[PCAP_ERRBUF_SIZE] ; char* devStr = "vboxnet0" ; pcap_t* dev = pcap_open_live( devStr , 65535 , 1 , 0 , errBuf ) ; if( !dev ) { printf( "[-] pcap_open_live( ) : %s\n" , errBuf ) ; exit( 1 ) ; } struct bpf_program filter ; // pcap_compile( dev , &filter , "( dst port 23 or dst host 192.168.44.1) and ( tcp ) " , 1 , 0 ) ; pcap_compile( dev , &filter , "src port 23 or dst port 23" , 1 , 0 ) ; // pcap_compile( dev , &filter , "dst port 23" , 1 , 0 ) ; // pcap_compile( dev , &filter , "src port 23" , 1 , 0 ) ; // pcap_compile( dev , &filter , "dst port 23 and (tcp[tcpflags] & tcp-push != 0)" , 1 , 0 ) ; pcap_setfilter( dev , &filter ) ; int id = 0 ; pcap_loop( dev , -1 , getPacket , (u_char *)&id ) ; pcap_close( dev ) ; return 0 ; }
C
// Copyright (c) 2018 Felix Schoeller // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #include <stdio.h> #include "memory.h" #include "value.h" #include "vm.h" #include "dictionary.h" #include "hashtable.h" #include "list.h" void *reallocate(void *previous, size_t size) { if (size <= 0) { free(previous); return NULL; } return realloc(previous, size); } static void mark(Object *object) { if (object->marked) { return; } if (object->type == OBJ_DICT) { ObjDict *dict = (ObjDict *) object; for (int i = 0; i < dict->content.cap; ++i) { HTItem *current = dict->content.buckets[i]; while (current) { mark((Object *) current->key.key_obj_string); if (current->value.type == OBJECT) { mark(current->value.o_value); } current = current->next; } } } else if (object->type == OBJ_LIST) { ObjList *list = (ObjList *) object; for (int i = 0; i < list->content.count; ++i) { CrispyValue *current = &list->content.values[i]; if (current->type == OBJECT) { mark(current->o_value); } } } object->marked = 1; } static void mark_all(Vm *vm) { for (int i = vm->frame_count - 1; i >= 0; --i) { CallFrame *curr_frame = vm->frames.frame_pointers[i]; // variables for (int j = 0; j < curr_frame->variables.count; ++j) { CrispyValue *value = &curr_frame->variables.values[j]; // TODO check reason for uinitcondition warning in valgrind if (value->type == OBJECT) { mark(value->o_value); } } // constants for (int j = 0; j < curr_frame->constants.count; ++j) { CrispyValue *value = &curr_frame->constants.values[j]; if (value->type == OBJECT) { mark(value->o_value); } } // stack for (int k = 0; k < vm->sp - vm->stack; k++) { if (vm->stack[k].type == OBJECT) { mark(vm->stack[k].o_value); } } } } static void sweep(Vm *vm) { Object **object = &vm->first_object; while (*object) { if (!(*object)->marked) { Object *unreached = *object; *object = unreached->next; // TODO don't free referenced elements in list vm->allocated_mem -= free_object(unreached); } else { (*object)->marked = 0; object = &(*object)->next; } } } void gc(Vm *vm) { #if DEBUG_TRACE_GC size_t mem_before = vm->allocated_mem; #endif #if DISABLE_GC return; #endif mark_all(vm); sweep(vm); vm->max_alloc_mem = vm->allocated_mem * 2; #if DEBUG_TRACE_GC printf("Collected %ld bytes, %ld remaining.\n", mem_before - vm->allocated_mem, vm->allocated_mem); #endif }
C
#include <stdio.h> #include <stdlib.h> void print_lines(char** lines, int num_lines,int num){ int i; for(i = num_lines-num ; i < num_lines; ++i){ printf("%s", lines[i]); } } void free_lines(char** lines, int num_lines){ int i; for(i = 0 ; i < num_lines; ++i){ free(lines[i]); } if(lines != NULL && num_lines > 0){ free(lines); } } void read_lines(FILE* fp, char*** lines, int* num_lines){ char ch; int i=0; char** line; ch = fgetc(fp); while (ch != EOF){ if(ch=='\n'){ *num_lines += 1; } ch = fgetc(fp); } line = (char**) malloc (sizeof(char*)*1000); for (i = 0;i<*num_lines;i++){ line[i] = (char*)malloc(sizeof(char)*1000); } rewind(fp); for (i = 0; i <*num_lines;i++){ fgets(line[i],1000,fp); //fseek(fp,1,SEEK_CUR); } for (i = 0; i<*num_lines;i++){ } *lines = line; } FILE* validate_input(int argc, char* argv[]){ FILE* fp = NULL; if(argc < 3){ printf("Not enough arguments entered.\nEnding program.\n"); exit(0); } else if(argc > 3){ printf("Too many arguments entered.\nEnding program.\n"); exit(0); } fp = fopen(argv[1], "r"); if(fp == NULL){ printf("Unable to open file: %s\nEnding program.\n", argv[1]); exit(0); } return fp; } int main(int argc, char* argv[]){ char** lines = NULL; int num_lines = 0; int num = atoi(argv[2]); FILE* fp = validate_input(argc, argv); read_lines(fp, &lines, &num_lines); if (num>num_lines){ num = num_lines; } print_lines(lines, num_lines,num); free_lines(lines, num_lines); fclose(fp); return 0; }
C
// https://www.urionlinejudge.com.br/judge/en/problems/view/1098 #include <stdio.h> int main() { int i, j; float frac; for (i = 0; i <= 20; i += 2) { frac = i / 10.f; for (j = 1; j <= 3; ++j) printf("I=%g J=%g\n", frac, j + frac); } return 0; }
C
#include "tab_instru.h" #include <stdio.h> #include <stdlib.h> /*struct instr{ char * inst; int val1, val2, val3; }*/ int idx_instr=0; void instr_add(char* name, int v1, int v2,int v3){ tab_instr[idx_instr].inst = name; tab_instr[idx_instr].val1=v1; tab_instr[idx_instr].val2=v2; tab_instr[idx_instr].val3=v3; idx_instr++; } void print_tab_ins(int ln){ printf("+++++++instruction+++++++++++\n"); printf("%s %d %d %d \n", tab_instr[ln].inst,tab_instr[ln].val1,tab_instr[ln].val2,tab_instr[ln].val3); printf("++++++++++++++++++++\n"); } int getmyindex(){ return idx_instr; } void changejumpline(int linenum, int value){ tab_instr[linenum].val1 = value; } void write_fichier(){ FILE* fichier = NULL; fichier = fopen("testTabSym.txt", "w"); if (fichier != NULL) { printf("Maitenant combien d'intructions: %d\n",idx_instr); for (int i=0;i<idx_instr;i++){ //Ecriture dans le fichier fprintf(fichier,"%s %d %d %d \n",tab_instr[i].inst,tab_instr[i].val1,tab_instr [i].val2,tab_instr[i].val3); } } fclose(fichier); } //int main(void){ // /*instr_add("load",'2','3'); // instr_add("b",'4','5'); // */ // printf("Write dans un fichier les instruction\n"); // write_fichier(); // return 0; //}
C
/** * program to find the square root of the given number till given precision * * @Harsh_Garg,1910990582,19/07/2021 * Assignment 1 */ #include<stdio.h> double find_square_root(int number,int precision); int main() { //declaring the variables for number and precision int number = 0; int precision = 0; printf("Enter the number:"); scanf("%d",&number); printf("Enter the precision:"); scanf("%d",&precision); double ans = find_square_root(number,precision); printf("%f",ans); } double find_square_root(int number,int precision) { //initialising the left and the right pointers for binary search int left = 0; int right = number; //initialising the variable for answer double ans = 0; while(left <= right) { int mid = left + (right - left) / 2; if (mid * mid == number) { ans = mid; break; } else if (mid * mid < number) { ans = mid; left = mid + 1; } else { right = mid-1; } } //calculating the fractional part double increment = 0.1; for(int i=0;i<precision;i++) { while(ans * ans <= number) { ans += increment; } ans -= increment; increment /= 10; } return ans; }
C
#include "support.h" int main(int argc, char **argv) { // Ensure valid command line args if (argc != 4) { fprintf(stderr,"usage: %s <hostname> <port> <filename>\n", argv[0]); exit(1); } // Get the hostname and the port number. // char *hostname = argv[1]; int portno = atoi(argv[2]); //char *filename = argv[3]; // Create the socket for UDP connection int sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { perror("Socket did not open."); exit(1); } // Find the server's DNS entry. /* struct hostent *server; server = gethostbyname(hostname); if (server == NULL) { fprintf(stderr,"ERROR, no such host as %s\n", hostname); exit(0); } */ // Set up the server IP struct sockaddr_in serveraddr; memset((char *) &serveraddr, 0, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_port = htons(portno); serveraddr.sin_addr.s_addr = INADDR_ANY; //bcopy((char *)server->h_addr, // (char *)&serveraddr.sin_addr.s_addr, server->h_length); // Wait for a message from the client. /* int BUFSIZE = 1024; char buf[BUFSIZE]; memset(buf, 0, BUFSIZE); printf("Please enter msg: "); fgets(buf, BUFSIZE, stdin); */ socklen_t serverlen = sizeof(serveraddr); int n; // Begin the TCP 3-way Handshake // First, make the SYN_Packet TCP_Packet SYN_Packet; SYN_Packet.seqNum = 1000; SYN_Packet.ackNum = 2000; SYN_Packet.SYN = 1; SYN_Packet.FIN = 0; SYN_Packet.PKG_TYPE = 0; //n = sendto(sockfd, buf, strlen(buf), 0, (const struct sockaddr *) &serveraddr, serverlen); // Then, send it to the server. n = sendto(sockfd, (struct TCP_Packet *) &SYN_Packet, sizeof(SYN_Packet), 0, (const struct sockaddr *) &serveraddr, serverlen); if (n < 0) { perror("sendto did not work"); exit(1); } printf("Sending packet %d SYN\n", SYN_Packet.seqNum); // Wait for the server to reply with a SYNACK packet. TCP_Packet * SYNACK_Packet = malloc(sizeof(TCP_Packet)); n = recvfrom(sockfd, SYNACK_Packet, sizeof(*SYNACK_Packet), 0, (struct sockaddr *) &serveraddr, &serverlen); printf("Receiving packet %d\n", SYNACK_Packet->ackNum); // Make the Packet sending requested filename TCP_Packet Request_Packet; Request_Packet.seqNum = SYNACK_Packet->ackNum; Request_Packet.ackNum = SYNACK_Packet->seqNum + MAX_PKT_LENGTH; Request_Packet.SYN = 0; Request_Packet.FIN = 0; Request_Packet.PKG_TYPE= 0; strcpy(Request_Packet.payload, argv[3]); // Then send it to the server n = sendto(sockfd, (struct TCP_Packet *) &Request_Packet, sizeof(Request_Packet), 0, (const struct sockaddr *) &serveraddr, serverlen); if (n < 0) { perror("sendto did not work"); exit(1); } printf("Sending packet %d\n", Request_Packet.seqNum); TCP_Packet * Result_Packet = malloc(sizeof(TCP_Packet)); n = recvfrom(sockfd, Result_Packet, sizeof(*Result_Packet), 0, (struct sockaddr *) &serveraddr, &serverlen); printf("Receiving packet %d\n", Result_Packet->ackNum); printf("Received File Content: %s\n", Result_Packet->payload); //SENDING THE PACKAGES TO SERVER // int slen=sizeof(serveraddr); // for(int i = 0; i < NUM_PKG; i++) { // printf("Sending packet %d\n", i); // sprintf(Request_Packet.payload, "This is packet %d\n", i); //// printf("***%s",Request_Packet.payload ); // if (sendto(sockfd, Request_Packet.payload, MAX_PKT_LENGTH, 0, (const struct sockaddr *) &serveraddr, slen)== -1) { // error("sendto() error"); // } // // } //DIVIDE FILE INTO SMALL CHUNK, meaning read file upto the allowed size and repeat the process /* FILE* fd = NULL; char buffer[MAX_PKT_LENGTH]; //1024 size_t byte_read = 0; fd = fopen(Request_Packet.payload, "r"); //open the client file if(fd == NULL) { //if file is empty then exit error("File is empty"); } fseek(fd, 0 , SEEK_END); long fileSize = ftell(fd); fseek(fd, 0 , SEEK_SET); */ /* if (fileSize <= 1008) { //if the size of fd is less or equal to 1008 fread(buffer, 1, fileSize, fd); printf("Sending packet %d\n", Request_Packet.seqNum); //output sequence number Request_Packet.seqNum += Request_Packet.seqNum + fileSize; //increase the sequence number by file size if (sendto(sockfd, buffer, MAX_PKT_LENGTH, 0, (const struct sockaddr *) &serveraddr, serverlen)== -1) { error("sendto() error"); } } else { while(1) { byte_read = fread(buffer, 1, 1008, fd); //loop untill file is greater than 1008 printf("Sending packet %d\n", Request_Packet.seqNum); //output sequence number Request_Packet.seqNum += Request_Packet.seqNum + 1008; //increase the sequence number by 1008 if (sendto(sockfd, buffer, MAX_PKT_LENGTH, 0, (const struct sockaddr *) &serveraddr, serverlen)== -1) { error("sendto() error"); } if (byte_read <= 0) { //if read all files then exit the loop break; } if (byte_read <= 1008) { //if file is less than 1008 then break fread(buffer, 1, byte_read, fd); printf("Sending packet %d\n", Request_Packet.seqNum); //output sequence number Request_Packet.seqNum += Request_Packet.seqNum + byte_read; //increase the sequence number by file size if (sendto(sockfd, buffer, MAX_PKT_LENGTH, 0, (const struct sockaddr *) &serveraddr, serverlen)== -1) { error("sendto() error"); } break; } } } */ // if (fd != NULL) { //check if the file is empty // // read up to sizeof(buffer) bytes // while ((byte_read = fread(buffer, 1, 1008, fd)) > 0) // { // // process bytesRead worth of data in buffer // printf("Sending packet DATA:: %s\n", buffer); // if (sendto(sockfd, buffer, MAX_PKT_LENGTH, 0, (const struct sockaddr *) &serveraddr, slen)== -1) { // error("sendto() error"); // } // } // } //fclose(fd); // BELOW CODE NOT RELAVANT, BUT SAVED FOR FUTURE REFERENCE /* // Print the server's reply n = recvfrom(sockfd, buf, strlen(buf), 0, (struct sockaddr *) &serveraddr, &serverlen); if (n < 0) { perror("recvfrom did not work"); exit(0); } printf("Echo from server: %s", buf); */ return 0; }
C
//----------------------------------------------------------------------------- // List.c // List ADT // Stephanie Lu, sqlu // 2020 Spring CSE101 PA2 //----------------------------------------------------------------------------- #include<stdio.h> #include<stdlib.h> #include<ctype.h> #include<string.h> #include "List.h" #define POWER 9 #define BASE 1000000000 //contains definitions of all exported functions //private // structs --------------------------------------------------- // private NodeObj type typedef struct NodeObj { type data; struct NodeObj *next; struct NodeObj *prev; } NodeObj; // private Node type typedef NodeObj *Node; // private ListObj type typedef struct ListObj { Node front; Node back; Node cursor; int length; int index; } ListObj; // Constructors-Destructors --------------------------------------------------- //newNode() // Returns reference to new Node object. Initializes next and data fields. Node newNode(type data) { Node N = malloc(sizeof(NodeObj)); N->data = data; N->next = NULL; N->prev = NULL; return (N); } // freeNode() // Frees heap memory pointed to by *pN, sets *pN to NULL. void freeNode(Node *pN) { if (pN != NULL && *pN != NULL) { free(*pN); *pN = NULL; } } // newList() // Returns reference to new empty List object. List newList(void) { List L; L = malloc(sizeof(ListObj)); L->front = L->back = NULL; L->cursor = NULL; L->length = 0; L->index = -1; return (L); } // freeList() // Frees all heap memory associated with List *pL, and sets *pL to NULL. void freeList(List *pL) { if (pL != NULL && *pL != NULL) { while (!isEmpty(*pL)) { deleteFront(*pL); } free(*pL); *pL = NULL; } } // Access functions ----------------------------------------------------------- //length() // Returns the number of elements in L int length(List L) { if (L == NULL) { printf("List Error: calling length() on NULL List reference\n"); exit(EXIT_FAILURE); } return (L->length); } //index() //returns index of cursor element if defined, -1 otherwise int index(List L) { if (L == NULL) { printf("List Error: calling index() on NULL List reference\n"); exit(EXIT_FAILURE); } if (isEmpty(L)) { return (L->index = -1); } if (L->cursor == NULL) { return (L->index = -1); } else return (L->index); //code for returning index of cursor element } //get() // Returns cursor element of L. Pre: length()>0, index()>=0 type get(List L) { if (L == NULL) { printf("Cursor Error: calling get() on NULL List reference\n"); exit(EXIT_FAILURE); } if (L->cursor == NULL) { printf("Cursor Error: cursor is undefined"); exit(EXIT_FAILURE); } return (L->cursor->data); } //listEquals() // Returns true (1) iff Lists A and B are in same // state, and returns false (0) otherwise. int listEquals(List A, List B) { int eq = 0; Node N = NULL; Node M = NULL; if (A == NULL || B == NULL) { printf("List Error: calling listEquals() on NULL List reference\n"); exit(EXIT_FAILURE); } eq = (A->length == B->length); N = A->front; M = B->front; while (eq && N != NULL) { eq = (N->data == M->data); N = N->next; M = M->next; } return eq; } //front() // Returns front element of L. Pre: length()>0 int front(List L) { if (L == NULL) { printf("List Error: calling front() on NULL List reference\n"); exit(EXIT_FAILURE); } if (isEmpty(L)) { printf("List Error: calling front() on empty List reference\n"); exit(EXIT_FAILURE); } return (L->front->data); } //back() // Returns back element of L. Pre: length()>0 int back(List L) { if (L == NULL) { printf("List Error: calling back() on NULL List reference\n"); exit(EXIT_FAILURE); } if (isEmpty(L)) { printf("List Error: calling back() on empty List reference\n"); exit(EXIT_FAILURE); } return (L->back->data); } //isEmpty() //returns true (1) if L is empty, otherwise returns false(0) int isEmpty(List L) { if (L == NULL) { printf("List Error: calling isEmpty() on NULL List reference\n"); exit(EXIT_FAILURE); } return (L->length == 0); } // Manipulation procedures ---------------------------------------------------- //clear() // Resets L to its original empty state. void clear(List L) { if (L == NULL) { printf("List Error: calling clear() on NULL List reference\n"); return; //exit(EXIT_FAILURE); } if (isEmpty(L)) { printf("List Error: calling clear() on empty List\n"); return; //exit(EXIT_FAILURE); } while (L->front != NULL) { deleteBack(L); } L->index = -1; } //moveFront() // If L is non-empty, sets cursor under the front element, // otherwise does nothing. void moveFront(List L) { if (isEmpty(L) || L == NULL) { return; } else { L->cursor = L->front; L->index = 0; } } //moveBack() // If L is non-empty, sets cursor under the back element, // otherwise does nothing. void moveBack(List L) { if (isEmpty(L) || L == NULL) { return; } else { L->cursor = L->back; L->index = L->length; } } //movePrev() // If cursor is defined and not at front, move cursor one // step toward the front of L; if cursor is defined and at // front, cursor becomes undefined; if cursor is undefined // do nothing void movePrev(List L) { if (L == NULL) { printf("Cursor Error: calling movePrev() on NULL List.\n"); exit(EXIT_FAILURE); } if (L->cursor != NULL && L->index != 0) { L->cursor = L->cursor->prev; L->index--; } if (L->cursor != NULL && L->index == 0) { L->cursor = NULL; L->index = -1; } if (L->cursor == NULL) { return; } } //moveNext() // If cursor is defined and not at back, move cursor one // step toward the back of L; if cursor is defined and at // back, cursor becomes undefined; if cursor is undefined // do nothing void moveNext(List L) { if (L == NULL) { printf("Cursor Error: calling moveNext() on NULL List.\n"); exit(EXIT_FAILURE); } else if (L->cursor != NULL && L->index != (L->length - 1)) { L->cursor = L->cursor->next; L->index++; } else if (L->cursor != NULL && L->cursor->next == NULL) { L->cursor = NULL; L->index = -1; } return; } //prepend() // Insert new element into L. If L is non-empty, // insertion takes place before front element. void prepend(List L, type data) { if (L == NULL) { printf("List Error: calling prepend() on NULL List reference\n"); exit(EXIT_FAILURE); } Node N = newNode(data); if (isEmpty(L)) { L->front = L->back = N; } else { L->front->prev = N; N->next = L->front; L->front = N; //N->next = L->front; //L->front->prev = N; //L->front = N; if (L->index != -1) { L->index++; } } L->length++; } // append() // Insert new element into L. If L is non-empty, // insertion takes place after back element. void append(List L, type data) { if (L == NULL) { printf("List Error: calling append() on NULL List reference\n"); exit(EXIT_FAILURE); } Node N = newNode(data); if (isEmpty(L)) { L->front = L->back = N; } else { L->back->next = N; N->prev = L->back; L->back = N; //N->prev = L->back; //L->back->next = N; //L->back = N; } L->length++; } //insertBefore() // Insert new element before cursor. // Pre: length()>0, index()>=0 void insertBefore(List L, type data) { Node N = newNode(data); if (L == NULL) { printf("List Error: calling insertBefore() on NULL List reference\n"); exit(EXIT_FAILURE); } if (isEmpty(L)) { printf("List Error: calling insertBefore() on empty List reference\n"); exit(EXIT_FAILURE); } if (L->cursor == NULL) { printf( "List Error: calling insertBefore() while cursor is undefined\n"); exit(EXIT_FAILURE); } else { N->prev = L->cursor->prev; N->next = L->cursor; L->cursor->prev = N; if (N->prev != NULL) { N->prev->next = N; } else { L->front = N; } } if (L->index != -1) { L->index++; } L->length++; } //insertAfter() // Insert new element after cursor. // Pre: length()>0, index()>=0 void insertAfter(List L, type data) { Node N = newNode(data); if (L == NULL) { printf("List Error: calling insertAfter() on NULL List reference\n"); exit(EXIT_FAILURE); } if (isEmpty(L)) { printf("List Error: calling insertAfter() on empty List reference\n"); exit(EXIT_FAILURE); } if (L->index == -1 || L->cursor == NULL) { printf("List Error: calling insertAfter() while cursor is undefined\n"); exit(EXIT_FAILURE); } else { N->next = L->cursor->next; N->prev = L->cursor; if (N->next != NULL) { N->next->prev = N; } else L->back = N; L->cursor->next = N; } L->length++; } //deleteFront() // Delete the front element. Pre: length()>0 void deleteFront(List L) { Node N = NULL; if (L == NULL) { printf("List Error: calling deleteFront() on NULL List reference\n"); exit(EXIT_FAILURE); } if (isEmpty(L)) { printf("List Error: calling deleteFront() on an empty List\n"); exit(EXIT_FAILURE); } if (length(L) > 1) { N = L->front; if (L->cursor == L->front) { L->cursor = NULL; L->index = -1; freeNode(&N); } else if(L->cursor != NULL) L->index--; L->front = N->next; freeNode(&N); } else{ N = L->back; L->front = N = NULL; } L->length--; } //deleteBack() // Delete the back element. Pre: length()>0 void deleteBack(List L) { Node N = NULL; if (L == NULL) { printf("List Error: calling deleteBack() on NULL List reference\n"); exit(EXIT_FAILURE); } if (isEmpty(L)) { printf("List Error: calling deleteBack() on an empty List\n"); exit(EXIT_FAILURE); } N = L->back; if (L->length > 1) { if (L->cursor == L->back) { L->cursor = NULL; L->index = -1; } L->back = L->back->prev; } else { L->back = L->front = L->cursor = NULL; } L->length--; freeNode(&N); } // set() // Overwrites the cursor element with x. Pre: length()>0, index()>=0 void set(List L, long x) { if (L == NULL) { printf("List Error: calling set() on NULL List reference\n"); exit(EXIT_FAILURE); } if (isEmpty(L)) { printf("List Error: calling set() on empty List reference\n"); exit(EXIT_FAILURE); } if (!isEmpty(L) && L->index == -1) { printf("List Error: calling set() on undefined cursor element\n"); exit(EXIT_FAILURE); } else { L->cursor->data = x; } } //delete() // Delete cursor element, making cursor undefined. // Pre: length()>0, index()>=0 void delete(List L) { Node N = NULL; if (L == NULL) { printf("List Error: calling delete() on NULL List reference\n"); exit(EXIT_FAILURE); } if (isEmpty(L)) { printf("List Error: calling delete() on empty List reference\n"); exit(EXIT_FAILURE); } if (!isEmpty(L) && L->index == -1) { printf("List Error: calling delete() on undefined cursor element\n"); exit(EXIT_FAILURE); } else { N = L->front; while (N != L->cursor) { N = N->next; } if (L->index == 0) { deleteFront(L); } else if (L->index == L->length) { deleteBack(L); } else if (N == L->cursor) { N->prev->next = N->next; N->next->prev = N->prev; } freeNode(&N); } L->cursor = NULL; L->index = -1; L->length--; } // Other operations ----------------------------------------------------------- //find length of a long int int getLongLen(long getNum) { int len = 0; if (getNum == 0) { return (1); } while (getNum != 0) { getNum = getNum / 10; len++; } return (len); } //printList() // Prints to the file pointed to by out, a // string representation of L consisting // of a space separated sequence of integers, // with front on left. void printList(FILE *out, List L) { if (L == NULL) { printf("List Error: calling printList() on NULL List reference\n"); exit(EXIT_FAILURE); } for (moveBack(L); index(L) >= 0; movePrev(L)) { if (index(L) == (length(L)) && get(L) == 0) movePrev(L); if (get(L) < ((BASE/10) - 1) && index(L) != length(L)) { int len = POWER - getLongLen(get(L)); for (int i = 0; i < len; i++) { fprintf(out, "%d", 0); } } fprintf(out, "%ld", get(L)); } fprintf(out, "\n\n"); } //copyList() // Returns a new List representing the same integer // sequence as L. The cursor in the new list is undefined, // regardless of the state of the cursor in L. The state // of L is unchanged. List copyList(List L) { if (L == NULL) { printf("List Error: calling copyList() on NULL List reference\n"); exit(EXIT_FAILURE); } List L2 = newList(); for (moveFront(L); index(L) >= 0; moveNext(L)) { append(L2, get(L)); } //Iterate through list, create elements for list L2->cursor = NULL; L2->index = -1; return L2; }
C
#include <stdio.h> #include <stdlib.h> typedef struct { int N; int *u; int *u_rank; }union_find; union_find *make_union_find(int N){ int i; union_find *uf = (union_find *)malloc(sizeof(union_find)); uf->N = N; uf->u = (int *)malloc(sizeof(int) * N); uf->u_rank = (int *)malloc(sizeof(int) * N); for(i = 0; i < N; i++){ (uf->u)[i] = i; (uf->u_rank)[i] = 1; } return uf; } int root_uf(int x, union_find *uf){ int *u = uf->u; if(u[x] == x){ return x; } else{ u[x] = root_uf(u[x], uf); return u[x]; } } void combine_uf(int x, int y, union_find *uf){ int x_root = root_uf(x, uf); int y_root = root_uf(y, uf); int *u = uf->u; int *u_rank = uf->u_rank; if(x_root == y_root){ return; } else if(u_rank[x_root] < u_rank[y_root]){ u[x_root] = y_root; u_rank[y_root] += u_rank[x_root]; u_rank[x_root] = 0; } else{ u[y_root] = x_root; u_rank[x_root] += u_rank[y_root]; u_rank[y_root] = 0; } } //x?y????????????1?,???????0??? int is_same_union_uf(int x, int y, union_find *uf){ if(root_uf(x, uf) == root_uf(y, uf)){ return 1; } else{ return 0; } } //x????????????? int rank_uf(int x, union_find *uf){ return (uf->u_rank)[root_uf(x, uf)]; } typedef struct { int u; int v; }pair; int compair(const void *a, const void *b){ return ((pair *)a)->u - ((pair *)b)->u; } int main(){ int N, M, s, i, j, tmp; scanf("%d%d%d", &N, &M, &s); s--; pair *ps = (pair *)malloc(sizeof(pair) * (M + 1)); ps[0].u = -1; ps[0].v = -1; for(i = 1; i <= M; i++){ scanf("%d%d", &ps[i].u, &ps[i].v); ps[i].u--; ps[i].v--; if(ps[i].u > ps[i].v){ tmp = ps[i].u; ps[i].u = ps[i].v; ps[i].v = tmp; } } qsort(ps, M + 1, sizeof(pair), compair); union_find *uf = make_union_find(N); int *ans = (int *)malloc(sizeof(int) * N); for(i = N - 1, j = M; i >= 0; i--){ // printf("i = %d\n", i); while(ps[j].u >= i){ // printf("j = %d\n", j); combine_uf(ps[j].u, ps[j].v, uf); j--; } if(is_same_union_uf(s, i, uf) == 1){ ans[i] = 1; } else{ ans[i] = 0; } } for(i = 0; i < N; i++){ if(ans[i] == 1){ printf("%d\n", i + 1); } } return 0; } ./Main.c: In function main: ./Main.c:80:2: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result] scanf("%d%d%d", &N, &M, &s); ^ ./Main.c:86:3: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result] scanf("%d%d", &ps[i].u, &ps[i].v); ^
C
/////////////////////////////////////////////////////////////////////////////// // Programa para el pic 16F1827 que muestra en numero de 4 cifras en 4 // // displays de siete segmentos digito a digito, la velociadad de cristal de // // cuarzo esta configurada a 4MHz // /////////////////////////////////////////////////////////////////////////////// // 'C' source line config statements #include <xc.h> // Bits de configuración // CONFIG1 #pragma config FOSC = XT // Oscilador con cristal de cuarzo de 4MHz conectado en los pines 15 y 16 #pragma config WDTE = OFF // Perro guardian (WDT deshabilidado) #pragma config PWRTE = OFF // Power-up Timer Enable (PWRT deshabilidado) #pragma config MCLRE = ON // Master clear habilitado (pin reset) #pragma config CP = OFF // Protección contra lectura de código #pragma config CPD = OFF // Data Memory Code Protection (Data memory code protection is disabled) #pragma config BOREN = ON // Brown-out Reset Enable (Brown-out Reset enabled) #pragma config CLKOUTEN = OFF // Clock Out Enable (CLKOUT function is disabled. I/O or oscillator function on the CLKOUT pin) #pragma config IESO = ON // Internal/External Switchover (Internal/External Switchover mode is enabled) #pragma config FCMEN = ON // Fail-Safe Clock Monitor Enable (Fail-Safe Clock Monitor is enabled) // CONFIG2 #pragma config WRT = OFF // Flash Memory Self-Write Protection (Write protection off) #pragma config PLLEN = OFF // PLL Enable (4x PLL disabled) #pragma config STVREN = ON // Stack Overflow/Underflow Reset Enable (Stack Overflow or Underflow will cause a Reset) #pragma config BORV = LO // Brown-out Reset Voltage Selection (Brown-out Reset Voltage (Vbor), low trip point selected.) #pragma config LVP = OFF // Low-Voltage Programming Enable (High-voltage on MCLR/VPP must be used for programming) #define _XTAL_FREQ 4000000 // Oscilador a 4MHz void main(){ TRISA = 240; // Configuro RA0, RA1, RA2 y RA3 como salidas para controlar // los transistores que habilitaran cada display TRISB = 0; // Puerto B como salida ANSELA = 0; // Puerto A Digital ANSELB = 0; // Puerto B Digital PORTA = 0; // Inicializo Puerto A en 0 PORTB = 0; // Inicializo Puerto B en 0 int cont = 0; // Variable que incrementara de 0 a 9999 char miles; // Almacenara los miles char centenas; // Almacenara las centenas char decenas; // Almacenara las decenas char unidades; // Almacenara las unidades int aux = 0; // Variable para almacenar datos temporalmente while(1){ // Inicio del código a ejecutar constantemente if(cont > 9999){ // Verifico que el contador no haya superado la cantidad maxima // representable en los cuatro displays cont = 0; // Si es así la reinicio a 0 } aux = cont; // Guardo en auxiliar el valor en cont centenas = 0; // Pongo en cero todos los digitos decenas = 0; unidades = 0; miles = 0; while(aux > 999){ // Mientras el valor sea superior a 999 aux -= 1000; // Le resto de a 1000 miles++; // y por cada resta aumento una unidad el digito miles } while(aux > 99){ // Mientras el valor sea superior a 99 aux -= 100; // Le resto de 100 centenas++; // y por cada resta aumento una unidad al digito centenas } while(aux > 9){ // Mientras el valor sea superior a 9 aux -= 10; // Le resto de 10 decenas++; // y por cada resta aumento una unidad al digito decenas } unidades = aux; // Por ultimo el valor restante lo asigno a unidades PORTA = 1; // Activo el transistor para las unidades PORTB = unidades; // y paso las unidades al display __delay_ms(10); // Doy un retardo, por lo general en una aplicación real debe ser de unos 3 a 5 milisegundos PORTA = 2; // Activo el transistor para las decenas PORTB = decenas; // y paso las decenas al display __delay_ms(10); // Retardo PORTA = 4; // Activo el transistor para las centenas PORTB = centenas; // y paso las centenas al display __delay_ms(10); // Retardo PORTA = 8; // Activo el transistor para los miles PORTB = miles; // y paso los miles al display __delay_ms(10); cont++; // Incremento en una unidad el contador } }
C
#include "cells.h" int main(void) { char command; char c = 'O'; int rule_arr[8] = {0}; int flag; term_size t_size; srand(time(0)); do { fflush(0); flag = 0; get_size(&t_size); get_rule(rule_arr); generate(rule_arr, &t_size, c); printf("Run again? (y/n) or change char? (c): "); command = getchar(); if (command == 'c' || command == 'C') { c = change_char(); flag = 1; } } while (command == 'y' || command == 'Y' || flag == 1); return (0); }
C
#include <stdio.h> extern int count; // extern ٸ Ͽ int total = 0; int input_data() { int pos; while (1) { printf(" Է : "); scanf("%d", &pos); if (pos < 0) break; count++; total += pos; } return total; }
C
#include <stdio.h> #include <stdlib.h> int fibo(int num1) { printf("Fibonacci Number %d \n", num1); if(num1==0) return 0; if(num1==1) return 1; return (fibo(num1-1) +fibo(num1-2)); } int main() { int num1; printf("input Fibonacci ="); scanf("%d", &num1); fibo(num1); }
C
#include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> #include "pattern.h" #include "clock.h" const int width = 800; SDL_Window * win; #define CIRCLE_RADIUS .005 #define CIRCLE_POINTS 24 #define FPS 50 void draw_circle(double x, double y, rgb_t color) { int i; glColor3ub(color.r, color.g, color.b); glPushMatrix(); glTranslatef(x, y, 0); glBegin(GL_TRIANGLE_FAN); glVertex2f(0, 0); for (i = 0; i <= CIRCLE_POINTS; i++) { glVertex2f(cos(M_PI * 2 * i / CIRCLE_POINTS) * CIRCLE_RADIUS, sin(M_PI * 2 * i / CIRCLE_POINTS) * CIRCLE_RADIUS); } glEnd(); glPopMatrix(); } int main() { int t; int pattern_num = 0; beat_clock_init(); if (SDL_Init(SDL_INIT_VIDEO) < 0) { exit(1); } win = SDL_CreateWindow("trees", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, width, SDL_WINDOW_OPENGL); SDL_GL_CreateContext(win); glEnable(GL_TEXTURE_2D); glViewport(0, 0, width, width); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0f, width, width, 0.0f, -1.0f, 1.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(width / 2, width / 2, 0); glScalef(width / 2, width / -2, 0); t = SDL_GetTicks(); while (!SDL_QuitRequested()) { int t2; size_t i, j; double z = beat_clock(); /* Handle SDL events */ SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_KEYDOWN && event.key.keysym.sym == ' ') { pattern_num = (pattern_num + 1) % pattern_count; } } glColor3ub(0, 0, 0); glBegin(GL_TRIANGLE_FAN); glVertex2f(-2, -2); glVertex2f(-2, 2); glVertex2f(2, 2); glVertex2f(2, -2); glEnd(); for (i = 0; i < pusher_config_count; i++) { for (j = 0; j < pushers[i].valid_pixels; j++) { double x = pushers[i].pixel_locations[j].x; double y = pushers[i].pixel_locations[j].y; draw_circle(x, y, pattern_arr[pattern_num].func(x, y, j, z)); } } SDL_GL_SwapWindow(win); t2 = SDL_GetTicks(); if (t2 < t + (1000/FPS)) { t += (1000/FPS); SDL_Delay(t - t2); } else { SDL_Delay(1); t = t2; } } return 0; }
C
#include <stdio.h> int main() { /* Escribe los numeros del 1 al 10*/ int numero = 1; do { printf ("%d\n", numero); numero++; }while (numero <= 10); return 0; }
C
#include"sem_header.h" int main() { key_t key = ftok(FILENAME, 'x'); int flag = IPC_CREAT; int perm = S_IRUSR|S_IWUSR; int id; ERRHANDLER(id = semget(key, 1, flag|perm)); struct sembuf sop; int n = 10; while(1) { sop.sem_num = 0; sop.sem_op = -1; sop.sem_flg = SEM_UNDO; if(semop(id, &sop, 1) != -1) { printf("the process %ld is printing a message\n", (long)getpid()); } else { perror("semop"); break; } } }
C
#include<stdio.h> #include<stdlib.h> struct node { ///INSERTION AT END int info; struct node *link; }; struct node *START=NULL; struct node*createNode() { struct node*n; n=(struct node*)malloc(sizeof(struct node)); return n; } void insertnode() { struct node*temp,*t; temp=createNode(); printf("Enter information\n"); scanf("%d",temp->info); temp->link=NULL; if(START==NULL) //if the list is empty START=NULL; else //in case if lists is there!!!! { t=START; while(t->link) {t=t->link;} t->link=temp; } } int main() { insertnode(); insertnode(); insertnode(); insertnode(); insertnode(); return 0; }
C
#include <stdio.h> #include <omp.h> int main() { int ii; #pragma omp parallel private(ii) { for(ii=0;ii<10;ii++) { printf("Iteration: %d from %d\n",ii,omp_get_thread_num()); } } printf("\n"); return 0; }
C
// Function prototypes for large file access // The function xL has the same prototype and semantics as the function x (x=fopen, fclose, etc) #include <stdio.h> #include <sys/stat.h> #include "DataStructures.h" typedef int FileHandle; FileHandle fopenL(const char *filename, const char *mode); int fcloseL(FileHandle); int statL(const char *filenameL, struct statL *buf) ; // The following functions use 'long long' to represent the position, assuming that type is 64 bits int fseekL(FileHandle, long long offset, int wherefrom); long long ftellL(FileHandle); size_t freadL (void *ptr, size_t element_size, size_t count, FileHandle); size_t fwriteL(void *ptr, size_t element_size, size_t count, FileHandle); int feofL(FileHandle);
C
#include <stdlib.h> #include <stdio.h> #include "bst.h" #include "queue.h" static BinNode * BST_node_new(int k) { BinNode * b = malloc(sizeof(BinNode)); b->key = k; b->left = NULL; b->right = NULL; return b; } BST * BST_new() { BST * b = malloc(sizeof(BST)); b->root = NULL; return b; } BinNode* BST_insert_aux(BinNode* node, int k){ if(k < node->key){ if(node->left == NULL){ node->left = BST_node_new(k); return node->left; }else return BST_insert_aux(node->left, k); }else if(k > node->key){ if(node->right == NULL){ node->right = BST_node_new(k); return node->right; }else return BST_insert_aux(node->right, k); } return NULL; } BinNode * BST_insert(BST * b, int k) { if(b->root == NULL){ b->root = BST_node_new(k); return b->root; } return BST_insert_aux(b->root, k); } BinNode* BST_find_aux(BinNode* node, int k){ if(k < node->key){ if(node->left == NULL) return NULL; else return BST_find_aux(node->left, k); }else if(k > node->key){ if(node->right == NULL) return NULL; else return BST_find_aux(node->right, k); } return node; } BinNode * BST_find(BST * b, int k) { if(b->root == NULL) return NULL; return BST_find_aux(b->root, k); } static void BST_delete_aux(BinNode * t) { if (t == NULL) return; BST_delete_aux(t->left); BST_delete_aux(t->right); free(t); } void BST_delete(BST * b) { if (b == NULL) return; BST_delete_aux(b->root); free(b); } void BST_print_aux(BinNode * t, int level) { if (t == NULL) return; int i; for (i = 0; i < level - 1; i++) { printf(" "); } if (level > 0) { printf(" |--"); } printf("%d\n", t->key); BST_print_aux(t->left, level + 1); BST_print_aux(t->right, level + 1); } void BST_print(BST * b){ return BST_print_aux(b->root, 0); } int maxOnLevel_aux(BinNode* node, int current, int level){ if(node == NULL) return -1; int left = -1, right = -1; if(current < level){ left = maxOnLevel_aux(node->left, current + 1, level); right = maxOnLevel_aux(node->right, current + 1, level); return (left > right) ? left : right; } return node->key; } int maxOnLevel (BST * b, int level){ if(b->root == NULL) return -1; if(level == 1) return b->root->key; return maxOnLevel_aux(b->root, 1, level); }
C
/* ** tekpixel.c for raytracer1 in /home/voravo_d/rendu/raytracer1 ** ** Made by dorian voravong ** Login <[email protected]> ** ** Started on Sun Jul 17 14:40:52 2016 dorian voravong ** Last update Sat Oct 8 18:51:17 2016 Quentin Fournier Montgieux */ #include "lapin.h" void tekpixel(t_bunny_pixelarray *pix, t_bunny_position *pos, t_color *color) { unsigned int *pixel; pixel = pix->pixels; if (pos->x < pix->clipable.clip_width && pos->y < pix->clipable.clip_height && pos->x >= 0 && pos->y >= 0) pixel[pix->clipable.clip_width * pos->y + pos->x] = color->full; } void tekray(const t_bunny_position *screen_info, int *x, int *y, int *z) { *x = screen_info[1].x - screen_info[0].x / 2; *y = screen_info[1].y - screen_info[0].y / 2; *z = 100; } unsigned int tekgetpixel(t_bunny_pixelarray *pix, t_bunny_position *pos) { unsigned int *pixel; if (pos->x >= pix->clipable.clip_width || pos->y >= pix->clipable.clip_height || pos->x < 0 || pos->y < 0) return (0); pixel = pix->pixels; return (pixel[pix->clipable.clip_width * pos->y + pos->x]); }
C
#include"util_2.h" extern void error(int, char *); double *DajWekt(int n) { double *we; if (!(we = (double *) malloc((unsigned) n * sizeof(double)))){ error(0, "wektor"); } return we; } void CzytWekt(FILE *fd, double *we, int n) { for (int k = 0; k < n; k++) { fscanf(fd, "%lf", &we[k]); } } void PiszWekt(FILE *fw, double *we, int n) { for (int k = 0; k < n; k++) { fprintf(fw, "%lf ", we[k]); if (!((k + 1) % 5)) fprintf(fw, "\n"); } }
C
/* * @Author: shishao * @Date: 2019-07-16 14:33:47 * @Last Modified by: shishao * @Last Modified time: 2019-07-16 14:45:44 */ #include <avl.h> #include <assert.h> #define get_height(node) (((node)==0)?(-1):((node)->height)) #define max(a,b) ((a)>(b)?(a):(b)) /* RR(Y rotates to the right): k2 k1 / \ / \ k1 Z ====== X k2 / \ / \ X Y Y Z */ /* Return which the root pointer(at a higher level) should point to */ static struct avl_node* rr_rotate(struct avl_node* k2) { assert(k2 != 0); struct avl_node* k1 = k2 -> left; k2 -> left = k1 -> right; k1 -> right = k2; k2 -> height = max(get_height(k2 -> left), get_height(k2 -> right)) + 1; k1 -> height = max(get_height(k1 -> left), k2 -> height) + 1; return k1; } /* LL(Y rotates to the left): k2 k1 / \ / \ X k1 ====== k2 Z / \ / \ Y Z X Y */ static struct avl_node* ll_rotate(struct avl_node* k2) { assert(k2 != 0); struct avl_node* k1 = k2 -> right; k2 -> right = k1 -> left; k1 -> left = k2; k2 -> height = max(get_height(k2 -> left), get_height(k2 -> right)) +1; k1 -> height = max(get_height(k1 -> right), k2 -> height) +1; return k1; } /* LR(B rotates to the left, then C rotates to the right): k3 k3 k2 / \ / \ / \ k1 D k2 D k1 k3 / \ ====== / \ ====== / \ / \ A k2 k1 C A B C D / \ / \ B C A B */ /* Return which the root pointer should point to */ static struct avl_node* lr_rotate(struct avl_node* k3) { assert(k3 != 0); k3 -> left = ll_rotate(k3 -> left); return rr_rotate(k3); } /* RL(D rotates to the right, then C rotates to the left): k3 k3 k2 / \ / \ / \ A k1 A k2 k3 k1 / \ ====== / \ ====== / \ / \ k2 B C k1 A C D B / \ / \ C D D B */ static struct avl_node* rl_rotate(struct avl_node* k3) { assert(k3 != 0); k3 -> right = rr_rotate(k3 -> right); return ll_rotate(k3); } /* return which the root pointer(at an outer/higher level) should point to, the root_node of AVL tree may change frequently during delete/insert, so the Root pointer should point to the REAL root node. */ struct avl_node* avl_insert(struct avl_node* root, void* val, int (*comparator)(const void* v1, const void* v2), int* cancelled) { assert(comparator != 0); if(root == 0) { root = malloc(sizeof(struct avl_node)); root -> val = val; root -> left = 0; root -> right = 0; root -> height = 0; return root; } int comp = comparator(val , root -> val); if(comp == AVL_CANCEL) { if(cancelled) (*cancelled) = 1; return root; } else if(comp < 0) root -> left = avl_insert(root -> left, val, comparator, cancelled); else root -> right = avl_insert(root -> right, val, comparator, cancelled); root -> height = max(get_height(root -> left), get_height(root -> right)) + 1; ssize_t height_delta= get_height(root -> left) - get_height(root -> right); if(height_delta == 2) { if(comparator(val, root -> left -> val) < 0) root = rr_rotate(root); else root = lr_rotate(root); } else if(height_delta == -2) { if(comparator(val, root -> right -> val) < 0) root = rl_rotate(root); else root = ll_rotate(root); } return root; } /* return which the root pointer(at an outer/higher level) should pointer to, cause the root_node of AVL tree may change frequently during delete/insert, so the Root pointer should point to the REAL root node. */ struct avl_node* avl_delete(struct avl_node* root, void* val, int (*comparator)(const void* v1, const void* v2), int* cancelled, int* found) { assert(comparator != 0); if(root == 0) return 0; int comp = comparator(val, root -> val); if(comp == AVL_CANCEL) { if(cancelled) (*cancelled) = 1; return root; } else if(comp == 0) { if(root -> right == 0) { struct avl_node* temp = root; root = root -> left; free(temp); if(found) (*found) = 1; return root; } else { struct avl_node* temp = root -> right; while(temp -> left) temp = temp -> left; root -> val = temp -> val; root -> right = avl_delete(root -> right, temp -> val, comparator, cancelled, found); } } else if(comp < 0) root -> left = avl_delete(root -> left, val, comparator, cancelled, found); else root -> right = avl_delete(root -> right, val, comparator, cancelled, found); root -> height = max(get_height(root -> left), get_height(root -> right)) + 1; ssize_t height_delta = get_height(root -> left) - get_height(root -> right); if(height_delta == 2) { if(get_height(root -> left -> left) >= get_height(root -> left -> right)) root = rr_rotate(root); else root = lr_rotate(root); } else if(height_delta == -2) { if(get_height(root -> right -> right) >= get_height(root -> right -> left)) root = ll_rotate(root); else root = rl_rotate(root); } return root; } // get the node that contains the value that equals to the given one struct avl_node* avl_search(struct avl_node* root, void* val, int (*comparator)(const void* v1, const void* v2)) { assert(comparator != 0); if(root == 0) return 0; int comp = comparator(val, root -> val); if(comp == 0) return root; else if(comp < 0) return avl_search(root -> left, val, comparator); else return avl_search(root -> right, val, comparator); } // get how many nodes in the tree size_t avl_node_count(struct avl_node* root) { if(root == 0) return 0; return 1 + avl_node_count(root -> left) + avl_node_count(root -> right); }
C
#include <stdio.h> int search(int a[], int v, int l, int r); main(){ int a[10] = {2, 43, 20, 878, 100, -34, 0, -5, 21}; int index = -2; index = search(a, 0, 0, 9); printf("%d\n", index); } int search(int a[], int v, int l, int r){ int i; for(i=l; i<=r; i++){ if(a[i] == v){ return i; } } return -1; }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <sys/types.h> #include <sys/wait.h> #include<sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h> //Function that parses out unnecessary characters //such as ' ', and '\t' char** parse(char* s) { static char* words[500]; memset(words, 0, sizeof(words)); char break_chars[] = " \t"; int i = 0; char* p = strtok(s, break_chars); words[i++] = p; while (p != NULL) { p = strtok(NULL, break_chars); words[i++] = p; } return words; } int main(int argc, const char * argv[]) { //Initializes two arrays: //1. For the current input //2. To keep track of all inputs char input[BUFSIZ]; char last_command[BUFSIZ]; memset(input, 0, BUFSIZ * sizeof(char)); memset(last_command, 0, BUFSIZ * sizeof(char)); //Condition to keep the command line going bool finished = false; bool redirectoutput = false; bool redirectinput = false; //While loop that runs the program while (!finished) { printf("osh> "); fflush(stdout); //gets input and stores it in the array //also get rid of the new line at the end fgets(input, BUFSIZ, stdin); input[strlen(input) - 1] = '\0'; //If input is empty, it will give an error and pop up the command line until a input is not empty if (strcmp(input, "\0") == 0) { fprintf(stderr, "no command entered\n\n"); } //If input is exit, then it will end the program else if(strncmp(input, "exit", 4) == 0){ return 0; } //this is the case where the input is not an empty command or //not "exit" to end the program //Scenario where "!!" or use previous command if(strncmp(input, "!!", 2) == 0){ //if there is no last command,it will give an error if(strlen(last_command) == 0){ printf("There is no last command!\n"); } else { //if there is a previous command it will, execute it again strcpy(input, last_command); printf("The last command was: %s\n\n", last_command); } } //scenario where it is an actual commmand and not "!!" if (strncmp(input, "!!", 2 ) != 0) { strcpy(last_command, input); char** words = parse(input); //creates child pid_t pid = fork(); //printf("\n Checking output\n"); //if child wasn't created if(pid < 0){ fprintf(stderr, "Unable to fork a child\n"); return 0; } //parent process else if (pid > 0) { wait(NULL); } //child process else if(pid == 0){ //printf("Child Process created...\n"); //printf("\nFirst word: %s\n", words[0]); //printf("Second word: %s\n\n", words[1]); //regular commands with no redirection of output and input if (words[1] == '\0'){ execvp(words[0], words); printf("\n\n"); } //instance when cat "filename" is used if(words[2] == '\0'){ execvp(words[0], words); printf("\n\n"); } //redirects input from file and executes it //format : // < "filename" if(strncmp(words[0], "<", 1) == 0){ printf("getting input from %s\n\n", words[1]); char infromfile[BUFSIZ]; memset(infromfile,0, BUFSIZ * sizeof(char)); int fd_in = open(words[1], O_RDONLY); dup2(fd_in, STDIN_FILENO); fgets(infromfile, BUFSIZ, stdin); char** inputcommands = parse(infromfile); //printf("Input from File: %s %s\n", inputcommands[0], inputcommands[1]); execvp(inputcommands[0], inputcommands); } // case for ls > text.txt if(strncmp(words[1], ">", 1) == 0){ printf("output will be stored in %s\n\n", words[2]); int fd_out = open(words[2], O_WRONLY | O_TRUNC | O_CREAT); char* out[BUFSIZ]; out[0] = words[0]; dup2(fd_out, STDOUT_FILENO); execvp(out[0], out); close(fd_out); printf("\n\n"); } // //case for cat "filename" > "outputfile" if(strncmp(words[2], ">", 1) == 0 && (strncmp(words[0], "cat", 3) == 0)){ printf("output will be stored in %s\n\n", words[3]); int fd_out = open(words[3], O_WRONLY | O_TRUNC | O_CREAT); dup2(fd_out, STDOUT_FILENO); char* out[BUFSIZ]; out[0]= words[0]; out[1] = words[1]; execvp(out[0], out); close(fd_out); } } } } }
C
// SigLib frequency domain plot header file // This file must be included after siglib.h // Frequency Domain Plots : // These functions support separate lengths for the source array and the DFT // so that short arrays can be zero padded to longer (power of 2) lengths // If the source dataset length is longer than the DFT length then the // DFT only operates on the DFT length, not the entire array // Time Domain Plots : // These functions generate simple time domain plots. // Copyright (C) 2020 Sigma Numerix Ltd. #include "string.h" #include <gnuplot_c.h> // Gnuplot/C SLError_t plot_frequency_domain (SLData_t *pSrc, const enum SLWindow_t WindowType, char *pLabelString, SLArrayIndex_t SampleLength, SLArrayIndex_t DFTLength); SLError_t plot_complex_frequency_domain (SLData_t *pSrcReal, SLData_t *pSrcImag, const enum SLWindow_t WindowType, char *pLabelString, SLArrayIndex_t SampleLength, SLArrayIndex_t DFTLength); SLError_t plot_frequency_magnitude (SLData_t *, SLData_t *, char *, SLArrayIndex_t); SLError_t plot_time_domain (SLData_t *pSrcReal, char *pLabelString, SLArrayIndex_t SequenceLength); SLError_t plot_complex_time_domain (SLData_t *pSrcReal, SLData_t *pSrcImag, char *pLabelString, SLArrayIndex_t SequenceLength); SLError_t plot_frequency_domain (SLData_t *pSrc, const enum SLWindow_t WindowType, char *pLabelString, SLArrayIndex_t SampleLength, SLArrayIndex_t DFTLength) { static h_GPC_Plot *h2DPlot; // Plot object static int FirstTimeFlag = 1; SLData_t Max; SLData_t *pFDPSrcReal, *pFDPRealData, *pFDPImagData, *pFDPResults, *pWindowCoeffs; SLArrayIndex_t MaxIndex; char PrintString [100]; strcpy (PrintString, pLabelString); strcat (PrintString, " (dB)"); pFDPSrcReal = SUF_VectorArrayAllocate (DFTLength); // Real source data array pFDPRealData = SUF_VectorArrayAllocate (DFTLength); // Real data array pFDPImagData = SUF_VectorArrayAllocate (DFTLength); // Imaginary data array pFDPResults = SUF_VectorArrayAllocate (DFTLength); // Results data array pWindowCoeffs = SUF_VectorArrayAllocate (DFTLength); // Window coeffs data array if ((NULL == pFDPSrcReal) || (NULL == pFDPRealData) || (NULL == pFDPImagData) || (NULL == pFDPResults) || (NULL == pWindowCoeffs)) { printf ("Memory allocation error ...\n"); return (SIGLIB_MEM_ALLOC_ERROR); } if (FirstTimeFlag == 1) { // If this is the first time then create the graph h2DPlot = // Initialize plot gpc_init_2d ("Frequency Domain", // Plot title "Frequency", // X-Axis "Magnitude (dB)", // Y-Axis GPC_AUTO_SCALE, // Scaling mode GPC_SIGNED, // Sign mode GPC_KEY_DISABLE); // Legend / key mode FirstTimeFlag = 0; } if (NULL == h2DPlot) { printf ("Graph creation error ...\n"); return (SIGLIB_ERROR); // Graph creation failed } // Generate window table SIF_Window (pWindowCoeffs, // Window coefficients pointer WindowType, // Window type SIGLIB_ZERO, // Window coefficient DFTLength); // Window length // Clear the FFT array to zero pad the data SDA_Clear (pFDPSrcReal, // Pointer to source array DFTLength); // Dataset length // Copy the input data to preserve it if (SampleLength <= DFTLength) { SDA_Copy (pSrc, // Pointer to source array pFDPSrcReal, // Pointer to destination array SampleLength); // Dataset length } else { SDA_Copy (pSrc, // Pointer to source array pFDPSrcReal, // Pointer to destination array DFTLength); // Dataset length } // Apply window to real data SDA_Window (pFDPSrcReal, // Source array pointer pFDPSrcReal, // Destination array pointer pWindowCoeffs, // Window array pointer DFTLength); // Window size // Perform DFT SDA_Rft (pFDPSrcReal, // Real source array pointer pFDPRealData, // Real destination array pointer pFDPImagData, // Imaginary destination array pointer DFTLength); // DFT length // Calc real power fm complex SDA_LogMagnitude (pFDPRealData, // Pointer to real source array pFDPImagData, // Pointer to imaginary source array pFDPResults, // Pointer to log magnitude destination array DFTLength); // Dataset length // printf ("\nInputMaxPos = %d\n", SDA_AbsMaxPos (pFDPSrcReal, SampleLength)); // printf ("\npFDPRealDataMaxPos = %d\n", SDA_AbsMaxPos (pFDPRealData, SampleLength)); // printf ("\npFDPImagDataMaxPos = %d\n", SDA_AbsMaxPos (pFDPImagData, SampleLength)); // printf ("\npFDPResultsMaxPos = %d\n", SDA_AbsMaxPos (pFDPResults, SampleLength)); // printf ("\nInputMax = %lf\n", SDA_AbsMax (pFDPSrcReal, SampleLength)); // printf ("\npFDPRealDataMax = %lf\n", SDA_Max (pFDPRealData, DFTLength)); // printf ("\npFDPImagDataMax = %lf\n", SDA_Max (pFDPImagData, DFTLength)); // printf ("\nResultMax = %lf\n", SDA_AbsMax (pFDPResults, DFTLength)); // printf ("\nMaxIndex = %d\n", SDA_DetectFirstPeakOverThreshold (pFDPResults, -20.0, DFTLength/2)); // SUF_PrintArray (pFDPSrcReal, SampleLength); // SUF_PrintArray (pFDPRealData, SampleLength); // SUF_PrintArray (pFDPImagData, SampleLength); // SUF_PrintArray (pFDPResults, SampleLength); Max = SDA_AbsMax (pFDPResults, // Pointer to source array DFTLength); // Dataset length SDA_Offset (pFDPResults, // Pointer to source array -Max, // Offset pFDPResults, // Pointer to destination array DFTLength); // Dataset length MaxIndex = SDA_DetectFirstPeakOverThreshold (pFDPResults, // Pointer to source array -20.0, // Threshold over which peak will be detected DFTLength/2); // Dataset length if (MaxIndex == ((DFTLength/2) - 1)) { // If there is not a peak above the threshold then detect the highest peak MaxIndex = SDA_MaxPos (pFDPResults, // Pointer to source array DFTLength/2); // Dataset length } gpc_plot_2d (h2DPlot, // Graph handle pFDPResults, // Dataset (int)(DFTLength/2), // Dataset length PrintString, // Dataset title SIGLIB_ZERO, // Minimum X value (double)((DFTLength/2) - 1), // Maximum X value "lines", // Graph type "blue", // Colour GPC_NEW); // New graph printf ("\nFrequency Domain Plot\nPeak location = %d\n", MaxIndex); // printf ("Please hit <Carriage Return> to continue . . .\n"); getchar (); free (pFDPSrcReal); // Free memory free (pFDPRealData); free (pFDPImagData); free (pFDPResults); free (pWindowCoeffs); return (SIGLIB_NO_ERROR); // Return success code } // End of plot_frequency_domain () SLError_t plot_complex_frequency_domain (SLData_t *pSrcReal, SLData_t *pSrcImag, const enum SLWindow_t WindowType, char *pLabelString, SLArrayIndex_t SampleLength, SLArrayIndex_t DFTLength) { static h_GPC_Plot *h2DPlot; // Plot object static int FirstTimeFlag = 1; SLData_t Max; SLData_t *pFDPSrcReal, *pFDPSrcImag, *pFDPRealData, *pFDPImagData, *pFDPResults, *pWindowCoeffs; SLArrayIndex_t MaxIndex; char PrintString [100]; strcpy (PrintString, pLabelString); strcat (PrintString, " (dB)"); pFDPSrcReal = SUF_VectorArrayAllocate (DFTLength); // Real source data array pFDPSrcImag = SUF_VectorArrayAllocate (DFTLength); // Imaginary source data array pFDPRealData = SUF_VectorArrayAllocate (DFTLength); // Real data array pFDPImagData = SUF_VectorArrayAllocate (DFTLength); // Imaginary data array pFDPResults = SUF_VectorArrayAllocate (DFTLength); // Results data array pWindowCoeffs = SUF_VectorArrayAllocate (DFTLength); // Window coeffs data array if ((NULL == pFDPSrcReal) || (NULL == pFDPSrcImag) || (NULL == pFDPRealData) || (NULL == pFDPImagData) || (NULL == pFDPResults) || (NULL == pWindowCoeffs)) { printf ("Memory allocation error ...\n"); return (SIGLIB_MEM_ALLOC_ERROR); } if (FirstTimeFlag == 1) { // If this is the first time then create the graph h2DPlot = // Initialize plot gpc_init_2d ("Complex Frequency Domain", // Plot title "Frequency", // X-Axis "Magnitude", // Y-Axis GPC_AUTO_SCALE, // Scaling mode GPC_SIGNED, // Sign mode GPC_KEY_DISABLE); // Legend / key mode FirstTimeFlag = 0; } if (NULL == h2DPlot) { printf ("Graph creation error ...\n"); return (SIGLIB_ERROR); // Graph creation failed } // Generate window table SIF_Window (pWindowCoeffs, // Window coefficients pointer WindowType, // Window type SIGLIB_ZERO, // Window coefficient DFTLength); // Window length // Clear the FFT arrays to zero pad the data SDA_Clear (pFDPRealData, // Pointer to source array DFTLength); // Dataset length SDA_Clear (pFDPImagData, // Pointer to source array DFTLength); // Dataset length // Copy the input data to preserve it if (SampleLength <= DFTLength) { SDA_Copy (pSrcReal, // Pointer to source array pFDPSrcReal, // Pointer to destination array SampleLength); // Dataset length SDA_Copy (pSrcImag, // Pointer to source array pFDPSrcImag, // Pointer to destination array SampleLength); // Dataset length } else { SDA_Copy (pSrcReal, // Pointer to source array pFDPSrcReal, // Pointer to destination array DFTLength); // Dataset length SDA_Copy (pSrcImag, // Pointer to source array pFDPSrcImag, // Pointer to destination array DFTLength); // Dataset length } // Apply window to real data SDA_ComplexWindow (pFDPSrcReal, // Source array pointer pFDPSrcImag, // Pointer to imaginary array pFDPSrcReal, // Destination array pointer pFDPSrcImag, // Pointer to imaginary array pWindowCoeffs, // Window array pointer pWindowCoeffs, // Window array pointer DFTLength); // Window size // Perform DFT SDA_Cft (pFDPSrcReal, // Real source array pointer pFDPSrcImag, // Imaginary source array pointer pFDPRealData, // Real destination array pointer pFDPImagData, // Imaginary destination array pointer DFTLength); // DFT length // Calc real power fm complex SDA_LogMagnitude (pFDPRealData, // Pointer to real source array pFDPImagData, // Pointer to imaginary source array pFDPResults, // Pointer to log magnitude destination array DFTLength); // Dataset length Max = SDA_AbsMax (pFDPResults, // Pointer to source array DFTLength); // Dataset length SDA_Offset (pFDPResults, // Pointer to source array -Max, // Offset pFDPResults, // Pointer to destination array DFTLength); // Dataset length MaxIndex = SDA_DetectFirstPeakOverThreshold (pFDPResults, // Pointer to source array -20.0, // Threshold over which peak will be detected DFTLength/2); // Dataset length if (MaxIndex == ((DFTLength/2) - 1)) { // If there is not a peak above the threshold then detect the highest peak MaxIndex = SDA_MaxPos (pFDPResults, // Pointer to source array DFTLength/2); // Dataset length } gpc_plot_2d (h2DPlot, // Graph handle pFDPResults, // Dataset (int)(DFTLength/2), // Dataset length PrintString, // Dataset title SIGLIB_ZERO, // Minimum X value (double)((DFTLength/2) - 1), // Maximum X value "lines", // Graph type "blue", // Colour GPC_NEW); // New graph printf ("\nFrequency Domain Plot\nPeak location = %d\n", MaxIndex); // printf ("Please hit <Carriage Return> to continue . . .\n"); getchar (); free (pFDPSrcReal); // Free memory free (pFDPSrcImag); free (pFDPRealData); free (pFDPImagData); free (pFDPResults); free (pWindowCoeffs); return (SIGLIB_NO_ERROR); // Return success code } // End of plot_complex_frequency_domain () SLError_t plot_frequency_magnitude (SLData_t *pSrcReal, SLData_t *pSrcImag, char *pLabelString, SLArrayIndex_t DFTLength) { static h_GPC_Plot *h2DPlot; // Plot object static int FirstTimeFlag = 1; SLData_t *pFDPResults; pFDPResults = SUF_VectorArrayAllocate (DFTLength); // Results data array if (NULL == pFDPResults) { printf ("Memory allocation error ...\n"); return (SIGLIB_MEM_ALLOC_ERROR); } if (FirstTimeFlag == 1) { // If this is the first time then create the graph h2DPlot = // Initialize plot gpc_init_2d ("Frequency Domain - Magnitude", // Plot title "Frequency", // X-Axis "Magnitude", // Y-Axis GPC_AUTO_SCALE, // Scaling mode GPC_SIGNED, // Sign mode GPC_KEY_DISABLE); // Legend / key mode FirstTimeFlag = 0; } if (NULL == h2DPlot) { printf ("Graph creation error ...\n"); return (SIGLIB_ERROR); // Graph creation failed } // Calc real power fm complex SDA_LogMagnitude (pSrcReal, // Pointer to real source array pSrcImag, // Pointer to imaginary source array pFDPResults, // Pointer to log magnitude destination array DFTLength); // Dataset length gpc_plot_2d (h2DPlot, // Graph handle pFDPResults, // Dataset DFTLength, // Dataset length pLabelString, // Dataset title SIGLIB_ZERO, // Minimum X value (double)(DFTLength - 1), // Maximum X value "lines", // Graph type "blue", // Colour GPC_NEW); // New graph printf ("\nFrequency Domain Plot\n"); // printf ("Please hit <Carriage Return> to continue . . .\n"); getchar (); free (pFDPResults); // Free memory return (SIGLIB_NO_ERROR); // Return success code } // End of plot_frequency_magnitude () SLError_t plot_time_domain (SLData_t *pSrcReal, char *pLabelString, SLArrayIndex_t SequenceLength) { static h_GPC_Plot *h2DPlot; // Plot object static int FirstTimeFlag = 1; if (FirstTimeFlag == 1) { // If this is the first time then create the graph h2DPlot = // Initialize plot gpc_init_2d ("Time Domain", // Plot title "Time", // X-Axis "Magnitude", // Y-Axis GPC_AUTO_SCALE, // Scaling mode GPC_SIGNED, // Sign mode GPC_KEY_DISABLE); // Legend / key mode FirstTimeFlag = 0; } if (NULL == h2DPlot) { printf ("Graph creation error ...\n"); return (SIGLIB_ERROR); // Graph creation failed } gpc_plot_2d (h2DPlot, // Graph handle pSrcReal, // Dataset SequenceLength, // Dataset length pLabelString, // Dataset title SIGLIB_ZERO, // Minimum X value (double)(SequenceLength - 1), // Maximum X value "lines", // Graph type "blue", // Colour GPC_NEW); // New graph printf ("\nTime Domain Plot\n"); // printf ("Please hit <Carriage Return> to continue . . .\n"); getchar (); return (SIGLIB_NO_ERROR); // Return success code } // End of plot_frequency_magnitude () SLError_t plot_complex_time_domain (SLData_t *pSrcReal, SLData_t *pSrcImag, char *pLabelString, SLArrayIndex_t SequenceLength) { static h_GPC_Plot *h2DPlot; // Plot object static int FirstTimeFlag = 1; char PrintString [100]; if (FirstTimeFlag == 1) { // If this is the first time then create the graph h2DPlot = // Initialize plot gpc_init_2d ("Complex Time Domain", // Plot title pLabelString, // X-Axis "Magnitude", // Y-Axis GPC_AUTO_SCALE, // Scaling mode GPC_SIGNED, // Sign mode GPC_KEY_DISABLE); // Legend / key mode FirstTimeFlag = 0; } if (NULL == h2DPlot) { printf ("Graph creation error ...\n"); return (SIGLIB_ERROR); // Graph creation failed } strcpy (PrintString, pLabelString); strcat (PrintString, " - real"); gpc_plot_2d (h2DPlot, // Graph handle pSrcReal, // Dataset SequenceLength, // Dataset length PrintString, // Dataset title SIGLIB_ZERO, // Minimum X value (double)(SequenceLength - 1), // Maximum X value "lines", // Graph type "blue", // Colour GPC_NEW); // New graph strcpy (PrintString, pLabelString); strcat (PrintString, " - imaginary"); gpc_plot_2d (h2DPlot, // Graph handle pSrcImag, // Dataset SequenceLength, // Dataset length PrintString, // Dataset title SIGLIB_ZERO, // Minimum X value (double)(SequenceLength - 1), // Maximum X value "lines", // Graph type "red", // Colour GPC_ADD); // New graph printf ("\n%s\n", pLabelString); return (SIGLIB_NO_ERROR); // Return success code } // End of plot_frequency_magnitude ()
C
#include "slide_line.h" /** * slide_line - slides and merges an array of integers * @line: array (int) * @size: length of array * @direction: direction of merge (L/R) * Return: 1 | 0 */ int slide_line(int *line, size_t size, int direction) { return 1; }
C
/************************************************************************* > File Name: 12_34.c > Author: Amano Sei > Mail: [email protected] > Created Time: 2020年09月23日 星期三 16时22分52秒 ************************************************************************/ #include "csapp.h" struct baseargs{ int m, n, q; int **a, **b, **ans; }; struct calcargs{ int ci; struct baseargs *recs; }; void *calcthread(void *vargp){ struct calcargs *p = vargp; int ci = p->ci; int cans; int **a = p->recs->a; int **b = p->recs->b; for(int i = p->recs->q-1; i >= 0; i--){ cans = 0; for(int j = p->recs->n-1; j >= 0; j--) cans += a[ci][j]*b[j][i]; p->recs->ans[ci][i] = cans; } return NULL; } int **calcrec(int **A, int **B, int m, int n, int q){ register int **ret = Malloc(m*sizeof(int *)); pthread_t *tids = Malloc(m*sizeof(pthread_t)); struct baseargs ba = { m, n, q, A, B, ret }; struct calcargs *ca = Malloc(m * sizeof(struct calcargs)); for(int i = 0; i < m ;i++){ ret[i] = Malloc(q*sizeof(int)); ca[i].recs = &ba; ca[i].ci = i; Pthread_create(&tids[i], NULL, calcthread, &ca[i]); } for(int i = 0; i < m; i++) Pthread_join(tids[i], NULL); free(tids); free(ca); return ret; }
C
#include <string.h> #include <stdio.h> int main(void) { char str1[] = "USC is in Columbia. USC's coach is Spurrier. USC is in the SEC."; char str2[100]; char str3[] = "USC"; char str4[] = "[Chickens!]"; int i, j; printf("The Original String is: \"%s\"\n", str1); i = j = 0; while (str1[i] != '\0') // Do 'til end of string { if (strncmp(&str1[i], str3, strlen(str3)) == 0) { strcpy(&str2[j], str3); j += strlen(str3); i += strlen(str3); strcpy(&str2[j], str4); j += strlen(str4); } else str2[j++] = str1[i++]; } str2[j] = '\0'; printf("The New String is: \"%s\"\n", str2); getchar(); }
C
void printarr(int a[], int size) { for (int i = 0; i < size; i++) printf("%d ", a[i]); printf("\n"); } void swap(int* p1, int* p2) { long tmp; tmp = *p1; *p1 = *p2; *p2 = tmp; } #include <stdio.h> void qs_sort(int Array[], int N, int start, int end) { int head = start, tail = end; int middle = (start + end) / 2; int x = Array[middle]; int w; do { while (Array[head] > x) { head++; } while (x > Array[tail]) { tail--; } if (head <= tail) { w = Array[head]; Array[head] = Array[tail]; Array[tail] = w; head++; tail--; } } while (head < tail); if (start < tail) { qs_sort(Array, N, start, tail); } if (head < end) { qs_sort(Array, N, head, end); } } void bubble(int arr[], int size) { int i, j = 1; while (j < size) { for (i = size - 1; i >= j; i--) { if (arr[i] > arr[i - 1]) { swap(&arr[i], &arr[i - 1]); //printarr(arr, size); } } j++; } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* show_usage.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ahugh <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/12/04 18:31:22 by ahugh #+# #+# */ /* Updated: 2019/12/10 23:16:13 by ahugh ### ########.fr */ /* */ /* ************************************************************************** */ #include "lem_in.h" void show_usage(char *name_of_program) { ft_putstr("usage: "); ft_putstr(name_of_program); ft_putstr(" [OPTIONS] < map_file\n"); ft_putstr("Options:\n"); ft_putstr("\t--steps show the number of lines of instructions\n"); ft_putstr("\t--color draw the output in different colors\n"); ft_putstr("\t--paths show the paths of the found flow\n"); ft_putstr("\t--flows show found flows\n"); ft_putstr("\t--short show only instructions without a map\n"); ft_putstr("\t--multi calculate multi maps at once\n"); ft_putstr("\t "); ft_putstr(name_of_program); ft_putstr(" --multi {map_file_0} {map_file_1} ... {map_file_n}\n"); exit(1); }
C
#include <stdio.h> int main() { int i; int j; int board[20][20]; for (i = 0; i < 20; i++){ for (j = 0; j < 20; j++) { board[i][j]=0; } } return 0; }
C
/* * Copyright (c) 2010, the Short-term Memory Project Authors. * All rights reserved. Please see the AUTHORS file for details. * Use of this source code is governed by a BSD license that * can be found in the LICENSE file. */ #include "meter.h" #ifdef SCM_RECORD_MEMORY_USAGE static long alloc_mem = 0; static long num_alloc = 0; /** * Keeps track of the allocated memory */ void inc_allocated_mem(long inc) { //alloc_mem += inc; __sync_add_and_fetch(&alloc_mem, inc); __sync_add_and_fetch(&num_alloc, 1); } static long freed_mem = 0; static long num_freed = 0; /** * Keeps track of the freed memory */ void inc_freed_mem(long inc) { //freed_mem += inc; __sync_add_and_fetch(&freed_mem, inc); __sync_add_and_fetch(&num_freed, 1); } static long pooled_mem = 0; /** * Keeps track of the pooled memory */ void inc_pooled_mem(long inc) { //pooled_mem += inc; __sync_add_and_fetch(&pooled_mem, inc); } void dec_pooled_mem(long inc) { //pooled_mem -= inc; __sync_sub_and_fetch(&pooled_mem, inc); } static long mem_overhead = 0 ; /** * Keeps track of memory overhead */ void inc_overhead(long inc) { //mem_overhead += inc; __sync_add_and_fetch(&mem_overhead, inc); } void dec_overhead(long inc) { //mem_overhead -= inc; __sync_sub_and_fetch(&mem_overhead, inc); } static long start_time = 0; /** * Prints the memory consumption for total, pooled, and used memory */ void print_memory_consumption() { struct timeval t; gettimeofday(&t, NULL); long usec = t.tv_sec * 1000000 + t.tv_usec; if (start_time == 0) { start_time = usec; } // struct mallinfo info = mallinfo(); printf("memory usage:\t%lu\t%ld\t%ld\t%ld\n", usec - start_time, alloc_mem - freed_mem, pooled_mem, alloc_mem - pooled_mem); printf("memory overhead:\t%lu\t%lu\n", usec - start_time, mem_overhead); // printf("mallinfo:\t%lu\t%d\n", usec - start_time, info.uordblks); } #endif /* SCM_RECORD_MEMORY_USAGE */
C
/*--------------------------------------------------------- Teste da funcao ccreate ---------------------------------------------------------*/ #include "../include/cthread.h" #include "../include/support.h" #include <stdlib.h> #include <stdio.h> void *foo(void *param) { int n=(int)param; printf("->Thread %d: Inicio\n", n); printf("->Thread %d: Sou a thread: %d\n", n, n); printf("->Thread %d: Fim\n", n); return NULL; } int main() { printf("\n************************************\nPrograma Teste da funcao ccreate.\n************************************\n"); printf("->Thread 0: Inicio\n"); printf("->Thread 0: Criando Thread 1\n"); int tid1 = ccreate(foo, (void *)1, 0); if (tid1 == 1) { printf("->Thread 0: Tid gerado: %d\n", tid1); } else { printf("Falha, id errado"); } printf("->Thread 0: Criando Thread 2\n"); int tid2 = ccreate(foo, (void *)2, 0); if (tid2 == 2) { printf("->Thread 0: Tid gerado: %d\n", tid2); } else { printf("Falha, id errado"); } printf("->Thread 0: Criando Thread 3\n"); int tid3 = ccreate(foo, (void *)3, 0); if (tid3 == 3) { printf("->Thread 0: Tid gerado: %d\n", tid3); } else { printf("Falha, id errado"); } printf("->Thread 0: Criando Thread 4\n"); int tid4 = ccreate(foo, (void *)4, 0); if (tid4 == 4) { printf("->Thread 0: Tid gerado: %d\n", tid4); } else { printf("Falha, id errado"); } printf("->Thread 0: Esperando pela thread 1\n"); cjoin(tid1); printf("->Thread 0: Esperando pela thread 2\n"); cjoin(tid2); printf("->Thread 0: Esperando pela thread 3\n"); cjoin(tid3); printf("->Thread 0: Esperando pela thread 4\n"); cjoin(tid4); printf("->Thread 0: Fim\n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #define CORE 12 // struct arg_struct // { // int arg1; // int arg2; // }; int step = 0; void *parallel_addition(void *arg) { int core = (int)step; // Each thread computes 1/4th of matrix addition for (size_t i = core * MAX / CORE; i < (core + 1) * MAX / CORE; i++) { for (size_t j = 0; j < MAX; j++) { // Compute Sum Row wise arr[2][i][j] = mat_A[i][j] + mat_B[i][j]; } } } int main(int argc, char **argv) { printf("%lld", atoll(argv[1])); int MAX = atoll(argv[1]); int mat_A[MAX][MAX], mat_B[MAX][MAX], sum[MAX][MAX]; for (size_t i = 0; i < MAX; i++) { for (size_t j = 0; j < MAX; j++) { mat_A[i][j] = rand() % 10; mat_B[i][j] = rand() % 10; } } pthread_t thread[CORE]; int arr[3][MAX][]; arr[0] = mat_A; arr[1] = mat_B; arr[2] = sum; for (size_t i = 0; i < CORE; i++) { pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&thread[i], &attr, parallel_addition, NULL); step++; } for (size_t i = 0; i < CORE; i++) { // Waiting for join threads after compute pthread_join(thread[i], NULL); } }
C
/* * encoding: UTF-8 with BOM * * ISSUE: Really weird bug at fgetws() with stdin, doesn't read the newline character * => getwc(stdin) to ignore it. */ #include <fcntl.h> //_O_U16TEXT #include <io.h> //_setmode() #include <stdio.h> #include <string.h> int wmain(int argc, wchar_t* argv[]) { _setmode(_fileno(stdout), _O_U16TEXT); //needed for output _setmode(_fileno(stdin), _O_U16TEXT); //needed for input // nhớ chuyển font của console sang Consolas (size 16) wprintf(L"%ls%ls%ls", L"Chương trình đọc và xuất chuỗi tiếng Việt\n\n", L" \"Gõ\" tiếng Việt bằng cách copy chuỗi tiếng Việt ở trình soạn thảo tiếng Việt\n", L"nào đó rồi click phải chuột vào màn hình console\n\n"); // nhập họ tên wchar_t username[40]; wprintf(L"Nhập họ tên của bạn: "); fgetws(username, 40, stdin); username[wcslen(username) - 1] = L'\0'; getwc(stdin); //comment out this line if fgetws did read the newline character from stdin wprintf(L">> Xin chào, %ls!\n\n", username); // nhập giới tính wchar_t gender; wprintf(L"Bạn là nam hay nữ:\n a. Nam\n b. Nữ\n"); wscanf(L"%lc", &gender); wprintf(L">> Giới tính: %ls\n\n", gender == L'a' ? L"Nam" : (gender == L'b' ? L"Nữ" : L"Không xác định")); // nhập tuổi int age; wprintf(L"Nhập tuổi của bạn: "); wscanf(L"%d", &age); wprintf(L">> Năm nay bạn được %d tuổi\n\n", age); // lưu file tiếng Việt (UTF-8 with BOM) FILE* fout = _wfopen(L"userinfo-c.txt", L"w, ccs=UTF-8"); if (!fout) { wprintf(L"Không thể tạo file userinfo-c.txt\n"); } else { fwprintf(fout, L"%ls\n%lc\n%d\n", username, gender, age); fclose(fout); } // đọc file tiếng Việt (định dạng UTF-8 with BOM) FILE* fin = _wfopen(L"userinfo-c.txt", L"r, ccs=UTF-8"); if (!fin) { wprintf(L"Không thể đọc file userinfo-c.txt\n"); } else { fgetws(username, 40, fin); username[wcslen(username) - 1] = L'\0'; //now fgetws works fine fwscanf(fin, L"%lc", &gender); fwscanf(fin, L"%d", &age); wprintf(L"Họ tên: %ls\nGiới tính: %ls\nTuổi: %d\n\n", username, gender == L'a' ? L"Nam" : (gender == L'b' ? L"Nữ" : L"Không xác định"), age); fclose(fin); } wprintf(L"Chương trình kết thúc.\n"); }
C
/* K Web Server 0.2.1 By Ark 2014.7.30 */ #include <sys/socket.h> #include <stdio.h> #include <sys/types.h> #include <stdlib.h> #include <netinet/in.h> #include <sys/wait.h> #include <errno.h> #include <string.h> #include <arpa/inet.h> #include <pthread.h> #include <unistd.h> #include <string.h> #include <signal.h> #define PORT 80 #define BUFFER 5 #define DEFAULT_INDEX_PAGE "index.html" #define PATH_MAX 512 //Epoll Support #include <fcntl.h> #include <sys/epoll.h> #define MAXFDS 5000 #define EVENTSIZE 100 void app_exit(); int sock_fd; int ep_fd; //epoll file descriptor typedef struct http_request_param { char *method; char *path; char *http_version; } http_request; int setnonblocking(int fd) { int opts; opts = fcntl(fd, F_GETFL); if (opts < 0) { perror("fcntl get failed/n"); return 0; } opts = opts | O_NONBLOCK; if (fcntl(fd, F_SETFL, opts) < 0) { perror("fcntl set failed/n"); return; } return; } int split(char *token, char *buffer, char **output, int max_size) { char *tok = NULL; int count = 0; tok = strtok(buffer, token); while (tok != NULL) { if (count > max_size - 1) break; output[count] = tok; count++; tok = strtok(NULL, token); } return count; } void not_found_404(int send_to) { send_msg(send_to, "<h3>Not Found 404</h3>"); } /*Send Message*/ int send_msg(int fd, char *msg) { int len = strlen(msg); if (len = send(fd, msg, len, 0) == -1) { perror("send_msg"); } return len; } /* Send Header Info * Parameters: int send_to * char* content_type*/ void send_header(int send_to, char *content_type) { char *head = "HTTP/1.0 200 OK\r\n"; int len = strlen(head); if (send(send_to, head, len, 0) == -1) { printf("send header error"); return; } if (content_type) { char temp_1[30] = "Content-type: "; strcat(temp_1, content_type); strcat(temp_1, "\r\n"); send_msg(send_to, temp_1); } } void send_data(int send_to, char *content_type, char *filepath) { if (strcmp(filepath, "./") == 0) { strcat(filepath, DEFAULT_INDEX_PAGE); } FILE *file; file = fopen(filepath, "r"); if (file != NULL) { send_header(send_to, content_type); send(send_to, "\r\n", 2, 0); char buf[1024]; fgets(buf, sizeof(buf), file); while (!feof(file)) { send(send_to, buf, strlen(buf), 0); fgets(buf, sizeof(buf), file); } } else { send_header(send_to, content_type); send(send_to, "\r\n", 2, 0); not_found_404(send_to); } if (file != NULL) fclose(file); } int get_line(int sock, char *buf, int size) { int i = 0; char c = '\0'; int n; while ((i < size - 1) && (c != '\n')) { n = recv(sock, &c, 1, 0); if (n > 0) { if (c == '\r') { n = recv(sock, &c, 1, MSG_PEEK); if ((n > 0) && (c == '\n')) recv(sock, &c, 1, 0); else c = '\n'; } buf[i] = c; i++; } else c = '\n'; } buf[i] = '\0'; return (i); } void send_cgi(int send_to, char *content_type) { //to implement } void process_php(char *path) { //to implement } struct http_request_param *get_client_request(int new_fd) { struct http_request_param *hrp = malloc(sizeof(struct http_request_param)); if (hrp == NULL) { perror("hrp malloc error!\n"); } char buf[1024]; char parsebuf[1024]; char *lines[10]; int numchars = 1; buf[0] = 'A'; buf[1] = '\0'; numchars = get_line(new_fd, buf, sizeof(buf)); if (numchars > 0) { memcpy(parsebuf, buf, sizeof(buf)); split(" ", parsebuf, lines, numchars); hrp->method = lines[0]; hrp->path = lines[1]; hrp->http_version = lines[2]; char *ext = memchr(hrp->path, '.', sizeof(hrp->path)); if (ext == NULL) { ext = ".html"; } } while ((numchars > 0) && strcmp("\n", buf)) { numchars = get_line(new_fd, buf, sizeof(buf)); //printf("Browser Request: %s\n",buf); } return hrp; } void init(int *init_sock_fd) { int bind_fd, listen_fd; struct sockaddr_in server_addr; sock_fd = socket(PF_INET, SOCK_STREAM, 0); if (sock_fd == -1) { perror("socket"); exit(1); } server_addr.sin_family = AF_INET; server_addr.sin_port = htons(PORT); server_addr.sin_addr.s_addr = INADDR_ANY; bzero(&(server_addr.sin_zero), 8); bind_fd = bind(sock_fd, (struct sockaddr *) &server_addr, sizeof(struct sockaddr)); if (bind_fd == -1) { perror("bind"); exit(1); } listen_fd = listen(sock_fd, 5); if (listen_fd == -1) { perror("listen"); exit(1); } else { int opt = SO_REUSEADDR; setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); *init_sock_fd = sock_fd; } } void *worker_epoll(void *args) { int i, ret, cfd, nfds;; struct epoll_event ev, events[EVENTSIZE]; char buffer[512]; while (1) { nfds = epoll_wait(ep_fd, events, EVENTSIZE, -1); for (i = 0; i < nfds; i++) { if (events[i].events & EPOLLIN) { cfd = events[i].data.fd; struct http_request_param *hrp; hrp = get_client_request(cfd); char path[PATH_MAX]; if(sizeof(hrp->path)>PATH_MAX){ sprintf(path, "./%s", DEFAULT_INDEX_PAGE); } sprintf(path, ".%s", hrp->path); send_data(cfd, "text/html", path); ev.data.fd = cfd; ev.events = EPOLLOUT | EPOLLET; epoll_ctl(ep_fd, EPOLL_CTL_MOD, cfd, &ev); } else if (events[i].events & EPOLLOUT) { cfd = events[i].data.fd; ev.data.fd = cfd; epoll_ctl(ep_fd, EPOLL_CTL_DEL, cfd, &ev); close(cfd); } } } return NULL; } int main() { int sock_fd, new_fd; int sin_size; struct sockaddr_in client_addr; struct epoll_event ev; pthread_t worker_t; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); signal(SIGINT, app_exit); ep_fd = epoll_create(MAXFDS); init(&sock_fd); int count = 0; if (pthread_create(&worker_t, &attr, worker_epoll, NULL) != 0) { perror("worker_epoll pthread_create failed/n"); return -1; } while (1) { sin_size = sizeof(struct sockaddr_in); new_fd = accept(sock_fd, (struct sockaddr *) &client_addr, &sin_size); count++; printf("Total : %d \n", count); if (new_fd == -1) { perror("accept"); continue; } setnonblocking(new_fd); ev.data.fd = new_fd; ev.events = EPOLLIN | EPOLLET; epoll_ctl(ep_fd, EPOLL_CTL_ADD, new_fd, &ev); printf("Server:got connection from %s\n", inet_ntoa(client_addr.sin_addr)); } while (waitpid(-1, NULL, 0) > 0); close(sock_fd); return 0; } void app_exit() { signal(SIGINT, SIG_DFL); close(sock_fd); printf("\nExit,Thank You For Using!\n"); exit(0); }
C
#include <ipconf.h> #include "net_sas.h" /* MODULE_HDR +----------------------------------------------------------+ ** ** <W[> SAS_GETSOCKOPT_01 ** ** <> SAS_GETSOCKOPT_01( void ) ** ** Ȃ ** ** <^[l> sXe[^X (BOOL) TEST_PASS I ** TEST_FAIL ُI ** ** <@\> DUAL04_getsockopt ɑ΂ EBADF G[𔭐B ** ** <l> EBADF( 9 )o͂,OK +-----------------------------------------------------------------------+ ** <ύX> ** Date Reason Ver. Name ** ( 040914 )(Original )(1.0 )(sri ) +-----------------------------------------------------------------------+*/ int SAS_GETSOCKOPT_01(void) { int err, ret, len, optval; char sname[20]; /* */ memset(sname, 0x00, sizeof(sname)); /* ViIݒ */ sprintf(sname, "%s", "SAS_GETSOCKOPT_01()"); /* NCAgNʒm */ (void)saSendReply(saCntlSock, REP_READY); len = sizeof(optval); /* FD-1ݒ肵EBADF(9)𔭐 */ ret = getsockopt(-1, SOL_SOCKET, SO_KEEPALIVE, (char *)&optval, (socklen_t *)&len); /* ʔ */ if(ret < 0){ err = NET_errno(); sprintf((char *)saRes[saResCnt++],"%s: Error no %d \n", sname, err); if ( err != EBADF ){ sprintf((char *)saRes[saResCnt++],"%s: TEST NG!!(An error number is different.)\n", sname); return TEST_FAIL; } } else { sprintf((char *)saRes[saResCnt++],"%s: TEST NG!!(An error does not occur.)\n", sname); return TEST_FAIL; } sprintf((char *)saRes[saResCnt++],"%s: TEST PASS.\n", sname); return TEST_PASS; } /* MODULE_HDR +----------------------------------------------------------+ ** ** <W[> SAS_GETSOCKOPT_02 ** ** <> SAS_GETSOCKOPT_02( void ) ** ** Ȃ ** ** <^[l> sXe[^X (BOOL) TEST_PASS I ** TEST_FAIL ُI ** ** <@\> DUAL04_getsockopt ɑ΂ EBADF G[𔭐B ** ** <l> EBADF( 9 )o͂,OK +-----------------------------------------------------------------------+ ** <ύX> ** Date Reason Ver. Name ** ( 040914 )(Original )(1.0 )(sri ) +-----------------------------------------------------------------------+*/ int SAS_GETSOCKOPT_02(void) { int err, ret, len, optval; char sname[20]; /* */ memset(sname, 0x00, sizeof(sname)); /* ViIݒ */ sprintf(sname, "%s", "SAS_GETSOCKOPT_02()"); /* NCAgNʒm */ (void)saSendReply(saCntlSock, REP_READY); len = sizeof(optval); /* FD0ݒ肵EBADF(9)𔭐 */ ret = getsockopt(0, SOL_SOCKET, SO_SNDBUF, (char *)&optval, (socklen_t *)&len); /* ʔ */ if(ret < 0){ err = NET_errno(); sprintf((char *)saRes[saResCnt++],"%s: Error no %d \n", sname, err); if ( err != EBADF ){ sprintf((char *)saRes[saResCnt++],"%s: TEST NG!!(An error number is different.)\n", sname); return TEST_FAIL; } } else { sprintf((char *)saRes[saResCnt++],"%s: TEST NG!!(An error does not occur.)\n", sname); return TEST_FAIL; } sprintf((char *)saRes[saResCnt++],"%s: TEST PASS.\n", sname); return TEST_PASS; } /* MODULE_HDR +----------------------------------------------------------+ ** ** <W[> SAS_GETSOCKOPT_03 ** ** <> SAS_GETSOCKOPT_03( void ) ** ** Ȃ ** ** <^[l> sXe[^X (BOOL) TEST_PASS I ** TEST_FAIL ُI ** ** <@\> DUAL04_getsockopt ɑ΂ ENOPROTOOPT G[𔭐B ** ** <l> ENOPROTOOPT( 42 )o͂,OK +-----------------------------------------------------------------------+ ** <ύX> ** Date Reason Ver. Name ** ( 040914 )(Original )(1.0 )(sri ) +-----------------------------------------------------------------------+*/ int SAS_GETSOCKOPT_03(void) { int sock, err, ret, len, optval; char sname[20]; /* */ memset(sname, 0x00, sizeof(sname)); /* ViIݒ */ sprintf(sname, "%s", "SAS_GETSOCKOPT_03()"); /* NCAgNʒm */ (void)saSendReply(saCntlSock, REP_READY); /* IPv4,stream\Pbg쐬 */ if((sock = socket(AF_INET,SOCK_STREAM,0)) < 0){ sprintf((char *)saRes[saResCnt++],"%s: socket error occured.\n", sname); return TEST_FAIL; } len = sizeof(optval); /* ̃xɂȂIvVw肵getsockoptsƂɂENOPROTOOPT(42)𔭐 */ ret = getsockopt(sock, IPPROTO_IP, IP_RECVOPTS, (char *)&optval, (socklen_t *)&len); /* ʔ */ if(ret < 0){ err = NET_errno(); sprintf((char *)saRes[saResCnt++],"%s: Error no %d \n", sname, err); if ( err != ENOPROTOOPT ){ sprintf((char *)saRes[saResCnt++],"%s: TEST NG!!(An error number is different.)\n", sname); (void)close(sock); return TEST_FAIL; } } else { sprintf((char *)saRes[saResCnt++],"%s: TEST NG!!(An error does not occur.)\n", sname); (void)close(sock); return TEST_FAIL; } /* close */ (void)close(sock); sprintf((char *)saRes[saResCnt++],"%s: TEST PASS.\n", sname); return TEST_PASS; } /* MODULE_HDR +----------------------------------------------------------+ ** ** <W[> SAS_GETSOCKOPT_04 ** ** <> SAS_GETSOCKOPT_04( void ) ** ** Ȃ ** ** <^[l> sXe[^X (BOOL) TEST_PASS I ** TEST_FAIL ُI ** ** <@\> DUAL04_getsockopt ɑ΂ ENOPROTOOPT G[𔭐B ** sȒlݒ肷B ** ** <l> EINVAL( 22 )o͂,OK +-----------------------------------------------------------------------+ ** <ύX> ** Date Reason Ver. Name ** ( 040914 )(Original )(1.0 )(sri ) +-----------------------------------------------------------------------+*/ int SAS_GETSOCKOPT_04(void) { int sock, err, ret, len, optval; char sname[20]; /* */ memset(sname, 0x00, sizeof(sname)); /* ViIݒ */ sprintf(sname, "%s", "SAS_GETSOCKOPT_04()"); /* NCAgNʒm */ (void)saSendReply(saCntlSock, REP_READY); /* IPv4,stream\Pbg쐬 */ if((sock = socket(AF_INET,SOCK_STREAM,0)) < 0){ sprintf((char *)saRes[saResCnt++],"%s: socket error occured.\n", sname); return TEST_FAIL; } len = sizeof(optval); /* level̒l-1Ɏw肵getsockoptsƂɂENOPROTOOPT(42)𔭐 */ ret = getsockopt(sock, -1, SO_KEEPALIVE, &optval, (socklen_t *)&len); /* ʔ */ if(ret < 0){ err = NET_errno(); sprintf((char *)saRes[saResCnt++],"%s: Error no %d \n", sname, err); if ( err != ENOPROTOOPT ){ sprintf((char *)saRes[saResCnt++],"%s: TEST NG!!(An error number is different.)\n", sname); (void)close(sock); return TEST_FAIL; } } else { sprintf((char *)saRes[saResCnt++],"%s: TEST NG!!(An error does not occur.)\n", sname); (void)close(sock); return TEST_FAIL; } /* close */ (void)close(sock); sprintf((char *)saRes[saResCnt++],"%s: TEST PASS.\n", sname); return TEST_PASS; } /* MODULE_HDR +----------------------------------------------------------+ ** ** <W[> SAS_GETSOCKOPT_05 ** ** <> SAS_GETSOCKOPT_05( void ) ** ** Ȃ ** ** <^[l> sXe[^X (BOOL) TEST_PASS I ** TEST_FAIL ُI ** ** <@\> DUAL04_getsockopt ɑ΂ENOPROTOPT G[𔭐B ** sȒlݒ肷B ** ** <l> ENOPROTOPT( 42 )o͂,OK +-----------------------------------------------------------------------+ ** <ύX> ** Date Reason Ver. Name ** ( 040914 )(Original )(1.0 )(sri ) +-----------------------------------------------------------------------+*/ int SAS_GETSOCKOPT_05(void) { int sock, err, ret, len, optval; char sname[20]; /* */ memset(sname, 0x00, sizeof(sname)); /* ViIݒ */ sprintf(sname, "%s", "SAS_GETSOCKOPT_05()"); /* NCAgNʒm */ (void)saSendReply(saCntlSock, REP_READY); /* IPv4,stream\Pbg쐬 */ if((sock = socket(AF_INET,SOCK_STREAM,0)) < 0){ sprintf((char *)saRes[saResCnt++],"%s: socket error occured.\n", sname); return TEST_FAIL; } len = sizeof(optval); /* optname̒l-1Ɏw肵getsockoptsƂɂENOPROTOOPT(42)𔭐 */ ret = getsockopt(sock, SOL_SOCKET, -1, &optval, (socklen_t *)&len); /* ʔ */ if(ret < 0){ err = NET_errno(); sprintf((char *)saRes[saResCnt++],"%s: Error no %d \n", sname, err); if ( err != ENOPROTOOPT ){ sprintf((char *)saRes[saResCnt++],"%s: TEST NG!!(An error number is different.)\n", sname); (void)close(sock); return TEST_FAIL; } } else { sprintf((char *)saRes[saResCnt++],"%s: TEST NG!!(An error does not occur.)\n", sname); (void)close(sock); return TEST_FAIL; } /* close */ (void)close(sock); sprintf((char *)saRes[saResCnt++],"%s: TEST PASS.\n", sname); return TEST_PASS; } /* MODULE_HDR +----------------------------------------------------------+ ** ** <W[> SAS_GETSOCKOPT_06 ** ** <> SAS_GETSOCKOPT_06( void ) ** ** Ȃ ** ** <^[l> sXe[^X (BOOL) TEST_PASS I ** TEST_FAIL ُI ** ** <@\> DUAL04_getsockopt ɑ΂ ENOPROTOOPT G[𔭐B ** 擾łȂ optname ݒB ** ** <l> ENOPROTOOPT( 42 )o͂,OK +-----------------------------------------------------------------------+ ** <ύX> ** Date Reason Ver. Name ** ( 040914 )(Original )(1.0 )(sri ) +-----------------------------------------------------------------------+*/ int SAS_GETSOCKOPT_06(void) { int sock, err, ret, len; struct ip_mreq optval; char sname[20]; /* */ memset(sname, 0x00, sizeof(sname)); /* ViIݒ */ sprintf(sname, "%s", "SAS_GETSOCKOPT_06()"); /* NCAgNʒm */ (void)saSendReply(saCntlSock, REP_READY); /* IPv4,stream\Pbg쐬 */ if((sock = socket(AF_INET,SOCK_STREAM,0)) < 0){ sprintf((char *)saRes[saResCnt++],"%s: socket error occured.\n", sname); return TEST_FAIL; } len = sizeof(struct ip_mreq); /* 擾̂łȂoptnamew肵getsockoptsƂɂENOPROTOOPT(42)𔭐 */ ret = getsockopt(sock,IPPROTO_IP,IP_ADD_MEMBERSHIP,&optval,(socklen_t *)&len); /* ʔ */ if(ret < 0){ err = NET_errno(); sprintf((char *)saRes[saResCnt++],"%s: Error no %d \n", sname, err); if ( err != ENOPROTOOPT ){ sprintf((char *)saRes[saResCnt++],"%s: TEST NG!!(An error number is different.)\n", sname); (void)close(sock); return TEST_FAIL; } } else { sprintf((char *)saRes[saResCnt++],"%s: TEST NG!!(An error does not occur.)\n", sname); (void)close(sock); return TEST_FAIL; } /* close */ (void)close(sock); sprintf((char *)saRes[saResCnt++],"%s: TEST PASS.\n", sname); return TEST_PASS; } /* MODULE_HDR +----------------------------------------------------------+ ** ** <W[> SAS_GETSOCKOPT_07 ** ** <> SAS_GETSOCKOPT_07( void ) ** ** Ȃ ** ** <^[l> sXe[^X (BOOL) TEST_PASS I ** TEST_FAIL ُI ** ** <@\> DUAL04_getsockopt ɑ΂ăG[𔭐B ** 擾łȂ optname ݒB ** ** <l> +-----------------------------------------------------------------------+ ** <ύX> ** Date Reason Ver. Name ** ( 040914 )(Original )(1.0 )(sri ) +-----------------------------------------------------------------------+*/ int SAS_GETSOCKOPT_07(void) { int sock, err, ret, len; struct ip_mreq optval; char sname[20]; /* */ memset(sname, 0x00, sizeof(sname)); /* ViIݒ */ sprintf(sname, "%s", "SAS_GETSOCKOPT_07()"); /* NCAgNʒm */ (void)saSendReply(saCntlSock, REP_READY); /* IPv4,stream\Pbg쐬 */ if((sock = socket(AF_INET,SOCK_STREAM,0)) < 0){ sprintf((char *)saRes[saResCnt++],"%s: socket error occured.\n", sname); return TEST_FAIL; } len = sizeof(struct ip_mreq); /* 擾̂łȂoptnamew肵getsockoptsƂɂENOPROTOOPT(42)𔭐 */ ret = getsockopt(sock,IPPROTO_IP,IP_DROP_MEMBERSHIP,&optval,(socklen_t *)&len); /* ʔ */ if(ret < 0){ err = NET_errno(); sprintf((char *)saRes[saResCnt++],"%s: Error no %d \n", sname, err); if ( err != ENOPROTOOPT ){ sprintf((char *)saRes[saResCnt++],"%s: TEST NG!!(An error number is different.)\n", sname); (void)close(sock); return TEST_FAIL; } } else { sprintf((char *)saRes[saResCnt++],"%s: TEST NG!!(An error does not occur.)\n", sname); (void)close(sock); return TEST_FAIL; } /* close */ (void)close(sock); sprintf((char *)saRes[saResCnt++],"%s: TEST PASS.\n", sname); return TEST_PASS; }
C
#include "parse.h" char **parse_args( char *line ) { int i; int counter = 2; for (i = 0; i < strlen(line); i++) { if (line[i] == ' ') { counter++; } } char **arr = calloc(counter, sizeof(char *)); char *tmp; counter = 0; while ((tmp = strsep(&line, " "))) { if (errno != 0) { printf("Error: %s\n", strerror(errno)); exit(-1); } arr[counter] = tmp; counter++; } return arr; }
C
/* Autore: Giovanni Giorgis Titolo: Implementazione di una struttura a Casaccio Data: 7/10/2019 Descrizione: Data una semplice struttura Casaccio, composta da un intero e da un char implementarne il toolkit */ #include <stdio.h> #include <stdlib.h> #include "casaccio.h" int main() { //controllo della prima funzione del toolkit Casaccio Casaccio* casa = crea(7, 'a'); printf("Prima funzione Casaccio* crea %d %c \n", casa->a, casa->c); //controllo dellaa seconda funzione crea senza paramtri Casaccio* casa2 = creaSP(); printf("Seconda funzione Casaccio* crea %d %c \n", casa2->a, casa2->c); //controllo dei getter printf("%d %c \n", getA(casa), getC(casa)); setA(100, casa2); setC('z', casa2); printf("funzioni setter su Casaccio*, nuovi valori = %d %c \n", casa2->a, casa2->c); //controllo del serializzatore printf("%s \n", toString(casa2)); //controllo con creazione da string Casaccio* casa3 = creaS("12,d"); printf("Terza Casaccio* crea %d %c \n", casa3->a, casa3->c); //controlliamo che il distruttore funzioni distruggi(casa); distruggi(casa2); return 0; }
C
#include "RWDungeon.h" #include "fibheap.h" void move_monster_help(int mon_index, mon_struct *mon); static int32_t distance_non_tunnel(const void *key, const void *with){ return ((tile_struct *) key)->nonTunnelNPC - ((tile_struct *) with)->nonTunnelNPC; } static int32_t distance_tunnel(const void *key, const void *with){ return ((tile_struct *) key)->tunnelNPC - ((tile_struct *) with)->tunnelNPC; } void create_fibonacci_heap(heap_node_t *board_nodes[DUNGEON_Y][DUNGEON_X], heap_t *queue){ int i, j; for (i = 0; i < DUNGEON_Y; i++){ for (j = 0; j < DUNGEON_X; j++) { board_nodes[i][j] = heap_insert(queue, &board[i][j]); } } } void create_distance_maps() { heap_t priority_queue; heap_node_t *board_nodes[DUNGEON_Y][DUNGEON_X]; bool found_char = false; for(int i = 0; i < DUNGEON_Y; i++){ for(int j = 0; j < DUNGEON_X; j++){ if(board[i][j].density == 0){ found_char = true; board[i][j].tunnelNPC = 0; board[i][j].nonTunnelNPC = 0; board[i][j].mon.type = 0; board[i][j].mon.speed = 10; board[i][j].mon.alive = true; board[i][j].mon.x = j; board[i][j].mon.y = i; pcX = j; pcY = i; } if (found_char) { break; } } if (found_char) { break; } } //map for monsters that cant tunnel heap_init(&priority_queue, distance_non_tunnel, NULL); create_fibonacci_heap(board_nodes, &priority_queue); while(priority_queue.size != 0) { tile_struct* peek_tile = (tile_struct*)heap_peek_min(&priority_queue); heap_remove_min(&priority_queue); int distance = ((peek_tile)->nonTunnelNPC) + 1; int x = (peek_tile)->x; int y = (peek_tile)->y; if (y - 1 >= 0) { if (board[x][y-1].density == 0){ if (board[x][y-1].nonTunnelNPC > distance) { board[x][y-1].nonTunnelNPC = distance; heap_decrease_key_no_replace(&priority_queue, board_nodes[x][y-1]); } } } if (x - 1 >= 0) { if (board[x-1][y].density == 0) { if (board[x-1][y].nonTunnelNPC > distance) { board[x-1][y].nonTunnelNPC = distance; heap_decrease_key_no_replace(&priority_queue, board_nodes[x-1][y]); } } } if (y + 1 < DUNGEON_X) { if (board[x][y+1].density == 0) { if (board[x][y+1].nonTunnelNPC > distance) { board[x][y+1].nonTunnelNPC = distance; heap_decrease_key_no_replace(&priority_queue, board_nodes[x][y+1]); } } } if (x + 1 < DUNGEON_Y) { if (board[x+1][y].density == 0) { if (board[x+1][y].nonTunnelNPC > distance) { board[x+1][y].nonTunnelNPC = distance; heap_decrease_key_no_replace(&priority_queue, board_nodes[x+1][y]); } } } if (x + 1 < DUNGEON_Y && y + 1 < DUNGEON_X) { if (board[x+1][y+1].density == 0) { if (board[x+1][y+1].nonTunnelNPC > distance) { board[x+1][y+1].nonTunnelNPC = distance; heap_decrease_key_no_replace(&priority_queue, board_nodes[x+1][y+1]); } } } if (x + 1 < DUNGEON_Y && y - 1 >= 0) { if (board[x+1][y-1].density == 0) { if (board[x+1][y-1].nonTunnelNPC > distance) { board[x+1][y-1].nonTunnelNPC = distance; heap_decrease_key_no_replace(&priority_queue, board_nodes[x+1][y-1]); } } } if (x - 1 >= 0 && y + 1 < DUNGEON_X) { if (board[x-1][y+1].density == 0){ if (board[x-1][y+1].nonTunnelNPC > distance) { board[x-1][y+1].nonTunnelNPC = distance; heap_decrease_key_no_replace(&priority_queue, board_nodes[x-1][y+1]); } } } if (x - 1 >= 0 && y - 1 >= 0) { if (board[x-1][y-1].density == 0) { if (board[x-1][y-1].nonTunnelNPC > distance) { board[x-1][y-1].nonTunnelNPC = distance; heap_decrease_key_no_replace(&priority_queue, board_nodes[x-1][y-1]); } } } } //map for monsters that can tunnel heap_init(&priority_queue, distance_tunnel, NULL); create_fibonacci_heap(board_nodes, &priority_queue); while(priority_queue.size != 0){ tile_struct* peek_tile = (tile_struct*)heap_peek_min(&priority_queue); heap_remove_min(&priority_queue); int x = (peek_tile)->x; int y = (peek_tile)->y; int distance = (peek_tile)->tunnelNPC; int distance_weighted; if (y - 1 >= 0) { if (board[x][y-1].density < 255){ if (board[x][y-1].density == 0) { distance_weighted = distance + 1; } else { distance_weighted = distance + board[x][y-1].density / 85; } if (board[x][y-1].tunnelNPC > distance_weighted){ board[x][y-1].tunnelNPC = distance_weighted; heap_decrease_key_no_replace(&priority_queue, board_nodes[x][y-1]); } } } if (x - 1 >= 0) { if (board[x-1][y].density < 255){ if (board[x-1][y].density == 0) { distance_weighted = distance + 1; } else { distance_weighted = distance + board[x-1][y].density / 85; } if (board[x-1][y].tunnelNPC > distance_weighted) { board[x-1][y].tunnelNPC = distance_weighted; heap_decrease_key_no_replace(&priority_queue, board_nodes[x-1][y]); } } } if (y + 1 < DUNGEON_X) { if (board[x][y+1].density < 255){ if (board[x][y+1].density == 0) { distance_weighted = distance + 1; } else { distance_weighted = distance + board[x][y+1].density / 85; } if (board[x][y+1].tunnelNPC > distance_weighted){ board[x][y+1].tunnelNPC = distance_weighted; heap_decrease_key_no_replace(&priority_queue, board_nodes[x][y+1]); } } } if (x + 1 < DUNGEON_Y) { if (board[x+1][y].density < 255){ if (board[x+1][y].density == 0) { distance_weighted = distance + 1; } else { distance_weighted = distance + board[x+1][y].density / 85; } if (board[x+1][y].tunnelNPC > distance_weighted){ board[x+1][y].tunnelNPC = distance_weighted; heap_decrease_key_no_replace(&priority_queue, board_nodes[x+1][y]); } } } if (x - 1 >= 0 && y + 1 < DUNGEON_X) { if (board[x-1][y+1].density < 255){ if (board[x-1][y+1].density == 0) { distance_weighted = distance + 1; } else { distance_weighted = distance + board[x-1][y+1].density / 85; } if (board[x-1][y+1].tunnelNPC > distance_weighted){ board[x-1][y+1].tunnelNPC = distance_weighted; heap_decrease_key_no_replace(&priority_queue, board_nodes[x-1][y+1]); } } } if (x + 1 < DUNGEON_Y && y + 1 < DUNGEON_X) { if (board[x+1][y+1].density < 255){ if (board[x+1][y+1].density == 0) { distance_weighted = distance + 1; } else { distance_weighted = distance + board[x+1][y+1].density / 85; } if (board[x+1][y+1].tunnelNPC > distance_weighted){ board[x+1][y+1].tunnelNPC = distance_weighted; heap_decrease_key_no_replace(&priority_queue, board_nodes[x+1][y+1]); } } } if (x - 1 >= 0 && y - 1 >= 0) { if (board[x-1][y-1].density < 255){ if (board[x-1][y-1].density == 0) { distance_weighted = distance + 1; } else { distance_weighted = distance + board[x-1][y-1].density / 85; } if (board[x-1][y-1].tunnelNPC > distance_weighted){ board[x-1][y-1].tunnelNPC = distance_weighted; heap_decrease_key_no_replace(&priority_queue, board_nodes[x-1][y-1]); } } } if (x + 1 < DUNGEON_Y && y - 1 >= 0) { if (board[x+1][y-1].density < 255){ if (board[x+1][y-1].density == 0) { distance_weighted = distance + 1; } else { distance_weighted = distance + board[x+1][y-1].density / 85; } if (board[x+1][y-1].tunnelNPC > distance_weighted){ board[x+1][y-1].tunnelNPC = distance_weighted; heap_decrease_key_no_replace(&priority_queue, board_nodes[x+1][y-1]); } } } } heap_delete(&priority_queue); } void display_distance_map(bool tunnel){ printf("\n"); for(int i = 0; i < DUNGEON_Y; i++) { for (int j = 0; j < DUNGEON_X; j++) { int distance; if (!tunnel) { distance = board[i][j].nonTunnelNPC; } else { distance = board[i][j].tunnelNPC; } for (int x = 10; x <= 80; x+=10) { if (distance < x) { distance -= (x - 10); distance += 48; break; } if (x == 80) { distance = 32; } } printf("%c", distance); } printf("\n"); } } void movePlayerRandom() { bool done = false; while (!done) { int direction = rand_range(0, 8); printf("%d", direction); switch (direction) { case 0: if (board[pcY-1][pcX].density == 0) { board[pcY-1][pcX].mon.type = 0; board[pcY][pcX].mon.type = -1; pcY -= 1; done = true; } break; case 1: if (board[pcY-1][pcX-1].density == 0) { board[pcY-1][pcX-1].mon.type = 0; board[pcY][pcX].mon.type = -1; pcY -= 1; pcX -= 1; done = true; } break; case 2: if (board[pcY-1][pcX+1].density == 0) { board[pcY-1][pcX+1].mon.type = 0; board[pcY][pcX].mon.type = -1; pcY -= 1; pcX += 1; done = true; } break; case 3: if (board[pcY][pcX+1].density == 0) { board[pcY][pcX+1].mon.type = 0; board[pcY][pcX].mon.type = -1; pcX += 1; done = true; } break; case 4: if (board[pcY][pcX-1].density == 0) { board[pcY][pcX-1].mon.type = 0; board[pcY][pcX].mon.type = -1; pcX -= 1; done = true; } break; case 5: if (board[pcY+1][pcX].density == 0) { board[pcY+1][pcX].mon.type = 0; board[pcY][pcX].mon.type = -1; pcY += 1; done = true; } break; case 6: if (board[pcY+1][pcX-1].density == 0) { board[pcY+1][pcX-1].mon.type = 0; board[pcY][pcX].mon.type = -1; pcY += 1; pcX -= 1; done = true; } break; case 7: if (board[pcY+1][pcX+1].density == 0) { board[pcY+1][pcX+1].mon.type = 0; board[pcY][pcX].mon.type = -1; pcY += 1; pcX += 1; done = true; } break; default: break; } } } void moveMonster(mon_struct *mon) { for (int i = 0; i < sizeof(monster_coords)/sizeof(monster_coords[0]); i++) { if (monster_coords[i][0] == -1) { break; } else { move_monster_help(i, mon); } } } void move_monster_help(int mon_index, mon_struct *mon) { int x = monster_coords[mon_index][0]; int y = monster_coords[mon_index][1]; int best_weight = 255; int bestX; int bestY; switch (board[y][x].mon.type) { case 1: if (board[y-1][x-1].nonTunnelNPC < best_weight) { best_weight = board[y-1][x-1].nonTunnelNPC; bestX = x-1; bestY = y-1; } if (board[y-1][x].nonTunnelNPC < best_weight) { best_weight = board[y-1][x].nonTunnelNPC; bestX = x; bestY = y-1; } if (board[y-1][x+1].nonTunnelNPC < best_weight) { best_weight = board[y-1][x+1].nonTunnelNPC; bestX = x+1; bestY = y-1; } if (board[y][x-1].nonTunnelNPC < best_weight) { best_weight = board[y][x-1].nonTunnelNPC; bestX = x-1; bestY = y; } if (board[y][x+1].nonTunnelNPC < best_weight) { best_weight = board[y][x+1].nonTunnelNPC; bestX = x+1; bestY = y; } if (board[y+1][x-1].nonTunnelNPC < best_weight) { best_weight = board[y+1][x-1].nonTunnelNPC; bestX = x-1; bestY = y+1; } if (board[y+1][x].nonTunnelNPC < best_weight) { best_weight = board[y+1][x].nonTunnelNPC; bestX = x; bestY = y+1; } if (board[y+1][x+1].nonTunnelNPC < best_weight) { best_weight = board[y+1][x+1].nonTunnelNPC; bestX = x+1; bestY = y+1; } printf("x: %d, y: %d", x, y); printf("bestx: %d bestY: %d, best weight: %d\n", bestX, bestY, best_weight); board[y][x].mon.type = -1; board[bestY][bestX].mon.type = 1; if (bestY == pcY && bestX == pcX) { game_over = true; } monster_coords[mon_index][0] = bestX; monster_coords[mon_index][1] = bestY; break; case 2: best_weight = 255; if (board[y-1][x-1].tunnelNPC <= best_weight) { best_weight = board[y-1][x-1].tunnelNPC; bestX = x-1; bestY = y-1; } if (board[y-1][x].tunnelNPC <= best_weight) { best_weight = board[y-1][x].tunnelNPC; bestX = x; bestY = y-1; } if (board[y-1][x+1].tunnelNPC <= best_weight) { best_weight = board[y-1][x+1].tunnelNPC; bestX = x+1; bestY = y-1; } if (board[y][x-1].tunnelNPC <= best_weight) { best_weight = board[y][x-1].tunnelNPC; bestX = x-1; bestY = y; } if (board[y][x+1].tunnelNPC <= best_weight) { best_weight = board[y][x+1].tunnelNPC; bestX = x+1; bestY = y; } if (board[y+1][x-1].tunnelNPC <= best_weight) { best_weight = board[y+1][x-1].tunnelNPC; bestX = x-1; bestY = y+1; } if (board[y+1][x].tunnelNPC <= best_weight) { best_weight = board[y+1][x].tunnelNPC; bestX = x; bestY = y+1; } if (board[y+1][x+1].tunnelNPC <= best_weight) { best_weight = board[y+1][x+1].tunnelNPC; bestX = x+1; bestY = y+1; } printf("x: %d, y: %d", x, y); printf("bestx: %d bestY: %d, best weight: %d\n", bestX, bestY, best_weight); board[y][x].mon.type = -1; if (bestY == pcY && bestX == pcX) { game_over = true; } board[bestY][bestX].mon.type = 2; monster_coords[mon_index][0] = bestX; monster_coords[mon_index][1] = bestY; break; } printf("mon index %d\n", mon_index); } void add_mons() { int mon_index = 0; while (mon_index != 2) { int x = rand_range(20, 70); int y = rand_range(2, 19); if (board[y][x].density == 0) { if (!board[y][x].player && board[y][x].mon.type == -1) { board[y][x].mon.type = mon_index+1; board[y][x].mon.speed = rand_range(5, 20); board[y][x].mon.alive = true; board[y][x].mon.x = x; board[y][x].mon.y = y; monster_coords[mon_index][0] = x; monster_coords[mon_index][1] = y; // all_npc[done].x = x; // all_npc[done].y = y; // all_npc[done].speed = rand_range(5, 20); // all_npc[done].type = done; // all_npc[done].isPlayer = false; // all_npc[done].alive = true; mon_index += 1; } } } } int32_t sort_heap(const void* key, const void* with){ return ((mon_struct*)key)->speed - ((mon_struct*)with)->speed; } int main(int argc, char* argv[]) { for (int i = 0; i < sizeof(monster_coords)/sizeof(monster_coords[0]); i++) { monster_coords[i][0] = -1; monster_coords[i][1] = -1; } srand(time(NULL)); heap_t priority_queue; heap_init(&priority_queue, sort_heap, NULL); main_dungeon(argc, argv); create_distance_maps(); heap_insert(&priority_queue, &board[pcY][pcX].mon); add_mons(); print_dungeon(); for (int i = 0; i < 2; i++){ heap_insert(&priority_queue, &board[monster_coords[i][1]][monster_coords[i][0]]); } while (!game_over) { fflush(stdout); system("clear"); mon_struct* min = (mon_struct*) heap_peek_min(&priority_queue); printf("min type: %d\n", min->type); if (min->type == 0) { movePlayerRandom(); heap_remove_min(&priority_queue); heap_insert(&priority_queue, min); } else { moveMonster(min); heap_remove_min(&priority_queue); heap_insert(&priority_queue, min); } print_dungeon(); usleep(250000); //help = 1; } printf("\nGAME OVER\n"); //printf("pcx: %d, pcy: %d\n", pcX, pcY); //display_distance_map(false); //display_distance_map(true); return 1; }
C
// Weather update client // Connects SUB socket to tcp://localhost:5556 // Collects weather updates and finds avg temp in zipcode #include "zhelpers.h" #include "msgpack.h" int main (int argc, char *argv []) { // Socket to talk to server printf ("Collecting updates from weather server…\n"); void *context = zmq_ctx_new (); void *subscriber = zmq_socket (context, ZMQ_SUB); int rc = zmq_connect (subscriber, "tcp://localhost:5555"); assert (rc == 0); rc = zmq_setsockopt (subscriber, ZMQ_SUBSCRIBE, "", 0); assert (rc == 0); // Process 100 updates int update_nbr; for (update_nbr = 0; update_nbr < 100; update_nbr++) { zmq_msg_t msg; rc = zmq_msg_init (&msg); assert (rc == 0); /* Block until a message is available to be received from socket */ rc = zmq_msg_recv (&msg, subscriber, 0); assert (rc != -1); msgpack_unpacked unpacked_msg; msgpack_unpacked_init(&unpacked_msg); void *message_copy = malloc(zmq_msg_size(&msg)); memcpy(message_copy, zmq_msg_data(&msg), zmq_msg_size(&msg)); bool success = msgpack_unpack_next(&unpacked_msg, (const char *)message_copy, zmq_msg_size(&msg), NULL); assert(success); const char *string = unpacked_msg.data.via.raw.ptr; printf("%s\n", string); /* int zipcode, temperature, relhumidity; */ /* sscanf (string, "%d %d %d", */ /* &zipcode, &temperature, &relhumidity); */ /* printf ("zip code is %d, temp %d, relhumidity %d\n", zipcode, temperature, relhumidity); */ msgpack_unpacked_destroy(&unpacked_msg); zmq_msg_close(&msg); free(message_copy); } zmq_close (subscriber); zmq_ctx_destroy (context); return 0; }
C
/* 编程练习6 编写一个程序,使其从标准输入读取字符,直到遇到文件结尾。对于每个字符,程序需要检查并报告该字符是否是一个字母。 如果是的话,程序还应报告该字母在字母表中的数值位置。例如,c和C的字母位置都是3.可以先实现这样一个函数:接受一个 字符参数,如果该字符为字母则返回该字母的数值位置,否则返回-1。 */ #include <stdio.h> int isabc(char ch); int main(void) { char ch; int flag; while( (ch = getchar()) != EOF) { if ( (flag = isabc(ch)) != -1) printf("%d", flag); } } int isabc(char ch) { if (ch >= 'a' && ch <= 'z' ) return (ch - 'a'+1); else if (ch >= 'A' && ch <= 'Z' ) return (ch - 'A'+1); else return -1; }
C
#include "holberton.h" /** * _isdigit - function to know if a character is a digit * @c: - input int parameter * Return: - return 1 if the input value is a digit otherwise returns 0 */ int _isdigit(int c) { if (c >= 48 && c <= 57) { return (1); } else { return (0); } }
C
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> /* Perror */ #include <errno.h> #include <stdlib.h> #include <string.h> #define BUFFER_SIZE 128 void sampleread(int fd ) { ssize_t nr; char buff[BUFFER_SIZE]; nr = read(fd, buff, BUFFER_SIZE); if (nr < 0) { perror("Error: Read Failed "); exit(EXIT_FAILURE); } printf("Data Read : %s \n", buff); } void optimize_read_buffer(int fd) { ssize_t ret = 0; long len = BUFFER_SIZE; char *buff = (char *)malloc(BUFFER_SIZE); start: while ( (len != 0) && ((ret = read(fd, buff, len)) != 0)) { if (ret == -1) { if (errno == EINTR) { perror("Read Error :Interrupt "); } else if (errno == EAGAIN) { goto start; } else { perror("Reea Error !!"); } } if (ret < len) { len = len - ret; } printf("%s", buff); (void)memset(buff, '\0', ret); } } int main() { int fd; fd = open("file.txt", O_RDONLY | O_NONBLOCK, S_IRUSR | S_IRGRP | S_IROTH); if (fd < 0) { perror("Error : File Not Found "); exit(EXIT_FAILURE); } optimizeread(fd); // sampleread(fd); /* This is Error as test var has no size */ /* ssize_t nr; char *test = "none of this is right"; nr = read(fd, test, ARRAY_SIZE); if (nr < 0) { perror("Error: Read Failed "); exit(EXIT_FAILURE); } printf("Data Read : %s \n", test); */ return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<sys/ipc.h> #include<sys/shm.h> int leer_car(); int main (int argc, char *argv[]) { int shmid, *variable; key_t llave; llave= ftok(argv[0],'k'); if ((shmid=shmget(llave,sizeof(int),IPC_CREAT|0600))==-1) { perror("Error en shmget"); exit(-1); } while(1) { printf("\nIntroduzca m para modificar el valor \n v para visualizar \n t para terminar:\n "); switch(leer_car()) { case 't': shmctl(shmid,IPC_RMID,0); break; case 'v': printf("\n variable= %d\n",*variable); break; case 'm': printf("Nuevo valor:"); scanf("%d",variable); break; default: printf("valor incorrecto"); break; } } } int leer_car() { char letra; char almacen[80]; scanf("%s",almacen); sscanf(almacen,"%c",&letra); return letra; }
C
#include <stdio.h> #include <stdlib.h> #include "stack.h" int main() { stack *stk = NULL; push(7, &stk); push(2, &stk); push(9, &stk); push(12,&stk); push(15,&stk); printf("%d\n",pop(&stk)); printf("%d\n",pop(&stk)); printf("%d\n",pop(&stk)); printf("%d\n",pop(&stk)); printf("%d\n",pop(&stk)); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define CONFIG_FILENAME "./config.ini" char db_ip[32] = {0}; char db_name[32] = {0}; int dump_period = 1; char lib_switch = 0; typedef struct { char *name; int type; #define TYPE_LONG 1 #define TYPE_ULONG 2 #define TYPE_STR 3 #define TYPE_CHAR 4 #define TYPE_YN 5 #define TYPE_INT16 6 #define TYPE_INT32 7 void *value; int size; } name_value_t; static name_value_t conf_table[] = { {"mysql_ip", TYPE_STR, db_ip, 0}, {"db_name", TYPE_STR, db_name, 0}, {"dump_thing", TYPE_INT32, &dump_period, 0}, {"some_switch", TYPE_YN, &lib_switch, 0}, }; static int read_local_config(void) { char buff[128], *pbuf = NULL; char buf[64]; int idx = 0, i, ret = 0; FILE *rule_file = open(CONFIG_FILENAME, "r"); if (!rule_file) { printf("open %s error"); return -1; } while (memset(buff, 0, sizeof(buff)) && fgets(buff, 64, rule_file)) { pbuf = strchr(buff, '='); if (pbuf == NULL) continue; pbuf++; for (idx = 0; idx < sizeof(conf_table) / sizeof(conf_table[0]); idx++) { if (strncasecmp(buff, conf_table[idx].name, strlen(conf_table[idx].name)) == 0) { while (*pbuf == ' ' || *pbuf == '\t') { pbuf++; } for (i = strlen(pbuf) - 1; i >= 0; i--) { if (pbuf[i] == '\r' || pbuf[i] == '\n') pbuf[i] = 0; } if (*pbuf != '\0') { if (conf_table[idx].type == TYPE_LONG) *(long *)(conf_table[idx].value) = atoi(pbuf); else if (conf_table[idx].type == TYPE_STR) strcpy((char *)(conf_table[idx].value), pbuf); else if (conf_table[idx].type == TYPE_CHAR) *(char *)(conf_table[idx].value) = pbuf[0]; else if (conf_table[idx].type == TYPE_YN) *(char *)(conf_table[idx].value) = (pbuf[0] == 'y' || pbuf[0] == 'Y') ? 1 : 0; else if (conf_table[idx].type == TYPE_ULONG) *(unsigned long *)(conf_table[idx].value) = atoi(pbuf); else if (conf_table[idx].type == TYPE_INT32) *(int *)(conf_table[idx].value) = atoi(pbuf); } break; } } } if (rule_file) fclose(rule_file); return 1; }
C
/* * calculator_operations.c * * Created on: 8 sep. 2020 * Author: cgimenez */ #include <stdio.h> #include <stdlib.h> int fSumOperation(float firstOperator, float secondOperator, float* pResult) { int ret = -1; if(pResult != NULL) { *pResult = firstOperator + secondOperator; ret = 0; } return ret; } int fRestOperation(float firstOperator, float secondOperator, float* pResult) { int ret = -1; if(pResult != NULL) { *pResult = firstOperator - secondOperator; ret = 0; } return ret; } int fDivideOperation(float firstOperator, float secondOperator, float* pResult) { int ret = -1; if (pResult != NULL && secondOperator != 0) { *pResult = firstOperator / secondOperator; ret =0; } if(secondOperator == 0) { ret =-2; } return ret; } int fMultiplyOperation(float firstOperator, float secondOperator, float* pResult) { int ret = -1; if(pResult != NULL) { *pResult = firstOperator * secondOperator; ret = 0; } return ret; } int fFactorial(float operator, unsigned long int* pResult) { int ret = -1; if(pResult != NULL && operator >= 0) { for(*pResult=1; operator>0; operator--) { *pResult = (unsigned long int)*pResult * ((unsigned long int)operator); } ret = 0; } else { if(operator < 0) { ret = -2; } } return ret; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/time.h> #include <signal.h> #include "ssu_runtime.h" int main(void) { sigset_t set; gettimeofday(&begin_t, NULL); sigemptyset(&set); sigaddset(&set, SIGINT); switch (sigismember(&set, SIGINT)) { case 1 : printf("SIGINT is included. \n"); break; case 0 : printf("SIGINT is not included. \n"); break; default : printf("failed to call sigismember() \n"); break; } switch (sigismember(&set, SIGSYS)) { case 1 : printf("SIGSYS is included. \n"); break; case 0 : printf("SIGSYS is not included. \n"); break; default : printf("failed to call sigismember() \n"); break; } gettimeofday(&end_t, NULL); ssu_runtime(&begin_t, &end_t); exit(0); }
C
#include <stdio.h> #include <stdlib.h> /* This programs explains usage of: 1. getw 2. putw These are used to read/write integer values */ void main() { FILE *Fptr; int i, j, k[6]; Fptr = fopen("file1", "w"); clrscr(); if (Fptr == NULL) { printf("File could not be opened."); exit(1); } else fprintf(stdout, "File is open. Enter data.\n"); for (i = 0; i < 6; i++) putw(k[i] = 5 * i, Fptr); fclose(Fptr); Fptr = fopen("file1", "r"); printf("The values of elements of array k are as below.\n"); for (j = 0; j < 6; j++) printf("%d\t", getw(Fptr)); printf("\n"); fclose(Fptr); }
C
#include <stdio.h> void SortDisp(int dt1,int dt2); int main(void) { int num1; int num2; printf("l-->"); scanf("%d",&num1); printf("l-->"); scanf(" %d",&num2); SortDisp(num1,num2); return 0; } void SortDisp(int dt1,int dt2) { int w; if(dt1 > dt2) { w = dt1; dt1 = dt2; dt2 = w; } printf("l1:%d\n",dt1); printf("l2:%d\n",dt2); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* project.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: pilespin <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/09/08 18:24:01 by pilespin #+# #+# */ /* Updated: 2015/09/25 10:54:14 by pilespin ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/project.h" void ft_draw_score(t_st *e) { int winner; int nb; winner = ft_check_if_team_have_win(e->shm); nb = ft_count_nbr_of_player_on_map(e->shm); if (system("clear")) usleep(50000); ft_printf("\n%d Players on map\n", nb); if (!e->min_player_reached) ft_draw_score_wait(e, nb); else { if (!winner && e->min_player_reached) e->tim = ft_utime() - e->time_start; if (e->time_start) printf("Running time %.1f sec\n", e->tim); if (e->min_player_reached && winner) ft_printf("Team \"%d\" Win !!\n", winner); } } void ft_draw_score_wait(t_st *e, int nb) { if (!e->min_player_reached && nb >= MIN_PLAYER_TO_START) { e->time_start = ft_utime(); e->min_player_reached = 1; } if (!e->time_start) ft_printf("Waiting \"%d\" Players !!\n", MIN_PLAYER_TO_START - nb); }
C
/* * professorStudent.c * * Problem Description: * You have been hired by the CIS Department to write code to help synchronize * a professor and his/her students during office hours. The professor, of * course, wants to take a nap if no students are around to ask questions; if * there are students who want to ask questions, they must synchronize with * each other and with the professor so that * (i) only one person is speaking at any one time, * (ii) each student question is answered by the professor, and * (iii) no student asks another question before the professor is done * answering the previous one. * * You are to write four procedures: * AnswerStart(), * AnswerDone(), * QuestionStart(), and * QuestionDone() * * The professor loops running the code: * AnswerStart(); give answer; * AnswerDone(). * * AnswerStart doesn't return until a question has been asked. Each student * loops running the code: * QuestionStart(); ask question; * QuestionDone(). * * QuestionStart() does not return until it is the student's turn to ask a * question. Since professors consider it rude for a student not to wait for an * answer, QuestionDone() should not return until the professor has finished * answering the question. Use semaphores for synchronization. */ #include <pthread.h> #include <semaphore.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <ostream> // 0 sem is shared between threads of the process // 1 sem is shared between processes #define SHARED 1 // function definitions void* Professor(void* arg); void* Student(void* arg); void AnswerStart(); void AnswerDone(); void QuestionStart(); void QuestionDone(); int numStudents; // parameter for number of students to create int student; // index of student thread as created in loop sem_t speak, question, answer; // semaphores, reference readme int main(int argc, char* argv[]) { // check to see if user gave appropriate arguments if (argc < 2) { printf("Usage: professorStudent <number of students>\n"); exit(0); } numStudents = atoi(argv[1]); // number of students from command line params pthread_t prof_id, stud_id; // one speaker is allowed at the start sem_init(&speak, SHARED, 1); // size starts at 0, because questions are generated by students sem_init(&question, SHARED, 0); // size starts at 0, because answers are generated by the professor sem_init(&answer, SHARED, 0); // create a professor thread pthread_create(&prof_id, NULL, Professor, NULL); // loop to create numStudents of student threads for (student = 0; student < numStudents; student++) { pthread_create(&stud_id, NULL, Student, NULL); pthread_join(stud_id, NULL); } pthread_join(prof_id, NULL); pthread_exit(0); } // Professor thread, only to be created once void* Professor(void* arg) { while(true) { AnswerStart(); std::cout << "The professor is answering the question." << std::endl; AnswerDone(); } } // Student thread, to be created numStudents times void* Student(void* arg) { int studentNum = student; // Have each thread grab what number student they are std::cout << student << " : The student is ready to ask a question." << std::endl; QuestionStart(); std::cout << studentNum << " : The student is asking a question." << std::endl; QuestionDone(); std::cout << studentNum << " : The student is done asking a question." << std::endl; } // Wait for a question to start answering void AnswerStart() { std::cout << "The professor wants to be asked a question." << std::endl; sem_wait(&question); // wait for a question sched_yield(); } // Post that the question has been answered void AnswerDone() { std::cout << "The professor is finished answering." << std::endl; sem_post(&answer); // post an answer sched_yield(); } // Wait for a turn to speak, then post that a question has been asked void QuestionStart() { sem_wait(&speak); // wait to speak sem_post(&question); // post a question sched_yield(); } /// Wait for an answer, then post that other threads may speak void QuestionDone() { sem_wait(&answer); // wait for an answer sem_post(&speak); // let others speak sched_yield(); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strjoin.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hangkim <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/07/16 18:50:56 by hangkim #+# #+# */ /* Updated: 2020/07/19 16:16:24 by hangkim ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> int ft_length(char *str) { int i; i = 0; while (str[i]) i++; return (i); } int ft_total_length(int size, char **strs, char *sep) { int i; int length; i = 0; length = ft_length(sep) * (size - 1); while (i < size) { length += ft_length(strs[i]); i++; } length += 1; return (length); } int ft_strcat_sub(int index, char *dest, char *src) { int i; i = 0; while (src[i]) { dest[index + i] = src[i]; i++; } return (index + i); } void ft_strcat(int size, char **strs, char *sep, char *res) { int i; int index; i = 0; index = 0; while (i < size) { index = ft_strcat_sub(index, res, strs[i]); if (i != size - 1) index = ft_strcat_sub(index, res, sep); i++; } res[index] = '\0'; } char *ft_strjoin(int size, char **strs, char *sep) { int length; char *res; if (size == 0) { res = (char *)malloc(sizeof(char) * 1); res[0] = 0; return (res); } length = ft_total_length(size, strs, sep); if (!(res = (char *)malloc(sizeof(char) * length))) return (0); ft_strcat(size, strs, sep, res); return (res); }
C
#include <stdio.h> int main(void) { int option; printf("Te encuentras en un sueno y tiens 3 caminos. \n"); printf("Escribe 1 si quieres ir por el camino de los dulces\nEscribe 2 si quieres ir por el caminio de madera\nEscribe 3 si quieres ir por el camino de los perros\n"); scanf("%i", &option); switch(option) { case 1: printf("Sigues dormido"); break; case 2: printf("Sigues dormido"); break; case 3: printf("Los perros te llevan a una puerta y despiertas"); break; default: printf("Sigues durmiendo"); break; } return 0; }
C
#include<stdio.h> int fun() { if(1 < 2) { return; } else { return 1; } } int main() { printf("%d\n",fun()); return 0; }
C
#include<stdio.h> #define MAX 50 void main() { int A[MAX][MAX],B[MAX][MAX],C[MAX][MAX]; int Arows,Acols,Brows,Bcols, i,j,k,sum=0; // First Matrix printf("Enter the First Matrix (Size) X by X \n"); scanf("%d %d",&Arows,&Acols); printf("Enter the Elements of Matrix A : \n"); for(i=0;i<Arows;i++) { for(j=0;j<Acols;j++) { scanf("%d",&A[i][j]); } } // Second Matrix printf("Enter the Second Matrix (Size) X by X"); scanf("%d %d",&Brows,&Bcols); printf("\nEnter the Elements of Matrix B : "); for(i=0;i<Brows;i++) { for(j=0;j<Bcols;j++) { scanf("%d",&B[i][j]); } } // Matrix Multiplication for(i=0;i<Arows;i++) { for(j=0;j<Bcols;j++) { for(k=0;k<Brows;k++) { sum+=A[i][k]*B[k][j]; } C[i][j]=sum; sum=0; } } // Display printf("\n A x B = \n"); for(i=0;i<Arows;i++) { for(j=0;j<Bcols;j++) { printf("%d ",C[i][j]); } printf("\n"); } }
C
/** ****************************************************************************** * @file hal_gpio.c * @author Eakkasit L. * @version V1.0.0 * @date 26-Aug-2015 * @brief Brief of file description ****************************************************************************** */ #include "hal/hal_gpio.h" #if (HAL_GPIO_ENABLED == HAL_ENABLED) #define HAL_GPIO_RESERVED_PIN_ADDR 0xFFFFFFFFUL #define HAL_GPIO_REG(x) ((GPIO_TypeDef *)(x)) /** * @brief List of pointer to GPIO PIN information. */ uint32_t gPinAddr[HAL_GPIO_MAX_PORTS][HAL_GPIO_PINS_PER_PORT]; /********************************************************************************** * GPIO Pin Initializations *********************************************************************************/ void HAL_GPIO_PinInit(hal_gpio_pin_info_t *pp_info, hal_gpio_pin_t p_pin) { hal_gpio_pin_info_t *ptr = (hal_gpio_pin_info_t *)(&gPinAddr + p_pin); if((uint32_t)ptr == HAL_GPIO_RESERVED_PIN_ADDR) { HAL_TRACE("ERROR: Trying to initial reserved GPIO Pin!"); } else if(ptr != 0) { HAL_TRACE("ERROR: Trying to initial used GPIO Pin!"); } else { pp_info->port_no = p_pin / HAL_GPIO_PINS_PER_PORT; pp_info->pin_no = p_pin % HAL_GPIO_PINS_PER_PORT; pp_info->port_addr = HAL_GPIO_PORT_BASE + HAL_GPIO_PORT_SIZE * pp_info->port_no; } } void HAL_GPIO_ClkEn(hal_gpio_pin_info_t *pp_info) { RCC->AHB1ENR |= (1 << pp_info->port_no); } /********************************************************************************** * GPIO Pin Configurations *********************************************************************************/ void HAL_GPIO_PinConfig(hal_gpio_pin_info_t *pp_info, hal_gpio_config_t *config) { HAL_GPIO_SetMode(pp_info, config->mode); if(config->mode != HAL_GPIO_MODE_INPUT) { HAL_GPIO_SetOutputType(pp_info, config->otype); HAL_GPIO_SetSpeed(pp_info, config->speed); } HAL_GPIO_SetPullupPulldown(pp_info, config->pupd); } void HAL_GPIO_SetMode(hal_gpio_pin_info_t *pp_info, hal_gpio_mode_t mode) { HAL_GPIO_REG(pp_info->port_addr)->MODER |= (mode << pp_info->pin_no * 2); } void HAL_GPIO_SetOutputType(hal_gpio_pin_info_t *pp_info, hal_gpio_output_t otype) { HAL_GPIO_REG(pp_info->port_addr)->OTYPER |= (otype << pp_info->pin_no); } void HAL_GPIO_SetSpeed(hal_gpio_pin_info_t *pp_info, hal_gpio_speed_t speed) { HAL_GPIO_REG(pp_info->port_addr)->OSPEEDR |= (speed << pp_info->pin_no * 2); } void HAL_GPIO_SetPullupPulldown(hal_gpio_pin_info_t *pp_info, hal_gpio_pupd_t pupd) { HAL_GPIO_REG(pp_info->port_addr)->PUPDR |= (pupd << pp_info->pin_no * 2); } void HAL_GPIO_SetAlternate(hal_gpio_pin_info_t *pp_info, hal_gpio_af_t af) { HAL_GPIO_REG(pp_info->port_addr)->AFR[pp_info->pin_no >> 3] |= (af << (pp_info->pin_no * 4) % 32); } /********************************************************************************** * GPIO Pin Operations *********************************************************************************/ /** * @brief GPIO Pin set. */ void HAL_GPIO_Set(hal_gpio_pin_info_t *pp_info) { HAL_GPIO_REG(pp_info->port_addr)->BSRR |= (0x01 << pp_info->pin_no); } /** * @brief GPIO Pin reset. */ void HAL_GPIO_Reset(hal_gpio_pin_info_t *pp_info) { HAL_GPIO_REG(pp_info->port_addr)->BSRR |= (0x0100 << pp_info->pin_no); } /** * @brief GPIO Pin toggle. */ void HAL_GPIO_Toggle(hal_gpio_pin_info_t *pp_info) { HAL_GPIO_REG(pp_info->port_addr)->ODR ^= (0x01 << pp_info->pin_no); } hal_gpio_stat_t HAL_GPIO_Read(hal_gpio_pin_info_t *pp_info) { return ((HAL_GPIO_REG(pp_info->port_addr)->IDR & (HAL_GPIO_STAT_SET << pp_info->pin_no)) != HAL_GPIO_STAT_RESET ? HAL_GPIO_STAT_SET : HAL_GPIO_STAT_RESET); } #endif
C
#include "functionTest.h" #include <string.h> Department *departmentCreate(char *name, char *location) { Department *department = (Department *)malloc(sizeof(Department)); char *n = (char *)malloc(128 * sizeof(char)); char *a = (char *)malloc(128 * sizeof(char)); strcpy(n, name); strcpy(a, location); department -> name = n; department -> location = a; department -> capacity = 0; return department; } void departmentInformation(Department *department) { int i; printf("Name: %s\n" "Location: %s\n\n", department -> name, department -> location ); for(i = 0; i < department -> capacity; i++) { doctorInformation(&department -> doctor[i]); patientInformation(&department -> patient[i]); } } void departmentAdd(departmentList **list, Department *department) { if (*list == NULL) { *list = (departmentList *)malloc(sizeof(departmentList)); departmentNode *temp = (departmentNode *)malloc(sizeof(departmentNode)); temp->department = department; temp->next = temp->prev = NULL; (*list)->head = (*list)->tail = temp; return; } else { departmentNode *temp = (departmentNode *)malloc(sizeof(departmentNode)); temp->department = department; temp->next = NULL; temp->prev = (*list)->tail; (*list)->tail->next = temp; (*list)->tail = temp; return; } } void departmentPrint(departmentList *list) { departmentNode *head; head = list->head; while (head != NULL) { departmentInformation(head->department); head = head->next; } } void departmentAddInformation(Department *department, Patient *patient, Doctor *doctor) { if(department -> capacity == 20) { printf("Department is full!"); return; } department -> doctor[department -> capacity] = *doctor; department -> patient[department -> capacity] = *patient; department -> capacity++; } int findMin(int a, int b) { if(a > b) return b; else return a; } void departmentCalculate(departmentList *list) { departmentNode *head; int i, min; head = list->head; min = head -> department -> patient -> dischargeDate; while (head != NULL) { if(head -> department -> capacity < 20) { printf("There is free space.\n"); return; } for(i = 0; i < 20; i++) { min = findMin(head -> department -> patient[i].dischargeDate, min); } head = head->next; } printf("The place will be vacated on %d.%d.%d\n", dayConvert(min), monthConvert(min), yearConvert(min)); } Doctor *doctorCreate(char *name, char *post, char *speciality) { Doctor *doctor = (Doctor *)malloc(sizeof(Doctor)); char *n = (char *)malloc(128 * sizeof(char)); char *a = (char *)malloc(128 * sizeof(char)); char *d = (char *)malloc(128 * sizeof(char)); strcpy(n, name); strcpy(a, post); strcpy(d, speciality); doctor -> name = n; doctor -> post = a; doctor -> speciality = speciality; return doctor; } void doctorInformation(Doctor *doctor) { printf("Name: %s\n" "Post: %s\n" "Speciality: %s\n\n", doctor -> name, doctor -> post, doctor -> speciality ); } void doctorAdd(doctorList **list, Doctor *doctor) { if (*list == NULL) { *list = (doctorList *)malloc(sizeof(doctorList)); doctorNode *temp = (doctorNode *)malloc(sizeof(doctorNode)); temp->doctor = doctor; temp->next = temp->prev = NULL; (*list)->head = (*list)->tail = temp; return; } else { doctorNode *temp = (doctorNode *)malloc(sizeof(doctorNode)); temp->doctor = doctor; temp->next = NULL; temp->prev = (*list)->tail; (*list)->tail->next = temp; (*list)->tail = temp; return; } } Patient *patientCreate(char *name, char *address, int dateOfBirth, char *diagnosis, int admissionDate, int dischargeDate, int roomNumber) { Patient *patient = (Patient *)malloc(sizeof(Patient)); char *n = (char *)malloc(128 * sizeof(char)); char *a = (char *)malloc(128 * sizeof(char)); char *d = (char *)malloc(128 * sizeof(char)); strcpy(n, name); strcpy(a, address); strcpy(d, diagnosis); patient -> name = n; patient -> address = a; patient -> dateOfBirth = dateOfBirth; patient -> diagnosis = d; patient -> admissionDate = admissionDate; patient -> dischargeDate = dischargeDate; patient -> roomNumber = roomNumber; return patient; } int yearConvert(int date) { return date / 365; } int monthConvert(int date) { return (date - yearConvert(date) * 365) / 31; } int dayConvert(int date) { return date - yearConvert(date) * 365 - monthConvert(date) * 31; } void patientInformation(Patient *patient) { printf("Name: %s\n" "Address: %s\n" "Date of birth: %d.%d.%d\n" "Diagnosis: %s\n" "Admission date: %d.%d.%d\n" "Discharge date: %d.%d.%d\n" "Room number: %d\n\n", patient -> name, patient -> address, dayConvert(patient -> dateOfBirth), monthConvert(patient -> dateOfBirth), yearConvert(patient -> dateOfBirth), patient -> diagnosis, dayConvert(patient -> admissionDate), monthConvert(patient -> admissionDate), yearConvert(patient -> admissionDate), dayConvert(patient -> dischargeDate), monthConvert(patient -> dischargeDate), yearConvert(patient -> dischargeDate), patient -> roomNumber ); } void patientAdd(patientList **list, Patient *patient) { if (*list == NULL) { *list = (patientList *)malloc(sizeof(patientList)); patientNode *temp = (patientNode *)malloc(sizeof(patientNode)); temp->patient = patient; temp->next = temp->prev = NULL; temp -> id = 0; (*list)->head = (*list)->tail = temp; return; } else { patientNode *temp = (patientNode *)malloc(sizeof(patientNode)); temp->patient = patient; temp->next = NULL; temp->prev = (*list)->tail; (*list)->tail->next = temp; temp -> id = temp -> prev -> id + 1; (*list)->tail = temp; return; } } void printMedicalCart(Patient *patient) { FILE *file; char name[] = "MedicalCart.txt"; char str[128]; if ((file = fopen(name, "w")) == NULL) { printf("File open error.\n"); return; } fputs("Name: ", file); fputs(patient -> name, file); fputs("\n", file); fputs("Address: ", file); fputs(patient -> address, file); fputs("\n", file); fputs("Date of birth: ", file); sprintf(str, "%d.%d.%d\n", dayConvert(patient -> dateOfBirth), monthConvert(patient -> dateOfBirth), yearConvert(patient -> dateOfBirth)); fputs(str, file); fputs("Diagnosis: ", file); fputs(patient -> diagnosis, file); fputs("\n", file); fputs("Admission date: ", file); sprintf(str, "%d.%d.%d\n", dayConvert(patient -> admissionDate), monthConvert(patient -> admissionDate), yearConvert(patient -> admissionDate)); fputs(str, file); fputs("Discharge date: ", file); sprintf(str, "%d.%d.%d\n", dayConvert(patient -> dischargeDate), monthConvert(patient -> dischargeDate), yearConvert(patient -> dischargeDate)); fputs(str, file); fputs("Room number: ", file); sprintf(str, "%d\n", patient -> roomNumber); fputs(str, file); fclose(file); printf("Medical cart was created successfully.\n"); } void medicalCart(patientList *list, int id) { patientNode *temp; Patient *sought = NULL; temp = list->head; while (temp != NULL) { if(temp -> id == id) { sought = temp -> patient; break; } temp = temp->next; } if(sought != NULL) printMedicalCart(sought); else printf("Incorrect ID.\n"); }
C
/* Передача размера массива в функцию Количество элементов массива можно найти вот так: sizeof(a) / sizeof(a[0]) Таким образом, если у нас есть массив, то можно легко найти количество элементов в нём. Но то же самое нельзя сделать с указателем, даже если он указывает на первый элемент массива. То есть в функции func уже невозможно будет найти размер массива, используя указатель p. В этом случае нам приходится передавать этот размер в функцию отдельным параметром. */ #include <stdio.h> void func(int* p, int size) { for (int i = 0; i < size; ++i) printf("%i ", p[i]); printf("\n"); } int main() { int a[6] = {10, 20, 30, 40, 50, 60}; printf("%i\n", sizeof(a) / sizeof(a[0])); func(a, sizeof(a) / sizeof(a[0])); } /* Задача: Что напечатает программа из данного примера? */
C
/* ** EPITECH PROJECT, 2021 ** B-CPP-300-STG-3-1-CPPD02M-clement.muth ** File description: ** tab_to_2dtab */ #include <stdio.h> #include <stdlib.h> void tab_to_2dtab(const int *tab, int length, int width, int ***res) { *res = malloc(sizeof(int *) * length); if (!*res) return; for (int x = 0; x < length; x++) { (*res)[x] = malloc(sizeof(int) * width); if (!(*res)[x]) return; for (int y = 0; y < width; y++) (*res)[x][y] = tab[x * width + y]; } }
C
/* ** EPITECH PROJECT, 2022 ** cpp_d02m_2018 ** File description: ** Created by Florian Louvet, */ #include <stdlib.h> void tab_to_2dtab(const int *tab, int length, int width, int ***res) { *res = malloc(sizeof(int *) * length + 1); int pos = 0; for (int i = 0; i < length; i++) { (*res)[i] = malloc(sizeof(int) * width + 1); for (int j = 0; j < width; j++) { (*res)[i][j] = tab[pos++]; } } }
C
#include <stdio.h> int main(int argc, int *argv[]){ if(argc>1){ int i; for(i=1;i<argc;i++){ char item[1]=argv[i]; if(i==argc-1){ printf("%i\n",(int)item); } else{ printf("%i ",(int)item); } } }else{ return 0; } }
C
#include<stdio.h> int count(int n); int main() { int n,res=0; printf("Enter the Number whose digits are to be counted"); scanf("%d",&n); res=count(n); printf("The number of digits in %d = %d",n,res); } int count(int n) { static int res=0; if(n!=0) { res++; count(n/10); } return res; }
C
#include "log.h" #define STR_INFO " INFO: " #define STR_DEBUG " DEBUG: " #define STR_WARNING "WARNING: " #define STR_ERROR " ERROR: " #define STR_FATAL " FATAL: " #define MAX_BUFF_SIZE 64 static void _log(FILE* stream, const char* logstr, const char* format, va_list args) { char buff[MAX_BUFF_SIZE]; const time_t currt = time(NULL); const struct tm* localt = localtime(&currt); strftime(buff, MAX_BUFF_SIZE, "%F %T", localt); fprintf(stream, "%s %s", buff, logstr); vfprintf(stream, format, args); fputc('\n', stream); fflush(stream); } void log_info(FILE* stream, const char* format, ...) { va_list args; va_start(args, format); _log(stream, STR_INFO, format, args); va_end(args); } void log_debug(FILE* stream, const char* format, ...) { va_list args; va_start(args, format); _log(stream, STR_DEBUG, format, args); va_end(args); } void log_warning(FILE* stream, const char* format, ...) { va_list args; va_start(args, format); _log(stream, STR_WARNING, format, args); va_end(args); } void log_error(FILE* stream, const char* format, ...) { va_list args; va_start(args, format); _log(stream, STR_ERROR, format, args); va_end(args); } void log_fatal(FILE* stream, const char* format, ...) { va_list args; va_start(args, format); _log(stream, STR_FATAL, format, args); va_end(args); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* list_files.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mpetruno <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/11/05 20:52:09 by mpetruno #+# #+# */ /* Updated: 2018/11/20 20:57:34 by mpetruno ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_ls.h" static void print_comma_separated(t_list *lst) { while (lst) { if (ISFLAG_GG(g_flags)) set_color(VP(lst->content)->pstat->st_mode); if (ISFLAG_I(g_flags)) ft_printf("%d ", VP(lst->content)->ino); ft_printf("%s", VP(lst->content)->name); if (ISFLAG_GG(g_flags)) set_color(0); if (lst->next) ft_putstr(", "); lst = lst->next; } write(1, "\n", 1); } void list_files(t_list *lst, int total) { if (lst == 0) return ; if (ISFLAG_L(g_flags) || ISFLAG_G(g_flags)) print_det_lst(lst, total); else if (ISFLAG_M(g_flags)) print_comma_separated(lst); else print_table(lst); }
C
#include <stdio.h> long string2int(char *); float string2float(char *); void string2bin(char *); void string2bin64(char *); void string2hex(char *); void string2hex16(char *); void int2bin(int); void int2hex(); int bin2int(); void bin2hex(); void bin2hex16(); void double2double(char *); void double2bin(float); void double2hex(); void bin2float(); void bin2double(); void float2bin(float); void float2hex(); void hex2hex(); int hex2int(); void hex2bin(); void hex2bin64(); void hex2float(); void hex2double(); // global variables int binaryArr[32]; int bin64Arr[64]; char hexArr[8]; char hexArr16[16]; int main(int argc, char** argv){ int j; // Error- Wrong number of arguments if(argc != 4){ fprintf(stderr,"ERROR: The number of arguments is wrong.\n"); fprintf(stderr,"Usage: ./clc -<input format> -<output format> <input>\n"); return 1; } // Error - wrong input argument if(!(argv[1][1]=='B' || argv[1][1]=='H' || argv[1][1]=='I' || argv[1][1]=='F' || argv[1][1]=='D')){ fprintf(stderr,"ERROR: The input argument is wrong.\n"); fprintf(stderr,"Possible input arguments are -B, -H, -I, -F and -D."); return 1; } // Error - wrong input argument if(!(argv[2][1]=='B' || argv[2][1]=='H' || argv[2][1]=='I' || argv[2][1]=='F' || argv[2][1]=='D')){ fprintf(stderr,"ERROR: The output argument is wrong.\n"); fprintf(stderr,"Possible output arguments are -B, -H, -I, -F and -D."); return 1; } // Input type - Integer if(argv[1][1]=='I'){ // check input format errors if(!((argv[3][0] == '-') || (argv[3][0]>=48 && argv[3][0]<=57))){ fprintf(stderr,"ERROR: Input format error at location 0.\n"); return 1; } while(argv[3][j+1]!='\0'){ if(!(argv[3][j+1]>=48 && argv[3][j+1]<=57)){ fprintf(stderr,"ERROR: Input format error at location %d.\n",j+1); return 1; } j++; } // check whether the input size is wrong if(string2int(argv[3])> 2147483647 || string2int(argv[3])< -2147483648){ fprintf(stderr,"ERROR: The input size is wrong.\n"); return 1; } // Integer --> Integer if(argv[2][1]=='I'){ fprintf(stdout,"%ld\n",string2int(argv[3])); } // Integer --> Binary if(argv[2][1]=='B'){ int2bin(string2int(argv[3])); for(j = 31 ; j>= 0; j--){ fprintf(stdout,"%d",binaryArr[j]); } fprintf(stdout,"\n"); } // Integer --> Double if(argv[2][1]=='D'){ fprintf(stderr,"ERROR: This conversion is not possible.\n"); return 1; } // Integer --> Float if(argv[2][1]=='F'){ fprintf(stdout,"%ld",string2int(argv[3])); fprintf(stdout,".00"); fprintf(stdout,"\n"); } // Integer --> Hexadecimal if(argv[2][1]=='H'){ fprintf(stdout,"0x"); int2bin(string2int(argv[3])); int2hex(); for(j=7;j>=0; j--){ fprintf(stdout,"%c",hexArr[j]); } fprintf(stdout,"\n"); } } // Input Format - Binary if(argv[1][1]=='B'){ int count=0; while(argv[3][j]!='\0'){ // count the number of bits in the input count++; j++; } if(argv[2][1]!='D'){ if(count!=32){ // check the input size error fprintf(stderr,"ERROR: The input size is wrong.\n"); return 1; } } else{ if(count!=64){ // check the input size error fprintf(stderr,"ERROR: The input size is wrong.\n"); return 1; } } for(j=0;j<count;j++){ // check input format error if(argv[3][j] != 48 && argv[3][j] != 49){ fprintf(stderr,"ERROR: Input format error at location %d.\n",j); return 1; } } string2bin(argv[3]); // Binary --> Integer if(argv[2][1]=='I'){ fprintf(stdout,"%d\n",bin2int()); } // Binary --> Binary if(argv[2][1]=='B'){ for(j = 0 ; j< count; j++){ fprintf(stdout,"%d",binaryArr[j]); } fprintf(stdout,"\n"); } // Binary --> Hexadecimal if(argv[2][1]=='H'){ fprintf(stdout,"0x"); bin2hex(); for(j=7;j>=0; j--){ fprintf(stdout,"%c",hexArr[j]); } fprintf(stdout,"\n"); } // Binary --> Float if(argv[2][1]=='F'){ bin2float(); } // Binary --> Double if(argv[2][1]=='D'){ if(count==64){ // check the input size error string2bin64(argv[3]); bin2double(); } else{ fprintf(stderr,"ERROR: The input size is wrong.\n"); return 1; } } } // Input format - Float if(argv[1][1]=='F'){ int count=0,k=0; // check input format error while(argv[3][j]!='\0'){ if(!((argv[3][j]>=48 && argv[3][j]<=57) || (argv[3][j]=='.' )|| (argv[3][j] == '-'))){ fprintf(stderr,"ERROR: Input format error at location %d.\n",j); return 1; } j++; } // check unwanted '.' in the input while(argv[3][k]!='\0'){ if(argv[3][k]=='.'){ ++count; } if(count>1){ fprintf(stderr,"ERROR: Input format error at location %d.\n",k); return 1; } k++; } // Float --> Double if(argv[2][1]=='D'){ fprintf(stderr,"ERROR: This conversion is not possible.\n"); return 1; } // Float --> Integer if(argv[2][1]=='I'){ int value = string2float(argv[3]); if(value > 2147483647 || value < -2147483648){ fprintf(stderr,"ERROR: This conversion is not possible.\n"); return 1; } else{ fprintf(stderr,"WARNING: There is a possibility for a precision loss."); fprintf(stdout,"%d\n",value); } } // Float --> Binary if(argv[2][1]=='B'){ float2bin(string2float(argv[3])); for(j=0;j<32;j++){ fprintf(stdout,"%d",binaryArr[j]); } fprintf(stdout,"\n"); } // Float --> Hexadecimal if(argv[2][1]=='H'){ float2bin(string2float(argv[3])); float2hex(); } // Float --> Float if(argv[2][1]=='F'){ fprintf(stdout,"%.2f\n",string2float(argv[3])); } } // Input format - Double if(argv[1][1]=='D'){ int count=0,k=0; // check input format error while(argv[3][j]!='\0'){ if(!((argv[3][j]>=48 && argv[3][j]<=57) || (argv[3][j]=='.' )|| (argv[3][j] == '-'))){ fprintf(stderr,"ERROR: Input format error at location %d.\n",j); return 1; } j++; } // check unwanted '.' in the input while(argv[3][k]!='\0'){ if(argv[3][k]=='.'){ ++count; } if(count>1){ fprintf(stderr,"ERROR: Input format error at location %d.\n",k); return 1; } k++; } // Double --> Double if(argv[2][1]=='D'){ fprintf(stdout,"%.6f\n",string2float(argv[3])); } // Double --> Float if(argv[2][1]=='F'){ fprintf(stderr,"ERROR: This conversion is not possible.\n"); return 1; } // Double --> Integer if(argv[2][1]=='I'){ fprintf(stderr,"ERROR: This conversion is not possible.\n"); return 1; } // Double --> Binary if(argv[2][1]=='B'){ double2bin(string2float(argv[3])); for(j=0;j<64;j++){ fprintf(stdout,"%d",bin64Arr[j]); } fprintf(stdout,"\n"); } // Double --> Hexadecimal if(argv[2][1]=='H'){ double2bin(string2float(argv[3])); double2hex(); } } // Input format - Hexadecimal if(argv[1][1]=='H'){ int count=0; while(argv[3][j]!='\0'){ // count the number of bits in the input count++; j++; } if(argv[2][1]!='D' && argv[2][1]!='B'){ if(count<8){ // check the input size error fprintf(stderr,"ERROR: The input size is wrong.\n"); return 1; } if(count>8){ // check the input size error fprintf(stderr,"ERROR: This conversion is not possible.\n"); return 1; } } else{ if(count<16){ // check the input size error fprintf(stderr,"ERROR: The input size is wrong.\n"); return 1; } if(count>16){ // check the input size error fprintf(stderr,"ERROR: This conversion is not possible.\n"); return 1; } } if(argv[2][1]=='B'){ if(count<8){ // check the input size error fprintf(stderr,"ERROR: The input size is wrong.\n"); return 1; } if(count>8 && count<16){ // check the input size error fprintf(stderr,"ERROR: This conversion is not possible.\n"); return 1; } if(count>16){ // check the input size error fprintf(stderr,"ERROR: This conversion is not possible.\n"); return 1; } } for(j=0;j<count;j++){ // check input format error if(!((argv[3][j] >= '0' && argv[3][j] <= '9') || (argv[3][j] >= 'A' && argv[3][j] <= 'F'))){ fprintf(stderr,"ERROR: Input format error at location %d.\n",j); return 1; } } string2hex(argv[3]); // Hexadecimal --> Hexadecimal if(argv[2][1]=='H'){ fprintf(stdout,"0x"); for(j=0;j<8;j++){ fprintf(stdout,"%c",hexArr[j]); } fprintf(stdout,"\n"); } // Hexadecimal --> Binary if(argv[2][1]=='B'){ if(count==8){ hex2bin(); for(j = 0 ; j< 32; j++){ fprintf(stdout,"%d",binaryArr[j]); } fprintf(stdout,"\n"); } else if(count==16){ string2hex16(argv[3]); hex2bin64(); for(j = 0 ; j< 64; j++){ fprintf(stdout,"%d",bin64Arr[j]); } fprintf(stdout,"\n"); } } // Hexadecimal --> Integer if(argv[2][1]=='I'){ int value = hex2int(); fprintf(stdout,"%d\n",value); } // Hexadecimal --> Float if(argv[2][1]=='F'){ hex2float(); } // Hexadecimal --> Double if( argv[2][1]=='D') { string2hex16(argv[3]); hex2double(); } } return 0; } // convert string input to integer long string2int(char *ch){ int a,i=0,k,arr[32],j=1; long sum=0; if(ch[0]!='-'){ while(ch[i]!='\0'){ a = ch[i]; arr[i]=a-48; ++i; } for(k=i-1;k>=0;k--){ sum = sum + arr[k]*j; j=j*10; } } else{ i=1; while(ch[i]!='\0'){ a = ch[i]; arr[i]=a-48; ++i; } for(k=i-1;k>=1;k--){ sum= sum+arr[k]*j; j=j*10; } sum=sum*(-1); } return sum; } // convert string input to float float string2float(char *ch){ int a,i=0,k,arr[32],newArr[32],j=1,b; long int_val=0; float float_part=0; if(ch[0]!='-'){ while(ch[i]!='.'){ a = ch[i]; arr[i]=a-48; ++i; } for(k=i-1;k>=0;k--){ int_val = int_val + arr[k]*j; j=j*10; } k=0; i++; while(ch[i]!='\0'){ a = ch[i]; newArr[k]=a-48; ++i; k++; } float c=0.1; for(b=0;b<k;b++){ float_part = float_part + newArr[b]*c; c=c/10; } return int_val+float_part; } else{ i=1; while(ch[i]!='.'){ a = ch[i]; arr[i]=a-48; ++i; } for(k=i-1;k>=1;k--){ int_val= int_val+arr[k]*j; j=j*10; } k=0; i++; while(ch[i]!='\0'){ a = ch[i]; newArr[k]=a-48; ++i; k++; } float c=0.1; for(b=0;b<k;b++){ float_part = float_part + newArr[b]*c; c=c/10; } return (int_val+float_part)*(-1); } } // Integer --> Binary void int2bin(int int_val){ int i=0,j; for(j = 31 ; j>= 0; j--){ binaryArr[j]=0; } if(int_val>0){ //when integer value > 0 while(int_val!=0){ binaryArr[i++]= int_val%2; int_val = int_val/2; } } else if(int_val<0){ // when integer value < 0 int_val = int_val*(-1); while(int_val!=0){ binaryArr[i++]= int_val%2; int_val = int_val/2; } for(i=31; i>=0; i--){ if(binaryArr[i] == 0){ binaryArr[i] = 1; continue; } if(binaryArr[i] == 1) binaryArr[i] = 0; } for(i=0; i<32; i++){ if(binaryArr[i] == 0){ binaryArr[i] = 1; break; } if(binaryArr[i] == 1) binaryArr[i] = 0; } } } // Integer --> Hexadecimal void int2hex(){ int newArr[32],i; for(i=0;i<32;i++){ newArr[i] = binaryArr[31-i]; } for(i=0;i<32;i++){ binaryArr[i] = newArr[i]; } bin2hex(); } // convert string input to Binary void string2bin(char * ch){ int i=0,j; for(j = 31 ; j>= 0; j--){ binaryArr[j]=0; } for(i=31; i>=0; i--){ if((ch[i])==48 || (ch[i])==49){ binaryArr[i] = ch[i]-48; } } } // convert 64bit String to Binary void string2bin64(char *ch){ int i=0,j; for(j = 63 ; j>= 0; j--){ bin64Arr[j]=0; } for(i=63; i>=0; i--){ if((ch[i])==48 || (ch[i])==49){ bin64Arr[i] = ch[i]-48; } } } // Binary --> Integer int bin2int(){ int i,value=0,j=1; if(binaryArr[0]==1){ for(i=31; i>=0; i--){ if(binaryArr[i] == 0){ binaryArr[i] = 1; continue; } if(binaryArr[i] == 1) binaryArr[i] = 0; } for(i=31; i>=0; i--){ if(binaryArr[i] == 0){ binaryArr[i] = 1; break; } if(binaryArr[i] == 1) binaryArr[i] = 0; } for(i=31; i>=0; i--){ value = value + binaryArr[i]*j; j = j*2; } return value*(-1); } for(i=31; i>=0; i--){ value = value + binaryArr[i]*j; j = j*2; } return value; } // Binary --> Hexadecimal void bin2hex(){ int i,j; for(i=28,j=0; i>=0 && j<8 ; i=i-4,j++){ if( binaryArr[i]==0 && binaryArr[i+1]==0 && binaryArr[i+2]==0 && binaryArr[i+3]==0 ) hexArr[j] = '0'; else if( binaryArr[i]==0 && binaryArr[i+1]==0 && binaryArr[i+2]==0 && binaryArr[i+3]==1) hexArr[j] = '1'; else if( binaryArr[i]==0 && binaryArr[i+1]==0 && binaryArr[i+2]==1 && binaryArr[i+3]==0 ) hexArr[j] = '2'; else if( binaryArr[i]==0 && binaryArr[i+1]==0 && binaryArr[i+2]==1 && binaryArr[i+3]==1 ) hexArr[j] = '3'; else if( binaryArr[i]==0 && binaryArr[i+1]==1 && binaryArr[i+2]==0 && binaryArr[i+3]==0 ) hexArr[j] = '4'; else if( binaryArr[i]==0 && binaryArr[i+1]==1 && binaryArr[i+2]==0 && binaryArr[i+3]==1 ) hexArr[j] = '5'; else if( binaryArr[i]==0 && binaryArr[i+1]==1 && binaryArr[i+2]==1 && binaryArr[i+3]==0 ) hexArr[j] = '6'; else if( binaryArr[i]==0 && binaryArr[i+1]==1 && binaryArr[i+2]==1 && binaryArr[i+3]==1 ) hexArr[j] = '7'; else if( binaryArr[i]==1 && binaryArr[i+1]==0 && binaryArr[i+2]==0 && binaryArr[i+3]==0 ) hexArr[j] = '8'; else if( binaryArr[i]==1 && binaryArr[i+1]==0 && binaryArr[i+2]==0 && binaryArr[i+3]==1 ) hexArr[j] = '9'; else if( binaryArr[i]==1 && binaryArr[i+1]==0 && binaryArr[i+2]==1 && binaryArr[i+3]==0 ) hexArr[j] = 'A'; else if( binaryArr[i]==1 && binaryArr[i+1]==0 && binaryArr[i+2]==1 && binaryArr[i+3]==1 ) hexArr[j] = 'B'; else if( binaryArr[i]==1 && binaryArr[i+1]==1 && binaryArr[i+2]==0 && binaryArr[i+3]==0 ) hexArr[j] = 'C'; else if( binaryArr[i]==1 && binaryArr[i+1]==1 && binaryArr[i+2]==0 && binaryArr[i+3]==1 ) hexArr[j] = 'D'; else if( binaryArr[i]==1 && binaryArr[i+1]==1 && binaryArr[i+2]==1 && binaryArr[i+3]==0 ) hexArr[j] = 'E'; else if( binaryArr[i]==1 && binaryArr[i+1]==1 && binaryArr[i+2]==1 && binaryArr[i+3]==1 ) hexArr[j] = 'F'; } } // Binary --> Float void bin2float(){ int i,arr[8],sum=0,j=1,int_val=0; float float_val=0,k=0.5; // get the exponent for(i=1;i<=8;i++){ arr[i-1] = binaryArr[i]; } for(i=7;i>=0;i--){ sum = sum + j*arr[i]; j = j*2; } int exponent = sum - 127; if(exponent>0){ j=1; // get the int value for(i=8+exponent;i>=9;i--){ int_val = int_val + j*binaryArr[i]; j=j*2; } int_val = int_val + j; // get the floating point numbers for(i=9+exponent;i<32;i++){ float_val = float_val + k*binaryArr[i]; k=k/2; } // print the output if(binaryArr[0]==0) fprintf(stdout,"%.2f\n",int_val+float_val); if(int_val!=0 && binaryArr[0]==1) fprintf(stdout,"%.2f\n",(int_val+float_val)*(-1)); } if(exponent<0){ exponent = exponent*(-1); // get the floating point numbers int Arr[exponent]; for(i=0;i<=exponent-2;i++){ Arr[i]=0; } Arr[exponent-1] = 1; k=0.5; for(i=0;i<=exponent-1;i++){ float_val = float_val + k*Arr[i]; k=k/2; } for(i=9;i<32;i++){ float_val = float_val + k*binaryArr[i]; k=k/2; } // print the output if(binaryArr[0]==0) fprintf(stdout,"%.2f\n",float_val); if(float_val!=0 && binaryArr[0]==1) fprintf(stdout,"%.2f\n",(float_val)*(-1)); } } // Binary --> Double void bin2double(){ int i,arr[11],sum=0,j=1,int_val=0; float float_val=0,k=0.5; // get the exponent for(i=1;i<=11;i++){ arr[i-1] = bin64Arr[i]; } for(i=10;i>=0;i--){ sum = sum + j*arr[i]; j = j*2; } int exponent = sum - 1023; // get the int value if(exponent>0){ j=1; for(i=11+exponent;i>=12;i--){ int_val = int_val + j*bin64Arr[i]; j=j*2; } int_val = int_val + j; // get the floating point numbers for(i=12+exponent;i<64;i++){ float_val = float_val + k*bin64Arr[i]; k=k/2; } // print the output if(bin64Arr[0]==0) fprintf(stdout,"%.6f\n",int_val+float_val); if(int_val!=0 && bin64Arr[0]==1) fprintf(stdout,"%.6f\n",(int_val+float_val)*(-1)); } if(exponent<0){ exponent = exponent*(-1); // get the floating point numbers int arr[exponent]; k=0.5; for(i=0;i<=exponent-2;i++){ arr[i]=0; } arr[exponent-1] = 1; for(i=0;i<=exponent-1;i++){ float_val = float_val + k*arr[i]; k=k/2; } for(i=12;i<64;i++){ float_val = float_val + k*bin64Arr[i]; k=k/2; } // print the output if(bin64Arr[0]==0) fprintf(stdout,"%f\n",float_val); if(float_val!=0 && bin64Arr[0]==1) fprintf(stdout,"%f\n",(float_val)*(-1)); } } // convert string input to Hexadecimal char array void string2hex(char *ch){ int i=0; for(i=7; i>=0; i--){ hexArr[i] = ch[i]; } } // Hexadecimal --> Integer int hex2int(){ hex2bin(); int value = bin2int(); return value; } // Hexadecimal --> Binary void hex2bin(){ int i,j; for(i=0,j=0; i<8 && j<=28; i++,j=j+4) { switch(hexArr[i]) { case '0': binaryArr[j] = 0; binaryArr[j+1] = 0; binaryArr[j+2] = 0; binaryArr[j+3] = 0; break; case '1': binaryArr[j] = 0; binaryArr[j+1] = 0; binaryArr[j+2] = 0; binaryArr[j+3] = 1; break; case '2': binaryArr[j] = 0; binaryArr[j+1] = 0; binaryArr[j+2] = 1; binaryArr[j+3] = 0; break; case '3': binaryArr[j] = 0; binaryArr[j+1] = 0; binaryArr[j+2] = 1; binaryArr[j+3] = 1; break; case '4': binaryArr[j] = 0; binaryArr[j+1] = 1; binaryArr[j+2] = 0; binaryArr[j+3] = 0; break; case '5': binaryArr[j] = 0; binaryArr[j+1] = 1; binaryArr[j+2] = 0; binaryArr[j+3] = 1; break; case '6': binaryArr[j] = 0; binaryArr[j+1] = 1; binaryArr[j+2] = 1; binaryArr[j+3] = 0; break; case '7': binaryArr[j] = 0; binaryArr[j+1] = 1; binaryArr[j+2] = 1; binaryArr[j+3] = 1; break; case '8': binaryArr[j] = 1; binaryArr[j+1] = 0; binaryArr[j+2] = 0; binaryArr[j+3] = 0; break; case '9': binaryArr[j] = 1; binaryArr[j+1] = 0; binaryArr[j+2] = 0; binaryArr[j+3] = 1; break; case 'A': binaryArr[j] = 1; binaryArr[j+1] = 0; binaryArr[j+2] = 1; binaryArr[j+3] = 0; break; case 'B': binaryArr[j] = 1; binaryArr[j+1] = 0; binaryArr[j+2] = 1; binaryArr[j+3] = 1; break; case 'C': binaryArr[j] = 1; binaryArr[j+1] = 1; binaryArr[j+2] = 0; binaryArr[j+3] = 0; break; case 'D': binaryArr[j] = 1; binaryArr[j+1] = 1; binaryArr[j+2] = 0; binaryArr[j+3] = 1; break; case 'E': binaryArr[j] = 1; binaryArr[j+1] = 1; binaryArr[j+2] = 1; binaryArr[j+3] = 0; break; case 'F': binaryArr[j] = 1; binaryArr[j+1] = 1; binaryArr[j+2] = 1; binaryArr[j+3] = 1; break; } } } // Hexadecimal --> Float void hex2float(){ hex2bin(); bin2float(); } // Hexadecimal --> Double void hex2double(){ hex2bin64(); bin2double(); } // convert 16 bit string hexadecimal input to char array void string2hex16(char *ch){ int i=0; for(i=15; i>=0; i--){ hexArr16[i] = ch[i]; } } // Hexadecimal(16 bit) --> Binary(64 bit) void hex2bin64(){ int i,j; for(i=0,j=0; i<16 && j<=60; i++,j=j+4) { switch(hexArr16[i]) { case '0': bin64Arr[j] = 0; bin64Arr[j+1] = 0; bin64Arr[j+2] = 0; bin64Arr[j+3] = 0; break; case '1': bin64Arr[j] = 0; bin64Arr[j+1] = 0; bin64Arr[j+2] = 0; bin64Arr[j+3] = 1; break; case '2': bin64Arr[j] = 0; bin64Arr[j+1] = 0; bin64Arr[j+2] = 1; bin64Arr[j+3] = 0; break; case '3': bin64Arr[j] = 0; bin64Arr[j+1] = 0; bin64Arr[j+2] = 1; bin64Arr[j+3] = 1; break; case '4': bin64Arr[j] = 0; bin64Arr[j+1] = 1; bin64Arr[j+2] = 0; bin64Arr[j+3] = 0; break; case '5': bin64Arr[j] = 0; bin64Arr[j+1] = 1; bin64Arr[j+2] = 0; bin64Arr[j+3] = 1; break; case '6': bin64Arr[j] = 0; bin64Arr[j+1] = 1; bin64Arr[j+2] = 1; bin64Arr[j+3] = 0; break; case '7': bin64Arr[j] = 0; bin64Arr[j+1] = 1; bin64Arr[j+2] = 1; bin64Arr[j+3] = 1; break; case '8': bin64Arr[j] = 1; bin64Arr[j+1] = 0; bin64Arr[j+2] = 0; bin64Arr[j+3] = 0; break; case '9': bin64Arr[j] = 1; bin64Arr[j+1] = 0; bin64Arr[j+2] = 0; bin64Arr[j+3] = 1; break; case 'A': bin64Arr[j] = 1; bin64Arr[j+1] = 0; bin64Arr[j+2] = 1; bin64Arr[j+3] = 0; break; case 'B': bin64Arr[j] = 1; bin64Arr[j+1] = 0; bin64Arr[j+2] = 1; bin64Arr[j+3] = 1; break; case 'C': bin64Arr[j] = 1; bin64Arr[j+1] = 1; bin64Arr[j+2] = 0; bin64Arr[j+3] = 0; break; case 'D': bin64Arr[j] = 1; bin64Arr[j+1] = 1; bin64Arr[j+2] = 0; bin64Arr[j+3] = 1; break; case 'E': bin64Arr[j] = 1; bin64Arr[j+1] = 1; bin64Arr[j+2] = 1; bin64Arr[j+3] = 0; break; case 'F': bin64Arr[j] = 1; bin64Arr[j+1] = 1; bin64Arr[j+2] = 1; bin64Arr[j+3] = 1; break; } } } // Float --> Binary void float2bin(float f){ int count=0,i,j,k,arr[32],newValue,expArr[8]; float floatPart,newf; if(f<0) newf=f*(-1); else newf=f; int intPart = newf; int2bin(intPart); for(i=0;i<32;i++){ arr[i]=0; } for(i=31;i>=0;i--){ if(binaryArr[i]==0) count++; if(binaryArr[i]==1) break; } for(j=0;j<(32-count);j++){ arr[j] = binaryArr[i]; i--; } i=j-1; floatPart = newf-intPart; k=0; while(floatPart!=0.0){ if(k==0) floatPart = floatPart*2; newValue = floatPart; arr[j]=newValue; floatPart = (floatPart-newValue)*2; j++; k++; } int exponent = 127+i; for(j=0;j<8;j++){ expArr[j]=0; } k=0; while(exponent != 0){ expArr[7-k] = exponent%2; exponent = exponent/2; k++; } for(j=1;j<9;j++){ binaryArr[j] = expArr[j-1]; } k=1; for(j=9;j<32;j++){ binaryArr[j]= arr[k]; k++; } if(f<0) binaryArr[0]=1; else binaryArr[0]=0; } // Float --> Hexadecimal void float2hex(){ int i; bin2hex(); fprintf(stdout,"0x"); for(i=7;i>=0;i--){ fprintf(stdout,"%c",hexArr[i]); } fprintf(stdout,"\n"); } //Double --> Binary void double2bin(float f){ int count=0,i,j,k,arr[64],newValue,expArr[11]; float floatPart,newf; if(f<0) newf=f*(-1); else newf=f; int intPart = newf; int2bin(intPart); for(i=0;i<64;i++){ arr[i]=0; } for(i=31;i>=0;i--){ if(binaryArr[i]==0) count++; if(binaryArr[i]==1) break; } for(j=0;j<(32-count);j++){ arr[j] = binaryArr[i]; i--; } i=j-1; floatPart = newf-intPart; k=0; while(floatPart!=0.0){ if(k==0) floatPart = floatPart*2; newValue = floatPart; arr[j] = newValue; floatPart = (floatPart-newValue)*2; j++; k++; } int exponent = 1023+i; for(j=0;j<12;j++){ expArr[j]=0; } k=0; while(exponent != 0){ expArr[10-k] = exponent%2; exponent = exponent/2; k++; } for(j=1;j<11;j++){ bin64Arr[j] = expArr[j-1]; } k=1; for(j=12;j<64;j++){ bin64Arr[j]= arr[k]; k++; } if(f<0) bin64Arr[0]=1; else bin64Arr[0]=0; } // Double --> Hexadecimal void double2hex(){ int i; bin2hex16(); fprintf(stdout,"0x"); for(i=15;i>=0;i--){ fprintf(stdout,"%c",hexArr16[i]); } fprintf(stdout,"\n"); } // Binary (64 bits)--> Hexadecimal(16 bits) void bin2hex16(){ int i,j; for(i=60,j=0; i>=0 && j<16 ; i=i-4,j++){ if( bin64Arr[i]==0 && bin64Arr[i+1]==0 && bin64Arr[i+2]==0 && bin64Arr[i+3]==0 ) hexArr16[j] = '0'; else if( bin64Arr[i]==0 && bin64Arr[i+1]==0 && bin64Arr[i+2]==0 && bin64Arr[i+3]==1) hexArr16[j] = '1'; else if( bin64Arr[i]==0 && bin64Arr[i+1]==0 && bin64Arr[i+2]==1 && bin64Arr[i+3]==0 ) hexArr16[j] = '2'; else if( bin64Arr[i]==0 && bin64Arr[i+1]==0 && bin64Arr[i+2]==1 && bin64Arr[i+3]==1 ) hexArr16[j] = '3'; else if( bin64Arr[i]==0 && bin64Arr[i+1]==1 && bin64Arr[i+2]==0 && bin64Arr[i+3]==0 ) hexArr16[j] = '4'; else if( bin64Arr[i]==0 && bin64Arr[i+1]==1 && bin64Arr[i+2]==0 && bin64Arr[i+3]==1 ) hexArr16[j] = '5'; else if( bin64Arr[i]==0 && bin64Arr[i+1]==1 && bin64Arr[i+2]==1 && bin64Arr[i+3]==0 ) hexArr16[j] = '6'; else if( bin64Arr[i]==0 && bin64Arr[i+1]==1 && bin64Arr[i+2]==1 && bin64Arr[i+3]==1 ) hexArr16[j] = '7'; else if( bin64Arr[i]==1 && bin64Arr[i+1]==0 && bin64Arr[i+2]==0 && bin64Arr[i+3]==0 ) hexArr16[j] = '8'; else if( bin64Arr[i]==1 && bin64Arr[i+1]==0 && bin64Arr[i+2]==0 && bin64Arr[i+3]==1 ) hexArr16[j] = '9'; else if( bin64Arr[i]==1 && bin64Arr[i+1]==0 && bin64Arr[i+2]==1 && bin64Arr[i+3]==0 ) hexArr16[j] = 'A'; else if( bin64Arr[i]==1 && bin64Arr[i+1]==0 && bin64Arr[i+2]==1 && bin64Arr[i+3]==1 ) hexArr16[j] = 'B'; else if( bin64Arr[i]==1 && bin64Arr[i+1]==1 && bin64Arr[i+2]==0 && bin64Arr[i+3]==0 ) hexArr16[j] = 'C'; else if( bin64Arr[i]==1 && bin64Arr[i+1]==1 && bin64Arr[i+2]==0 && bin64Arr[i+3]==1 ) hexArr16[j] = 'D'; else if( bin64Arr[i]==1 && bin64Arr[i+1]==1 && bin64Arr[i+2]==1 && bin64Arr[i+3]==0 ) hexArr16[j] = 'E'; else if( bin64Arr[i]==1 && bin64Arr[i+1]==1 && bin64Arr[i+2]==1 && bin64Arr[i+3]==1 ) hexArr16[j] = 'F'; } }
C
#include "utl/assert.h" #include "utl/test.h" #include "../src/linkedlist.c" CMC_CREATE_UNIT(linkedlist_test, true, { CMC_CREATE_TEST(new, { linkedlist *ll = ll_new(); cmc_assert_not_equals(ptr, NULL, ll); bool passed = ll->count == 0 && ll->head == NULL && ll->tail == NULL; cmc_assert_equals(size_t, 0, ll_count(ll)); cmc_assert_equals(ptr, NULL, ll->head); cmc_assert_equals(ptr, NULL, ll->tail); CMC_TEST_PASS_ELSE_FAIL(passed); ll_free(ll); }); CMC_CREATE_TEST(clear[count capacity], { linkedlist *ll = ll_new(); cmc_assert_not_equals(ptr, NULL, ll); for (size_t i = 0; i < 50; i++) ll_push_back(ll, i); cmc_assert_equals(size_t, 50, ll_count(ll)); ll_clear(ll); cmc_assert_equals(size_t, 0, ll_count(ll)); CMC_TEST_PASS_ELSE_FAIL(ll_count(ll) == 0); ll_free(ll); }); CMC_CREATE_TEST(clear[edge_case:count = 0], { linkedlist *ll = ll_new(); cmc_assert_not_equals(ptr, NULL, ll); ll_clear(ll); cmc_assert_equals(size_t, 0, ll_count(ll)); CMC_TEST_PASS_ELSE_FAIL(ll_count(ll) == 0); ll_free(ll); }); CMC_CREATE_TEST(push_front[count], { linkedlist *ll = ll_new(); cmc_assert_not_equals(ptr, NULL, ll); ll_push_front(ll, 1); cmc_assert_not_equals(ptr, NULL, ll->head); cmc_assert_not_equals(ptr, NULL, ll->tail); cmc_assert_equals(size_t, 1, ll_count(ll)); CMC_TEST_PASS_ELSE_FAIL(ll->head && ll->tail && ll_count(ll) == 1); ll_free(ll); }); CMC_CREATE_TEST(push_front[item_preservation], { linkedlist *ll = ll_new(); cmc_assert_not_equals(ptr, NULL, ll); for (size_t i = 0; i < 200; i++) ll_push_front(ll, i); bool passed = true; for (size_t i = 0; i < ll_count(ll); i++) { passed = passed && ll_get(ll, i) == (ll_count(ll) - i - 1); cmc_assert_equals(size_t, ll_get(ll, i), ll_count(ll) - i - 1); } CMC_TEST_PASS_ELSE_FAIL(passed && ll_count(ll) == 200); ll_free(ll); }); });
C
/* API for thread handling */ /*********************************************************************/ /* Global includes */ /*********************************************************************/ #include <stdio.h> #include <unistd.h> #include <pthread.h> #include <signal.h> #include <sys/eventfd.h> #include <poll.h> #include <errno.h> /*********************************************************************/ /* Local includes */ /*********************************************************************/ #include "base.h" #include "integ_log.h" #include "os.h" /*********************************************************************/ /* Global variables */ /*********************************************************************/ /*********************************************************************/ /* API functions */ /*********************************************************************/ int OS_sem_init(OS_semaphore_t *i_sem, t_uint32 i_value) { int ret = 0; if (!i_sem) ret = -1; if (0 == ret) { /* Check init status for the semaphore */ if (i_sem->is_init != OS_RET_OK) { /* Semaphores are not to be shared among processes */ ret = sem_init(&i_sem->semaphore, 0, i_value); if (0 == ret) i_sem->is_init = OS_RET_OK; } } if (0 == ret) i_sem->init_value = i_value; return ret; } int OS_sem_destroy(OS_semaphore_t *i_sem) { int ret = 0; if (NULL == i_sem) ret = -1; if (0 == ret) { if (OS_RET_KO == i_sem->is_init) ret = 0; else { ret = sem_destroy(&i_sem->semaphore); } if (0 == ret) i_sem->is_init = OS_RET_KO; } return ret; } int OS_sem_post(OS_semaphore_t *i_sem) { int ret = 0; if (NULL == i_sem) { LOG_ERR("OS : null pointer to semaphore"); ret = -1; } if (0 == ret) { if (OS_RET_OK == i_sem->is_init) ret = sem_post(&i_sem->semaphore); else { LOG_ERR("OS : semaphore not initialised"); ret = -2; } } return ret; } int OS_sem_wait(OS_semaphore_t *i_sem) { int ret = 0; if (NULL == i_sem) { LOG_ERR("OS : null pointer to semaphore"); ret = -1; } if (0 == ret) { if (OS_RET_OK == i_sem->is_init) ret = sem_wait(&i_sem->semaphore); else { LOG_ERR("OS : semaphore not initialised"); ret = -2; } } return ret; } int OS_sem_trywait(OS_semaphore_t *i_sem) { int ret = 0; if (NULL == i_sem) { LOG_ERR("OS : null pointer to semaphore"); ret = -1; } if (0 == ret) { if (OS_RET_OK == i_sem->is_init) ret = sem_trywait(&i_sem->semaphore); else { LOG_ERR("OS : semaphore not initialised"); ret = -2; } if ( (-1 == ret) && (EAGAIN == errno) ) ret = 1; } return ret; } /* Same function as OS_sem_init but with eventfd */ int OS_semfd_init(OS_semfd_t *i_sem, t_uint32 i_value) { int ret = 0; if (!i_sem) ret = -1; if (0 == ret) { /* Check init status for the semaphore */ if (i_sem->is_init != OS_RET_OK) { /* Declare the eventfd to be a semaphore */ i_sem->fd = eventfd(i_value, EFD_SEMAPHORE); if (-1 == i_sem->fd) { LOG_ERR("OS : error while creating semaphore file descriptor, errno = %d", errno); i_sem->is_init = OS_RET_KO; ret = -2; } else { i_sem->is_init = OS_RET_OK; ret = 0; } } } if (0 == ret) i_sem->init_value = i_value; return ret; } int OS_semfd_destroy(OS_semfd_t *i_sem) { int ret = 0; if (NULL == i_sem) ret = -1; if (0 == ret) { if (OS_RET_KO == i_sem->is_init) ret = 0; else ret = close(i_sem->fd); if (0 == ret) { i_sem->init_value = 0; i_sem->is_init = OS_RET_KO; } else { LOG_ERR("OS : error while closing semaphore file descriptor, errno = %d", errno); ret = -2; } } return ret; } int OS_semfd_post(OS_semfd_t *i_sem) { int ret = 0; if (NULL == i_sem) { LOG_ERR("OS : null pointer to semaphore"); ret = -1; } if (0 == ret) { if (OS_RET_OK == i_sem->is_init) { t_uint64 buf; buf = 1; ret = write(i_sem->fd, &buf, sizeof(buf)); if (sizeof(buf) == ret) ret = 0; else { LOG_ERR("OS : error while posting to semaphore, ret = %d (expected %d)", ret, sizeof(buf)); ret = -2; } } else { LOG_ERR("OS : semaphore not initialised"); ret = -4; } } return ret; } int OS_semfd_wait(OS_semfd_t *i_sem) { int ret = 0; if (NULL == i_sem) { LOG_ERR("OS : null pointer to semaphore"); ret = -1; } if (0 == ret) { if (OS_RET_OK == i_sem->is_init) { t_uint64 buf; buf = 1; ret = read(i_sem->fd, &buf, sizeof(buf)); if (sizeof(buf) == ret) ret = 0; else ret = -2; } else { LOG_ERR("OS : semaphore not initialised"); ret = -4; } } return ret; } int OS_semfd_trywait(OS_semfd_t *i_sem) { int ret = 0; if (NULL == i_sem) { LOG_ERR("OS : null pointer to semaphore"); ret = -1; } if (0 == ret) { if (OS_RET_OK == i_sem->is_init) { struct pollfd try_fd; try_fd.fd = i_sem->fd; try_fd.events = POLLIN; /* Check whether the file descriptor is ready for reading */ ret = poll(&try_fd, 1, 0); /* Read only if the call would not block */ if ( (1 == ret) && (POLLIN & try_fd.revents) ) { t_uint64 buf; buf = 1; ret = read(i_sem->fd, &buf, sizeof(buf)); if (sizeof(buf) == ret) ret = 0; else ret = -2; } else { /* Call would block */ ret = 1; } } else { LOG_ERR("OS : semaphore not initialised"); ret = -4; } } return ret; } int OS_semfd_timedwait(OS_semfd_t *i_sem, int i_timeout) { int ret = 0; if (NULL == i_sem) { LOG_ERR("OS : null pointer to semaphore"); ret = -1; } if (0 == ret) { if (OS_RET_OK == i_sem->is_init) { struct pollfd try_fd; try_fd.fd = i_sem->fd; try_fd.events = POLLIN; /* Check whether the file descriptor is ready for reading */ ret = poll(&try_fd, 1, i_timeout); /* Read only if the call would not block */ if ( (1 == ret) && (POLLIN & try_fd.revents) ) { t_uint64 buf; buf = 1; ret = read(i_sem->fd, &buf, sizeof(buf)); if (sizeof(buf) == ret) ret = 0; else ret = -2; } else { /* Call would block */ ret = 1; } } else { LOG_ERR("OS : semaphore not initialised"); ret = -4; } } return ret; } /*********************************************************************/ /* Fonctions locales */ /*********************************************************************/
C
#include<stdio.h> int main() { int n1,n2,n3,max1,max2; printf("number 1 : "); scanf("%d",&n1); printf("number 2 : "); scanf("%d",&n2); printf("number 3 : "); scanf("%d",&n3); if(n1>=n2 && n1>=n3) { max1 = n1; if(n2 >= n3) {max2 = n2;} else {max2 = n3;} } if(n2>=n1 && n2>=n3) { max1 = n2; if(n1 >= n3) {max2 = n1;} else {max2 = n3;} } if(n3>=n1 && n3>=n2) { max1 = n3; if(n1 >= n2) {max2 = n1;} else {max2 = n2;} } printf("%d and %d",max1,max2); return 0; }
C
#include <stdio.h> void minmax(int *data, int *max, int *min); int main(void) { int i; int max; int min; int array[10]; printf("0~100の範囲の整数値を複数入力せよ。\n"); printf("入力要素の上限は10とする。\n"); printf("-1が入力された場合入力終了とみなす。\n"); for (i=0; i<10; i++) { printf("%dつ目の数字を入力してください\n", i + 1); scanf("%d", &array[i]); if (array[i] == -1) { break; } } minmax(array, &max, &min); printf("min:%d max:%d\n", min, max); return 0; } void minmax(int *data, int *max, int *min) { int j; j = 0; *min = 100; *max = 0; while (data[j] != -1) { if (data[j] > *max) *max = data[j]; if (data[j] < *min) *min = data[j]; j++; } return; }
C
/* _rename.c -- Implementation of the low-level rename() routine * * Copyright (c) 2004 National Semiconductor Corporation * * The authors hereby grant permission to use, copy, modify, distribute, * and license this software and its documentation for any purpose, provided * that existing copyright notices are retained in all copies and that this * notice is included verbatim in any distributions. No written agreement, * license, or royalty fee is required for any of the authorized uses. * Modifications to this software may be copyrighted by their authors * and need not follow the licensing terms described here, provided that * the new terms are clearly indicated on the first page of each file where * they apply. */ #include <fcntl.h> #include <stdio.h> #include <unistd.h> #include <alloca.h> #include <errno.h> int _rename (char *from, char *to) { void* buf; int f_from; int f_to; int size; f_from = open(from,O_RDONLY); if (f_from < 0) { errno = ENOENT; return -1; }; f_to = open(to,O_CREAT|O_WRONLY|O_EXCL); if (f_to < 0) { close(f_from); errno = EACCES; return -1; }; buf = alloca(32768); do { size = read(f_from, buf, 32768); if (size >= 0) size = write(f_to, buf, size); }while (size == 32768); close(f_to); close(f_from); if (size == -1) { errno = EACCES; return -1; }; remove(from); return (0); };
C
#include <string.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <termios.h> #include <signal.h> int alarmFlag=0, alarmCounter=0; int maxPackageSize = 512, retries = 3, timeOut = 3; int cntTrasmit = 0, cntRetransmit = 0, cntReceived = 0, cntRejSend = 0, cntRejReceived = 0, cntTimeOuts = 0; int generateError = 0; unsigned int randInterval(unsigned int min, unsigned int max) { int r; const unsigned int range = 1 + max - min; const unsigned int buckets = RAND_MAX / range; const unsigned int limit = buckets * range; do { r = rand(); } while (r >= limit); return min + (r / buckets); } void atende() { cntTimeOuts++; alarmCounter++; printf("alarme # %d\n", alarmCounter); alarmFlag=1; } void printHex(unsigned char* hexMsg, int size) { printf("HEX ARRAY:"); int i; for(i=0; i<size; i++) { printf(" 0x%02X",hexMsg[i]); } printf("\n"); }
C
#include <stdio.h> #include <pthread.h> #include <sys/types.h> #include <sys/syscall.h> #if 0 int *func(void *p) { printf("thread executed\n"); return 0; } int main (void) { pthread_t th; int s; s = pthread_create(&th, NULL, func, NULL); if(s != 0) { perror("thread create"); return 0; } pthread_exit(NULL); return 0; } #endif #if 1 int main (void) { char *s = "hello""world"; printf("%s\n",s); return 0; } #endif
C
#include <stdio.h> #include <stdlib.h> int main() { void Binary(int n) { int A[n]; if (n < 1) { for (int i = 0; i < n; i++) printf("%d", A[i]); } else { A[n - 1] = 0; Binary(n - 1); A[n - 1] = 1; Binary(n - 1); } } Binary(3); return 0; }
C
#include<stdio.h> #include<string.h> int main(){ int n,x,d[100],e[100],resp=0,i; char c; while(scanf("%d",&n)!=EOF){ memset(d,0,sizeof(d)); memset(e,0,sizeof(e)); while(n--){ scanf("%d %c",&x,&c); switch(c){ case 'D': d[x]++; break; case 'E': e[x]++; break; } } for (i=0;i<100;i++){ if (d[i]<e[i]) resp+=d[i]; else resp+=e[i]; } printf("%d\n",resp); resp=0; } return 0; }
C
#include<stdio.h> int main() { int C; scanf_s("%d", &C); for (int i = 1; i <= C;i++) { int N; int cnt = 0; double score[1000]; double sum = 0, avr; scanf_s("%d", &N); for (int j = 0; j < N; i++) { scanf_s("%lf", &score[j]); sum += score[j]; } avr =sum / N; for (int j = 0; j < N;j++) { if (avr<score[j]) cnt++; } printf("%.3lf%%\n", (double)cnt/N*100); } return 0; }
C
#include "libft.h" #include <stdio.h> int main(void) { char str[] = "You're slow, even when you are falling."; ft_putstr("str: "); ft_putendl(str); ft_putstr("call ft_strstr(str, \"even\", 25): "); ft_putendl(ft_strnstr(str, "even", 25)); ft_putstr("call ft_strstr(str, \"even\", 10): "); printf("%s\n", ft_strnstr(str, "even", 10)); return (0); }
C
#include <stdio.h> struct t{ unsigned long long int soma; int next; }vet[1000]; unsigned long long int v[1000], k, R, euros,aux; int N; int main(void) { int t,inst,i,j,p; scanf("%d",&t); for(inst=1;inst<=t;inst++){ scanf("%llu %llu %d",&R, &k, &N); for(i=0;i<N;i++) scanf("%llu",&v[i]); for(i=0;i<N;i++) { j=i+1; if(j>=N) j =0; vet[i].soma = v[i]; while(v[j]+vet[i].soma <= k && j != i) { vet[i].soma+= v[j]; j++; if(j>=N) j=0; } vet[i].next = j; } euros = i = 0; while(R--){ euros += vet[i].soma; i = vet[i].next; } printf("Case #%d: %llu\n",inst,euros); } return 0; }
C
#include "holberton.h" /** * _sqrt_recursion - function that returns the natural square root of a num * @n: integer to find square root of * Return: int */ int _sqrt_recursion(int n) { int sqr; sqr = _pow(1, n); return (sqr); } /** * _pow - checks whether the square of a number * @x: will be square, incremented * @y: limiter * Return: int */ int _pow(int x, int y) { if ((x * x) < y) return (_pow((x + 1), y)); if ((x * x) == y) return (x); if ((x * x) > y) return (-1); return (x); }
C
// ECE 6110 - Quiz 2 - Tyler McCormick // // This code implements a function generator, where a user can choose from a sine, sawtooth, or square wave. The amplitude of all // three functions is adjustable from 1-9, as well as the frequency, in Hz. For a square wave, the duty cycle can also be chosen. // // All choices are entered via a UART console, such as Hyperterminal or PUTTY. The output can be viewed via selecting the variable // "signalOutput" in STM32CubeMonitor. #include "main.h" #include <stdbool.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <math.h> TIM_HandleTypeDef htim16; TIM_HandleTypeDef htim17; UART_HandleTypeDef huart1; void SystemClock_Config(void); static void MX_GPIO_Init(void); static void MX_TIM16_Init(void); static void MX_TIM17_Init(void); static void MX_USART1_UART_Init(void); void squareInit(void); void generateSquare(void); void sinInit(void); void generateSin(void); void generateSaw(void); void serialPrint(char buffer[]); int squareSignal = 0; float sinSignal; int sigNum = -1; int sinScale = 1; int sawScale = 1; float signalOutput; int sinCount = 0; int sawCount = 0; float sinArray[100] = {0}; float xArray[100] = {0}; int squareScale = 5; // This value in the ARR results in a sin wave with f=1Hz int baseSinFreq = 99; // Frequency of the signal in Hz int freq = 1; // %Duty cycle of wave float dutyCycle = 50; float duty; // Used for Square Wave generation // This corresponds to 1 Hz int timPeriod = 5000; uint32_t masterARR = 0; int main(void) { HAL_Init(); SystemClock_Config(); MX_GPIO_Init(); MX_TIM16_Init(); MX_TIM17_Init(); MX_USART1_UART_Init(); HAL_TIM_Base_Start(&htim16); __HAL_TIM_ENABLE_IT(&htim16, TIM_IT_UPDATE ); // The x-increment value float baseNum = 0.01; // Create the x-array // // This is also used for the saw-tooth wave for (int i = 0 ; i<100; i++) { xArray[i] = i*baseNum; } // Pre-compute sine, and store the results // in the array, these values only change amplitude // for (int i = 0 ; i<100; i++) { sinArray[i] = sin(6.3*xArray[i]); } while (1) { // Choice storage char waveSel[2] = {0}; char ampSel[2] = {0}; char freqSel[2] = {0}; char dutySel[2] = {0}; char choice[2] = {0}; serialPrint(" \n\r"); serialPrint("Select an option: A) Sine B) Sawtooth C) Square : "); while(HAL_OK != HAL_UART_Receive(&huart1, (uint8_t*)waveSel , 1, HAL_MAX_DELAY)); serialPrint(waveSel); serialPrint(" \n\r"); serialPrint("Enter an amplitude: "); while(HAL_OK != HAL_UART_Receive(&huart1, (uint8_t*)ampSel , 1, HAL_MAX_DELAY)); serialPrint(ampSel); serialPrint(" \n\r"); serialPrint("Enter a frequency (in Hz): "); while(HAL_OK != HAL_UART_Receive(&huart1, (uint8_t*)freqSel , 1, HAL_MAX_DELAY)); serialPrint(freqSel); serialPrint(" Hz"); serialPrint(" \n\r"); if (waveSel[0] == 67) { serialPrint("Enter a duty cycle: "); while(HAL_OK != HAL_UART_Receive(&huart1, (uint8_t*)dutySel , 2, HAL_MAX_DELAY)); char tempS[2] = {0}; tempS[0] = dutySel[0]; tempS[1] = dutySel[1]; serialPrint(tempS); serialPrint("%"); serialPrint(" \n\r"); } serialPrint("Confirm selection? (y/n): "); while(HAL_OK != HAL_UART_Receive(&huart1, (uint8_t*)choice , 1, HAL_MAX_DELAY)); serialPrint(choice); serialPrint(" \n\r"); // Yes, confirm an start wave generation if (choice[0] == 121) { sinScale = sawScale = squareScale = atoi(ampSel); freq = atoi(freqSel); if (waveSel[0] == 65) { sinInit(); sigNum = 0; } else if (waveSel[0] == 66) { sinInit(); sigNum = 1; } else if (waveSel[0] == 67) { dutyCycle = (float)atoi(dutySel); squareInit(); sigNum = 2; } else { sigNum = -1; } } } } // Timer done interrupt void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { // Make sure that this is the timer16 interrupt if (htim == &htim16 ) { if (sigNum == 0) { generateSin(); } else if (sigNum == 1) { generateSaw(); } else if (sigNum == 2) { generateSquare(); } else { signalOutput = 0; } } } void squareInit(void) { // Adjust the frequency to match the entered value float per = timPeriod/freq-1; TIM16->ARR = (uint32_t)per; masterARR = (uint32_t)(per*2); duty = dutyCycle/100; } void sinInit(void) { // Just adjust the timer interrupt for // printing the sine values, they are just // printer further or closer together float sinARR = 0; sinARR = ((baseSinFreq+1)/freq)-1; TIM16->ARR = (uint32_t)sinARR; } void generateSaw(void) { if (sawCount == 100) { sawCount = 0; } // Reads straight from the array of 100 values from 0->100 // in 0.01 increments signalOutput = sawScale*xArray[sawCount]; sawCount++; } void generateSin(void) { if (sinCount == 100) { sinCount = 0; } // Reads from the sine array, which has been pre-computed to save cpu time signalOutput = sinScale*sinArray[sinCount]; sinCount++; } void generateSquare(void) { // Toggles the output if (signalOutput == 0) { signalOutput = 1; } else if (signalOutput >= 1) { signalOutput = 0; } // Scales the output based on the amplitude requirement signalOutput = signalOutput*squareScale; // This is actually pretty cool, it adjusts the // ARR value based on the duty cycle along with 1, // this way it always ensures that the whole frequency is obeyed duty = 1-duty; TIM16->ARR = (uint32_t)((duty)*(masterARR+1)-1); } // Just to avoid copy-pasting this awful string every time void serialPrint(char buffer[]) { HAL_UART_Transmit(&huart1, (uint8_t*)buffer , strlen(buffer), HAL_MAX_DELAY); } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; RCC_PeriphCLKInitTypeDef PeriphClkInit = {0}; /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI; RCC_OscInitStruct.MSIState = RCC_MSI_ON; RCC_OscInitStruct.MSICalibrationValue = 0; RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_6; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_MSI; RCC_OscInitStruct.PLL.PLLM = 1; RCC_OscInitStruct.PLL.PLLN = 40; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV7; RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2; RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /** Initializes the CPU, AHB and APB buses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK) { Error_Handler(); } PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1; PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK2; if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK) { Error_Handler(); } /** Configure the main internal regulator output voltage */ if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK) { Error_Handler(); } } /** * @brief TIM16 Initialization Function * @param None * @retval None */ static void MX_TIM16_Init(void) { /* USER CODE BEGIN TIM16_Init 0 */ /* USER CODE END TIM16_Init 0 */ /* USER CODE BEGIN TIM16_Init 1 */ /* USER CODE END TIM16_Init 1 */ htim16.Instance = TIM16; htim16.Init.Prescaler = 7999; htim16.Init.CounterMode = TIM_COUNTERMODE_UP; htim16.Init.Period = 49; htim16.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; htim16.Init.RepetitionCounter = 0; htim16.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; if (HAL_TIM_Base_Init(&htim16) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN TIM16_Init 2 */ /* USER CODE END TIM16_Init 2 */ } /** * @brief TIM17 Initialization Function * @param None * @retval None */ static void MX_TIM17_Init(void) { /* USER CODE BEGIN TIM17_Init 0 */ /* USER CODE END TIM17_Init 0 */ /* USER CODE BEGIN TIM17_Init 1 */ /* USER CODE END TIM17_Init 1 */ htim17.Instance = TIM17; htim17.Init.Prescaler = 0; htim17.Init.CounterMode = TIM_COUNTERMODE_UP; htim17.Init.Period = 65535; htim17.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; htim17.Init.RepetitionCounter = 0; htim17.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; if (HAL_TIM_Base_Init(&htim17) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN TIM17_Init 2 */ /* USER CODE END TIM17_Init 2 */ } /** * @brief USART1 Initialization Function * @param None * @retval None */ static void MX_USART1_UART_Init(void) { /* USER CODE BEGIN USART1_Init 0 */ /* USER CODE END USART1_Init 0 */ /* USER CODE BEGIN USART1_Init 1 */ /* USER CODE END USART1_Init 1 */ huart1.Instance = USART1; huart1.Init.BaudRate = 115200; huart1.Init.WordLength = UART_WORDLENGTH_8B; huart1.Init.StopBits = UART_STOPBITS_1; huart1.Init.Parity = UART_PARITY_NONE; huart1.Init.Mode = UART_MODE_TX_RX; huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE; huart1.Init.OverSampling = UART_OVERSAMPLING_16; huart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE; huart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT; if (HAL_UART_Init(&huart1) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN USART1_Init 2 */ /* USER CODE END USART1_Init 2 */ } /** * @brief GPIO Initialization Function * @param None * @retval None */ static void MX_GPIO_Init(void) { GPIO_InitTypeDef GPIO_InitStruct = {0}; /* GPIO Ports Clock Enable */ __HAL_RCC_GPIOE_CLK_ENABLE(); __HAL_RCC_GPIOC_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); __HAL_RCC_GPIOD_CLK_ENABLE(); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(GPIOE, M24SR64_Y_RF_DISABLE_Pin|M24SR64_Y_GPO_Pin|ISM43362_RST_Pin, GPIO_PIN_RESET); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(GPIOA, ARD_D10_Pin|SPBTLE_RF_RST_Pin|ARD_D9_Pin, GPIO_PIN_RESET); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(GPIOB, ARD_D8_Pin|ISM43362_BOOT0_Pin|ISM43362_WAKEUP_Pin|LED2_Pin |SPSGRF_915_SDN_Pin|ARD_D5_Pin, GPIO_PIN_RESET); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(GPIOD, USB_OTG_FS_PWR_EN_Pin|PMOD_RESET_Pin|STSAFE_A100_RESET_Pin, GPIO_PIN_RESET); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(SPBTLE_RF_SPI3_CSN_GPIO_Port, SPBTLE_RF_SPI3_CSN_Pin, GPIO_PIN_SET); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(GPIOC, VL53L0X_XSHUT_Pin|LED3_WIFI__LED4_BLE_Pin, GPIO_PIN_RESET); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(SPSGRF_915_SPI3_CSN_GPIO_Port, SPSGRF_915_SPI3_CSN_Pin, GPIO_PIN_SET); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(ISM43362_SPI3_CSN_GPIO_Port, ISM43362_SPI3_CSN_Pin, GPIO_PIN_SET); /*Configure GPIO pins : M24SR64_Y_RF_DISABLE_Pin M24SR64_Y_GPO_Pin ISM43362_RST_Pin ISM43362_SPI3_CSN_Pin */ GPIO_InitStruct.Pin = M24SR64_Y_RF_DISABLE_Pin|M24SR64_Y_GPO_Pin|ISM43362_RST_Pin|ISM43362_SPI3_CSN_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(GPIOE, &GPIO_InitStruct); /*Configure GPIO pins : USB_OTG_FS_OVRCR_EXTI3_Pin SPSGRF_915_GPIO3_EXTI5_Pin SPBTLE_RF_IRQ_EXTI6_Pin ISM43362_DRDY_EXTI1_Pin */ GPIO_InitStruct.Pin = USB_OTG_FS_OVRCR_EXTI3_Pin|SPSGRF_915_GPIO3_EXTI5_Pin|SPBTLE_RF_IRQ_EXTI6_Pin|ISM43362_DRDY_EXTI1_Pin; GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOE, &GPIO_InitStruct); /*Configure GPIO pin : BUTTON_EXTI13_Pin */ GPIO_InitStruct.Pin = BUTTON_EXTI13_Pin; GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(BUTTON_EXTI13_GPIO_Port, &GPIO_InitStruct); /*Configure GPIO pins : ARD_A5_Pin ARD_A4_Pin ARD_A3_Pin ARD_A2_Pin ARD_A1_Pin ARD_A0_Pin */ GPIO_InitStruct.Pin = ARD_A5_Pin|ARD_A4_Pin|ARD_A3_Pin|ARD_A2_Pin |ARD_A1_Pin|ARD_A0_Pin; GPIO_InitStruct.Mode = GPIO_MODE_ANALOG_ADC_CONTROL; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); /*Configure GPIO pins : ARD_D1_Pin ARD_D0_Pin */ GPIO_InitStruct.Pin = ARD_D1_Pin|ARD_D0_Pin; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Alternate = GPIO_AF8_UART4; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /*Configure GPIO pins : ARD_D10_Pin SPBTLE_RF_RST_Pin ARD_D9_Pin */ GPIO_InitStruct.Pin = ARD_D10_Pin|SPBTLE_RF_RST_Pin|ARD_D9_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /*Configure GPIO pin : ARD_D4_Pin */ GPIO_InitStruct.Pin = ARD_D4_Pin; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; GPIO_InitStruct.Alternate = GPIO_AF1_TIM2; HAL_GPIO_Init(ARD_D4_GPIO_Port, &GPIO_InitStruct); /*Configure GPIO pin : ARD_D7_Pin */ GPIO_InitStruct.Pin = ARD_D7_Pin; GPIO_InitStruct.Mode = GPIO_MODE_ANALOG_ADC_CONTROL; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(ARD_D7_GPIO_Port, &GPIO_InitStruct); /*Configure GPIO pins : ARD_D13_Pin ARD_D12_Pin ARD_D11_Pin */ GPIO_InitStruct.Pin = ARD_D13_Pin|ARD_D12_Pin|ARD_D11_Pin; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Alternate = GPIO_AF5_SPI1; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /*Configure GPIO pin : ARD_D3_Pin */ GPIO_InitStruct.Pin = ARD_D3_Pin; GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(ARD_D3_GPIO_Port, &GPIO_InitStruct); /*Configure GPIO pin : ARD_D6_Pin */ GPIO_InitStruct.Pin = ARD_D6_Pin; GPIO_InitStruct.Mode = GPIO_MODE_ANALOG_ADC_CONTROL; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(ARD_D6_GPIO_Port, &GPIO_InitStruct); /*Configure GPIO pins : ARD_D8_Pin ISM43362_BOOT0_Pin ISM43362_WAKEUP_Pin LED2_Pin SPSGRF_915_SDN_Pin ARD_D5_Pin SPSGRF_915_SPI3_CSN_Pin */ GPIO_InitStruct.Pin = ARD_D8_Pin|ISM43362_BOOT0_Pin|ISM43362_WAKEUP_Pin|LED2_Pin |SPSGRF_915_SDN_Pin|ARD_D5_Pin|SPSGRF_915_SPI3_CSN_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /*Configure GPIO pins : DFSDM1_DATIN2_Pin DFSDM1_CKOUT_Pin */ GPIO_InitStruct.Pin = DFSDM1_DATIN2_Pin|DFSDM1_CKOUT_Pin; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; GPIO_InitStruct.Alternate = GPIO_AF6_DFSDM1; HAL_GPIO_Init(GPIOE, &GPIO_InitStruct); /*Configure GPIO pins : QUADSPI_CLK_Pin QUADSPI_NCS_Pin OQUADSPI_BK1_IO0_Pin QUADSPI_BK1_IO1_Pin QUAD_SPI_BK1_IO2_Pin QUAD_SPI_BK1_IO3_Pin */ GPIO_InitStruct.Pin = QUADSPI_CLK_Pin|QUADSPI_NCS_Pin|OQUADSPI_BK1_IO0_Pin|QUADSPI_BK1_IO1_Pin |QUAD_SPI_BK1_IO2_Pin|QUAD_SPI_BK1_IO3_Pin; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Alternate = GPIO_AF10_QUADSPI; HAL_GPIO_Init(GPIOE, &GPIO_InitStruct); /*Configure GPIO pins : INTERNAL_I2C2_SCL_Pin INTERNAL_I2C2_SDA_Pin */ GPIO_InitStruct.Pin = INTERNAL_I2C2_SCL_Pin|INTERNAL_I2C2_SDA_Pin; GPIO_InitStruct.Mode = GPIO_MODE_AF_OD; GPIO_InitStruct.Pull = GPIO_PULLUP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Alternate = GPIO_AF4_I2C2; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /*Configure GPIO pins : INTERNAL_UART3_TX_Pin INTERNAL_UART3_RX_Pin */ GPIO_InitStruct.Pin = INTERNAL_UART3_TX_Pin|INTERNAL_UART3_RX_Pin; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Alternate = GPIO_AF7_USART3; HAL_GPIO_Init(GPIOD, &GPIO_InitStruct); /*Configure GPIO pins : LPS22HB_INT_DRDY_EXTI0_Pin LSM6DSL_INT1_EXTI11_Pin ARD_D2_Pin HTS221_DRDY_EXTI15_Pin PMOD_IRQ_EXTI12_Pin */ GPIO_InitStruct.Pin = LPS22HB_INT_DRDY_EXTI0_Pin|LSM6DSL_INT1_EXTI11_Pin|ARD_D2_Pin|HTS221_DRDY_EXTI15_Pin |PMOD_IRQ_EXTI12_Pin; GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOD, &GPIO_InitStruct); /*Configure GPIO pins : USB_OTG_FS_PWR_EN_Pin SPBTLE_RF_SPI3_CSN_Pin PMOD_RESET_Pin STSAFE_A100_RESET_Pin */ GPIO_InitStruct.Pin = USB_OTG_FS_PWR_EN_Pin|SPBTLE_RF_SPI3_CSN_Pin|PMOD_RESET_Pin|STSAFE_A100_RESET_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(GPIOD, &GPIO_InitStruct); /*Configure GPIO pins : VL53L0X_XSHUT_Pin LED3_WIFI__LED4_BLE_Pin */ GPIO_InitStruct.Pin = VL53L0X_XSHUT_Pin|LED3_WIFI__LED4_BLE_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); /*Configure GPIO pins : VL53L0X_GPIO1_EXTI7_Pin LSM3MDL_DRDY_EXTI8_Pin */ GPIO_InitStruct.Pin = VL53L0X_GPIO1_EXTI7_Pin|LSM3MDL_DRDY_EXTI8_Pin; GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); /*Configure GPIO pin : USB_OTG_FS_VBUS_Pin */ GPIO_InitStruct.Pin = USB_OTG_FS_VBUS_Pin; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(USB_OTG_FS_VBUS_GPIO_Port, &GPIO_InitStruct); /*Configure GPIO pins : USB_OTG_FS_ID_Pin USB_OTG_FS_DM_Pin USB_OTG_FS_DP_Pin */ GPIO_InitStruct.Pin = USB_OTG_FS_ID_Pin|USB_OTG_FS_DM_Pin|USB_OTG_FS_DP_Pin; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Alternate = GPIO_AF10_OTG_FS; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /*Configure GPIO pins : INTERNAL_SPI3_SCK_Pin INTERNAL_SPI3_MISO_Pin INTERNAL_SPI3_MOSI_Pin */ GPIO_InitStruct.Pin = INTERNAL_SPI3_SCK_Pin|INTERNAL_SPI3_MISO_Pin|INTERNAL_SPI3_MOSI_Pin; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Alternate = GPIO_AF6_SPI3; HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); /*Configure GPIO pin : PMOD_SPI2_SCK_Pin */ GPIO_InitStruct.Pin = PMOD_SPI2_SCK_Pin; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Alternate = GPIO_AF5_SPI2; HAL_GPIO_Init(PMOD_SPI2_SCK_GPIO_Port, &GPIO_InitStruct); /*Configure GPIO pins : PMOD_UART2_CTS_Pin PMOD_UART2_RTS_Pin PMOD_UART2_TX_Pin PMOD_UART2_RX_Pin */ GPIO_InitStruct.Pin = PMOD_UART2_CTS_Pin|PMOD_UART2_RTS_Pin|PMOD_UART2_TX_Pin|PMOD_UART2_RX_Pin; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Alternate = GPIO_AF7_USART2; HAL_GPIO_Init(GPIOD, &GPIO_InitStruct); /*Configure GPIO pins : ARD_D15_Pin ARD_D14_Pin */ GPIO_InitStruct.Pin = ARD_D15_Pin|ARD_D14_Pin; GPIO_InitStruct.Mode = GPIO_MODE_AF_OD; GPIO_InitStruct.Pull = GPIO_PULLUP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Alternate = GPIO_AF4_I2C1; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /* EXTI interrupt init*/ HAL_NVIC_SetPriority(EXTI9_5_IRQn, 0, 0); HAL_NVIC_EnableIRQ(EXTI9_5_IRQn); HAL_NVIC_SetPriority(EXTI15_10_IRQn, 0, 0); HAL_NVIC_EnableIRQ(EXTI15_10_IRQn); } /* USER CODE BEGIN 4 */ /* USER CODE END 4 */ /** * @brief This function is executed in case of error occurrence. * @retval None */ void Error_Handler(void) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t *file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /* USE_FULL_ASSERT */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
C
#include "../include/bytecode.h" BytecodeHeader* new_bytecodeheader( void ){ BytecodeHeader* bch = malloc( sizeof(BytecodeHeader) ); bch->entry_point_ = 0; bch->code_size_ = 0; return bch; } void bytecodeheader_set_entrypoint( BytecodeHeader* _ptr_bch,unsigned int _data ){ _ptr_bch->entry_point_ = _data; } void bytecodeheader_set_codesize( BytecodeHeader* _ptr_bch,unsigned int _data ){ _ptr_bch->code_size_ = _data; } void bytecodeheader_delete( BytecodeHeader* _ptr_bytecodeheader ){ free( _ptr_bytecodeheader ); } char* bytecode_to_string( byte _id ){ if( _id == BPUSH ) return STRING_BPUSH; else if( _id == BPOP ) return STRING_BPOP; else if( _id == BMOV ) return STRING_BMOV; else if( _id == IMOV ) return STRING_IMOV; else if( _id == HALT ) return STRING_HALT; else if( _id == JMP ) return STRING_JMP; return ""; } byte bytecode_to_int( char* _text ){ if( _text == STRING_BPUSH ) return BPUSH; else if( _text == STRING_BPOP ) return BPOP; else if( _text == STRING_BMOV ) return BMOV; else if( _text == STRING_IMOV ) return IMOV; else if( _text == STRING_HALT ) return HALT; return -1; }
C
#include <stdlib.h> #include <stdio.h> int main() { int num1 = 20; int* ptr_num1 = &num1; int* ptr_num2 = malloc(sizeof(int)); ptr_num2 = ptr_num1; int num2 = *ptr_num2; free(ptr_num2); }
C
/* triangle-float.c: triangle classifier via floating-point arithmetic * author: David Eisenstat <[email protected]> * date: 2014-01-13 */ #include <complex.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #if 0 static long double FabsCarg(long double complex z) { return fabsl(cargl(z)); } #else /* same order properties, less trig! */ static long double FabsCarg(long double complex z) { long double x = creall(z); long double y = cimagl(z); /* must test to avoid 0/0 => NaN */ return copysignl(y != 0 ? x / y : INFINITY, -x); } #endif static long double Angle(long double complex a, long double complex b, long double complex c) { return FabsCarg((a - b) * conjl(c - b)); } static void Sort(long double *alpha, long double *beta) { if (*alpha > *beta) { long double gamma = *alpha; *alpha = *beta; *beta = gamma; } } int main(int argc, char *const *argv) { long double complex a = strtold(argv[1], (char **)NULL) \ + strtold(argv[2], (char **)NULL) * I; long double complex b = strtold(argv[3], (char **)NULL) \ + strtold(argv[4], (char **)NULL) * I; long double complex c = strtold(argv[5], (char **)NULL) \ + strtold(argv[6], (char **)NULL) * I; long double alpha = Angle(c, a, b); long double beta = Angle(a, b, c); long double gamma = Angle(b, c, a); Sort(&alpha, &beta); Sort(&beta, &gamma); Sort(&alpha, &beta); long double zero = FabsCarg(1); long double pi = FabsCarg(-1); if (alpha == zero || gamma == pi) { printf("not a triangle\n"); } else { static char const *const side_type[] = { "scalene", "isosceles", "equilateral" }; char const *angle_type; long double half_pi = FabsCarg(I); if (gamma > half_pi) { angle_type = "obtuse"; } else if (gamma == half_pi) { angle_type = "right"; } else { angle_type = "acute"; } printf("%s %s\n", side_type[(alpha == beta) + (beta == gamma)], angle_type); } }
C
#include <stdio.h> // github ø void main(){ int num1, num2, num3; int result; printf(" Էϼ: ex)3 4 5(Enter)"); scanf("%d %d %d", &num1, &num2, &num3); result = (num1-num2)*(num2+num3)*(num3%num1); printf("(%d-%d)X(%d+%d)X(%d%%%d)=%d", num1, num2, num2, num3, num3, num1, result); }
C
#include <stdio.h> #include <stdlib.h> #include "rmsd.h" #include "drmsd.h" #include <time.h> #include "clrec.h" #include <string.h> #include "nnlsh.h" #include <assert.h> #define bufSize 2048 int main(int argc, char *argv[]) { if(argc!=2 && argc!=5 && argc!=6) { printf("Wrong arguments!\n"); return -1; } FILE* fp; char buflen[bufSize]; int i,j,tablescounter,rows,choice,val; double ***input,***inputbig; if(argc==2) choice=1; else choice=0; if(argc==6) val=1; else val=0; if(choice==1) { printf("Press 0 for c-RMSD or 1 for d-RMSD\n"); scanf("%d",&choice); if(choice==0) { fp = fopen((argv[1]), "r"); fscanf(fp, "%s", buflen); tablescounter=atoi(buflen); fscanf(fp, "%s", buflen); rows=atoi(buflen); printf("%d %d\n",tablescounter,rows); input=malloc(tablescounter*sizeof(double**)); inputbig=malloc(tablescounter*sizeof(double**)); for(i=0;i<tablescounter;i++) { input[i]=malloc(rows *sizeof(double*)); inputbig[i]=malloc(rows *sizeof(double*)); for(j=0;j<rows;j++) { input[i][j]=malloc(3*sizeof(double)); inputbig[i][j]=malloc(3*sizeof(double)); } } readfile(fp,tablescounter,rows,input,inputbig); fclose(fp); assert(crmsdmethod(input,inputbig,tablescounter,rows)); for(i=0;i<tablescounter;i++) { for(j=0;j<rows;j++) { free(input[i][j]); free(inputbig[i][j]); } free(input[i]); free(inputbig[i]); } free(input); free(inputbig); } else if(choice==1) { fp = fopen((argv[1]), "r"); fscanf(fp, "%s", buflen); tablescounter=atoi(buflen); fscanf(fp, "%s", buflen); rows=atoi(buflen); input=malloc(tablescounter*sizeof(double**)); inputbig=malloc(tablescounter*sizeof(double**)); for(i=0;i<tablescounter;i++) { input[i]=malloc(rows *sizeof(double*)); inputbig[i]=malloc(rows *sizeof(double*)); for(j=0;j<rows;j++) { input[i][j]=malloc(3*sizeof(double)); inputbig[i][j]=malloc(3*sizeof(double)); } } readfile(fp,tablescounter,rows,input,inputbig); fclose(fp); assert(drmsdmethod(input,tablescounter,rows)); for(i=0;i<tablescounter;i++) { for(j=0;j<rows;j++) { free(input[i][j]); free(inputbig[i][j]); } free(input[i]); free(inputbig[i]); } free(input); free(inputbig); } else printf("WRONG CHOICE!\n"); } else if(choice==0) { printf("Press 0 for NN-LSH or 1 for Clustering\n"); scanf("%d",&choice); if(choice==0) assert(nnlsh(argv[2],argv[4],val)); else if(choice==1) assert(clusrec(argv[2],argv[4],val)); else printf("WRONG CHOICE!\n"); } else printf("WRONG CHOICE!\n"); }
C
/* Formats binary values into ascii strings using the standard c format syntax E.g. to format the value stored in variable data as an integer at least three characters wide. printformat("%3i" , data); */ #ifndef _MSP430_PRINTF_ #define _MSP430_PRINTF_ #include <msp430g2553.h> #include "stdarg.h" void printformat(char *format, ...); #ifdef printf # undef printf # define printf printformat #endif /* printf */ #endif /* _MSP430_PRINTF_ */
C
#include <stdlib.h> #include <stdio.h> #define MAX_ROWS 50 #define MAX_COLS 50 #define WHITE_PIXEL '.' #define BLUE_PIXEL '#' #define RED_PIXEL_1 '/' #define RED_PIXEL_2 '\\' int main(void) { FILE *f_in, *f_out; if (!(f_in = fopen("A.in", "r"))) { printf("ERROR: no input file.\n"); return EXIT_FAILURE; } f_out = fopen("A.out", "w+"); int i, j, k, n; int cols, rows; int error; char ch; char grid[MAX_ROWS][MAX_COLS]; fscanf(f_in, "%d\n", &n); for(i = 0; i < n; i++) { fprintf(f_out, "Case #%d:\n", i+1); fscanf(f_in, "%d %d\n", &rows, &cols); //On a rcupr la grille. for(j = 0; j < rows; j++) { for(k = 0; k < cols; k++) { ch = '\n'; while (ch == '\n') fscanf(f_in, "%c", &ch); grid[j][k] = ch; } } //On va maintenant la transformer. error = 0; for(j = 0; j < rows; j++) { for(k = 0; k < cols; k++) { switch(grid[j][k]) { case BLUE_PIXEL: if (k == cols-1 || j == rows-1) { error = 1; } else { if (grid[j+1][k] == BLUE_PIXEL && grid[j][k+1] == BLUE_PIXEL && grid[j+1][k+1] == BLUE_PIXEL) { grid[j][k] = RED_PIXEL_1; grid[j][k+1] = RED_PIXEL_2; grid[j+1][k] = RED_PIXEL_2; grid[j+1][k+1] = RED_PIXEL_1; } else { error = 1; } } break; default: break; } if (error == 1) break; } if (error == 1) break; } //On affiche la sortie selon qu'il y a une erreur ou pas. if (error == 1) { fprintf(f_out, "Impossible\n"); } else { for(j = 0; j < rows; j++) { for(k = 0; k < cols; k++) { fprintf(f_out, "%c", grid[j][k]); } fprintf(f_out, "\n"); } } } fclose(f_in); fclose(f_out); return EXIT_SUCCESS; }
C
#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <time.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdbool.h> typedef struct banned_ip { in_addr_t addr; struct banned_ip *next; } banned_ip_t; typedef struct request { in_addr_t addr; bool warning; time_t last_request; struct request *next; } request_t; bool is_banned(in_addr_t addr, banned_ip_t* banned_list){ while(banned_list != NULL){ if(memcmp(&banned_list->addr,&addr,4)) return true; } return false; } request_t* last_request(in_addr_t addr, request_t* requests){ while(requests != NULL){ if(memcmp(&requests->addr,&addr,4)) return requests; } return NULL; } int main(int argc, char *argv[]) { int simpleSocket = 0; int simplePort = 0; int returnStatus = 0; struct sockaddr_in simpleServer; if (2 != argc) { fprintf(stderr, "Usage: %s <port>\n", argv[0]); exit(1); } simpleSocket = socket(AF_INET, SOCK_DGRAM, 0); if (simpleSocket == -1) { perror("Could not create a socket!\n"); exit(1); } else { fprintf(stderr, "Socket created!\n"); } /* retrieve the port number for listening */ simplePort = atoi(argv[1]); /* setup the address structure */ /* use INADDR_ANY to bind to all local addresses */ memset(&simpleServer, '\0', sizeof(simpleServer)); simpleServer.sin_family = AF_INET; simpleServer.sin_addr.s_addr = htonl(INADDR_ANY); simpleServer.sin_port = htons(simplePort); /* bind to the address and port with our socket */ returnStatus = bind(simpleSocket, (struct sockaddr *)&simpleServer, sizeof(simpleServer)); if (returnStatus == 0) { fprintf(stderr, "Bind completed!\n"); } else { fprintf(stderr, "Could not bind to address!\n"); close(simpleSocket); exit(1); } char buffer[256]; struct sockaddr_in senderAddr; socklen_t addrlen; banned_ip_t* banned_list = NULL; request_t* requests = NULL; while (1) { ssize_t e = recvfrom(simpleSocket, buffer, 256, 0, (struct sockaddr *)&senderAddr, &addrlen); if(e == -1){ perror("Error reciving from UDP"); break; } time_t rawtime; if(is_banned(senderAddr.sin_addr.s_addr, banned_list)) continue; request_t* last_same_request = last_request(senderAddr.sin_addr.s_addr, requests); if(last_same_request == NULL){ request_t request; request.addr = senderAddr.sin_addr.s_addr; request.last_request = time(&rawtime); request.warning = false; request.next = requests; requests = &request; }else{ time(&rawtime); printf("%lf\n", difftime(time(&rawtime),last_same_request->last_request)); if(difftime(rawtime,last_same_request->last_request)<10){ if(last_same_request->warning){ banned_ip_t banned_ip; banned_ip.addr = last_same_request->addr; banned_ip.next = banned_list; banned_list = &banned_ip; printf("NEW BAN - %s\n", inet_ntoa(senderAddr.sin_addr)); continue; }else{ last_same_request->warning = true; printf("NEW WARNING - %s\n", inet_ntoa(senderAddr.sin_addr)); e = sendto(simpleSocket, "please wait", strlen("please wait"), 0, (struct sockaddr *)&senderAddr, addrlen); if(e == -1){ perror("Error sending to UDP"); break; } continue; } last_same_request->last_request = time(NULL); } } printf("Sender IP: %s Post: %d Message: %s\n", inet_ntoa(senderAddr.sin_addr), ntohs(senderAddr.sin_port), buffer); e = sendto(simpleSocket, buffer, strlen(buffer), 0, (struct sockaddr *)&senderAddr, addrlen); if(e == -1){ perror("Error sending to UDP"); break; } } close(simpleSocket); return 0; }
C
#include <stdio.h> #include <math.h> int main() { int num, power, ans = 0; for (num = 1; num < 10000; ++num) { for (power = 0; power < 10000; ++power) { int digitOfNum = (power * log10(num)) + 1; ans += digitOfNum == power; } } printf("%d\n", ans); return 0; }
C
#include <stdio.h> int main() { int t; scanf("%d",&t); while(t--) { int n,m,x,y; scanf("%d %d %d %d",&n,&m,&x,&y); if(((n-1)%x==0&&(m-1)%y==0&&(n-1)>=0&&(m-1)>=0)||((n-2)%x==0&&(m-2)%y==0)&&(n-2)>=0&&(m-2)>=0) printf("Chefirnemo\n"); else printf("Pofik\n"); } return 0; }
C
/* * echoserveri.c - An iterative echo server */ /* $begin echoserverimain */ #include "csapp.h" #include <sys/epoll.h> #define MAX_EVENTS 100000 void echo(int connfd); int main(int argc, char **argv) { int listenfd, connfd, port, clientlen, epfd, nfds, i, nr; struct sockaddr_in clientaddr; struct hostent *hp; char *haddrp; struct epoll_event events[MAX_EVENTS]; struct epoll_event ev, *evp; if (argc != 2) { fprintf(stderr, "usage: %s <port>\n", argv[0]); exit(0); } port = atoi(argv[1]); listenfd = Open_listenfd(port); epfd = epoll_create(MAX_EVENTS); if (epfd == -1) { perror("epoll create"); exit(0); } ev.events = EPOLLIN; ev.data.fd = listenfd; if (epoll_ctl(epfd, EPOLL_CTL_ADD, listenfd, &ev) == -1) { perror("epoll_ctl: listenfd"); exit(0); } nr = 0; while (1) { nfds = epoll_wait(epfd, events, MAX_EVENTS, -1); if (nfds == -1) { perror("epoll_wait"); exit(0); } for (i = 0; i < nfds; i++) { evp = &events[i]; if (evp->events & EPOLLIN) { if (evp->data.fd == listenfd) { clientlen = sizeof(clientaddr); connfd = Accept(listenfd, (SA *)&clientaddr, &clientlen); /* determine the domain name and IP address of the client */ hp = Gethostbyaddr((const char *)&clientaddr.sin_addr.s_addr, sizeof(clientaddr.sin_addr.s_addr), AF_INET); haddrp = inet_ntoa(clientaddr.sin_addr); printf("server connected to %s (%s)\n", hp->h_name, haddrp); Set_nonblocking(connfd); ev.events = EPOLLIN; ev.data.fd = connfd; if (epoll_ctl(epfd, EPOLL_CTL_ADD, connfd, &ev) == -1) { perror("epoll_ctl"); Close(connfd); } nr++; printf("number connection: %d\n", nr); } else { //echo(evp->data.fd); ssize_t n, bs; int c = 0; char buf[MAXLINE]; while ((n = read(evp->data.fd, buf, MAXLINE)) > 0) { bs = write(evp->data.fd, buf, n); } if (!n) { ev.data.fd = evp->data.fd; epoll_ctl(epfd, EPOLL_CTL_DEL, evp->data.fd, &ev); printf("disconnected\n"); Close(evp->data.fd); nr--; printf("number connection: %d\n", nr); } } } } } exit(0); } /* $end echoserverimain */
C
/** * @file HRI_ACMP.h * @brief Declaraciones a nivel de registros del ADC (LPC845) * @author Esteban E. Chiama * @date 4/2020 * @version 1.0 */ #ifndef HRI_ACMP_H_ #define HRI_ACMP_H_ #include <stdint.h> #if defined (__cplusplus) extern "C" { #endif #define ACMP_BASE 0x40024000 //!< Direccion base del Comparador Analígico //! Registro de control del comparador analógico typedef struct { uint32_t : 3; //!< Reservado uint32_t EDGESEL : 2; //!< Selección de tipo de flanco que establece el bit COMPEDGE. uint32_t : 1; //!< Reservado uint32_t COMPSA : 1; //!< Configura salida directa o sincronizada al bus. uint32_t : 1; //!< Reservado uint32_t COMP_VP_SEL : 3; //!< Selección de entrada para voltaje positivo. uint32_t COMP_VM_SEL : 3; //!< Selección de entrada para voltaje negativo. uint32_t : 6; //!< Reservado uint32_t EDGECLR : 1; //!< Bit de limpieza de interrupción. uint32_t COMPSTAT: 1; //!< Refleja el estado de salida de la comparación. uint32_t : 1; //!< Reservado uint32_t COMPEDGE : 1; //!< Indica si hubo o no detección de flanco. uint32_t INTENA : 1; //!< Enable de interrupción. uint32_t HYS : 2; //!< Control de histérisis del comparador. uint32_t : 5; //!< Reservado }ACMP_CTRL_reg_t; //! Registro de habilitación y control de la voltage ladder. typedef struct { uint32_t LADEN : 1; //!< Enable de voltage ladder. uint32_t LADSEL : 5; //!< Valor de la voltage ladder. uint32_t LADREF : 1; //!< Selección del voltage de referencia Vref para la voltage ladder. uint32_t : 25; //!< Reservado }ACMP_LAD_reg_t; typedef struct { ACMP_CTRL_reg_t CTRL; ACMP_LAD_reg_t LAD; }ACMP_per_t; extern volatile ACMP_per_t * const ACMP; //!< Periferico Comparador Analógico. #if defined (__cplusplus) } // extern "C" #endif #endif /* HRI_ACMP_H_ */
C
#include <stdio.h> #include <stdlib.h> #include <string.h> struct Node { int num; struct Node *left; struct Node *right; }; struct Node *insert(struct Node *root, int num) { if (root == NULL) { root = malloc(sizeof(struct Node)); root->num = num; root->left = NULL; root->right = NULL; printf("inserted\n"); } else if (num < root->num) { root->left = insert(root->left, num); } else if (num > root->num) { root->right = insert(root->right, num); } else { printf("not inserted\n"); } return root; } int search(struct Node *root, int num) { if (root != NULL) { if (root -> num == num) { return 1; } if (num < root->num) { return search(root->left, num); } else if (num > root->num) { return search(root->right, num); } } return 0; } void print(struct Node *root) { if (root == NULL) return; printf("("); print(root->left); printf("%i", root->num); print(root->right); printf(")"); } struct Node* delete(struct Node *root, int num) { if (root == NULL) { return root; } if (num < root-> num) { root->left = delete(root->left, num); } else if (num > root-> num) { root->right = delete(root->right, num); } else { if (root->left == NULL && root-> right == NULL) { free(root); return NULL; } else if (root -> right == NULL) { struct Node* n = root->left; free(root); return n; } else if(root-> left == NULL) { struct Node* n = root->right; free(root); return n; } else { struct Node *parent = root->left; struct Node *ptr = root->left->right; if (ptr == NULL) { root->left = NULL; parent->right = root->right; free(root); free(ptr); return parent; } else { while (ptr->right != NULL) { parent = ptr; ptr = ptr->right; } parent->right = NULL; ptr->right = root->right; ptr->left = root->left; free(root); return ptr; } } } return root; } void freeAll(struct Node *root) { if (root == NULL) { return; } freeAll(root->left); freeAll(root->right); free(root); } int main() { char input[20]; char c; int i; struct Node *root = NULL; while (1) { if (fgets(input, 20, stdin) == NULL) break; sscanf(input, "%c %d", &c, &i); if (c == 'i') { root = insert(root, i); } else if (c == 's') { if(search(root, i) == 1) { printf("present\n"); } else { printf("absent\n"); } } else if (c == 'p') { print(root); printf("\n"); } else if (c == 'd') { if (search(root, i) == 1) { root = delete(root, i); printf("deleted\n"); } else { printf("absent\n"); } } else { break; } } freeAll(root); return 0; }
C
#include "../../testing/utest.h" #include <stdio.h> #include <stdlib.h> #include <string.h> //INCLUDE LIBRARY TO TEST #include "../../inc/LinkedList.h" #include "../../testing/inc/Employee.h" void removeTestSetup(void) { utest_print("Setup...\r\n"); } void removeTestCase01(void) { LinkedList* list; int r; list = ll_newLinkedList(); ll_add(list,NULL); r = ll_remove(list,0); utest_assertEqualsIntMsg(r,0,"\nError en el valor de retorno de <remove> si los parametros son correctos es 0\n"); } void removeTestCase02(void) { LinkedList* list; void* pElement; void* pElement2 = newEmployee(10,"JUAN","PEREZ",1,1); list = ll_newLinkedList(); ll_add(list,NULL); ll_add(list,NULL); ll_add(list,pElement2); ll_remove(list,1); pElement = ll_get(list,1); utest_assertEqualsPointerMsg(pElement,pElement2,"\nError en el valor de retorno de <get> al solicitar \nun elemento luego de eliminar su antecesor\n"); utest_assertEqualsIntMsg(ll_len(list),2,"\nError en el len() de la lista luego de quitar un elemento"); } void removeTestCase03(void) { LinkedList* list; int r; list = ll_newLinkedList(); ll_add(list,NULL); r = ll_remove(list,-1); utest_assertEqualsIntMsg(r,-1,"\nError en el valor de retorno de <remove> al intentar eliminar un elemento fuera de indice (< 0),\n se deberia retornar -1\n"); r = ll_remove(list,1); utest_assertEqualsIntMsg(r,-1,"\nError en el valor de retorno de <remove> al intentar eliminar un elemento fuera de indice (>= ll_len),\n se deberia retornar -1\n"); } void removeTestCase04(void) { int r; r = ll_remove(NULL,0); utest_assertEqualsIntMsg(r,-1,"\nError en el valor de retorno de <remove> si la lista pasada es NULL\n el valor a retornar es (-1)\n"); } void removeTestCase05(void) { LinkedList* list; // void* pElement; // void* pElement2 = newEmployee(10,"JUAN","PEREZ",1,1); list = ll_newLinkedList(); ll_add(list,NULL); ll_remove(list,0); utest_assertEqualsPointerMsg(list->pFirstNode,NULL,"\nEl valor de pFirstNode luego de quitar el ultimo elemento debe ser NULL\n"); }
C
#include <stdio.h> int main(void){ int n; scanf("%d",&n); for(int i = 1; i <= n; i++){ for(int j = n-i; j > 0; j--){ printf(" "); } for(int k = 1; k <= 2*i-1; k++){ printf("*"); } printf("\n"); } }
C
#include <stdio.h> #include <string.h> void xoa(char s[], char s1[]) { char kq[100]; int t = 0, i = 0, j, k, ns1 = strlen(s1); strcat(s, "|"); while (s[i] != '|') { k = i; j = 0; while (s[k] == s1[j]) { k++; j++; } if (j == ns1) { i = ns1 + i; } else { kq[t++] = s[i++]; } } for (int i = 0; i < t; i++) printf("%c", kq[i]); } void sapxep(char s[]) { char ds[20][10], t[10]; int n = 0; char *p = strtok(s, " "); while (p != NULL) { strcpy(ds[n++], p); p = strtok(NULL, " "); } for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (strcmp(ds[i], ds[j]) > 0) { strcpy(t, ds[i]); strcpy(ds[i], ds[j]); strcpy(ds[j], t); } } } for (int i = 0; i < n; i++) { printf("%s ", ds[i]); } } void tach(char hoten[]) { char *token; token = strtok(hoten, " "); int c = 0; char mang[5][15]; while (token != NULL) { printf(" %s\n", token); strcpy(mang[c], token); c++; token = strtok(NULL, " "); } for (int i = 0; i < c; i++) { printf("%s ", mang[i]); } return (0); } int main() { char s1[100], s2[100]; fgets(s1, 100, stdin); fgets(s2, 100, stdin); xoa(s1, s2); return 0; }
C
#include <stdio.h> #define BR_ELEMENTI 100 void preuredi(int *a, int m); int main() { int a[BR_ELEMENTI], i, j, m; printf("Vnesete broj na elementi M:"); scanf("%d", &m); printf("\nVnesete ja nizata:\n"); for (i=0;i<m;i++) { printf("a[%d]=", i); scanf("%d", &a[i]); } printf("\nNizata pred da se preuredi e:\n\n"); for (j=0;j<m;j++) printf("%10d", a[j]); printf("\n"); preuredi(a,m); printf("\nNizata po preureduvanjeto e:\n\n"); for (j=0;j<m;j++) printf("%10d", a[j]); printf("\n"); return 0; } void preuredi(int *a, int m) { int i=0,x=1; while(i<m) { *(a+i)=*(a+i++)*x; x*=2; } }
C
#include <stdio.h> #include <string.h> #define COMBINATIONS 6561 #define OPS 8 void generateCombination(int permutationIdentifier, char* arr){ int arrPtr = 0; for(int i = 1; i < OPS ; i++, permutationIdentifier /= 3){ arr[arrPtr] = i + '0'; arrPtr++; int op = permutationIdentifier % 3; if(op == 0){ arr[arrPtr] = '+'; arrPtr++; } else if(op == 1){ arr[arrPtr] = '-'; arrPtr++; } } arr[arrPtr] = '9'; arr[arrPtr + 1] = '\0'; } int eval(char* exp){ int lastInt = 0, val = 0; char lastOp = '+'; int len = strlen(exp); for(int i = 0; i < len; i++){ char c = exp[i]; if(c >= '1' && c <= '9'){ lastInt *= 10; lastInt += (c - '0'); } else if(c == '+' || c == '-'){ if(lastOp == '+'){ val += lastInt; } else {val -= lastInt;} lastInt = 0; lastOp = c; } } if(lastOp == '+'){ val+= lastInt; } else{ val -= lastInt ;} return val; } int main(){ for(int i = 0; i < COMBINATIONS; i++){ char expression[20]; generateCombination(i,expression); int valExpression = eval(expression); if(valExpression == 100){ printf("%s = %d\n", expression, valExpression); } } return 0; }