language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { int codProd; char denumire[50]; char um[10]; int cantitate; int pretUnitar; }produs; void readProcess(char* numeFis, produs *p, int *n) { FILE *pf = fopen(numeFis, "r"); if (pf == NULL) { printf("Couldn't open File"); exit(1); } *n = 0; while (1) { if (fscanf(pf, "%s", p[*n].denumire) != 1) { break; } p[*n].denumire[strlen(p[*n].denumire)] = '\0'; int x, iter = 0; char ch; do { fseek(pf, 3, SEEK_CUR); fscanf(pf, "%d%c", &x, &ch); switch (iter) { case 0: p[*n].codProd = x; iter++; fseek(pf, 3, SEEK_CUR); fscanf(pf, "%s", p[*n].um); p[*n].um[strlen(p[*n].um)] = '\0'; break; case 1: p[*n].cantitate = x; iter++; break; case 2: p[*n].pretUnitar = x; iter++; break; default: break; } } while (ch != '.'); (*n)++; iter = 0; } fclose(pf); } void writeFile(char* numeFis, produs* p, int n) { FILE *pf = fopen(numeFis, "w"); // 0 9 7 5 8 5 4 // 0 1 2 3 4 5 6 int ord[11]; int aux; for (int i = 0; i < n; i++) { ord[i] = i; } for (int i = 0; i < n/2; i++) { for (int j = 0; j < n - 1; j++) { if (p[ord[j]].codProd > p[ord[j + 1]].codProd) { aux = ord[j]; ord[j] = ord[j + 1]; ord[j + 1] = aux; } } } for (int i = 0; i < n; i++) { fprintf(pf, "%s %d %s %d %d\n", p[ord[i]].denumire, p[ord[i]].codProd, p[ord[i]].um, p[ord[i]].cantitate, p[ord[i]].pretUnitar); } fflush(pf); fclose(pf); for (int i = 0; i < n; i++) { printf("%s %d %s %d %d\n", p[ord[i]].denumire, p[ord[i]].codProd, p[ord[i]].um, p[ord[i]].cantitate, p[ord[i]].pretUnitar); } } int main(int argc, char *argv[]) { produs p[100]; int n; readProcess("produse.txt", p, &n); writeFile("PSortat.txt", p, n); system("pause"); return 0; }
C
#include "io.h" void main() { int sum[10]; int i; i = 2; sum[0] = 1; sum[1] = 1; while(i<10) { sum[i] = sum[i-1] + sum[i-2]; i = i +1; } i = 0; while(i<10) { print_i(sum[i]); i = i+1; } }
C
#include <stdio.h> #include <stdlib.h> #include "prio.h" int main() { struct FP P; P = prio_creer_vide(); prio_affiche(P); P = prio_inserer(P, 1, 102); prio_affiche(P); P = prio_inserer(P, 2, 12); P = prio_inserer(P, 3, 48); P = prio_inserer(P, 4, 36); P = prio_inserer(P, 5, 12); P = prio_inserer(P, 6, 12); P = prio_inserer(P, 7, 12); prio_affiche(P); struct elem e; printf("### %d ###\n", P.nb_elem); e = prio_extraire(&P); printf("%d %d\n", e.id, e.prio); printf("### %d ###\n", P.nb_elem); prio_affiche(P); e = prio_extraire(&P); printf("%d %d\n", e.id, e.prio); printf("### %d ###\n", P.nb_elem); prio_affiche(P); e = prio_extraire(&P); printf("%d %d\n", e.id, e.prio); printf("### %d ###\n", P.nb_elem); prio_affiche(P); e = prio_extraire(&P); printf("%d %d\n", e.id, e.prio); exit(0); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* export_utility_two_support.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: molabhai <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/04/16 13:47:13 by molabhai #+# #+# */ /* Updated: 2021/04/16 13:47:14 by molabhai ### ########.fr */ /* */ /* ************************************************************************** */ #include "../minishell.h" char *return_adding_quote(char *s, int j) { char *s2; int i; s2 = ft_calloc(sizeof(char ), j + 3); if (!(s2)) return (NULL); s2[0] = '\"'; j = 1; i = 0; while (s[i] != '=') i += 1; if (s[i] == '=') i += 1; while (s[i] != '\0') { s2[j] = s[i]; i += 1; j += 1; } s2[j] = '\"'; j += 1; s2[j] = '\0'; return (s2); } char *return_loc(char *s, char *s2, char *str) { int i; int j; i = 0; j = 0; while (s[i] != '=') { str[i] = s[i]; i += 1; } str[i] = s[i]; i += 1; while (s2[j] != '\0') { str[i] = s2[j]; i += 1; j += 1; } str[i] = '\0'; return (str); } void print_count(char *str, int *i, int *count) { int j; j = *i; while (((ft_isprint(str[j]) == 1 ) || str[j] == '=') && ((check_single_double_quote(str[j]) == 0) || (check_single_double_quote(str[j]) == 1 && j > 0 && str[j - 1] == '\\'))) j += 1; *count += 1; *i = j; } void double_quote_count(char *str, int *i, int *count) { int j; j = *i + 1; while (check_double_quotes(str[j]) == 0 && str[j] != '\0') j += 1; *count += 1; *i = j; } void single_quote_count(char *str, int *i, int *count) { int j; j = *i + 1; while (check_single_quotes(str[j]) == 0 && str[j] != '\0') j += 1; *count += 1; *i = j; }
C
#include<stdio.h> int main(void) { int max,min,n; int tmp,i,s[100]; scanf("%d",&n); for(i=0;i<n;i++){ scanf("%d",&s[i]); } max=s[0]; min=s[0]; for(i=1;i<n;i++){ if(max<s[i]) max=s[i]; if(min>s[i]) min=s[i]; } tmp=max-min; printf("%d\n",tmp); return 0; } ./Main.c: In function main: ./Main.c:8:2: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result] scanf("%d",&n); ^ ./Main.c:11:3: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result] scanf("%d",&s[i]); ^
C
#include <stdio.h> #include<stdlib.h> #include "answer11.h" // -------------------------------------------------------------------- HuffNode /** * A Huffman coding tree. We must implement two small functions... * * (1) HuffNode_create(value); // create a new HuffNode * (2) HuffNode_destroy(tree); // free all memory safely */ /** * Create a new, properly intialized HuffNode */ HuffNode * HuffNode_create(int value) { HuffNode * node = malloc(sizeof(HuffNode)); node->value = value; node->left = NULL; node->right = NULL; return node; } /** * Destroy a tree, including all sub-children. Must handle NULL values safely. */ void HuffNode_destroy(HuffNode * tree) { if (tree == NULL) { return; } HuffNode_destroy(tree->left); HuffNode_destroy(tree->right); free(tree); } // ----------------------------------------------------------------------- Stack /** * We need a "Stack" to build the tree structure that is used to decode * a Huffman encoding. Stacks are very simple to implement with linked lists. * We must implement the following functions (given below). Each of these * functions should only be a few lines of code. * * (1) Stack_create(); // Allocate a brand new stack. * (2) Stack_destroy(stack); // Clean up memory for the stack. * (3) Stack_isEmpty(stack); // TRUE iff (if and only if) the stack is empty. * (4) Stack_pushFront(stack, tree); // Push a tree onto the stack. * (6) Stack_popFront(stack); // Remove a tree from the stack and return it. * * Altogether, these six functions should be around 40 lines of code. */ /** * Returns a pointer to a new empty stack struct */ Stack * Stack_create() { Stack * st = malloc(sizeof(Stack)) ; st ->head = NULL; return st; } /** * Frees all memory associated with the stack. * Don't forget that you must free the entire contained linked-list. * Also, you must safely do nothing if stack == NULL. */ void Stack_destroy(Stack * stack) { if(stack == NULL) { return; } StackNode* head = stack->head; StackNode * temp = head; while(head != NULL) { temp = head->next; HuffNode_destroy(head->tree); free(head); head = temp; } free(stack); } /** * Returns TRUE (something other than zero) if the stack is empty. */ int Stack_isEmpty(Stack * stack) { if(( stack->head) == NULL) { return 1; } return 0; } /** * Pop the front (top) 'value' (i.e. Huffman tree) from the stack. * * More precisely, this function must do three things: * (1) Save the value (i.e. Huffman tree) of the head node of the stack's list * (2) Remove the head node of the stack's list, freeing it. * (3) Return the value (i.e. Huffman tree) saved in (1). */ HuffNode * Stack_popFront(Stack * stack) { if(stack == NULL) { return NULL; } HuffNode * node = stack->head->tree; StackNode * temp = stack->head->next; free(stack->head); stack->head = temp; return node; } /** * Push a 'value' (i.e. Huffman tree) onto the front (top) of the stack. * * More precisely, this function must do two things: * (1) Create a new StackNode with 'tree' for its tree. * (2) Push that new StackNode onto the front of the stack's list. */ void Stack_pushFront(Stack * stack, HuffNode * tree) { StackNode * node = malloc(sizeof(StackNode)); node-> tree = tree; node->next = stack->head; stack->head = node; } // -------------------------------------------------------- Pop Pop combine Push /** * This function helps simplify building a Huffman Coding Tree from the header * information. It takes a stack as input. As a precondition, you can assume * that the stack has at least two nodes. This function pops the front (top) * two nodes, combines them into a single node, and pushes the new node back * onto the stack. See Huffman_Coding.pdf to understand conceptually how this * should be done. */ void Stack_popPopCombinePush(Stack * stack) { HuffNode * tree1 = Stack_popFront(stack); HuffNode * tree2 = Stack_popFront(stack); HuffNode * tree3 = HuffNode_create(0); tree3->left = tree2; tree3->right = tree1; Stack_pushFront(stack, tree3); } // ---------------------------------------------------- Reading HuffTree headers /** * Read a Huffman Coding Tree (in text format) from 'fp'. */ HuffNode * HuffTree_readTextHeader(FILE * fp) { int iter = 0; int c; if( fp == NULL) { return NULL; } Stack * stack = Stack_create(); while(iter != -1) { if(fgetc(fp) == '1') { c = fgetc(fp); HuffNode * tree = HuffNode_create(c); Stack_pushFront(stack,tree); } else { if(stack->head->next != NULL) { Stack_popPopCombinePush(stack); } else { iter = -1; } } } HuffNode * trees = stack->head->tree; free(stack-> head); free(stack); return trees; } /** * Read a Huffman Coding Tree (in binary format) from 'fp'. * You will need to (conceptually) read a file a bit at a time. See the README * for hints on how to do this. */ // Code used from Pr. Lu's online textbook. int readBit(FILE * fptr, unsigned char * bit, unsigned char * whichbit, unsigned char * curbyte) { int ret = 1; if((*whichbit) == 0) { // read a byte from a file ret = fread(curbyte, sizeof(unsigned char), 1, fptr); } if(ret != 1) { return -1; } unsigned char temp = (*curbyte) >> (7-(*whichbit)); temp = temp & 0X01; *whichbit = ((*whichbit) + 1) % 8; *bit = temp; return 1; } // Code used from Pr. Lu's online textbook. HuffNode * HuffTree_readBinaryHeader(FILE * fp) { int iter = 0; unsigned char whichbit = 0; unsigned char curbyte = 0; unsigned char onebit = 0; Stack * stack = Stack_create() ; // decreasing to ensure the list is a stack while (iter == 0) { readBit (fp ,& onebit ,& whichbit ,& curbyte ); if (onebit == 1) { int bitcount ; unsigned char value = 0; for (bitcount = 0; bitcount < 8; bitcount ++) { value <<= 1; // shift left by one readBit (fp, & onebit, & whichbit, &curbyte ); value |= onebit ; } HuffNode * tn = HuffNode_create(value); Stack_pushFront(stack, tn); } else { if (stack->head->next != NULL) { Stack_popPopCombinePush(stack); } else { iter = 1; } } } HuffNode * root = stack->head->tree; free (stack->head ); free(stack); return root ; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <signal.h> #include <fcntl.h> void set_fl(int fd,int flag) { int oldflag=fcntl(fd,F_GETFL); int newflag=flag|oldflag; if(fcntl(fd,F_SETFL,newflag)<0) { fprintf(stderr,"fcntl: %s\n",strerror(errno)); exit(1); } } void sig_handler(int signo) { if(signo == SIGPIPE) { printf("%d receive sigpipe signal!\n",getpid()); } } int main(void) { if(signal(SIGPIPE,sig_handler) == SIG_ERR) { fprintf(stderr,"signal: %s\n",strerror(errno)); exit(1); } int fd[2]; if(pipe(fd)<0) { fprintf(stderr,"pipe: %s\n",strerror(errno)); exit(1); } set_fl(fd[0],O_NONBLOCK); set_fl(fd[1],O_NONBLOCK); pid_t pid; if((pid =fork())<0) { fprintf(stderr,"fork: %s\n",strerror(errno)); exit(1); }else if(pid == 0) { close(fd[1]); //pause(); //close(fd[0]); sleep(10); ssize_t n_read; char buffer[65536]={0}; if((n_read=read(fd[0],buffer,65536))<0) { fprintf(stderr,"read: %s\n",strerror(errno)); exit(1); } printf("nread: %d,buffer:%s\n",n_read,buffer); pause(); }else { close(fd[1]); //sleep(1); /*while(1) { char buffer[256] = {0}; strcpy(buffer,"Message"); int len=strlen(buffer); if(write(fd[1],buffer,len)!=len) { fprintf(stderr,"write: %s\n",strerror(errno)); exit(1); } }*/ //close(fd[1]); /*int counter=0; while(1) { if(write(fd[1],"a",1)!=1) { fprintf(stderr,"write: %s\n",strerror(errno)); //exit(1); break; } counter++; printf("Already write %d bytes!\n",counter); }*/ wait(NULL); } return 0; }
C
#include "lcd.h" void main(void) { LCD_Initialize(); while (1) { for(char i = 0; i < 100; i++){ LCDGoto(0, 0); LCDPutChar(i/10 + 48); LCDGoto(1, 0); LCDPutChar(i%10 + 48); for(char j = 0; j < 5; j++) __delay_ms(50); } } }
C
#if 0 static const struct { //must do linear search on these const unsigned char *magic; MIMEtype type; unsigned short len; unsigned short offset; } extra_mimes[]={ {"Microsoft Word 6.0 Document",(MIMEtype){"application","msword"},27,2080}, {"Documento Microsoft Word 6",(MIMEtype){"application","msword"},26,2080}, {"Microsoft Excel 5.0 Worksheet",(MIMEtype){"application","vnd.ms-excel"},29,2080}, {"Foglio di lavoro Microsoft Exce",(MIMEtype){"application","vnd.ms-excel"},31,2080}, {"MSWordDoc",(MIMEtype){"application","msword"},9,2112}, {"CD001",(MIMEtype){"application","x-iso9660-image"},5,32769}, }; MIMEtype *mime_search(const MIMEMagic *mimes,int count,int offset,const char *buf){ int i=count>>1,bot=0,top=count,cmp; for (; bot<=top; i=(bot+top)>>1){ cmp=memcmp(buf+offset,mimes[i].magic,mimes[i].len); if (! cmp) return (MIMEtype *)&mimes[i].type; //match found else if (cmp>0) bot=i+1; else top=i-1; } return (MIMEtype *)NULL; } MIMEtype *mime_find(const char *buf,int offset, int len){ //TODO int i; for(i=0;i<(sizeof(extra_mimes)/sizeof(extra_mimes[0]));i++){ if (offset > extra_mimes[i].offset) continue; if (offset+len < extra_mimes[i].offset) return (MIMEtype *)NULL; if (!memcmp(buf+(extra_mimes[i].offset-offset),extra_mimes[i].magic,extra_mimes[i].len)) return (MIMEtype *)&extra_mimes[i].type; } return (MIMEtype *)NULL; } #endif
C
#include "word.h" char* int2word(mpz_t nb, char* charset, int base, char* word) { //printf(" == %d : %s : %d == ", base, charset, nb); int i = 0; int t = 0; int k = 0; int nb_char= 0; int start = 0; mpz_t tmp, tmp2, tmp3, inf, number; mpz_init_set(number, nb); mpz_init_set(tmp, number); mpz_init(tmp2); mpz_init(tmp3); mpz_init_set_si(inf, 0); while(mpz_cmp_si(tmp, 0) >= 0) { //tmp -= (long)pow(base, nb_char+1); mpz_ui_pow_ui(tmp2, base, nb_char+1); mpz_sub(tmp, tmp, tmp2); nb_char++; } //printf("\nnb_char : %d\n", nb_char); start = nb_char-1; do{ for(i=1;i<start;i++) { mpz_ui_pow_ui(tmp2, base, i); mpz_add(inf, inf, tmp2); //inf += (long)pow(base,i); } //gmp_printf("\nk : %d, inf : %Zd\n", k, inf); mpz_set_si(tmp, base-1); if(start != 0) { mpz_add_ui(tmp2, tmp, 1); mpz_ui_pow_ui(tmp3, base, start); mpz_mul(tmp2, tmp2, tmp3); mpz_add(tmp2, tmp2, inf); //while(((tmp+1)*(long)pow(base,start)+inf > nb)) while(mpz_cmp(tmp2, number) > 0) { /* tmp++ */ mpz_sub_ui(tmp, tmp, 1); mpz_add_ui(tmp2, tmp, 1); /* tmp3 doesn't change; useless to recalc */ mpz_mul(tmp2, tmp2, tmp3); mpz_add(tmp2, tmp2, inf); } t = mpz_get_si(tmp); } else { t = mpz_get_si(number); } //gmp_printf("i : %d,\tt : %d,\tnb : %Zd\n", start, t, number); //printf("start : %d \n", t); word[k] = charset[t]; //printf("%d : %s\n", start, word); /* mpz_sub_ui(number, number, ((t+1)*(long)pow(base, start))); */ mpz_ui_pow_ui(tmp3, base, start); mpz_mul_ui(tmp3, tmp3, t+1); mpz_sub(number, number, tmp3); start--; k++; mpz_set_si(inf, 0); }while(start >= 0); word[nb_char] = '\0'; //gmp_printf("%s \n", word); mpz_clear(tmp); mpz_clear(tmp2); mpz_clear(tmp3); mpz_clear(inf); mpz_clear(number); return word; }
C
#include <stdio.h> #include <stdlib.h> #include <cs50.h> #include <string.h> #include <ctype.h> void encrypt(string, int k); int main (int argc, char* argv[]) { int k; /*Get the command line-argument and convert from string to int If no argument is provided return 1 and printf error message*/ if (argc == 2) { k = atoi(argv[1]); k = k % 26; // Makes sure that the key is between 0-26 } else { printf("You have to enter a Rotation key!\n"); return 1; } //Get the phrase to encrypt and use function encrypt() string phrase = GetString(); encrypt(phrase, k); return 0; } /*encrypt() needs a string and the rotation as input It checks if the character is upper-/lowercase or a another character*/ void encrypt(string s, int k) { char encryptedchar; for (int i = 0, j = strlen(s); i < j; i++) { if (s[i] >= 'a' && s[i] <= 'z') { ((s[i] + k) > 'z') ? (encryptedchar = (s[i] + k) - 26) : (encryptedchar = (s[i] + k)); } if (s[i] >= 'A' && s[i] <= 'Z') { ((s[i] + k) > 'Z') ? (encryptedchar = (s[i] + k) - 26) : (encryptedchar = (s[i] + k)); } if (!((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z'))) { encryptedchar = s[i]; } printf("%c", encryptedchar); // Print the char every loop after it went through the if loopsls } printf("\n"); }
C
#include <stdio.h> #include <string.h> //For strlen #include <mpi.h> //For MPI functions #define MAX_STRING 100 int main(void) { char greeting[MAX_STRING]; int comm_size; int my_id; MPI_Init(NULL,NULL); MPI_Comm_size(MPI_COMM_WORLD,&comm_size); MPI_Comm_rank(MPI_COMM_WORLD,&my_id); if(my_id != 0) { sprintf(greeting, "Greetings from process %d of %d!" ,my_id,comm_size); MPI_Send(greeting,strlen(greeting),MPI_CHAR, 0, 0, MPI_COMM_WORLD); } else { printf("Greeting from process %d of %d!\n", my_id,comm_size); int q =1; MPI_Status status; int number; for(; q<comm_size;q++) { MPI_Recv(greeting, MAX_STRING, MPI_CHAR, q, 0, MPI_COMM_WORLD, &status); MPI_Get_count(&status, MPI_CHAR, &number); printf("%s\n",greeting); printf("Received %d numbers Message source = %d, " "tag = %d\n", number, status.MPI_SOURCE, status.MPI_TAG); } } MPI_Finalize(); return 0; }
C
#include "monty.h" /** *pall - print all the stack *@stack: pointer to the top element *@line_number: line number *Return: void */ void pall(stack_t **stack, unsigned int line_number) { stack_t *st = *stack; while (st != NULL) { printf("%d\n", st->n); st = st->next; } (void) line_number; } /** *pint - print top element of the stack *@stack: pointer to the top element *@line_number: line number *Return: void */ void pint(stack_t **stack, unsigned int line_number) { stack_t *st = *stack; if (st != NULL) printf("%d\n", st->n); else { exit_failure(stack, "L%d: can't pint, stack empty\n"); } (void) line_number; } /** *pstr - print top element of the stack *@stack: pointer to the top element *@line_number: line number *Return: void */ void pstr(stack_t **stack, unsigned int line_number) { stack_t *st = *stack; if (!(*stack)) { printf("\n"); } else { while (st != NULL) { if (st->n >= 32 && st->n <= 126) printf("%c", st->n); else { break; } st = st->next; } printf("\n"); fflush(stdout); (void) line_number; } } /** *pchar - print top element of the stack *@stack: pointer to the top element *@line_number: line number *Return: void */ void pchar(stack_t **stack, unsigned int line_number) { stack_t *st = *stack; if (st != NULL) { if (st->n >= 32 && st->n <= 126) printf("%c\n", st->n); else { exit_failure(stack, "L%d: can't pchar, value out of range\n"); } st = st->next; } else { exit_failure(stack, "L%d: can't pchar, stack empty\n"); } (void) line_number; }
C
#include<reg51.h> #define smotor P2 void wiper(); void delay(unsigned int d); sbit rain_sensor=P1^0; void main() { rain_sensor=1; //making as input port smotor=0x00; for(;;) { while(rain_sensor==1); //wait till the rain is not present wiper(); //run the motor } } void wiper() { for(;;) { smotor=0x09; delay(1000); smotor=0x0c; delay(1000); smotor=0x06; delay(1000); smotor=0x03; // delay(1000); // smotor=0x09; // delay(1000); // smotor=0x03; // delay(1000); smotor=0x06; delay(1000); smotor=0x0c; delay(1000); smotor=0x09; delay(1000); } } void delay(unsigned int d) { unsigned char i; for(;d>0;d--) { for(i=255;i>0;i--); for(i=255;i>0;i--); } }
C
#include <stdarg.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include "bano_html.h" #include "bano_perror.h" static int resize_data(bano_html_t* html, size_t size) { const size_t new_size = (size + 0x1000) & ~(0x1000 - 1); void* const new_data = realloc(html->data, new_size); if (new_data == NULL) { BANO_PERROR(); html->is_err = 1; return -1; } html->data = new_data; html->size = new_size; return 0; } static void free_data(bano_html_t* html) { if (html->data != NULL) free(html->data); html->data = NULL; html->size = 0; html->off = 0; } int bano_html_init(bano_html_t* html) { html->off = 0; html->data = NULL; html->size = 0; html->is_err = 0; return 0; } void bano_html_fini(bano_html_t* html) { free_data(html); } int bano_html_printf(bano_html_t* html, const char* fmt, ...) { int len; size_t size; va_list va; unsigned int once = 1; if (html->is_err) return -1; do_vsnprintf: size = html->size - html->off; va_start(va, fmt); len = vsnprintf(html->data + html->off, size, fmt, va); va_end(va); if (len < 0) { BANO_PERROR(); goto on_error; } if (len >= (int)size) { if (once == 0) { BANO_PERROR(); goto on_error; } once = 0; if (resize_data(html, html->off + (size_t)len + 1) == -1) { BANO_PERROR(); goto on_error; } goto do_vsnprintf; } html->off += (size_t)len; return 0; on_error: free_data(html); html->is_err = 1; return -1; } int bano_html_include(bano_html_t* html, const char* filename) { struct stat st; size_t new_size; int err = -1; int fd; if (html->is_err) return -1; fd = open(filename, O_RDONLY); if (fd == -1) { BANO_PERROR(); goto on_error_0; } if (fstat(fd, &st)) { BANO_PERROR(); goto on_error_1; } new_size = html->off + st.st_size; if (new_size > html->size) { if (resize_data(html, new_size)) { BANO_PERROR(); goto on_error_1; } } if (read(fd, html->data + html->off, st.st_size) != st.st_size) { BANO_PERROR(); goto on_error_1; } html->off += st.st_size; err = 0; on_error_1: close(fd); on_error_0: if (err) { free_data(html); html->is_err = 1; return -1; } return 0; }
C
/* ** EPITECH PROJECT, 2021 ** number_generator.c ** File description: ** number_generator */ #include "../include/helper.h" #include "../include/my.h" asciiart *number_generator(void) { asciiart *ascart = malloc(sizeof(asciiart)); ascart->zero = zero(); ascart->one = one(); ascart->two = two(); ascart->three = three(); ascart->four = four(); ascart->five = five(); ascart->six = six(); ascart->seven = seven(); ascart->eight = eight(); ascart->nine = nine(); return (ascart); } asciiart *string_gen(asciiart *ascart, char **av) { for (int i = 0; av[i]; i++) { if (strcmp(av[i], "-n") == 0) { ascart->canvas_size = my_strlen(av[i + 1]); ascart->nb_str = strdup(av[i + 1]); } } return (ascart); } char **fill_canvas(asciiart *ascart, char **final_canvas, char *mod_str) { char *cur_line = NULL; for (int i = 0 ; i < 5; i++) { for (int j = 0 ; j < ascart->canvas_size ; j++) { cur_line = get_cur_line(i, ascart->nb_str[j], ascart); cur_line = add_space(ascart->canvas_size, j, cur_line); if (mod_str != NULL) cur_line = apply_mod(mod_str, cur_line, j, ascart->nb_str); final_canvas[i] = strcat(final_canvas[i], cur_line); } } return (final_canvas); }
C
#include <stdio.h> void imprimirJogadores(int i, int n, int jogador[]) { if (i < n) { printf("%d\n", jogador[i]); imprimirJogadores(i+1, n, jogador); } } int decomporTabuleiro(int casa, int n) { if(n > casa) { return casa; } else{ return decomporTabuleiro(casa-n, n); } } void rodadaSapo(int i, int n, int m, int casas[], int jogador[]) { if (i < m) { int dado, valor; scanf("%d", &dado); valor = dado + jogador[i]; if (valor > 0) { valor = valor % n; } if (casas[valor] != 0) { valor += casas[valor]; if (valor < 0) { valor = decomporTabuleiro(valor*(-1), n); valor = n - valor; } else{ valor = valor % n; } } jogador[i] = valor; rodadaSapo(i+1, n, m, casas, jogador); } } void jogoSapo(int n, int m, int o, int casas[], int jogador[]) { if (o > 0) { rodadaSapo(0, n, m, casas, jogador); jogoSapo(n, m, o-1, casas, jogador); } } void lerJogador(int i, int m, int jogador[]) { if (i < m) { jogador[i] = 0; lerJogador(i+1, m, jogador); } } void lerCasas(int i, int n, int casas[]) { if (i < n) { scanf("%d", &casas[i]); lerCasas(i+1, n, casas); } } int main () { int n, m, o; scanf("%d%d%d", &n, &m, &o); int casas[n], jogador[m]; lerCasas(0, n, casas); lerJogador(0, m, jogador); jogoSapo(n, m, o, casas, jogador); imprimirJogadores(0, m, jogador); return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #define PI 3.14 #define R 2 #define S PI * R * R #define AREA(r) PI * r * r #define ADD(a, b) a + b #define MUL(a, b) ((a) * (b)) /* *#define MAX(a, b) do{ \ * if (a > b) \ * { \ * printf("max = %d\n", a); \ * } \ * else \ * { \ * printf("max = %d\n", b); \ * } \ * }while(0) * */ #define MAX(a, b) do{if (a > b){printf("max = %d\n", a);}else{printf("max = %d\n", b);}}while(0) #define MAX1(a, b) (((a) > (b)) ? (a) : (b)) float area(int r) { return PI * r * r; } int main(void) { const float a = 3.14; /*PI = 4.14;*/ int r = 2; int num1, num2; printf("please input num1 and num2 : "); scanf("%d%d", &num1, &num2); int max; MAX(num1, num2); max = MAX1(num1, num2); printf("max = %d\n", max); printf("ADD = %d\n", ADD(6, 3)); printf("MUL = %d\n", MUL(4 + 2, 3)); printf("area(r) = %.2f\n", area(r)); printf("AREA(r) = %.2f\n", AREA(r)); printf("s = %.2f\n", PI * r * r); printf("s = %.2f\n", S); printf("PI = %.2f\n", PI); printf("a = %.2f\n", a); return 0; }
C
#include <avr/io.h> #include <avr/interrupt.h> #include <util/delay.h> #define F_CPU 1000000UL #define BAUD 2400 #define BAUDRATE ((F_CPU)/(BAUD*16UL)-1) // define posible commands we can recieve via UART #define READ_0 ((unsigned char) 0) #define READ_1 ((unsigned char) 1) #define READ_2 ((unsigned char) 2) #define READ_3 ((unsigned char) 3) #define MOVE_RIGHT ((unsigned char) 4) #define MOVE_LEFT ((unsigned char) 5) #define MOVE_RIGHT_FULL ((unsigned char) 6) #define MOVE_LEFT_FULL ((unsigned char) 7) #define OK ((unsigned char) 0) void init_uart () { // set baudrate UBRRH = (BAUDRATE >> 8); UBRRL = BAUDRATE; // enable receiver and transmitter and interupts UCSRB |= (1 << TXEN) | (1 << RXEN) | (1 << RXCIE); // 8 bit data format UCSRC |= (1 << URSEL) | (1 << UCSZ0) | (1 << UCSZ1); } void init_adc () { // enable ADC and set ADCSRA register with division fasctor 32 ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADPS0); // use AVCC as VRef (reference voltage) and 8 bit precision ADMUX = (1 << REFS0) | (1 << ADLAR); } void init_gpio () { // define output ports // Wire colors: // -PINB6: WHITE // -PINB7: BLACK // -PIND5: ORANGE // -PIND6: BLUE // -PIND7: RED // -PINB0: YELLOW DDRD = (1 << PIND5) | (1 << PIND6) | (1 << PIND7); DDRB = (1 << PINB0) | (1 << PINB6) | (1 << PINB7); // make them high since the 'ouput' is active when low PORTD = 0xFF; PORTB = 0xFF; // PORTD &= ~(1 << PIND5); // PORTD &= ~(1 << PIND6); // PORTD &= ~(1 << PIND7); // PORTB &= ~(1 << PINB0); // PORTB &= ~(1 << PINB6); // PORTB &= ~(1 << PINB7); } void uart_send (unsigned char data) { while (!(UCSRA & (1 << UDRE))); UDR = data; } unsigned char read_voltage(unsigned char pin) { // select pin to read // (careful! don't forget to alse set REFS0 and ADLARsince it uses same register) ADMUX = pin | (1 << REFS0) | (1 << ADLAR); // start conversion ADCSRA |= (1 << ADSC); while (ADCSRA & (1 << ADSC)); // since we use 8 bit percision we only need to read ADCH register return ADCH; } void move_right () { // move order: orange -> red -> blue -> yellow // STEP 1: PORTD = ~(1 << PIND5); // orrange PORTB = ~(1 << PINB6); // white _delay_ms(200); PORTD = 0xFF; PORTB = 0xFF; _delay_ms(200); // STEP 2: PORTD = ~(1 << PIND7); // red PORTB = ~(1 << PINB7); // black _delay_ms(200); PORTD = 0xFF; PORTB = 0xFF; _delay_ms(200); // STEP 3: PORTD = ~(1 << PIND6); // blue PORTB = ~(1 << PINB6); // white _delay_ms(200); PORTD = 0xFF; PORTB = 0xFF; _delay_ms(200); // STEP 4: PORTD = 0xFF; // we don't use it PORTB = ~(1 << PINB0) & ~(1 << PINB7); // yeelow and black _delay_ms(200); PORTD = 0xFF; PORTB = 0xFF; _delay_ms(200); // reset all the ports PORTD = 0xFF; PORTB = 0xFF; uart_send(OK); } void move_left () { // move order: blue -> red -> orange -> yellow // STEP 1: PORTD = ~(1 << PIND6); // blue PORTB = ~(1 << PINB6); // white _delay_ms(200); PORTD = 0xFF; PORTB = 0xFF; _delay_ms(200); // STEP 2: PORTD = ~(1 << PIND7); // red PORTB = ~(1 << PINB7); // black _delay_ms(200); PORTD = 0xFF; PORTB = 0xFF; _delay_ms(200); // STEP 3: PORTD = ~(1 << PIND5); // orange PORTB = ~(1 << PINB6); // white _delay_ms(200); PORTD = 0xFF; PORTB = 0xFF; _delay_ms(200); // STEP 4: PORTD = 0xFF; // we don't use it PORTB = ~(1 << PINB0) & ~(1 << PINB7); // yeelow and black _delay_ms(200); PORTD = 0xFF; PORTB = 0xFF; _delay_ms(200); // reset all the ports PORTD = 0xFF; PORTB = 0xFF; uart_send(OK); } void move_right_full () { // move order: orange&red -> red&blue -> blue&yellow -> yellow&orange // STEP1: PORTD = ~(1 << PIND5) & ~(1 << PIND7); // orange and red _delay_ms(200); // STEP 2: PORTD = ~(1 << PIND6) & ~(1 << PIND7); // blue and red _delay_ms(200); // STEP 3: PORTB = ~(1 << PINB0); // yellow PORTD = ~(1 << PIND6); // blue _delay_ms(200); // STEP 4: PORTB = ~(1 << PINB0); // yellow PORTD = ~(1 << PIND5); // orange _delay_ms(200); } void move_left_full () { // move order: yellow&blue -> blue&red -> red&orange -> orange&yellow // STEP1: PORTB = ~(1 << PINB0); // yellow PORTD = ~(1 << PIND6); // blue _delay_ms(200); // STEP 2: PORTD = ~(1 << PIND6) & ~(1 << PIND7); // blue and red _delay_ms(200); // STEP 3: PORTD = ~(1 << PIND5) & ~(1 << PIND7); // orange and red _delay_ms(200); // STEP 4: PORTB = ~(1 << PINB0); // yellow PORTD = ~(1 << PIND5); // orange _delay_ms(200); } int main () { init_uart(); init_adc(); init_gpio(); sei(); while (1) {}; } // handle interupts ISR(USART_RXC_vect) { unsigned char command = UDR; unsigned char res; switch(command) { case READ_0: case READ_1: case READ_2: case READ_3: res = read_voltage(command); uart_send(res); break; case MOVE_RIGHT: move_right(); break; case MOVE_LEFT: move_left(); break; case MOVE_RIGHT_FULL: move_right_full(); break; case MOVE_LEFT_FULL: move_left_full(); break; } }
C
#include <stdio.h> #include <stdlib.h> /** numĵַõֵַָһ */ void change(int *num) { // nummainеnumͬһ // ļһӰmainеnum *num += 1; } int main(void) { int num = 9; change(&num); // ú printf("num = %d\n", num); // Ϊ10 return (0); }
C
#include <stdio.h> #include <string.h> int main(void) { printf("hello!\n"); printf("\033[1mhello!\033[0m\n"); printf("\033[4mhello!\033[0m\n"); printf("\033[31;42mhello!\033[0m\n"); /* *printf("ESC[2Ihello![0I\n"); *printf("\033[3Ihello!\033[0I\n"); */ return 0; }
C
#include <stdio.h> int main() { char *chessboard [8][8]; for (int i=0;i<8;i++) { for (int j = 0; j<8;j++) { if (i==0 || i==7) { switch (j) { case 0: case 7: chessboard[i][j] ="R"; break; case 1: case 6: chessboard[i][j] ="N"; break; case 2: case 5: chessboard[i][j] ="B"; break; case 3: chessboard[i][j] ="Q"; break; case 4: chessboard[i][j] ="K"; break; } } else if(i==1 || i == 6) { chessboard[i][j] ="P"; } else chessboard[i][j] =" "; } } for (int i=0;i<8;i++) { for (int j = 0; j<8;j++) { printf("%s",chessboard[i][j]); } printf("\n"); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <mpi.h> #include "misc.h" #include "hotplate.h" #define WIDTH 768 #define HEIGHT 768 #define MSG_SLICE_START 0 #define MSG_SLICE_END 1 #define MSG_DONE 2 int nproc, iproc; Hotplate *plate; int main(int argc, char *argv[]) { int iter = 0; double start = 0.0, finish = 0.0; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &nproc); MPI_Comm_rank(MPI_COMM_WORLD, &iproc); if (iproc == 0) { printf("Number of nodes: %d\n", nproc); } // All nodes: { // int i; MPI_Status status; printf("Node %d started...\n", iproc); start = when(); // Do our job: plate = hp_initialize(WIDTH, HEIGHT); plate->iproc = iproc; plate->nproc = nproc; hp_slice(plate, nproc, iproc); hp_fill(plate, 50.0); hp_hline(plate, 0, 0, WIDTH-1, 0.0); hp_hline(plate, HEIGHT-1, 0, WIDTH-1, 100.0); hp_vline(plate, 0, 0, HEIGHT-1, 0.0); hp_vline(plate, WIDTH-1, 0, HEIGHT-1, 0.0); hp_etch_hotspots(plate); hp_copy_to_source(plate); int done = FALSE; int recv_done; while (!done) { // fprintf(stderr, "[%d] Node: %d\n", iter, iproc); // Send top row up if (iproc > 0) MPI_Send(hp_slice_start_row(plate), plate->width, MPI_FLOAT, iproc-1, MSG_SLICE_START, MPI_COMM_WORLD); // Send bottom row down if (iproc < nproc-1) MPI_Send(hp_slice_end_row(plate), plate->width, MPI_FLOAT, iproc+1, MSG_SLICE_END, MPI_COMM_WORLD); // Receive top row from above if (iproc > 0) MPI_Recv(hp_slice_start_row(plate) - plate->width, plate->width, MPI_FLOAT, iproc-1, MSG_SLICE_END, MPI_COMM_WORLD, &status); // Receive bottom row from below if (iproc < nproc-1) MPI_Recv(hp_slice_end_row(plate) + plate->width, plate->width, MPI_FLOAT, iproc+1, MSG_SLICE_START, MPI_COMM_WORLD, &status); hp_slice_heat(plate); hp_etch_hotspots(plate); done = hp_is_steady_state(plate); MPI_Allreduce (&done, &recv_done, 1, MPI_INT, MPI_LAND, MPI_COMM_WORLD); done = recv_done; if (done) printf("%d reached steady state (%d)\n", iproc, iter); else iter++; hp_swap(plate); } hp_destroy(plate); // Done job finish = when(); } MPI_Finalize(); // All nodes: { printf("Node %d completed %d iterations in %f seconds.\n", iproc, iter, finish - start); // printf("%d cells had a value greater than 50.0.\n", gt_count); } return 0; }
C
#include <stdio.h> int main(int argc, char const *argv[]) { int i,count,distancia,vezes,k,step,matriz[100]; scanf("%d",&count); for (i = 0; i < count; i++) { scanf("%d %d",&distancia,&vezes); for (k = 0; k < vezes; k++) { scanf("%d",&step); matriz[k]=step; } k=0; if(matriz[0]==0){ printf("voltou demais\n"); }else{ for (k = 0; k < vezes; k++) { if (distancia != 0) { if (matriz[k] == 1) { distancia--; }else{ distancia++; } }else{ printf("chegou\n"); } } if (distancia>0) { printf("parou no meio\n"); } } } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cnahmias <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/01/14 12:54:16 by cnahmias #+# #+# */ /* Updated: 2020/07/06 10:17:32 by cnahmias ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line.h" int ft_len(char *ptr) { int a; a = 0; if (ptr == (char *)0) return (0); while (ptr[a]) a++; return (a); } int ft_search(char *s) { int x; if (ft_len(s) == 0) return (-1); x = 0; while (s[x] != '\0') { if (s[x] == '\n') return (x); x++; } return (-1); } int get_next_line_bis(int fd, char **line, char **rst, char *buffer) { int cpt; buffer = ft_strnew_2(BUFFER_SIZE, buffer); while (((cpt = read(fd, buffer, BUFFER_SIZE)) >= 0)) { if ((cpt != BUFFER_SIZE) && (ft_search(buffer) == -1)) { *line = ft_copy(*line, buffer, cpt); free(buffer); return (0); } else if (ft_search(buffer) != -1) { *line = ft_copy(*line, buffer, ft_search(buffer)); *rst = ft_copy_neg_2(buffer, *rst); return (1); } *line = ft_copy(*line, buffer, cpt); buffer = ft_strnew_2(BUFFER_SIZE, buffer); } return (0); } int get_next_line(int fd, char **line) { int i; char *buffer; static char *rst[1]; if (fd < 0 || line == NULL || BUFFER_SIZE < 1 || read(fd, 0, 0) == -1) return (-1); *line = NULL; if ((ft_len(*rst) != 0) && (ft_search(*rst) != -1)) { *line = ft_copy(*line, *rst, ft_search(*rst)); *rst = ft_copy_neg_1(*rst, ft_search(*rst)); return (1); } *line = (ft_len(*rst) != 0 ? ft_copy(*line, *rst, -3) : *line); free(*rst); *rst = NULL; buffer = ft_strnew(BUFFER_SIZE); i = get_next_line_bis(fd, line, rst, buffer); if (i == 0) free(*rst); return (i); }
C
#include "sort.h" /** * insertion_sort_list - sorts a double linked list * of integers in ascending order * @list: list listint_t * Return: Void */ void insertion_sort_list(listint_t **list) { listint_t *l_list = NULL; listint_t *a = NULL; listint_t *b = NULL; listint_t *tmp = NULL; listint_t *tmp_1 = NULL; if (!list || !(*list) || !(*list)->next) { return; } l_list = (*list)->next; while (l_list) { b = l_list; a = b->prev; while (a && a->n > b->n) { tmp = b->next; tmp_1 = a->prev; a->next = b->next; b->prev = a->prev; a->prev = b; b->next = a; if (tmp_1) tmp_1->next = b; if (tmp) tmp->prev = a; if (!b->prev) *list = b; print_list(*list); a = b->prev; } l_list = l_list->next; } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define LIM 40 char * s_gets(char *st, int n); void search(char *str); int main() { char *input[LIM]; printf("Enter a string less than %d: \n", LIM); gets(input); search(input); return 0; } char * s_gets(char *st, int n) { char ret_val; int i = 0; ret_val = fgets(st, n ,stdin); if(ret_val) { while(st[i] != '\n' && st[i] != '\0') i++; if(st[i] == '\n') st[i] = '\0'; else while(getchar() != '\n') continue; } return ret_val; } /*void search(char *str) { int i, j = 0, mark = 0, t, a[LIM]; for(i = 0; *str; i++) { if(str[i] >= '0' && str[i] <= '9' && mark == 0){ t = atoi(str[i]); mark = 1; } else if(str[i] >= '0' && str[i] <= '9' && mark == 1){ t = t * 10 + atoi(str[i]); } else if(mark == 1){ a[j] == t; j++; mark == 0; } if(str[i-1]>='0'&&str[i-1]<='9'){ a[j] = t; j++; } } for(i = 0; i < j; i++) { printf("%d ", a[i]); } }*/ void search(char *str){ int i, j = 0, flag = 0, t = 0, a[20]; for(i = 0; str[i] != '\0'; i++){ if(str[i] >= '0' && str[i] <= '9' && flag == 0){ flag = 1; t = (int)str[i] - '0'; } else if(str[i] >= '0' && str[i] <= '9' && flag != 0) t = t * 10 + (int)str[i] - '0'; else if(flag != 0){ a[j] = t; j++; flag = 0; } } if(str[i-1] >= '0' && str[i-1] <= '9'){ a[j] = t; j++; } for(i = 0; i < j; i++) printf("%d ", a[i]); }
C
/* * gmem.h * * Memory routines with out-of-memory checking. * * Copyright 1996-2003 Glyph & Cog, LLC */ #ifndef GMEM_H #define GMEM_H #include <stdio.h> #ifdef __cplusplus extern "C" { #endif /* * Same as malloc, but prints error message and exits if malloc() * returns NULL. */ extern void *gmalloc(int size); /* * Same as realloc, but prints error message and exits if realloc() * returns NULL. If <p> is NULL, calls malloc instead of realloc(). */ extern void *grealloc(void *p, int size); /* * These are similar to gmalloc and grealloc, but take an object count * and size. The result is similar to allocating nObjs * objSize * bytes, but there is an additional error check that the total size * doesn't overflow an int. */ extern void *gmallocn(int nObjs, int objSize); extern void *greallocn(void *p, int nObjs, int objSize); /* * Same as free, but checks for and ignores NULL pointers. */ extern void gfree(void *p); #ifdef DEBUG_MEM /* * Report on unfreed memory. */ extern void gMemReport(FILE *f); #else #define gMemReport(f) #endif /* * Allocate memory and copy a string into it. */ extern char *copyString(char *s); #ifdef __cplusplus } #endif #endif
C
#include "binary_trees.h" /** * binary_tree_depth - function that measures the depth * of a node in a binary tree. * @tree: pointer to the node to measure the depth. * Return: 0 if tree is NULL */ size_t binary_tree_depth(const binary_tree_t *tree) { size_t count = 0; if (tree == NULL) { return (0); } while (tree->parent != NULL) { count++; tree = tree->parent; } return (count); } © 2021 GitHub, Inc.T
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* parse_pointers.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: skoskine <skoskine@student.hive.fi> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/25 19:08:42 by skoskine #+# #+# */ /* Updated: 2021/02/05 15:30:18 by skoskine ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include "ft_printf.h" #include <stdlib.h> int parse_pointer(t_data *specs, void *ptr, char **result) { uintmax_t value; char *number; size_t result_len; value = (uintmax_t)ptr; if (!(number = ft_uintmax_itoa_base(value, 16, 0))) return (-1); result_len = ft_strlen(number) + 2; specs->conversion = 'x'; specs->alt_form = 1; specs->has_precision = 0; specs->precision = 0; specs->min_field_width = (specs->min_field_width > result_len) ? (specs->min_field_width - result_len) : 0; result_len += specs->min_field_width; if (!(*result = parse_int_result(specs, number, result_len))) return (-1); free(number); return (result_len); }
C
#include<stdio.h> #include<conio.h> void main() { int n,k; printf("enter the celsius:"); scanf("%d",&n); k=n+273.5; printf("\n%d",k); }
C
/** @file icm20948.h @author Andre Renaud @date July 2020 @brief Interface routines for the ICM 20948 IMU chip */ #ifndef ICM20948_H #define ICM20948_H #ifdef __cplusplus extern "C" { #endif #include <stdbool.h> #include "config.h" #include "twi.h" /** Define datatype for handle to ICM20948 functions. */ typedef struct { twi_t twi; /* TWI bus */ twi_slave_addr_t imu_addr; /* Address of the ICM20948 - one of 0x68 or 0x69 */ int bank; /* Which bank in the ICM 20948 is currently active */ } icm_t; /** * Initialise the ICM20948 object, attached on a TWI/I2C bus * NOTE: Only one of these can currently be created * * @param twi TWI bus on which the ICM20948 device exists * @parma slave_addre TWI address of the ICM20948 device * @return ICM20948 object, or NULL on failure */ icm_t *icm20948_create(twi_t twi, twi_slave_addr_t slave_addr); /** * Return true if IMU has data ready. * * @param ICM20948 object pointer * @return true if the ICM20948 has IMU data ready, false otherwise */ bool icm20948_is_imu_ready(icm_t *icm); /** * Return raw accelerometer data. * * @param icm ICM20948 object pointer * @param acceldata Array of 3 16-bit integers to store the accelerometer * data into * @return true if the data was read successfully, false otherwise */ bool icm20948_read_accel(icm_t *icm, int16_t acceldata[3]); /** * Return raw gyroscope data. * * @param icm ICM20948 object pointer * @param gyrodata Array of 3 16-bit integers to store the gyro * data into * @return true if the data was read successfully, false otherwise */ bool icm20948_read_gyro(icm_t *icm, int16_t gyrodata[3]); /** * Return true if magnetometer has data ready. * * @param icm ICM20948 object pointer * @return true if the ICM20948 has magnetometer data ready, false otherwise */ bool icm20948_is_mag_ready(icm_t *icm); /** * Return raw magetometer data. * * @param icm ICM20948 object pointer * @param magdata Array of 3 16-bit integers to store the magnetometer * data into. * @return true if the data was read successfully, false otherwise */ bool icm20948_read_mag(icm_t *icm, int16_t magdata[3]); /** * Return the temperature of the ICM * * @param icm ICM20948 object pointer * @param temp Pointer to the integer to store the temperature, * in 1/100th of a degree * @return true if the temperature was read successfully, false otherwise */ bool icm20948_read_temperature(icm_t *icm, int *temp); #ifdef __cplusplus } #endif #endif
C
// mysh.c ... a small shell // Started by John Shepherd, September 2018 // Completed by Yuancong, July 2020 #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <signal.h> #include <sys/wait.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <glob.h> #include <assert.h> #include <fcntl.h> #include <errno.h> #include "history.h" // This is defined in string.h // BUT ONLY if you use -std=gnu99 //extern char *strdup(char *); // Function forward references void trim(char *); char **tokenise(char *, char *); char **fileNameExpand(char **); void freeTokens(char **); char *findExecutable(char *, char **); int isExecutable(char *); void prompt(void); void pwd(void); int checkRedirect(char **, int); int howManyTokens(char **); int checkInput(char *); int checkOutput(char *); void redirect(char **, int); // Global Constants #define MAXLINE 200 #define VALID 0 #define INVALID 1 #define NONE 2 // Main program // Set up enviroment and then run main loop // - read command, execute command, repeat int main(int argc, char *argv[], char *envp[]) { pid_t pid; // pid of child process int stat; // return status of child char **path; // array of directory names int cmdNo; // indicate which command number to get int seqNo; // seqence number of the last entry int i; // generic index // set up command PATH from environment variable for (i = 0; envp[i] != NULL; i++) { if (strncmp(envp[i], "PATH=", 5) == 0) break; } if (envp[i] == NULL) path = tokenise("/bin:/usr/bin",":"); else // &envp[i][5] skips over "PATH=" prefix path = tokenise(&envp[i][5],":"); #ifdef DBUG for (i = 0; path[i] != NULL;i++) printf("path[%d] = %s\n",i,path[i]); #endif // initialise command history // - use content of ~/.mymysh_history file if it exists seqNo = initCommandHistory(); // main loop: print prompt, read line, execute command char line[MAXLINE]; // input line buffer char **args; // arguements holding tokenised lines char *fullpath; // fullpath of executable int length = 0; // numbers of tokens int redirctStatus = 0; // hold a value which determine whther to redirect prompt(); while (fgets(line, MAXLINE, stdin) != NULL) { // remove leading/trailing space trim(line); // if command is "exit", exit if (!strcmp(line,"exit")) break; // if empty command, ignore if (!strcmp(line, "")) { prompt(); continue; } // handle ! history substitution if (line[0] == '!') { // !! if (line[1] == '!') { if (seqNo != 0) { strcpy(line, getCommandFromHistory(seqNo)); printf("%s\n", line); } else { printf("No command #0\n"); prompt(); continue; } } else { // !# if (sscanf(line, "!%d", &cmdNo) == 1) { if (getCommandFromHistory(cmdNo) != NULL) { strcpy(line, getCommandFromHistory(cmdNo)); printf("%s\n",line); } else { printf("No command #%d\n", cmdNo); prompt(); continue; } } else { printf("Invalid history substitution\n"); prompt(); continue; } } } // tokenise args = tokenise(line, " "); // handle *?[~ filename expansion args = fileNameExpand(args); // handle shell built-ins if (!strcmp(args[0], "h") || !strcmp(args[0], "history")) { showCommandHistory(stdout); seqNo++; addToCommandHistory(line, seqNo); prompt(); freeTokens(args); continue; } if (!strcmp(args[0], "pwd")) { pwd(); seqNo++; addToCommandHistory(line, seqNo); prompt(); freeTokens(args); continue; } if (!strcmp(args[0], "cd")) { // cd -> "HOME" if (args[1] == NULL) { chdir(getenv("HOME")); pwd(); seqNo++; addToCommandHistory(line, seqNo); // cd path } else { if (chdir(args[1]) == 0) { pwd(); seqNo++; addToCommandHistory(line, seqNo); } else { printf("%s: %s\n", args[1],strerror(errno)); } } prompt(); freeTokens(args); continue; } // check for input/output redirections length = howManyTokens(args); redirctStatus = checkRedirect(args, length); if (redirctStatus == INVALID) { prompt(); freeTokens(args); continue; } // find executable using first token fullpath = findExecutable(args[0], path); // if none, then Command not found if (fullpath == NULL) { printf("%s: Command not found\n", args[0]); freeTokens(args); free(fullpath); prompt(); continue; } // run the command printf("Running %s ...\n", fullpath); printf("--------------------\n"); pid = fork(); if (pid > 0) { wait(&stat); } else if (pid == 0) { // sort out redirections if (redirctStatus == VALID) { redirect(args, length); } execve(fullpath, args, envp); printf("%s: unknown type of executable\n", args[0]); exit(-1); } else { perror("Fork error"); } printf("--------------------\n"); printf("Returns %d\n", WEXITSTATUS(stat)); seqNo++; addToCommandHistory(line, seqNo); // print prompt prompt(); freeTokens(args); free(fullpath); } saveCommandHistory(); cleanCommandHistory(); freeTokens(path); printf("\n"); return(EXIT_SUCCESS); } // fileNameExpand: expand any wildcards in command-line args // - returns a possibly larger set of tokens char **fileNameExpand(char **tokens) { glob_t buffer; int i = 0; if (tokens[i] != NULL) { glob(tokens[i], GLOB_NOCHECK|GLOB_TILDE, NULL, &buffer); i++; } for ( ; tokens[i] != NULL; i++) { glob(tokens[i], GLOB_NOCHECK|GLOB_TILDE|GLOB_APPEND, NULL, &buffer); } freeTokens(tokens); tokens = malloc((buffer.gl_pathc + 1) * sizeof(char *)); assert(tokens != NULL); for (i = 0; i < buffer.gl_pathc; i++) { tokens[i] = strdup(buffer.gl_pathv[i]); } tokens[i] = NULL; globfree(&buffer); return tokens; } // findExecutable: look for executable in PATH char *findExecutable(char *cmd, char **path) { char executable[MAXLINE]; executable[0] = '\0'; if (cmd[0] == '/' || cmd[0] == '.') { strcpy(executable, cmd); if (!isExecutable(executable)) executable[0] = '\0'; } else { int i; for (i = 0; path[i] != NULL; i++) { sprintf(executable, "%s/%s", path[i], cmd); if (isExecutable(executable)) break; } if (path[i] == NULL) executable[0] = '\0'; } if (executable[0] == '\0') return NULL; else return strdup(executable); } // isExecutable: check whether this process can execute a file int isExecutable(char *cmd) { struct stat s; // must be accessible if (stat(cmd, &s) < 0) return 0; // must be a regular file //if (!(s.st_mode & S_IFREG)) if (!S_ISREG(s.st_mode)) return 0; // if it's owner executable by us, ok if (s.st_uid == getuid() && s.st_mode & S_IXUSR) return 1; // if it's group executable by us, ok if (s.st_gid == getgid() && s.st_mode & S_IXGRP) return 1; // if it's other executable by us, ok if (s.st_mode & S_IXOTH) return 1; return 0; } // tokenise: split a string around a set of separators // create an array of separate strings // final array element contains NULL char **tokenise(char *str, char *sep) { // temp copy of string, because strtok() mangles it char *tmp; // count tokens tmp = strdup(str); int n = 0; strtok(tmp, sep); n++; while (strtok(NULL, sep) != NULL) n++; free(tmp); // allocate array for argv strings char **strings = malloc((n+1)*sizeof(char *)); assert(strings != NULL); // now tokenise and fill array tmp = strdup(str); char *next; int i = 0; next = strtok(tmp, sep); strings[i++] = strdup(next); while ((next = strtok(NULL,sep)) != NULL) strings[i++] = strdup(next); strings[i] = NULL; free(tmp); return strings; } // freeTokens: free memory associated with array of tokens void freeTokens(char **tokens) { for (int i = 0; tokens[i] != NULL; i++) free(tokens[i]); free(tokens); } // trim: remove leading/trailing spaces from a string void trim(char *str) { int first, last; first = 0; while (isspace(str[first])) first++; last = strlen(str)-1; while (isspace(str[last])) last--; int i, j = 0; for (i = first; i <= last; i++) str[j++] = str[i]; str[j] = '\0'; } // prompt: print a shell prompt // done as a function to allow switching to $PS1 void prompt(void) { printf("mymysh$ "); } // pwd: print current working directory void pwd(void) { char buffer[MAXLINE]; getcwd(buffer, sizeof(buffer)); printf("%s\n", buffer); } // howManyTokens: count how many tokens are in char **tokens int howManyTokens(char **tokens) { int length = 0; while (tokens[length] != NULL) { length++; } return length; } // checkRedirect: check if the redirection can be executed // return VALID if redirection can be done // return INVALD if redirction cannot be done // return NONE if not redirction is detected int checkRedirect(char **tokens, int length) { // if number of tokens is <= 1 and ">" or "<" appears, definitly invalid if (length < 2) { if (!strcmp(tokens[0], ">") || !strcmp(tokens[0], "<")) { printf("Invalid i/o redirection\n"); return INVALID; } else { return NONE; } } // if >= 2, check if it is in right place for (int i = 0; tokens[i] != NULL; i++) { if ((!strcmp(tokens[i], ">") || !strcmp(tokens[i], "<")) && (i != length - 2 || i == 0)) { printf("Invalid i/o redirection\n"); return INVALID; } } // if right, check if the objected file is accessable if (!strcmp(tokens[length-2], "<")) { if (!checkInput(tokens[length-1])) { return VALID; } else { return INVALID; } } else if (!strcmp(tokens[length-2], ">")) { if (!checkOutput(tokens[length-1])) { return VALID; } else { return INVALID; } // if no ">" or "<", return NONE } else { return NONE; } } // checkInput: check if the input document exist or can be access int checkInput(char *arg) { FILE *input = fopen(arg, "r"); if (input != NULL) { fclose(input); return 0; } else { perror("Input redirection"); return 1; } } // checkOutput: check if the output ducument can be access int checkOutput(char *arg) { FILE *output = fopen(arg, "w"); if (output != NULL) { fclose(output); return 0; } else { perror("Output redirection"); return 1; } } // redirct: redirect stdin/stdout to objected ducuments void redirect(char **tokens, int length) { if (!strcmp(tokens[length-2], "<")) { int inputFd = open(tokens[length-1], O_RDONLY); dup2(inputFd, STDIN_FILENO); free(tokens[length-1]); free(tokens[length-2]); tokens[length-2] = NULL; } else if (!strcmp(tokens[length-2], ">")) { int outputFd = open(tokens[length-1], O_WRONLY|O_CREAT|O_TRUNC, 0644); dup2(outputFd, STDOUT_FILENO); free(tokens[length-1]); free(tokens[length-2]); tokens[length-2] = NULL; } }
C
#include <stdio.h> int main(){ //int n,fatorial; int n; int fatorial=1; printf("Insira um inteiro positivo:\n" ); scanf("%d",&n); while(n>1){ fatorial=fatorial*n; n--; //ou n=n-1; } printf("O fatorial do numero inserido e %d\n",fatorial ); return 0; }
C
#include<stdio.h> #include<stdlib.h> // Use a linked list for no particular reason, i just wanted to use a linked list typedef struct node{ char data; int count; struct node * next; }node; void add(node * head, char c){ while(head->next != NULL){ if(head->data == c) break; head = head->next; } if(head->data == c) head->count++; else{ head->next = malloc(sizeof(node)); head->next->count = 1; head->next->data = c; head->next->next = NULL; } } int main(){ int c; node * head = malloc(sizeof(node)); head->data = getchar(); head->count = 1; head->next = NULL; while( (c = getchar()) != EOF ){ add(head,c); } while(head->next != NULL){ printf("%c",head->data); for(int i=0;i<head->count;i++) putchar('-'); head = head->next; putchar('\n'); } }
C
#include <stdio.h> int main() { int numero, qtdhrstrab; float valorhora, salario; scanf("%d", &numero); scanf("%d", &qtdhrstrab); scanf("%f", &valorhora); salario = (qtdhrstrab * valorhora); printf("NUMBER = %d\n", numero); printf("SALARY = U$ %0.2f\n", salario); return 0; }
C
// LinkList.cpp // 30.12.2020 #include<stdio.h> #include<process.h> #include<stdlib.h> struct node{ int info; struct node* link; }; struct node* start=NULL; void create(); void traverse(); void insert_beg(); void insert_last(); void insert_after(); void delete_beg(); void delete_last(); void delete_after(); void search(); void sorting(); void dup(); int main(){ int choice; create(); while(1){ printf("\n\nMENU\n\n"); printf("1.Traverse\n"); printf("2.Insert at beg\n"); printf("3.Insert at last\n"); printf("4.Insert after\n"); printf("5.Delete at beg\n"); printf("6.Delete at last\n"); printf("7.Delete after\n"); printf("8.Search\n"); printf("9.Sorting\n"); printf("10.Duplicate\n"); printf("11.Exit\n"); printf("Enter your choice: ",choice); scanf("%d",&choice); switch(choice){ case 1: traverse(); break; case 2: insert_beg(); break; case 3: insert_last(); break; case 4: insert_after(); break; case 5: delete_beg(); break; case 6: delete_last(); break; case 7: delete_after(); break; case 8: search(); break; case 9: sorting(); break; case 10: dup(); break; case 11: exit(0); default : printf("Invalid choice."); } } return 0; } void create(){ struct node *new,*ptr; int item; char ans='y'; while(ans=='y'||ans=='Y') { printf("Enter item value: ",item); scanf("%d",&item); new=(struct node*)malloc(sizeof(struct node)); if(new==NULL){ printf("Memory overflow\n"); return; } new->info=item; new->link=NULL; if(start==NULL){ start=new; } else { ptr=start; while(ptr->link!=NULL) ptr=ptr->link; ptr->link=new; } printf("Do you want to add more nodes? "); scanf(" %c",&ans); } } void traverse(){ struct node* ptr; if(start==NULL){ printf("List is empty"); return; } else { ptr=start; while(ptr!=NULL) { printf("\t%d",ptr->info); ptr=ptr->link; } } } void insert_beg(){ struct node *new; int item; new=(struct node*)malloc(sizeof(struct node)); if(new==NULL){ printf("memory overflow\n"); return; } printf("Enter item value: "); scanf("%d",&item); new->info=item; new->link=start; start=new; } void insert_last(){ struct node* new,*ptr; int item; new=(struct node*)malloc(sizeof(struct node)); if(new==NULL){ printf("Memory overflow\n"); return; } printf("Enter item value: "); scanf("%d",&item); new->info=item; new->link=NULL; if(start==NULL){ start=new; } else{ ptr=start; while(ptr->link!=NULL) { ptr=ptr->link; } ptr->link=new; } } void insert_after(){ struct node* new,*ptr; int item,i,pos; new=(struct node*)malloc(sizeof(struct node)); if(new==NULL){ printf("Memory overflow\n"); return; } printf("Enter item value: "); scanf("%d",&item); printf("Enter position after which you want to insert: "); scanf("%d",&pos); new->info=item; i=1,ptr=start; while(i<pos){ if(ptr==NULL){ printf("Invalid input\n"); return; } ptr=ptr->link; i++; } new->link=ptr->link; ptr->link=new; } void delete_beg(){ struct node* temp; if(start==NULL){ printf("Underflow\n"); return; } temp=start; start=start->link; printf("Deleted node is %d",temp->info); free(temp); } void delete_last(){ struct node *ptr,*save; if(start==NULL){ printf("Underflow"); return; } if(start->link==NULL){ ptr=start; start=start->link; } save=start; ptr=start->link; while(ptr->link!=NULL){ save=ptr; ptr=ptr->link; } save->link=NULL; printf("Deleted node is %d",ptr->info); free(ptr); } void delete_after(){ struct node *ptr,*temp; int i,pos; if(start==NULL){ printf("\nUnderflow"); return; } printf("Enter position "); scanf("%d",&pos); temp=start; ptr=start->link; for(i=1;i<pos;i++){ temp=ptr; ptr=ptr->link; if(ptr=NULL){ printf("\nInvalid position"); return; } } printf("\nDeleted node is: %d",ptr->info); temp->link=ptr->link; free(ptr); } void search(){ struct node *ptr; int item,i; if(start==NULL){ printf("List is empty\n"); return; } printf("Enter item you want to find: "); scanf("%d",&item); ptr=start; i=1; while(ptr!=NULL){ if(ptr->info==item){ printf("%d found at %d position",item,i); break; } i++; ptr=ptr->link; } if(ptr=NULL){ printf("\n%d Item not found",item); } } void sorting(){ struct node *ptr,*ptr1; int temp; if(start==NULL){ printf("List if empty"); return; } for(ptr=start;ptr->link!=NULL;ptr=ptr->link){ for(ptr1=ptr->link;ptr1!=NULL;ptr1=ptr1->link) if(ptr->info>ptr1->info){ temp=ptr->info; ptr->info=ptr1->info; ptr1->info=temp; } } } void dup(){ struct node* ptr,*ptr1,*prev,*temp; int data; if(start==NULL){ printf("underflow"); return; } ptr=start; while(ptr!=NULL){ data=ptr->info; prev=ptr; ptr1=ptr->link; while(ptr1!=NULL){ if(data==ptr1->info){ temp=ptr1; prev->link=ptr1->link; ptr1=ptr1->link; free(temp); } else{ prev=ptr1; ptr1=ptr1->link; } } ptr=ptr->link; } }
C
#include "holberton.h" /** * is_all_digits - checks to see if all characters in a string are digits * @s: string to check * Return: 1 if all chars are digits, 0 otherwise */ int is_all_digits(char *s) { int i = 0; while (s[i]) { if (s[i] < 48 || s[i] > 57) return (0); i++; } return (1); } /** * build_row - multiplies 'a' with 'b[i]' * @size: length of buffer * @row_idx: i in b[i], index of current sum in progress * @a: first string of digits * @b: second string of digits * @len_a: length of first string * @len_b: length of second string * Return: string representation of product of 'a' and 'b[i]' */ char *build_row(int size, int row_idx, char *a, char *b, int len_a, int len_b) { char *row = malloc(sizeof(char) * (size + 1)); int column_index = row_idx; char char_b = b[len_b - 1]; int int_b = char_to_int(char_b); int index_a = len_a - 1; int carry = 0; pad_zeros(row, row_idx); while (index_a >= 0) { char char_a = a[index_a]; int int_a = char_to_int(char_a); int product = ((int_a * int_b) + carry); carry = 0; if (product > 9) { carry = product / 10; product %= 10; } row[column_index] = int_to_char(product); column_index++; index_a--; } if (carry > 0) { row[column_index] = int_to_char(carry); column_index++; } row[column_index] = '\0'; return (row); } /** * print_string - prints a string to standard output * @s: string to print * Return: void */ void print_string(char *s) { int i; int is_printing = 0; if (s) { for (i = 0; s[i] ; i++) { if (!is_printing && s[i] != '0') is_printing = 1; if (is_printing) _putchar(s[i]); } if (!is_printing) _putchar('0'); _putchar('\n'); } } /** * free_rows - frees each strings in an array of strings * @rows: array containing strings to be freed * @row_count: number of strings to be free * Return: void */ void free_rows(char **rows, int row_count) { int i = 0; while (i < row_count) { free(*rows); rows++; i++; } } /** * get_string_length - gets the length of a character array * @s: character array to count * Return: length of character array */ int get_string_length(char *s) { int length = 0; while (1 == 1) { if (s[length] == '\0') break; length++; } return (length); } /** * _exit - custom exit with message * @exit_code: exit code * Return: void */ void _exit(int exit_code) { print_string("Error"); exit(exit_code); }
C
#include "../../inc/koala.h" /** ** Create a token of a pipe **/ int tokenize_pipe(char **tok, t_que **lex) { if (*tok) { if (**tok != '\0') push_que(0, *tok, lex); free(*tok); (*tok) = NULL; } (*tok) = ft_strdup("|"); if (!(*tok)) exit(1); if (*tok) { push_que(0, *tok, lex); free(*tok); (*tok) = NULL; } (*tok) = ft_strdup("\0"); if (!(*tok)) exit(1); return (0); } /** ** Create a token for closed quotes **/ static void check_push_quot(char quot, char *line, char **tok, t_que **lex) { if (*tok) { if (quot == '\'' && (**tok) != '\0') { if (!(*(line + 1)) || *(line + 1) == ' ') push_que(2, *tok, lex); } else if (!(*(line + 1)) || *(line + 1) == ' ') push_que(1, *tok, lex); if (!(*(line + 1)) || *(line + 1) == ' ') { free(*tok); (*tok) = NULL; } } if (!(*(line + 1)) || *(line + 1) == ' ') (*tok) = ft_strdup("\0"); if (!(*tok)) exit(1); } int tokenize_quot(char quot, char *line, char **tok, t_que **lex) { int count; count = 1; while (line[count] != quot) { do_join(1, tok, ft_charstr(line[count])); count++; } if (line[count] == '\'' || line[count] == '\"') check_push_quot(quot, line + count, tok, lex); return (count); } /** ** Create a token of the redirection < << > >> **/ static int check_push_red(char **tok, t_que **lex) { int out; out = 0; if (*tok) { out = ft_strlen(*tok); push_que(0, *tok, lex); free(*tok); (*tok) = NULL; } (*tok) = ft_strdup("\0"); if (!(*tok)) exit(1); return (out - 1); } int tokenize_red(char *line, char **tok, t_que **lex) { if (*tok) { if (**tok != '\0') push_que(0, *tok, lex); free(*tok); (*tok) = NULL; } if (line[0] == '<' && line[1] == '<') (*tok) = ft_strdup("<<"); else if (line[0] == '>' && line[1] == '>') (*tok) = ft_strdup(">>"); else if (line[0] == '<') (*tok) = ft_strdup("<"); else if (line[0] == '>') (*tok) = ft_strdup(">"); return (check_push_red(tok, lex)); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* stalkcursor.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbelondr <sbelondr@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/12 17:19:17 by aleduc #+# #+# */ /* Updated: 2019/05/15 16:30:43 by sbelondr ### ########.fr */ /* */ /* ************************************************************************** */ #include "sh21.h" void get_cursor(int i, int j, char *answer, t_pos *pos) { char xchar[5]; char ychar[5]; ft_bzero(xchar, 5); ft_bzero(ychar, 5); ++i; while (answer[i] && answer[i] != ';') { if ((answer[i] >= '0' && answer[i] <= '9')) xchar[j++] = answer[i]; ++i; } xchar[j] = '\0'; j = 0; ++i; while (answer[i] && answer[i] != 'R') { if ((answer[i] >= '0' && answer[i] <= '9')) ychar[j++] = answer[i]; ++i; } ychar[j] = '\0'; pos->row = ft_atoi(xchar); pos->column = ft_atoi(ychar); } void stalk_cursor(t_pos *pos) { char *answer; size_t answerlen; int i; int j; i = 1; j = 0; if (!(answer = ft_memalloc(sizeof(char) * 16))) return ; ioctl(STDOUT_FILENO, TIOCGWINSZ, &pos->termsize); write(0, "\x1B[6n", 5); answerlen = 0; while (answerlen < 16 - 1 && read(STDIN_FILENO, answer + answerlen, 1) == 1) { if (answer[answerlen++] == 'R') break ; } answer[answerlen] = '\0'; get_cursor(i, j, answer, pos); free(answer); } void get_tail(t_pos *pos) { if (pos->tailcolumn < pos->termsize.ws_col) pos->tailcolumn++; if (pos->tailcolumn == pos->termsize.ws_col) { pos->tailcolumn = 0; if (pos->tailrow < pos->termsize.ws_row) pos->tailrow++; } if (pos->tailrow >= pos->termsize.ws_row) pos->tailrow = pos->termsize.ws_row; } void savecursor(t_pos *pos) { stalk_cursor(pos); pos->savecolumn = pos->column; pos->saverow = pos->row; } void cursorback(t_pos *pos) { tputs(tgoto(tgetstr("cm", NULL), pos->savecolumn - 1, pos->saverow - 1), 1, ft_outc); }
C
#include "BCDCompute.h" byte BCDaddOne(byte BCDvalue, byte BCDmin, byte BCDmax) { if (BCDvalue >= BCDmax) return BCDmin; if (BCDvalue < BCDmin) return BCDmin; if ((BCDvalue & 0xF) != 9) BCDvalue++; else BCDvalue = (BCDvalue & 0xF0) + 0x10; return BCDvalue; } byte BCDsubOne(byte BCDvalue, byte BCDmin, byte BCDmax) { if (BCDvalue > BCDmax) return BCDmax; if (BCDvalue <= BCDmin) return BCDmax; if ((BCDvalue & 0xF) != 0) BCDvalue--; else BCDvalue = (BCDvalue & 0xF0) - 0x10 + 0x09; return BCDvalue; }
C
// WAP to SUM two numbers entered through keyboard by using a suitable user // defined function (say SUM) for addition operation. // (By using Category-1: Function taking arguments and returns value) #include<stdio.h> int SUM(int, int); //Function Prototype or Function Declaration int main() { int a, b, c; printf("\nEnter two numbers :"); scanf("%d %d",&a, &b); c = SUM(a,b); //Function Call printf("\nAddition of two numbers is %d.", c); return 0; } /*Function definition of SUM taking * arguments and returns value*/ /*int SUM(int x, int y) { int z; z= x + y; return z; } OR*/ /*Function definition SUM taking arguments * and returns value*/ int SUM(int x, int y) { return x+y; }
C
/* * Clientes_lib.c * * Created on: 10 oct. 2019 * Author: alumno */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdio_ext.h> #include "Clientes_lib.h" int hardCodeClientesList(Cliente list[], int length) { list[0].id=1; strncpy(list[0].nombre,"Hycite SRL",length); strncpy(list[0].direccion,"Suipacha 555",length); strncpy(list[0].localidad,"CABA",length); strncpy(list[0].cuit,"20-3213213-2",length); list[0].isEmpty=0; list[1].id=2; strncpy(list[1].nombre,"MAti SA", length); strncpy(list[1].direccion,"Mitre 420",length); strncpy(list[1].localidad,"Quilmes", length); strncpy(list[1].cuit,"20-789546548-2",length); list[1].isEmpty=0; list[0].id=3; strncpy(list[2].nombre,"Coca Cola ARG SRL", length); strncpy(list[2].direccion,"9 de julio 803", length); strncpy(list[2].localidad,"CABA", length); strncpy(list[2].cuit,"20-4564565213-2", length); list[2].isEmpty=0; return 0; } int initClientes(Cliente list[],int length) { int retorno =-1; int i; if(list!=NULL && length>0) { for(i=0;i<length;i++) { list[i].isEmpty=1; } retorno =0; } return retorno; } int printClienteList(Cliente list[], int length) { int i; int retorno =-1; if(list!=NULL && length>0) { for(i=0;i<length;i++) { if(list[i].isEmpty==0) { printf("\n****************************************\n"); printf("\n id de cliente: %d",list[i].id); printf("\n Nombre: %s",list[i].nombre); printf("\n direccion: %s",list[i].direccion); printf("\n localidad: %s", list[i].localidad); printf("\n cuit: %s", list[i].cuit); printf("\n****************************************\n"); } } retorno=0; } return retorno; } int addCliente(Cliente list[], int length, char name[], char direccion[],int strLength, char localidad[], char cuit[]) { int retorno =-1; int i; if(list!= NULL && length>0) { for(i=0;i<length;i++) { if(list[i].isEmpty==0) { printf("\nla posicion %d esta siendo utilizada", list[i].id); } if(list[i].isEmpty==1){ strncpy(list[i].nombre,name,strLength); strncpy(list[i].direccion,direccion,strLength); strncpy(list[i].localidad,localidad,strLength); strncpy(list[i].cuit,cuit,strlen(cuit)); list[i].isEmpty=0; list[i].id=i+1; retorno=0; break; } } } if(retorno==0) { printf("se ingreso correctamente el Cliente con el id: %d", list[i].id); } return retorno; } int findClienteById(Cliente list[],int length,int *pId,int *position) { int retorno =-1; int i; int id=*pId; if(list!=NULL && length>0) { for(i=0;i<length;i++) { if(list[i].isEmpty==1) { continue; } else if(list[i].id==id) { retorno=0; *position=i; } } } return retorno; } int printClienteById(Cliente list[],int length, int *id) { int retorno =-1; int i; int buffer = *id; if(list!=NULL && length>0) { for(i=0;i<length;i++) { if(list[i].id==buffer) { printf("\n****************************************"); printf("\n Idcliente : %d", list[i].id); printf("\n nombre : %s", list[i].nombre); printf("\n direccion : %s", list[i].direccion); printf("\n localidad : %s", list[i].localidad); printf("\n cuit : %s\n", list[i].cuit); printf("\n****************************************\n"); retorno=0; break; } } } return retorno; }
C
#include <stdio.h> int main(){ char board[20][20]; int q; scanf("%d", &q); while(q--){ for(int i = 0; i < 15; i++) scanf("%s", board[i]); char winner = 'n'; for(int i = 0; i < 15; i++){ for(int j = 0; j < 15; j++){ if(board[i][j] != '.'){ if(i + 4 < 15 && board[i][j] == board[i + 1][j] && board[i][j] == board[i + 2][j] && board[i][j] == board[i + 3][j] && board[i][j] == board[i + 4][j]) winner = board[i][j]; if(j + 4 < 15 && board[i][j] == board[i][j + 1] && board[i][j] == board[i][j + 2] && board[i][j] == board[i][j + 3] && board[i][j] == board[i][j + 4]) winner = board[i][j]; if(i + 4 < 15 && j + 4 < 15 && board[i][j] == board[i + 1][j + 1] && board[i][j] == board[i + 2][j + 2] && board[i][j] == board[i + 3][j + 3] && board[i][j] == board[i + 4][j + 4]) winner = board[i][j]; if(i + 4 < 15 && j - 4 >=0 && board[i][j] == board[i + 1][j - 1] && board[i][j] == board[i + 2][j - 2] && board[i][j] == board[i + 3][j - 3] && board[i][j] == board[i + 4][j - 4]) winner = board[i][j]; } } } if(winner == 'w') printf("white\n"); else if(winner == 'b') printf("black\n"); else printf("none\n"); } }
C
int main(int argc, char *argv[]); __size32 fib(int param1); /** address: 0x100004bc */ int main(int argc, char *argv[]) { int g3; // r3 int g3_2; // r3{12} int g5; // r5 int local0; // m[g1 - 24] printf("Input number: "); g5 = scanf("%d", &local0); /* Warning: also results in %g6, %g7, %g8, %g10, %g11, %g12 */ if (local0 > 1) { g3_2 = fib(local0 - 1); /* Warning: also results in g5, %g6, %g7, %g8, %g10, %g11, %g12, %CR1 */ g3 = fib(g3_2 - 1); printf("%d", g3_2 + g3); printf("fibonacci(%d) = %d\n", local0, g3_2); } else { g5 = 1; if (local0 != 1) { g5 = local0; } printf("fibonacci(%d) = %d\n", local0, g5); } return 0; } /** address: 0x10000440 */ __size32 fib(int param1) { __size32 CR1; // r65 __size1 CR1_1; // r65 __size32 g10; // r10 __size32 g11; // r11 __size32 g12; // r12 int g3; // r3 int g3_2; // r3{11} int g3_4; // r3{25} __size32 g5; // r5 __size32 g6; // r6 __size32 g7; // r7 __size32 g8; // r8 int local3; // g3{14} __size32 local4; // CR1{23} local4 = CR1; if (param1 > 1) { g3_4 = fib(param1 - 1); g3 = fib(g3_4 - 1); /* Warning: also results in CR1 */ %CR1 = %CR1 & ~0x4; g5 = printf("%d", g3_4 + g3); /* Warning: also results in g6, g7, g8, g10, g11, g12 */ local4 = CR1_1; g3 = g3_4; } else { g3_2 = 1; local3 = g3_2; if (param1 != 1) { g3 = param1; local3 = g3; } g3 = local3; } CR1 = local4; return g3; /* WARNING: Also returning: g5 := g5, g6 := g6, g7 := g7, g8 := g8, g10 := g10, g11 := g11, g12 := g12, CR1 := CR1 */ }
C
void call_interrupt(uint8_t PIN) { detachInterrupt(digitalPinToInterrupt(PIN)); } void call_interrupt(uint8_t PIN, void (*isr)) // przesłanie funkcji jako parametru { attachInterrupt(digitalPinToInterrupt(PIN), isr, FALLING); } void read_rpm_seeder() { rpm_seeder_read_window_time_now = millis(); if (rpm_seeder_read_window_time_now - rpm_seeder_read_window_time_past < RPM_SEEDER_READ_WINDOW) { return; } rpm_seeder_counter++; rpm_seeder_read_window_time_past = rpm_seeder_read_window_time_now; } void read_rpm_roller() { rpm_roller_read_window_time_now = millis(); if (rpm_roller_read_window_time_now - rpm_roller_read_window_time_past < RPM_ROLLER_READ_WINDOW) { return; } rpm_roller_counter++; rpm_roller_read_window_time_past = rpm_roller_read_window_time_now; } void get_seeder_speed() { call_interrupt(GET_SEEDER_RPM); unsigned long time_diff = millis() - rpm_seeder_read_window_time_past; call_interrupt(GET_SEEDER_RPM, read_rpm_seeder); if(time_diff < 3000) { if(DEBUG) { Serial.print(time_diff);Serial.print(" ");Serial.println(rpm_seeder_counter); } } } void get_roller_speed() { call_interrupt(GET_ROLLER_RPM); unsigned long time_diff = millis() - rpm_roller_read_window_time_past; call_interrupt(GET_ROLLER_RPM, read_rpm_roller); if(time_diff < 3000) { if(DEBUG) { Serial.print(time_diff);Serial.print(" ");Serial.println(rpm_roller_counter); } } } enum e_command { do_nothing, // nie wykonuj akcji do_stop, // wymus zatrzymanie bierzacej akcji set_sound_alarm_on, set_sound_alarm_off, set_marker_zero, // zlozenie znacznikow set_marker_left, // rozlozenie tylko lewego znacznika set_marker_right, // rozlozenie tylko prawego znacznika set_marker_left_right, // rozlozenie lewego i prawego znacznika set_seeder_up, // podnies siewnik set_seeder_down, // opusc siewnik set_tpath_on, // zablokuj wysiewanie na sciezkach set_tpath_off // odblokuj wysiewanie na sciezkach } seeder_command(do_nothing); /* * marker types: * 1 - dwa siłowniki jednostronnego działania, lub jeden siłownik podwójny, sterowane pojedyńczym zaworem. * Trójnik przełączający - podawanie ciśnienia składanie. Otwieranie zaworu, sprężyny rozkładają znaczniki. * 2 - dwa siłowniki jednostronnego działania, lub jeden siłownik podwójny, sterowane pojedyńczym zaworem. * Bezpośrednie podawanie ciśnienia poprzez 2 osobne zawory sterujące. * 3 - siłowniki elektryczne z krańcówkami wbudowanymi. Czasowe rozkładanie. Sterowanie 4 portami. */ error_code set_seeder_marker_zero(int marker_type = 1) { /* * Funkcja do pdnoszenia znaczników. */ if (0 == SEEDER_ERROR && !marker_is_busy) // jesli obecnie nie ma zadnej akcji na znacznikach { marker_is_busy_timer = millis(); // zresetuj licznik zabezpieczenia czasowego dla znacznikow marker_short_run_on_timer = millis(); // zresetuj licznik zabezpieczenia czasowego dla detekcji l/r znaacznikow } if (set_marker_zero == seeder_command && // jesli jest komenda (((digitalRead(GET_R_MARKER) || // jesli prawy znacznik NIE jest złożony lub digitalRead(GET_L_MARKER)) && // jesli lewy znacznik NIE jest złożony oraz millis() - marker_is_busy_timer < MARKER_BUSY_WINDOW) || // jesli licznik zabezpieczenia czasowego nie jest przekroczony lub marker_force_command)) // jest wymuszenie komendy { // włącz składanie znaczników marker_is_busy = true; // zajętość akcji na znacznikach switch(marker_type) { case 1: if(millis() - marker_short_run_on_timer < MARKER_SHORT_RUN_WINDOW) { digitalWrite(SET_L_MARKER, HIGH); // włącz siłownik znacznika na krotka chwile marker_short_run_off_timer = millis(); } else { if(millis() - marker_short_run_off_timer < MARKER_SHORT_RUN_WINDOW/2) { digitalWrite(SET_L_MARKER, LOW); // wyłącz siłownik znacznika na krotka chwile } else { digitalWrite(SET_L_MARKER, HIGH); // włącz siłownik znacznika aż znaczniki zostaną ustawione } } break; case 2: digitalWrite(SET_L_MARKER, HIGH); // wyłącz siłownik znacznika digitalWrite(SET_R_MARKER, HIGH); // wyłącz siłownik znacznika break; default: break; } if(DEBUG) { Serial.println("set_seeder_marker_zero, składanie znacznikow"); } } else if(set_marker_zero == seeder_command) { // wyłącz składanie znaczników digitalWrite(SET_L_MARKER, LOW); digitalWrite(SET_R_MARKER, LOW); marker_is_busy = false; marker_is_busy_timer = 0; marker_short_run_on_timer = 0; marker_short_run_off_timer = 0; seeder_command = do_nothing; if(DEBUG) { Serial.println("set_seeder_marker_zero, koniec"); } } return NONE; } error_code set_seeder_marker_right_or_left(uint8_t marker_get, uint8_t marker_set, const e_command seder_command_expected, int marker_type = 1) { /* * Funkcja do opuszczania wybranego znacznika - prawy lub lewy. * Poniewaz brakuje krancowek przy rozłożonym znaczniku uzywany jest timer. * Najpierw sprawdzany jest status znacznikow, potem przez pewien czas rozkladany jest znacznik, jesli spełnione są warunki. * Następnie sprawdzne jest czy poprawny znacznik został rozłożony. Jeśli nie, procedura jest powtarzana. * Jeśli powtórne rozkładanie nie zadziała zwracany jest kod błędu. */ if (0 == SEEDER_ERROR && !marker_is_busy && // jesli obecnie nie ma zadnej akcji na znacznikach !digitalRead(marker_get)) // jesli wybrany znacznik jest zamkniety { marker_open_timer = millis(); // zresetuj licznik zabezpieczenia czasowego dla otwierania znaacznikow } if (seder_command_expected == seeder_command && // jesli jest komenda (millis() - marker_open_timer < MARKER_OPEN_WINDOW || // jesli licznik zabezpieczenia czasowego nie jest przekroczony lub marker_force_command)) // jest wymuszenie komendy { // włącz rozkładanie wybranego znacznika marker_is_busy = true; // zajętość akcji na znacznikach switch(marker_type) { case 1: digitalWrite(SET_L_MARKER, HIGH); // wyłącz ogólny siłownik znacznika break; case 2: digitalWrite(marker_set, HIGH); // wyłącz siłownik znacznika break; default: break; } if(DEBUG) { Serial.println("set_seeder_marker_right_or_left, rozkładanie znacznika"); } } else if(seder_command_expected == seeder_command) { // wyłącz składanie znaczników digitalWrite(SET_L_MARKER, LOW); digitalWrite(SET_R_MARKER, LOW); marker_is_busy = false; marker_open_timer = 0; if(!digitalRead(marker_get)) // jesli wybrany znacznik nadal jest zamkniety { if(marker_procedure_repetation_counter) { // ERROR if(set_marker_left == seeder_command) SEEDER_ERROR = ERROR_SET_RIGHT_MARKER; if(set_marker_right == seeder_command) SEEDER_ERROR = ERROR_SET_LEFT_MARKER; return SEEDER_ERROR; } marker_procedure_repetation_counter++; set_seeder_marker_right_or_left(marker_get, marker_set, seder_command_expected, marker_type); // wykonaj procedure rozłożenia wybranego znacznika ponownie } marker_procedure_repetation_counter = 0; seeder_command = do_nothing; if(DEBUG) { Serial.println("set_seeder_marker_right_or_left, koniec"); } } return NONE; } error_code set_seeder_marker_right_and_left(int marker_type = 1) { /* * Funkcja do opuszczania prawego i lewego znacznika. */ if (0 == SEEDER_ERROR && !marker_is_busy && // jesli obecnie nie ma zadnej akcji na znacznikach (!digitalRead(GET_L_MARKER) || !digitalRead(GET_R_MARKER))) // jesli choć jeden znacznik jest podniesiony { marker_open_timer = millis(); // zresetuj licznik zabezpieczenia czasowego dla otwierania znaacznikow marker_short_run_on_timer = millis(); } if (set_marker_left_right == seeder_command && // jesli jest komenda (millis() - marker_open_timer < MARKER_OPEN_WINDOW || // jesli licznik zabezpieczenia czasowego nie jest przekroczony lub marker_force_command)) // jest wymuszenie komendy { // włącz rozkładanie znacznika prawego i lewego marker_is_busy = true; // zajętość akcji na znacznikach switch(marker_type) { case 1: if(millis() - marker_short_run_on_timer < MARKER_SHORT_RUN_WINDOW) { digitalWrite(SET_L_MARKER, HIGH); // włącz siłownik znacznika na krotka chwile marker_short_run_off_timer = millis(); } else { if(millis() - marker_short_run_off_timer < MARKER_SHORT_RUN_WINDOW/2) { digitalWrite(SET_L_MARKER, LOW); // wyłącz siłownik znacznika na krotka chwile } else { digitalWrite(SET_L_MARKER, HIGH); // włącz siłownik znacznika aż znaczniki zostaną ustawione } } break; case 2: digitalWrite(SET_L_MARKER, HIGH); // wyłącz siłownik znacznika digitalWrite(SET_R_MARKER, HIGH); // wyłącz siłownik znacznika break; default: break; } if(DEBUG) { Serial.println("set_seeder_marker_right_and_left, rozkładanie znacznikow"); } } else if(set_marker_left_right == seeder_command) { // wyłącz składanie znaczników digitalWrite(SET_L_MARKER, LOW); digitalWrite(SET_R_MARKER, LOW); marker_is_busy = false; marker_open_timer = 0; if(!digitalRead(GET_R_MARKER) || !digitalRead(GET_L_MARKER)) // jesli wybrany znacznik nadal jest zamkniety { if(marker_procedure_repetation_counter) { // ERROR SEEDER_ERROR = ERROR_SET_LEFT_RIGHT_MARKER; return SEEDER_ERROR; } marker_procedure_repetation_counter++; set_seeder_marker_right_and_left(); // wykonaj procedure rozłożenia znaczników ponownie } marker_procedure_repetation_counter = 0; seeder_command = do_nothing; if(DEBUG) { Serial.println("set_seeder_marker_right_and_left, koniec"); } } return NONE; } void control_seeder() { set_seeder_marker_zero(); set_seeder_marker_right_or_left(GET_R_MARKER, SET_R_MARKER, set_marker_right); set_seeder_marker_right_or_left(GET_L_MARKER, SET_L_MARKER, set_marker_left); } String meassure_seed_level() { String level = ""; level += analogRead(GET_SEED_1); level += ";"; level += analogRead(GET_SEED_2); level += ";"; level += analogRead(GET_SEED_3); level += ";"; level += analogRead(GET_SEED_4); level += ";"; level += analogRead(GET_SEED_5); level += ";"; level += analogRead(GET_SEED_6); if(NANO) { level += ";"; level += analogRead(GET_SEED_7); level += ";"; level += analogRead(GET_SEED_8); } return level; }
C
/* chapter 27 exercise 1 page 1033 */ #include <stdio.h> #include <stdlib.h> size_t jd_strlen(const char* p) { if (p == 0) return 0; const char* last = p; while (*last) last++; return last - p; } int jd_strcmp(const char* s1, const char* s2) { while (*s1 == *s2 && *s1 != 0 && *s2 != 0) { s1++; s2++; } if (*s1 == *s2) return 0; else if (*s1 < *s2) return -1; else return 1; } char* jd_strcpy(char* s1, const char* s2) { int i; for (i = 0; *(s1 + i) = *s2++; ++i); return s1; } int main(void) { const char* s1 = "Jeff"; const char* s2 = "Jeffrey"; //test jd_strlen() printf("Length of %s is %d, and the length of %s is %d.\n", s1,jd_strlen(s1),s2,jd_strlen(s2)); //4, 7 //test jd_strcmp() if (jd_strcmp("dog","dog") == 0) printf("dog and dog are equivalent.\n"); if (jd_strcmp("ape","dodo") < 0) printf("ape comes before dodo in a dictionary.\n"); if (jd_strcmp("pig","cow") > 0) printf("ping comes after cow in a dictionary.\n"); //test jd_strcpy() { const char* s3 = "Testing jd_strcpy()"; char* s4 = (char*) malloc(jd_strlen(s3)+1); jd_strcpy(s4,s3); printf("%s\n",s4); free(s4); } return 0; }
C
#include <stdio.h> int main() { //定义整型 int num; int num = 5; //定义长整型 long long bignum; long long bignum = 123456789012345LL //longlong赋初值>2^31-1需要加上LL //定义无符号型 unsigned int a1; unsigned long long a2; //定义单精度浮点型 有效精度6-7位 float fl; float fl = 3.1415; //定义双精度浮点型 有效精度15-16位 double db; double db = 3.1415926536; //定义字符型变量和字符常量 char c; char c = 'e'; return 0; }
C
#include "eqg_types.h" uint32_t eqg_skip_materials(uint8_t* data, uint32_t length, uint32_t count) { uint32_t p = 0; uint32_t i; for (i = 0; i < count; i++) { EQGMaterial* mat = (EQGMaterial*)(data + p); p += sizeof(EQGMaterial); if (p > length) return 0xffffffff; p += sizeof(EQGProperty) * mat->propertyCount; if (p > length) return 0xffffffff; } return p; }
C
#include "CUDAArray.h" #include "cuda_runtime.h" #include "device_launch_parameters.h" #include <float.h> #include <stdlib.h> #include <stdio.h> #ifndef CONVOLUTION_HELPER #define CONVOLUTION_HELPER int defaultThreadCount = 32; // GPU FUNCTIONS __global__ void cudaArrayAdd(CUDAArray<float> source, CUDAArray<float> addition) { int row = defaultRow(); int column = defaultColumn(); if(source.Width>column&&source.Height>row) { float newValue = source.At(row,column)+addition.At(row,column); source.SetAt(row,column,newValue); } } __global__ void cudaArraySubtract(CUDAArray<float> source, CUDAArray<float> subtract) { int row = defaultRow(); int column = defaultColumn(); if(source.Width>column&&source.Height>row) { float newValue = source.At(row,column)-subtract.At(row,column); source.SetAt(row,column,newValue); } } __global__ void cudaConvolve(CUDAArray<float> target, CUDAArray<float> source, CUDAArray<float> filter) { int row = defaultRow(); int column = defaultColumn(); if(source.Width>column&&source.Height>row) { int tX = threadIdx.x; int tY = threadIdx.y; __shared__ float filterCache[32*32]; if(tX<filter.Width&&tY<filter.Height) { int indexLocal = tX+tY*filter.Width; filterCache[indexLocal] = filter.At(tY,tX); } __syncthreads(); int center = filter.Width/2; float sum = 0.0f; for(int drow=-center;drow<=center;drow++) { for(int dcolumn=-center;dcolumn<=center;dcolumn++) { float filterValue1 = filterCache[filter.Width*(drow+center)+dcolumn+center]; int valueRow = row+drow; int valueColumn = column+dcolumn; if(valueRow<0 || valueRow>=source.Height || valueColumn<0 || valueColumn>=source.Width) continue; float value = source.At(valueRow,valueColumn); sum+=filterValue1*value; } } target.SetAt(row, column, sum); } } // CPU FUNCTIONS void AddArray(CUDAArray<float> source, CUDAArray<float> addition) { dim3 blockSize = dim3(defaultThreadCount,defaultThreadCount); dim3 gridSize = dim3(ceilMod(source.Width,defaultThreadCount), ceilMod(source.Height,defaultThreadCount)); cudaArrayAdd<<<gridSize,blockSize>>>(source, addition); } void SubtractArray(CUDAArray<float> source, CUDAArray<float> subtract) { dim3 blockSize = dim3(defaultThreadCount,defaultThreadCount); dim3 gridSize = dim3(ceilMod(source.Width,defaultThreadCount), ceilMod(source.Height,defaultThreadCount)); cudaArraySubtract<<<gridSize,blockSize>>>(source, subtract); } void Convolve(CUDAArray<float> target, CUDAArray<float> source, CUDAArray<float> filter) { dim3 blockSize = dim3(defaultThreadCount,defaultThreadCount); dim3 gridSize = dim3(ceilMod(source.Width,defaultThreadCount), ceilMod(source.Height,defaultThreadCount)); cudaConvolve<<<gridSize,blockSize>>>(target, source, filter); cudaError_t error = cudaDeviceSynchronize(); int i=0; } void ComplexConvolve(CUDAArray<float> targetReal, CUDAArray<float> targetImaginary, CUDAArray<float> sourceReal,CUDAArray<float> sourceImaginary, CUDAArray<float> filterReal,CUDAArray<float> filterImaginary) { CUDAArray<float> tempReal = CUDAArray<float>(targetReal.Width,targetReal.Height); CUDAArray<float> tempImaginary = CUDAArray<float>(targetImaginary.Width,targetImaginary.Height); Convolve(targetReal, sourceReal, filterReal); Convolve(tempReal, sourceImaginary, filterImaginary); Convolve(targetImaginary, sourceReal, filterImaginary); Convolve(tempImaginary, sourceImaginary, filterReal); AddArray(targetImaginary,tempImaginary); SubtractArray(targetReal,tempReal); tempReal.Dispose(); tempImaginary.Dispose(); } #endif
C
int main(void) { int Counter=0, k; int number[5]; int seed=0; while (1) { Counter++; for(k=0; k<5; k++) { number[k]=0; number[k]=rand(seed)% 2; } } }
C
// Does not require a separate prototype #include <stdio.h> float getNumber() { float x; printf("Enter a number: "); scanf("%f", &x); return x; } int main() { float i; i = getNumber(); printf("%f\n", i); return (0); }
C
#include "circuits.h" #include <stdbool.h> #include <stdlib.h> #include <stdio.h> #include <string.h> /* Used this source - https://www.hackerearth.com/practice/data-structures/linked-list/singly-linked-list/tutorial/ - to help implement struct, addNode and createNode */ //Creates a new node Node createNode(void) { Node newNode; //Allocates memory for node newNode = malloc(sizeof(struct LinkedList)); //Sets attribute value of next to NULL newNode->next = NULL; return newNode; } //Adds a node to the end of a linked list Node addNode(Node head, Wire* wire) { Node newNode; Node tail; //Creates the node by allocating space and setting initial values. newNode = createNode(); //Sets wire attribute to given wire. newNode->wire = wire; //If the head of the list is null (so list is empty) then set head to newNode if (head == NULL) { head = newNode; //Otherwise set head to tail } else { tail = head; //And keep updating tail to next element until the end of the list is reached while (tail->next != NULL) { tail = tail->next; } /* Finally at end of list, set tail->next to newNode and set the index of the newNode to 1 greater than the index of tail */ tail->next = newNode; } return head; } /*Counts size of linked list @head - first node of list */ int sizeOfLinkedList(Node head) { if (head == NULL) return 0; else return (sizeOfLinkedList(head->next) + 1); } /*Returns boolean signifying whether wire with given name is in linked list. @head - first node of linked list. @nodeStr - wire to find. */ bool linkedListContains(Node head, char* nodeStr) { //If first element equals NULL (before wire is found) return false if (head == NULL) { return false; } else { //If nodeStr matches wire name then return true if (!strcmp(head->wire->name, nodeStr)) return true; //Recursively call function until equal to nodeStr or NULL Node newNode = head->next; if (newNode != NULL) return linkedListContains(newNode, nodeStr); } return false; } /*Gets a node given a node's name @head - first node in list @nodeStr - name of node */ Wire* getNode(Node head, char* nodeStr) { //Returns NULL if head is NULL if (head == NULL) { return NULL; } else { Node newNode = head->next; //Returns wire if found if (!strcmp(head->wire->name, nodeStr)) return (head->wire); //Recursively calls getNode until found or NULL if (newNode != NULL) return getNode(newNode, nodeStr); } return NULL; } /*Resets value and next value of wire if wire is not 'one' @head - first node of linked list */ void reset_wires(Node head) { //If head is not NULL if (head != NULL) { //Skips reseting of wire if name is one if (strcmp(head->wire->name, "one")) { head->wire->val = 0; head->wire->nextVal = 0; } //recursively reset wires reset_wires(head->next); } } //Recursively frees linked list void freeLinkedList(Node node) { Node newNode = node->next; free(node); if (newNode != NULL) freeLinkedList(newNode); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/wait.h> #include <sys/types.h> int main(){ int i=0,status,pid; for(;i<10;i++){ pid=fork(); if(pid>0){ wait(NULL); if(WIFEXITED(status)) printf("Meu filho morreu %d\n",WEXITSTATUS(status)); exit(0); } printf("FILHO %d, PID %d PPID %d",i,getpid(),getppid()); if(i=9) exit(0); } return 0; }
C
/* <SOURCE-LICENSE> [ PA(Peter-Anna) OS ] ======================================== Peter-Anna OS is a real time OS. Peter-Anna OS is made by Peter and Anna. Peter and Anna lives in South Korea. They love each other so much. Peter usually develops PAOS, Anna usually feeds hungry Peter. Peter sometimes makes money, Anna sometimes makes cookie. Like shared memory region, PAOS is where they live in together. They belong to PAOS. PAOS belongs to them. 03/29/2006 Peter and Anna ( kangmo.kim@gmail.com ) [ License Information ] ====================================== Apache v2 License [ Information on Layering Architecture of PAOS ] ============= Files in lower layer are not allowed to use,include files in upper layer. user ; user program layer ; main.c pthread ; pthread layer ; pthread.c conc ; concurrency layer ; conc_mutex.c conc_cond.c evt ; event layer ; evt.c sched ; scheduler layer ; sched.c task ; task layer ; task.c base ; base layer ; base.c list.c debug.c md ; machine dependent layer ; md.c md_asm.S uart.c config ; configuration layer ; config.h </SOURCE-LICENSE> $Id$ */ #include "debug.h" #include "list.h" /* Initialize a list */ void list_init(list_t * list) { /* Set both the head node and the tail node to the NULL node of the list */ list->head = LIST_NODE_NULL(list); list->tail = LIST_NODE_NULL(list); } /* Add a node to the head of a list */ void list_add_head(list_t *list, list_node_t *node ) { node->next = list->head; node->prev = LIST_NODE_NULL(list); /* if list->head is LIST_NODE_NULL, "list->head->prev" equals to "list->tail" */ list->head->prev = node; list->head = node; } /* Add a node to the tail of a list */ void list_add_tail(list_t *list, list_node_t *node ) { node->next = LIST_NODE_NULL(list); node->prev = list->tail; /* if list->tail is LIST_NODE_NULL, "list->tail->next" equals to "list->head" */ list->tail->next = node; list->tail = node; } /* Remove a node from a list */ void list_remove(list_t *list, list_node_t *node ) { /* 1. if node->prev is LIST_NODE_NULL, node is the head node - "node->prev->next" becomes "list->head" - "node->prev->next = node->next" means "list->head = node->next" */ node->prev->next = node->next; /* 2. if node->next is LIST_NODE_NULL, node is the tail node - "node->next->prev" becomes "list->tail" - "node->next->tail := node->prev" means "list->tail = node->prev */ node->next->prev = node->prev; } /* Append all nodes in list2 to the tail of list1 */ void list_append_to_tail(list_t * list1, list_t * list2 ) { if ( ! list_isempty( list2 ) ) { /* if list1->tail is LIST_NODE_NULL, list1->tail->next is list1->head */ list1->tail->next = list2->head; list1->tail = list2->tail; list2->head->prev = list1->tail; list2->tail->next = LIST_NODE_NULL( list1 ); } } /* Append all nodes in list2 to the head of list1 */ void list_append_to_head(list_t * list1, list_t * list2 ) { list_append_to_tail(list2, list1 ); list1->head = list2->head; list1->tail = list2->tail; }
C
/* Tiny helper function library ============================ TOC: * Memory manipulation functions * Character string functions License (BSD-2) =============== Copyright (c) 2013, Gusts 'gusC' Kaksis <gusts.kaksis@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "lib.h" #include "common.h" // // Memory manipulation functions // void mem_copy(uint8 *dest, uint32 len, const uint8 *src){ while (len--){ *(dest++) = *(src++); } } void mem_fill(uint8 *dest, uint32 len, uint8 val){ while (len--){ *(dest++) = val; } } bool mem_compare(const uint8 *buff1, const uint8 *buff2, uint32 len){ while (len--){ if (*(buff1++) != *(buff2++)){ return false; } } return true; } // // String functions // #define MAX_INT_STR 32 uint32 str_copy(char *dest, uint32 len, const char *src){ char *sp = (char *)src; char *dp = (char *)dest; uint32 s = 0; while (*sp != 0 && len != 0){ // Copy till the end of source or destination has been reached *(dp++) = *(sp++); len --; s ++; } return s; } uint32 str_length(const char *str){ uint32 len = 0; while (*(str++) != 0){ // Increment till the end of string len ++; } return len; } int32 str_char_idx(const char *haystack, const char needle, uint32 offset){ int32 idx = 0; // Move offset while (offset--){ if (*(haystack++) == 0){ // End of the string return -1; } } while (*haystack != 0){ if (*haystack == needle){ // Found an occurence return idx; } idx++; haystack++; } return -1; } uint32 int_to_str(char *dest, uint32 len, int32 val, int32 base){ static char tmp[MAX_INT_STR + 1]; mem_fill((uint8 *)tmp, MAX_INT_STR + 1, 0); char *b = (char *)tmp + MAX_INT_STR; char c = 0; if (val >= 0){ // Process positive value do { c = (char)(val % base); if (c > 9){ *--b = 'A' + (c - 10); } else { *--b = '0' + c; } val /= base; } while (val != 0); } else if (val < 0){ // Process negative value do { c = (char)(val % base); if (c < -9){ *--b = 'A' - (c + 10); } else { *--b = '0' - c; } val /= base; } while (val != 0); // Add minus sign only for decimals if (base == 10){ *--b = '-'; } } // Copy the result and return number of digits processed return str_copy(dest, len, b); } int32 str_to_int(const char *str, int32 base){ char *b = (char *)str; int32 val = 0; uint8 negative = 0; // Trim leading spaces while (*b == 0x20 || *b == 0x09){ // space || tab b++; } // Check if a negative number if (*b == '-'){ negative = 1; } // Calculate integer value while (*b >= 0x30 && *b <= 0x39){ // >= 0 && <= 9 (as in ascii 0, 1, ..., 9) val *= 10; // multiply upwwards val += (*b) - 0x30; // add current digit b ++; } // Set minus sign if necessary if (negative){ return 0 - val; } return val; } uint32 str_write_f(char *dest, uint32 len, const char *format, ...){ va_list args; va_start(args, format); uint32 ret = __write_f(dest, len, format, args); va_end(args); return ret; } uint32 str_read_f(const char *src, const char *format, ...){ va_list args; va_start(args, format); uint32 ret = __read_f(src, format, args); va_end(args); return ret; } // // Private functions // uint32 __write_f(char *dest, uint32 len, const char *format, va_list args){ char *f = (char *)format; char *d = (char *)dest; uint32 ret = 0; // Temporary value variables uint32 val_len; int32 val_int32; uint32 val_uint32; char val_char; char *val_str; while (*f && ret < len){ if (*f == '%'){ // possible specifier switch (*(f + 1)){ case 'd': // integer val_int32 = va_arg(args, int32); val_len = int_to_str(d, MAX_INT_STR, val_int32, 10); d += val_len; ret += val_len; f ++; break; case 'u': // unsigned integer val_uint32 = va_arg(args, uint32); val_len = int_to_str(d, MAX_INT_STR, val_uint32, 10); d += val_len; ret += val_len; f ++; break; case 'x': // unsigned integer in hex val_uint32 = va_arg(args, uint32); val_len = int_to_str(d, MAX_INT_STR, val_uint32, 16); d += val_len; ret += val_len; f ++; break; case 'b': // unsigned integer in binary val_uint32 = va_arg(args, uint32); val_len = int_to_str(d, MAX_INT_STR, val_uint32, 2); d += val_len; ret += val_len; f ++; break; case 'c': // char val_char = (char)va_arg(args, int32); // chars are promoted to int in va_list *(d++) = val_char; ret ++; f ++; break; case 's': // string val_str = (char *)va_arg(args, uint32); while (*val_str){ *(d ++) = *(val_str ++); ret ++; } f ++; break; default: // not a specifier *(d ++) = *f; ret ++; break; } f ++; } else { // copy string *(d ++) = *(f ++); ret ++; } } return ret; } uint32 __read_f(const char *src, const char *format, va_list args){ return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> void getNeighbors(int n, int i, int* n1, int* n2) { if(i == 0) { *n1 = n - 1; *n2 = 1; } else if(i == n - 1) { *n1 = n - 2; *n2 = 0; } else { *n1 = i - 1; *n2 = i + 1; } } bool isPeak(int value, int n1, int n2) { if((n1 > value && n2 > value) || (n1 < value && value > n2)) return true; else return false; } int main(int argc, char const *argv[]) { int n, i, *array, value, n1, n2, peaks; scanf("%d", &n); while(n != 0) { array = malloc(n * sizeof(int)); peaks = 0; for(i = 0; i < n; i++) scanf("%d", array + i); if(n == 2) { peaks = 2; goto REPORT_ANS; } for(i = 0; i < n; i++) { getNeighbors(n, i, &n1, &n2); value = *(array + i); n1 = *(array + n1); n2 = *(array + n2); if(isPeak(value, n1, n2)) peaks++; } REPORT_ANS: printf("%d\n", peaks); scanf("%d", &n); } return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include "spell-checker_data.h" /** * A Trie implementation to hold the dictionary data. * * See https://en.wikipedia.org/wiki/Trie for a description of a Trie. * * TODO: Extract the implementation out, put into specific implementation file, * to easily test with other data-structures. * * This implementation is a bit wasteful in memory, but should be rather fast. * It is wasteful, as it is allocating an empty array for each node created, * even though potentially none of the children will be used. In practice, most * of them will probably not be used (TODO: measure how much exactly). * It is, however, rather fast, as the access to each element is O(1), as each * child is located at the index of it's character representation. * * Visual representation of the Trie containing a single word 'air': * * (0) <-- Root * ______|______ * | | | * (0)...(a)...(0xFF) <-- ... 256 children (all but one empty) * ______|_______ * | | | * (0)...(i)...(0xFF) <-- ... 256 children (all but one empty) * ______|_______ * | | | * (0)...(r)...(0xFF) <-- ... 256 children (all but one empty) * ______|_______ * | | * (0) (0xFF) <-- ... 256 children (all empty) * * * Multiple strategies may be implemented to improve memory waste: allocating * nodes for legal characters only, allocating nodes as-needed only, not * allocating nodes for the leafs, etc.. All have different pros and cons. * * Each node in the Trie holds a single character and a list of children. * The root node has its character element set to 0. * Upon initialization, only the root node is created, with its children's * array zero-ed out. * Every time a word is added, a new node is created in place of the appropriate * child node. */ /* *Max ascii values (with extended characters) */ #define MAX_CHARS_PER_NODE 256 /* * Each data node holds a character and an array of MAX_CHARS_PER_NODE children. */ struct _SpellCheckerData { char chr; struct _SpellCheckerData *child; }; /* * Recursively delete a node. * Note: the node itself is not deleted, but all its children does. */ static void scdDeleteNode(SpellCheckerDataHandle node) { if (node) { if (node->child) { for(int i = 0; i < MAX_CHARS_PER_NODE; ++i) scdDeleteNode(&node->child[i]); free(node->child); node->child = NULL; } } } /* * Initialize a node with the given character, and allocate memory for the * children array. */ static int scdInitNode(char chr, SpellCheckerDataHandle node) { node->chr = chr; node->child = calloc(MAX_CHARS_PER_NODE, sizeof(struct _SpellCheckerData)); if (!node->child) { printf("Failed allocating memory for child array\n"); return -1; } return 0; } static SpellCheckerDataHandle scdCreateNode(void) { SpellCheckerDataHandle node = malloc(sizeof(struct _SpellCheckerData)); if (!node) { printf("Failed allocating memory for node\n"); return NULL; } if (-1 == scdInitNode(0, node)) { free(node); return NULL; } return node; } SpellCheckerDataHandle scdInit(void) { return scdCreateNode(); } void scdFinalize(SpellCheckerDataHandle data) { scdDeleteNode(data); free(data); } /* * Return an unsigned char instead of a signed one, and transform upper-case * letters to lower-case. */ static inline unsigned char scdNormalizeChar(char c) { if (('A' <= c) && ('Z' >= c)) return c + 0x20; return c; } /* * Make sure a word is valid, per the requirements given in spell-checker.h. */ static inline int scdIsValid(const char *word) { for (size_t i = 0; i < strlen(word); ++i) { if (!( (('a' <= word[i]) && ('z' >= word[i])) || (('A' <= word[i]) && ('Z' >= word[i])) || (('0' <= word[i]) && ('9' >= word[i])) || (0x80 <= scdNormalizeChar(word[i])) )) return 0; } return 1; } int scdAddWord(SpellCheckerDataHandle data, const char *word) { if (!data || !word || !data->child) { printf("Invalid arguments when trying to add a word\n"); return -1; } if (!scdIsValid(word)) { #ifdef DEBUG printf("Attempted to add an invalid word (%s) to dictionary\n", word); #endif return -1; } SpellCheckerDataHandle node = data; size_t i = 0; const size_t n = strlen(word); /* Find existing nodes (characters) */ while ((i < n) && (0 != node->child[scdNormalizeChar(word[i])].chr)) { node = &node->child[scdNormalizeChar(word[i])]; ++i; } /* If word is longer than what we have stored, we need to add each letter */ while (i < n) { if (-1 == scdInitNode(scdNormalizeChar(word[i]), &node->child[scdNormalizeChar(word[i])])) { /* TODO: cleanup nodes that were already created */ return -1; } node = &node->child[scdNormalizeChar(word[i])]; ++i; } return 0; } int scdHasWord(SpellCheckerDataHandle data, const char *word) { if (!data || !word || !data->child) { printf("Invalid arguments passed to scdHasWord\n"); return -1; } SpellCheckerDataHandle node = data; const size_t n = strlen(word); size_t i = 0; while (i < n) { if (0 == node->child[scdNormalizeChar(word[i])].chr) return 0; else node = &node->child[scdNormalizeChar(word[i])]; ++i; } return (i == n); }
C
/** * @file pgm.c * @brief Funções relativas à leitura dos ficheiros pgm * @author Emanuel João Conceição Lopes <2140825@student.estg.ipleiria.pt> */ #include "pgm.h" #include "debug.h" #include "errors.h" #include "common.h" #include "memory.h" /** * @brief abreo o ficheiro pgm * @details [long description] * * @param path * @param pgmFile * * @return !=0 falha */ int open_file_pgm(char *path, pgm_t *pgmFile) { FILE *stream = fopen(path, "r"); if (stream == NULL) { WARNING("fopen() failed %s", path); return ERR_OPEN_FAILED; } //read header int status = read_header_pgm(stream, path, &(pgmFile->header)); if (status != 0) { fclose(stream); return status; } //read body status = read_body_pgm(stream, pgmFile); if (status != 0) { fclose(stream); return status; } fclose(stream); return 0; } /** * @brief ĺê o cabeçalho do ficheiro * * @param stream FILE stream * @param path nome do ficheiro * @param header estrutura do header * @return 0-ok 1-falha */ int read_header_pgm(FILE *stream, const char *path, header_pgm_t *header) { char *line = NULL; strncpy(header->filename, path, MAX_FILENAME + 1); //get version line = read_line(stream); int versiontmp = is_pgm_file(line, &(header->type)); //FREE(line); if (versiontmp) return versiontmp; //get height and width of cod file line = read_line(stream); if (!get_size(line, &(header->width), &(header->height))) { //FREE(line); return ERR_INVALID_SIZE; } //get max Value line = read_line(stream); if (!max_value(line, &(header->max_value))) {return ERR_INVALID_MAX_VALUE;} //FREE(line); if (header->type == P2) { if ((header->max_value < 1) || (header->max_value >= 256)) { return ERR_INVALID_MAX_VALUE; } } else if (header->type == P5) { if ((header->max_value < 1) || (header->max_value >= 65536)) { return ERR_INVALID_MAX_VALUE; } } return 0; } /** * @brief verifica e devolve a versao do ficheiro P2 ou P5 * * @param line - linha do ficheiro de texto * @param version - versao do ficheiro * * @return 0-succefull, !=0 em caso de erro */ int is_pgm_file(char *line, file_pgm_t *version) { char *token; int counter = -1; token = strtok(line, SPACE); while (token != NULL) { counter++; token = strtok(NULL, SPACE); } FREE(token); if (counter > 0)return ERR_MISSING_HEADER; if (line[0] == 'P') { if (strcmp(line, "P2") == 0) { *version = P2; return 0; } else if (strcmp(line, "P5") == 0) { *version = P5; return 0; } else { return ERR_INVALID_FORMAT; } } else { return ERR_MISSING_HEADER; } return ERR_MISSING_HEADER; } /** * @brief lê o corpo do ficheiro * * @param stream * @param codFile * * @return !=0 erro 0=ok */ int read_body_pgm(FILE *stream, pgm_t *pgmFile) { int counterPixels = 0; //allocate memory for pixels pgmFile->pixels = MALLOC(sizeof(unsigned short *) * pgmFile->header.width); unsigned short *data = MALLOC(sizeof(unsigned short) * pgmFile->header.width * pgmFile->header.height); unsigned int i; for (i = 0; i < pgmFile->header.width; ++i) { pgmFile->pixels[i] = &data[i * pgmFile->header.height]; } if (pgmFile->pixels[0] == NULL) { return ERR_ALLOC_MEMORY; } //ficheiro p2 if (pgmFile->header.type == P2) { int indexCounter = 0; int lineNumber = 0; char *line = NULL; while (strcmp((line = read_line(stream)), "EOF") != 0) { char *token; char *endptr = NULL; errno = 0; token = strtok(line, SPACE); while (token != NULL) { long value = strtol(token, &endptr, 10); if (*endptr != '\0' && *endptr != '\n') { return ERR_INVALID_PGM_FILE; } if (errno != 0) { return ERR_INVALID_PGM_FILE; } if (value < 0 || (unsigned int)value > pgmFile->header.max_value) { return ERR_INVALID_PGM_FILE; } if (counterPixels >= (int)(pgmFile->header.height * pgmFile->header.width)) return ERR_INVALID_PGM_FILE; if ((unsigned int)indexCounter >= pgmFile->header.height) { indexCounter = 0; lineNumber++; } pgmFile->pixels[lineNumber][indexCounter] = (unsigned short) value; indexCounter++; counterPixels++; token = strtok(NULL, SPACE); } FREE(token); //free(line); } if ((unsigned int)counterPixels == (pgmFile->header.width * pgmFile->header.height)) return 0; //lê ficheiros p5 } else if (pgmFile->header.type == P5) { int i, j; unsigned int pixel = 0; for (i = 0; i < (int)pgmFile->header.width; i++) { for (j = 0; j < (int)pgmFile->header.height; j++) { counterPixels++; if (fread(&pixel, 1, 1, stream) != 1) { return ERR_INVALID_PGM_FILE; } if ((short)(pixel) < 0 || (short)(pixel) > (int)pgmFile->header.max_value) { return ERR_INVALID_PGM_FILE; } pgmFile->pixels[i][j] = pixel; } } char ch; fread(&ch, 1, 1, stream); if (!feof(stream)) { return ERR_INVALID_PGM_FILE; } if ((unsigned int)counterPixels == (pgmFile->header.width * pgmFile->header.height)) return 0; } return ERR_INVALID_PGM_FILE; }
C
#include <stdio.h> #define ALPHABET_SIZE 256 /* count char frequencies */ main() { int alphabet[ALPHABET_SIZE]; for (int i = 0; i < ALPHABET_SIZE; i++) { alphabet[i] = 0; } int c; while ((c = getchar()) != EOF) { if (c == ' ' || c == '\t' || c == '\n') { /* skip */ } else { alphabet[c]++; } } for (int j = 0; j < ALPHABET_SIZE; j++) { if (alphabet[j] > 0) { putchar(j); printf(": "); for (int k = 0; k < alphabet[j]; k++) { printf("-"); } printf("\n"); } } }
C
#include "parseheader.h" #include "httpd.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> /*implemetation the HTTP header *fd is a file content the header info */ void parse_header(int fd) { char buf[512]; /*---------a modifier-------getline is not pratice to use*/ ssize_t headernum = my_getline(fd, buf, sizeof(buf)); printf("getline: %s\n", buf); char *method; char *delim = " "; method = strtok(buf, delim); /*store the method into p*/ while (method != NULL) { printf( " %s\n", method); break; } if (strcasecmp(method, "POST") == 0) printf("post message\n"); ;/*recieve a post message*/ if (strcasecmp(method, "GET") == 0) { method = strtok(NULL, delim); while (method != NULL) { printf("uri is %s\n", method); break; } /*recieve a get message*/ } if (strcasecmp(method, "POST") && strcasecmp(method, "GET")) no_service(fd); /*get URI web info*/ method = strtok(NULL, delim); while (method != NULL) { printf("%s\n", method); break; } /*get version info*/ method = strtok(NULL, delim); while (method != NULL) { printf("%s\n", method); break; } } int main(void) { int fdtest = open("test", O_RDONLY | O_CREAT); parse_header(fdtest); close (fdtest); }
C
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.c * Author: Admin * * Created on 11 de abril de 2020, 11:21 */ #include <stdio.h> #include <stdlib.h> #include <limits.h> #define MAYOR LONG_MAX //cual es el mayor valor real? #define MAYOR_ENTERO INT_MAX /* * */ void imprimirRep(int clientesEstadistica1, double clientesEstadistica2, double clientesEstadistica3, int clienteMayorConsumo, int clienteMenosConsumo, int clienteEstadistica5 ){ printf("eL NUMERO DE CLIENTES QUE RESIDE EN LAS CIUDADES 21,45,67 DEL PAIS 3: %d\n", clientesEstadistica1); printf("el porcentaje de clientes que tiene menos de 5 años de servicios y que pagan en promedio mas de 50.00 diario: %.2lf%%\n",clientesEstadistica2 ); printf("La tarifa promedio de los clientes qye viene en la ciudad 60 y que ingresaron al servicio antes de 1/07/2004: %.4lf\n", clientesEstadistica3); printf("El cliente que mas pagó y el que menos pago por su consumo promedio:\n mas: %d \n Menos: %d\n",clienteMayorConsumo, clienteMenosConsumo); printf("El cliente con mayor tiempo promedio en llamadas con menor tarifa: %d\n",clienteEstadistica5); } int cumpleEstadistica1(int num){ int pais, ciudad; pais= num/100000000; ciudad= (num/ 1000000)-pais*100; if(pais==3){ if(ciudad==21 || ciudad==45 || ciudad==67) return 1; } return 0; } int cumpleEstadistica2(int fecha, double timeMin, double tarifa){ int fechaHace5anhos=20150411; if(timeMin*tarifa > 50 && fecha>fechaHace5anhos){ return 1; } return 0; } void acumulaEstadistica3(int fecha,int num,double tarifa, int *contEstadist3, double *sumaTarifa){ int ciudad, pais; pais=num/100000000; ciudad=num/1000000 -(pais*100); if(fecha<20040701 && ciudad==60){ (*contEstadist3)++; (*sumaTarifa)+=tarifa; } } /* void EstadisticaDelConsumoPromedio(double tarifa,double timeMin,int dni,int *clienteMayorConsumo,int*clienteMenosConsumo){ double consumoMayor=0, consumoMenor=MAYOR; double consumo; consumo=tarifa*timeMin; if(consumo > consumoMayor){ consumoMayor=consumo; (*clienteMayorConsumo)=dni; } if(consumo <consumoMenor){ consumoMenor=consumo; (*clienteMenosConsumo)=dni; } } */ void cumpleEstadistica5(int *clienteEstadistica5, double timeMin, double tarifa, int dni){ double mayorTiempo=0; double menorTarifa=MAYOR; if(timeMin>mayorTiempo){ mayorTiempo=timeMin; if(tarifa<menorTarifa){ menorTarifa=tarifa; (*clienteEstadistica5)=dni; //se tiene que actualizar cada vez que entra a esta funcion, no devolver un valor cada vez que entra } } } int main(int argc, char** argv) { int clientesEstadistica1=0, clienteMayorConsumo,clienteMenosConsumo,clienteEstadistica5, totalClientes=0, contEstadist2=0,contEstadist3=0; double clientesEstadistica2,clientesEstadistica3,timeMin, sumaTarifa=0; int dni, anho, dia,mes, num,hora,min, seg, fecha; // long int dni double tarifa; double consumoMayor=0, consumoMenor=MAYOR,consumo,mayorTiempo=0,menorTarifa=MAYOR;; while(1){ scanf("%d %d/%d/%d %d %d:%d:%d %lf",&dni, &dia,&mes,&anho, &num, &hora,&min, &seg, &tarifa); printf("\n"); printf("%d %d/%d/%d %d %d:%d:%d %lf\n",dni, dia,mes,anho, num, hora,min, seg, tarifa); if(dni==0) break; fecha=(anho*10000)+ mes*100 + dia; timeMin= hora*60 + min + seg/60.0; clientesEstadistica1+= cumpleEstadistica1(num); contEstadist2+=cumpleEstadistica2(fecha, timeMin, tarifa); acumulaEstadistica3(fecha,num,tarifa, &contEstadist3, &sumaTarifa); //void pues me modifica 2 cantidades, no devuelve un valor totalClientes++; //Hallando el consumo mayor y menor consumo=tarifa*timeMin; if(consumo > consumoMayor){ consumoMayor=consumo; (clienteMayorConsumo)=dni; } if(consumo <consumoMenor){ consumoMenor=consumo; (clienteMenosConsumo)=dni; } //Estadistica 5 if(timeMin>mayorTiempo){ mayorTiempo=timeMin; if(tarifa<menorTarifa){ menorTarifa=tarifa; (clienteEstadistica5)=dni; } } } clientesEstadistica2= contEstadist2*100.0/totalClientes; clientesEstadistica3=sumaTarifa/contEstadist3; imprimirRep(clientesEstadistica1, clientesEstadistica2,clientesEstadistica3,clienteMayorConsumo, clienteMenosConsumo, clienteEstadistica5 ); return (EXIT_SUCCESS); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ybouladh <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/10/15 21:33:52 by ybouladh #+# #+# */ /* Updated: 2018/10/21 17:33:59 by ybouladh ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line.h" t_list *check_fd_list(t_list **lst, int fd) { t_list *temporary; t_list *new; temporary = *lst; while (temporary) { if ((int)temporary->content_size == fd) return (temporary); temporary = temporary->next; } if (!(new = (t_list*)malloc(sizeof(t_list)))) return (NULL); if (!(new->content = ft_strnew(BUFF_SIZE))) return (NULL); new->content_size = fd; ft_lstadd(lst, new); return (*lst); } int mover(char **src, int jumper) { int hopper; hopper = 0; if ((*src)[jumper] == '\n') jumper++; while ((*src)[jumper]) (*src)[hopper++] = (*src)[jumper++]; while ((*src)[hopper]) (*src)[hopper++] = '\0'; return (0); } int copy_past(int funct, char **dst, char **src) { int jumper; char *temporary; jumper = -1; if (!(temporary = ft_strnew(BUFF_SIZE))) return (-1); if (funct == 1) { while ((*src)[++jumper] != '\n' && (*src)[jumper]) temporary[jumper] = (*src)[jumper]; temporary[jumper] = '\0'; mover(src, jumper); *dst = ft_strjoin(*dst, temporary); free(temporary); return (0); } else { if ((*src)[0] == '\0') return (-1); while ((*src)[++jumper]) if ((*src)[jumper] == '\n') return (1); return (0); } } int ghost_reader(char **temporary, int fd, char **line) { int jumper; jumper = 0; while ((jumper = read(fd, *temporary, BUFF_SIZE))) { if (jumper < 0) return (-1); ((char*)(*temporary))[jumper] = '\0'; if (copy_past(0, line, (char**)&(*temporary)) == 1) { copy_past(1, line, (char**)&(*temporary)); return (1); } else if (copy_past(0, line, (char**)&(*temporary)) == 0) copy_past(1, line, (char**)&(*temporary)); } return (0); } int get_next_line(const int fd, char **line) { static t_list *string; t_list *temporary; int jumper; if (BUFF_SIZE < 0 || line == NULL || fd < 0) return (-1); temporary = check_fd_list(&string, fd); *line = ft_strnew(1); if ((jumper = copy_past(0, line, (char**)&temporary->content)) != -1) { copy_past(1, line, (char**)&temporary->content); if (jumper == 1) return (1); } if (ghost_reader((char**)&temporary->content, fd, line) == 1) return (1); else if (ghost_reader((char**)&temporary->content, fd, line) == -1) return (-1); if ((*line)[0] == '\0') return (0); return (1); }
C
/* ID: southp01 LANG: C TASK: frac1 */ #include <stdio.h> #include <string.h> #define MAX_D 160 struct frac { int n; /* numerator */ int d; /* denominator */ float val; }; int cmp_frac(const void *a, const void* b) { const struct frac* fa = a; const struct frac* fb = b; float diff = fb->val - fa->val; if(diff > 0.0f) { return -1; } else if(diff < 0.0f) { return 1; } else if(diff < 10e-6 && diff > -10e-6) { return 0; } } struct frac sol[MAX_D * MAX_D + 1]; int sol_count = 0; int N; int seive[MAX_D + 1][MAX_D + 1]; int main(int argc, char* argv[]) { FILE* in; FILE* out = fopen("frac1.out", "w"); int d, n, i; if(argc == 2) in = fopen(argv[1], "r"); else in = fopen("frac1.in", "r"); fscanf(in, "%d", &N); printf("N: %d\n", N); memset(sol, 0, sizeof(sol)); memset(seive, 0, sizeof(seive)); for(d = 1; d <= N; ++d) { for(n = 0; n <= d; ++n) { int mul_d = d, mul_n = n; int mul = 1; if(!seive[d][n]) { sol[sol_count].d = d; sol[sol_count].n = n; sol[sol_count].val = (float)n / (float)(d); ++sol_count; } while(mul_d <= N) { seive[mul_d][mul_n] = 1; ++mul; mul_d = d*mul; mul_n = n*mul; } } } qsort(sol, sol_count, sizeof(struct frac), cmp_frac); for(i = 0; i < sol_count; ++i) { struct frac* f = &sol[i]; printf("%d/%d\n", f->n, f->d); fprintf(out, "%d/%d\n", f->n, f->d); } return 0; }
C
//5. Write a C program to print all odd number between 1 to 100. #include<stdio.h> int main() { int i; printf("All ODD Numbers between 1 to 100\n"); for(i=1;i<=100;i++) { if(i%2!=0) printf("%d ",i); } return 0; }
C
/* newClones - Find new clones. */ #include "common.h" #include "linefile.h" #include "hash.h" #include "cheapcgi.h" #include "obscure.h" static char const rcsid[] = "$Id: newClones.c,v 1.3 2003/05/06 07:22:30 kate Exp $"; void usage() /* Explain usage and exit. */ { errAbort( "newClones - Find new clones\n" "usage:\n" " newClones old.lst new.lst\n" ); } void newClones(char *oldFile, char *newFile) /* newClones - Find new clones. */ { struct slName *oldList = readAllLines(oldFile); struct slName *newList = readAllLines(newFile); struct slName *el; struct hash *hash = newHash(0); for (el = oldList; el != NULL; el = el->next) { chopSuffix(el->name); hashAdd(hash, el->name, NULL); } for (el = newList; el != NULL; el = el->next) { chopSuffix(el->name); if (!hashLookup(hash, el->name)) printf("%s\n", el->name); } } int main(int argc, char *argv[]) /* Process command line. */ { cgiSpoof(&argc, argv); if (argc != 3) usage(); newClones(argv[1], argv[2]); return 0; }
C
#include<stdio.h>//二叉树的顺序存储结构 #include<stdlib.h> #include"SeqStack.h" #define MaxTreeNodeNum 100 typedef int DataType; void Visit(int t) { printf("%d",t); } typedef struct { DataType data[MaxTreeNodeNum]; int n; }QBTree; typedef struct bonde{ DataType data; struct bonde *lchild,*rchild; }Bonde,*BTree; void PreOrder (BTree t)//先序遍历的递归算法 { if(t) { Visit(t->data); PreOrder(t->lchild); PreOrder(t->rchild); } } void unPreOrder (BTree t)//先序遍历的非递归算法 { PSeqStack S; BTree p=t; S=Init_SeqStack(); while(p||!Empty_SeqStack(S)) { if(p) { Visit(p->data); Push_SeqStack(S,p->data); p=p->lchild; } else { Pop_SeqStack(S,&p->data); p=p->rchild; } } } void InOrder(BTree t)//中序便利店递归的算法 { if(t) { InOrder(t->lchild); Visit(t->data); InOrder(t->rchild); } } void unPreOrder (BTree t)//中序遍历的非递归算法 { PSeqStack S; BTree p=t; S=Init_SeqStack(); while(p||!Empty_SeqStack(S)) { if(p) { Push_SeqStack(S,p->data); p=p->lchild; } else { Pop_SeqStack(S,&p->data); Visit(p->data); p=p->rchild; } } } void PreOrder (BTree t)//后序遍历的递归算法 { if(t) { PreOrder(t->lchild); PreOrder(t->rchild); Visit(t->data); } } void unPreOrder (BTree t)//后序遍历的非递归算法 { PSeqStack S1; PSeqStack S2; BTree p; p=t; S1=Init_SeqStack(); S2=Init_SeqStack(); while(p||!Empty_SeqStack(S2)) { if(p) { Push_SeqStack(S1,p->data); Push_SeqStack(S2,p->data); p=p->lchild; } else { Pop_SeqStack(S2,&p->data); p=p->rchild; } } while (!Empty_SeqStack(S1)) { Pop_SeqStack(S1,&p->data); Visit(p->data); } }
C
#include <stdlib.h> #include <stddef.h> #include <pthread.h> #include <stdarg.h> #include <stdio.h> #include <math.h> #include <string.h> #include <signal.h> #include <unistd.h> #define MAXLINE 4096 #define DEFAULT_THREADCOUNT 10 #define DEFAULT_SAMPLESIZE 100 #define ERR(source) (perror(source),\ fprintf(stderr,"%s:%d\n",__FILE__,__LINE__),\ exit(EXIT_FAILURE)) volatile sig_atomic_t last_signal = 0; void handler(int dummy); void sethandler( void (*f)(int), int sigNo) { struct sigaction act; memset(&act, 0, sizeof(struct sigaction)); act.sa_handler = f; if (-1==sigaction(sigNo, &act, NULL)) ERR("sigaction"); } typedef unsigned int UINT; typedef struct argsEstimation { pthread_t tid; UINT seed; int divide; int *counter; } args_t; void ReadArguments(int argc, char **argv, int *threadCount); void* job(void *args); int main(int argc, char** argv) { int threadCount; int count = 1; ReadArguments(argc, argv, &threadCount); args_t* data = (args_t*) malloc(sizeof(args_t) * threadCount); if (data == NULL) ERR("Malloc error for estimation arguments!"); srand(time(NULL)); for (int i = 0; i < threadCount; i++) { data[i].counter = &count; data[i].seed = rand(); } sethandler(handler, SIGINT); for(int i = 0; i<threadCount; i++){ data[i].divide = (rand_r(&data[i].seed) % (100 + 1 - 2)) + 2; } for (int i = 0; i < threadCount; i++) { int err = pthread_create(&(data[i].tid), NULL, job, &data[i]); if (err != 0) ERR("Couldn't create thread"); } while(last_signal==0){ nanosleep((const struct timespec[]){{0, 100000000L}}, NULL); count++; } for (int i = 0; i < threadCount; i++) { int err = pthread_join(data[i].tid, NULL); if (err != 0) ERR("Can't join with a thread"); } printf("\n"); } void ReadArguments(int argc, char **argv, int *threadCount) { *threadCount = DEFAULT_THREADCOUNT; if (argc >= 2) { *threadCount = atoi(argv[1]); if (*threadCount <= 0) { printf("Invalid value for 'threadCount'"); exit(EXIT_FAILURE); } } } void* job(void *voidPtr){ args_t *args = voidPtr; while(1){ if(last_signal) break; if((*args->counter % args->divide)==0) printf("%d jest podzielne przez %d\n", *args->counter, args->divide); } } void handler(int dummy){ last_signal = 1; printf("\nYou hit Ctrl+C\n"); }
C
#include <stdlib.h> #include <stdio.h> double m(double *x, int n) { double a, b; int i=0; a=x[1]; for (i = 0; i< n; ++i) { if (a<x[i]){ a=x[i]; } } b=x[1]; for (i = 0; i< n; ++i) { if (b>x[i]){ b=x[i]; } } return a - b; } int main() { double s; int n; int i=0; printf("please input:\n"); scanf("%d", &n); double *x = (double*)malloc(n*20); printf("enter:\n "); for (i = 0; i < n; ++i){ scanf("%lf", &x[i]); } s=m(x, n); printf("%lf\n", s); return 0; }
C
#include "processamento.h" int hora_de_mover_tiro_canhao(J* jogo) { if (jogo->contador_tempo % 2 == 0) return 1; else return 0; } int hora_de_mover_tiro_alien(J* jogo) { if (jogo->contador_tempo % 6 == 0) return 1; else return 0; } void processa_lista(J* jogo, char input) /* processa todos os elementos da lista de jogo */ { /* recebe os parametros a partir do estado do jogo */ int mover_alien, mover_tiro_alien, mover_tiro_canhao, tocou, atirar; tocou = 0; atirar = hora_de_atirar_aliens(jogo); mover_alien = hora_de_mover_aliens(jogo); mover_tiro_alien = hora_de_mover_tiro_alien(jogo); mover_tiro_canhao = hora_de_mover_tiro_canhao(jogo); if ( mover_alien ) { mudar_estado_impressao(jogo); tocou = tocou_borda(jogo); if (tocou) { jogo->sentido = !(jogo->sentido); if ( (jogo->velocidade) < VELOCIDADE_MAXIMA) jogo->velocidade++; } } /* lista usada por comodidade */ t_lista *L; L = &(jogo->lista); inicializa_atual_inicio(L); int tam; tamanho_lista(&tam, L); elemento* e; int removeu; int contador_atual; for(contador_atual = 1; contador_atual <= tam; contador_atual++) /* processa cada elemento da lista de acordo com seu tipo */ { consulta_item_atual(&e, L); removeu = 0; if (e->tipo == tiro_canhao || e->tipo == tiro_alien) move_tiros(L, e, mover_tiro_alien, mover_tiro_canhao, &removeu); /* so retiramos os tiros diretamente da lista se eles colidem com as bordas do tabuleiro. eh mais comodo remove-los, quando colidem, ao mesmo tempo que removemos o elemento a qual eles colidiram. */ else if (e->tipo == alien1 || e->tipo == alien2 || e->tipo == alien3) { move_e_atira_alien(L, e, tocou, mover_alien, atirar, jogo->sentido); processa_colisao(jogo, L, e, contador_atual, &removeu); if (e->tipo == alien_morrendo) /* quando um alien colide, nao o retiramos nos o transformamos no tipo "alien morrendo", que tem um contador que diz quanto tempo este fica nesse estado antes de ser removido da lista */ { jogo->quantidade_aliens--; e->contador = 8; jogo->score = jogo->score + 100; } } else if (e->tipo == barreira) processa_colisao(jogo, L, e, contador_atual, &removeu); else if (e->tipo == alien_morrendo) { if (e->contador == 0) /* quando o contador chega a 0, retiramos o elemento da lista */ removeu = 1; else e->contador--; } else if (e->tipo == canhao) { move_e_atira_canhao(L, e, input, contador_atual); processa_colisao(jogo, L, e, contador_atual, &removeu); if (removeu) jogo->vivo = 0; } else if (e->tipo == nave) { if ( hora_de_mover_nave(jogo) ) move_esquerda_alien(e); processa_colisao(jogo, L, e, contador_atual, &removeu); if (e->tipo == alien_morrendo) { jogo->paralisacao = 250; jogo->score = jogo->score + 1000; } } if (removeu) /* se eh necessario remover o elemento que estamos processando: */ { elemento lixo; remove_item_atual(&lixo, L); /* coloco o elemento no lixo */ tamanho_lista(&tam, L); /* atualizo o tamanho da lista, ja que acabamos de tirar um elemento */ contador_atual--; /* volta-se um elemento na lista, para processarmos todos os elementos. */ } else incrementa_atual(L); } }
C
#include<stdio.h> int arr[8] = { 15,22,13,27,12,10,20,25 }; typedef struct Node{ int data; struct node *next; }node; typedef struct queue{ node *front; node *rear; int count; }Queue; void InitQueue(Queue *q) { q->count = 0; q->front = NULL; q->rear = NULL; } int IsEmpty(Queue *q) { return (q->count) == 0; } void Enqueue(Queue *q, int t) { node *n = (node *)malloc(sizeof(node)); n->data = t; n->next = NULL; if (IsEmpty(q)) { q->front = n; } else { q->rear->next = n; } q->rear = n; q->count++; } int Dequeue(Queue *q) { int re = 0; node *now; if (IsEmpty(q))//ť { return re; } now = q->front;// 带 now re = now->data;//ȯ now data q->front = now->next;// now free(now);//now Ҹ q->count--;// 1 return re; } void quicksort(int low, int high) { Queue L; Queue R; int start, end; InitQueue(&L); InitQueue(&R); Enqueue(&L, low); Enqueue(&R, high); int top = 1; int pp; while (top > 0) { start=Dequeue(&L, low); end=Dequeue(&R, high); top--; partition(start, end); if (pp - 1 > start) { top++; Enqueue(&L, start); Enqueue(&R, pp-1); } else if (pp + 1 < end) { } } } void main(void) { }
C
/* ** change_line.c for in /home/fernan_w/Téléchargements/backup/readline ** ** Made by ** Login <fernan_w@epitech.net> ** ** Started on Thu Jun 2 23:15:23 2016 ** Last update Sun Jun 5 19:13:25 2016 retyt */ #include <unistd.h> #include "readline.h" #include "my.h" static int write_line_up(char *str) { int i; i = 0; if ((my_putstr("\033[1A", 1)) == -1) return (-1); while (i < 1000) { if ((my_tputs(str, 1)) == -1) return (-1); i += 1; } return (1); } int line_up(void) { char buffer[32]; int size_read; int i; char str[4]; str[0] = 27; str[1] = 91; str[2] = 67; str[3] = 0; if ((my_putstr("\033[6n", 1)) == -1) return (-1); if ((size_read = read(0, buffer, 31)) == -1) return (my_putstr("error: could not read\n", 2)); i = 0; while (buffer[i] && buffer[i] != ';') i += 1; if (buffer[i] && buffer[i + 1] == '1' && buffer[i + 2] == 'R') return (write_line_up(str)); return (0); } static int my_little_atoi(char *str) { int i; int number; i = 0; number = 0; while (str[i] >= 48 && str[i] <= 57) { number *= 10; number += (str[i] - 48); i++; } return (number); } static int write_line_down(int size) { char *left; int i; i = 0; if ((write(1, "\033[1B", 4)) == -1) return (-1); if ((left = tgetstr("le", NULL)) == NULL) return (my_putstr("error: tgetstr\n", 2)); while (i < size) { if ((write(1, left, 1)) == -1) return (-1); i += 1; } return (0); } int line_down(int size) { char buffer[32]; char str[4]; int size_read; int i; int tmp; str[0] = 27; str[1] = 91; str[2] = 67; str[3] = 0; if ((write(1, "\033[6n", 4)) == -1) return (-1); if ((size_read = read(0, buffer, 31)) == -1) return (my_putstr("error: could not read\n", 2)); buffer[size_read] = 0; i = 0; while (buffer[i] && buffer[i] != ';') i += 1; tmp = my_little_atoi(buffer + i + 1); if (tmp == size && write_line_down(size) == -1) return (-1); else if (tmp != size) if (write(1, str, 4) == -1) return (-1); return (0); }
C
#include <stdio.h> //정수 한 개 입력받아 아스키 문자로 출력하기 int main(void) { int a; scanf("%d", &a); printf("%c", a); }
C
#include<stdio.h> int id[20],completed[20],arrivalTime[20],burstTime[20],ct[20],tat[20],wt[20]; int n,t=0,noOfCompletedProcess=0,i; void print_table() { float avgWT=0,avgTAT=0; printf("\n\n\n\n\n"); printf("\n|---------------------------------------------------------------------------|"); printf("\n| id | Arrival Time | Burst Time | Turtaround Time | Waiting Time |"); printf("\n|---------------------------------------------------------------------------|"); for(int i=0;i<n;i++) { printf("\n| %d | %d | %d | %d | %d |",id[i],arrivalTime[i],burstTime[i],tat[i],wt[i]); printf("\n|---------------------------------------------------------------------------|"); } for(int i=0;i<n;i++) { avgTAT+=tat[i]; avgWT+=wt[i]; } avgTAT/=n; avgWT/=n; printf("\n\n"); printf("\nAverage waiting time : %.3f\n",avgWT); printf("\nAverage Turnaround time : %.3f\n\n\n",avgTAT); } void print_gnatt() { printf("\n\n\n"); printf("___________Gnatt Chart____________\n\n\n"); printf("|-----------------|--------------|\n"); printf("| Time Interval | Process ID |\n"); printf("|-----------------|--------------|"); } int notDone(int x) { for(i=0;i<=noOfCompletedProcess;i++) { if(completed[i]==x) { return 1; } } return 0; } int nextProcess() { for(int i=0;i<n;i++) { if(notDone(id[i])) { continue; } else { if(t>=arrivalTime[i]) { completed[noOfCompletedProcess]=id[i];noOfCompletedProcess++; printf("\n| %d -",t); t+=burstTime[i]; printf(" %d | %d |\n",t,id[i]); printf("|-----------------|--------------|"); ct[i]=t; tat[i]=ct[i]-arrivalTime[i]; wt[i]=tat[i]-burstTime[i]; return i; } } } t++; printf("\n| %d - %d | IDLE |\n",t-1,t); printf("|-----------------|--------------|"); return nextProcess(); } int main() { printf("GOR SMIT HASMUKHBHAI(19BCT0103)"); int i,nextid; printf("\nEnter the total number of processes : "); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter the process id : "); scanf("%d",&id[i]); printf("Enter the Arrival time : "); scanf("%d",&arrivalTime[i]); printf("Enter the Burst time : "); scanf("%d",&burstTime[i]); printf("\n"); } print_gnatt(); do { nextid=nextProcess(); } while (noOfCompletedProcess!=n); print_table(); printf("\n\nSubmited By SMIT GOR\n Reg. No. : 19BCT0103"); }
C
#include <avr/io.h> #include "pacer.h" static uint16_t pacer_period; /* Initialise the pacer module. */ void pacer_init (uint16_t pacer_frequency) { /* TODO: initialise timer/counter peripheral the same way as in lab2/lab2-ex2/timer.c but also calculate the timer/counter value from the pacer frequency */ } /* Pace a while loop. */ void pacer_wait (void) { /* TODO: Implement the same way as the timer_delay () function lab2-except reset TCNT1 after the while loop. */ }
C
#include "stack.h" void init(){ start = NULL; } int push(unsigned int n){ t_node *p = start; start = (t_node*)malloc(sizeof(t_node)); if(!start){ return 1; } start->data = n; start->next = p; return 0; } int pop(unsigned int *n){ if(start){ *n = start->data; t_node *p = start; start = start->next; free(p); return 1; }else{ return 0; } }
C
// Sorting integers with bubble sort void printarr(int*, int); void bubblesort(int* arr, int size){ // 'Bubble' up the largest element to the last position for(int i = size-1; i>=0; --i){ int tmp; for(int j=1; j<=i; ++j){ // Swap if(arr[j]<arr[j-1]){ tmp = arr[j-1]; arr[j-1] = arr[j]; arr[j] = tmp; } } } printf("Bubblesort done!\n"); }
C
/*** Timer handling APIs ***/ /************************************************************************ * * This file contains the definitions of functions concerned with the * handling of timers in Nucleus SE: * * NUSE_Timer_Control() * NUSE_Timer_Get_Remaining() * NUSE_Timer_Reset() * NUSE_Timer_Information() * NUSE_Timer_Count() * ************************************************************************/ #include "nuse_config.h" #include "nuse_codes.h" #include "nuse_types.h" #include "nuse_data.h" #include "nuse_prototypes.h" /************************************************************************* * * FUNCTION * * NUSE_Timer_Control() * * DESCRIPTION * * Timer can be enabled or disabled * When enabled, the timer is set to the initial time or the reschedule time * Initial time is used if the timer has not expired since it was initialized or last reset * Reschedule time is used if the timer has previously expired * Disabling sets the timer count to 0 * * INPUTS * * NUSE_TIMER timer index of the timer to be enabled/disabled * OPTION enable required function: NUSE_ENABLE_TIMER or NUSE_DISABLE_TIMER * * RETURNS * * NUSE_SUCCESS the timer was successfully enabled/disabled * NUSE_INVALID_TIMER the timer index was invalid * NUSE_INVALID_ENABLE the function selection [enable] was invalid; i.e. not NUSE_ENABLE_TIMER or NUSE_DISABLE_TIMER * * OTHER OUTPUTS * * (none) * *************************************************************************/ #if NUSE_TIMER_CONTROL || (NUSE_INCLUDE_EVERYTHING && (NUSE_TIMER_NUMBER != 0)) STATUS NUSE_Timer_Control(NUSE_TIMER timer, OPTION enable) { #if NUSE_API_PARAMETER_CHECKING if (timer >= NUSE_TIMER_NUMBER) { return NUSE_INVALID_TIMER; } if ((enable != NUSE_ENABLE_TIMER) && (enable != NUSE_DISABLE_TIMER)) { return NUSE_INVALID_ENABLE; } #endif NUSE_CS_Enter(); if (enable == NUSE_ENABLE_TIMER) { NUSE_Timer_Status[timer] = TRUE; if (NUSE_Timer_Expirations_Counter[timer] == 0) { NUSE_Timer_Value[timer] = NUSE_Timer_Initial_Time[timer]; } else { NUSE_Timer_Value[timer] = NUSE_Timer_Reschedule_Time[timer]; } } else /* enable == NUSE_DISABLE_TIMER */ { NUSE_Timer_Status[timer] = FALSE; } NUSE_CS_Exit(); return NUSE_SUCCESS; } #endif /************************************************************************* * * FUNCTION * * NUSE_Timer_Get_Remaining() * * DESCRIPTION * * Returns the remaining number of ticks before the timer will expire * * INPUTS * * NUSE_TIMER timer index of the timer to be queries * U16 *remaining_time pointer to storage for the timer remaining time * * RETURNS * * NUSE_SUCCESS the remaining time was retuned successfully * NUSE_INVALID_TIMER the timer index was invalid * NUSE_INVALID_POINTER the return data pointer [remaining time] was NULL * * OTHER OUTPUTS * * U16 *remaining_time remaining time value * *************************************************************************/ #if NUSE_TIMER_GET_REMAINING || (NUSE_INCLUDE_EVERYTHING && (NUSE_TIMER_NUMBER != 0)) STATUS NUSE_Timer_Get_Remaining(NUSE_TIMER timer, U16 *remaining_time) { #if NUSE_API_PARAMETER_CHECKING if (timer >= NUSE_TIMER_NUMBER) { return NUSE_INVALID_TIMER; } if (remaining_time == NULL) { return NUSE_INVALID_POINTER; } #endif NUSE_CS_Enter(); *remaining_time = NUSE_Timer_Value[timer]; NUSE_CS_Exit(); return NUSE_SUCCESS; } #endif /************************************************************************* * * FUNCTION * * NUSE_Timer_Reset() * * DESCRIPTION * * Restores the specified timer to its initialized state * Uses the same initialization routine as on start-up - in nuse_init.c * Then, the timer is enabled, if required * * INPUTS * * NUSE_TIMER timer the index of the timer to be reset * OPTION enable the required state of the timer after reset; NUSE_ENABLE_TIMER or NUSE_DISABLE_TIMER * * RETURNS * * NUSE_SUCCESS the timer was successfully reset * NUSE_INVALID_TIMER the timer index was invalid * NUSE_INVALID_ENABLE the state selection [enable] was invalid; i.e. not NUSE_ENABLE_TIMER or NUSE_DISABLE_TIMER * * OTHER OUTPUTS * * (none) * *************************************************************************/ #if NUSE_TIMER_RESET || (NUSE_INCLUDE_EVERYTHING && (NUSE_TIMER_NUMBER != 0)) STATUS NUSE_Timer_Reset(NUSE_TIMER timer, OPTION enable) { #if NUSE_API_PARAMETER_CHECKING if (timer >= NUSE_TIMER_NUMBER) { return NUSE_INVALID_TIMER; } if ((enable != NUSE_ENABLE_TIMER) && (enable != NUSE_DISABLE_TIMER)) { return NUSE_INVALID_ENABLE; } #endif if (NUSE_Timer_Status[timer]) { return NUSE_NOT_DISABLED; } NUSE_CS_Enter(); NUSE_Init_Timer(timer); if (enable == NUSE_ENABLE_TIMER) { NUSE_Timer_Status[timer] = TRUE; } /* else enable==NUSE_DISABLE_TIMER and status remains FALSE */ NUSE_CS_Exit(); return NUSE_SUCCESS; } #endif /************************************************************************* * * FUNCTION * * NUSE_Timer_Information() * * DESCRIPTION * * Returns a number of items of data about a timer * Unsupported items are handled in nuse.h * * INPUTS * * NUSE_TIMER timer index of timer about which information is required * OPTION *enable pointer to storage for the timer status * U8 *expirations pointer to storage for the expirations count * U8 *id pointer to storage for the expiration function parameter * U16 *initial_time pointer to storage for the initial time setting * U16 *reschedule_time pointer to storage for the reschedule time setting * * RETURNS * * NUSE_SUCCESS the information was successfully returned * NUSE_INVALID_TIMER the timer index was not valid * NUSE_INVALID_POINTER one or more of the pointer parameters was NULL * * OTHER OUTPUTS * * OPTION *enable timer status; NUSE_ENABLE_TIMER or NUSE_DISABLE_TIMER * U8 *expirations expirations count - the number of times the timer has expired since initialization or reset * U8 *id expiration function parameter [if this facility is configured] * U16 *initial_time initial time setting * U16 *reschedule_time reschedule time setting * *************************************************************************/ #if NUSE_TIMER_INFORMATION || (NUSE_INCLUDE_EVERYTHING && (NUSE_TIMER_NUMBER != 0)) STATUS NUSE_Timer_Information(NUSE_TIMER timer, OPTION *enable, U8 *expirations, U8 *id, U16 *initial_time, U16 *reschedule_time) { #if NUSE_API_PARAMETER_CHECKING if (timer >= NUSE_TIMER_NUMBER) { return NUSE_INVALID_TIMER; } #endif NUSE_CS_Enter(); if (NUSE_Timer_Status[timer]) { *enable = NUSE_ENABLE_TIMER; } else { *enable = NUSE_DISABLE_TIMER; } *expirations = NUSE_Timer_Expirations_Counter[timer]; #if NUSE_TIMER_EXPIRATION_ROUTINE_SUPPORT *id = NUSE_Timer_Expiration_Routine_Parameter[timer]; #endif *initial_time = NUSE_Timer_Initial_Time[timer]; *reschedule_time = NUSE_Timer_Reschedule_Time[timer]; NUSE_CS_Exit(); return NUSE_SUCCESS; } #endif /************************************************************************* * * FUNCTION * * NUSE_Timer_Count() * * DESCRIPTION * * Returns the number of timers in the system * Code is trivial, as the number of timers is fixed in Nucleus SE, * so a constant is returned * * INPUTS * * (none) * * RETURNS * * U8 value number of timers in the system [Value: 0-15] * * OTHER OUTPUTS * * (none) * *************************************************************************/ #if NUSE_TIMER_COUNT || NUSE_INCLUDE_EVERYTHING U8 NUSE_Timer_Count(void) { return NUSE_TIMER_NUMBER; } #endif
C
#include<stdio.h> long add(int n , int d) { int c = n/d -( n%d==0) ; return (long)d * c*(c+1)/2 ; } int main() { int t , n , i,c; long int sum; scanf("%d",&t); while(t--) { fflush(stdin); scanf("%d",&n); sum = 0; sum+=add(n,3); sum+=add(n,5); sum-=add(n,15); printf("%ld\n",sum); } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/msg.h> #include <unistd.h> /*--------------------------------------------------------------*/ #define N 1000000 #define CHAVE 6 /*---------------------------------------------------------*/ struct msg{ long tipo; int gc; }; /*--------------------------------------------------------------*/ void le_dna(char *arquivo, char *dna){ char c; int i = 0; FILE *f = fopen(arquivo,"r"); while ( ( c = fgetc(f) ) != EOF && c!='\n' ){ dna[i++] = c; } dna[i] = '\0'; } /*--------------------------------------------------------------*/ int conta_gc(char *str, int ini, int fim){ int i, gc = 0; for ( i=ini; i<fim; i++ ){ if ( str[i]=='C' || str[i]=='G'){ gc++; } } return(gc); } /*--------------------------------------------------------------*/ int main(int argc, char **argv){ int fila, pid; struct msg msg; int total = 0; char str[N]; fila = msgget(CHAVE,0600|IPC_CREAT); le_dna("dna.txt",str); pid = fork(); if ( pid > 0 ){ pid = fork(); if ( pid > 0 ){ msgrcv(fila,&msg,sizeof(msg.gc),0,0); total += msg.gc; msgrcv(fila,&msg,sizeof(msg.gc),0,0); total += msg.gc; wait(NULL); wait(NULL); msgctl(fila, IPC_RMID, NULL); printf("Conteudo GC: %.2f\n", (float)total/strlen(str)); } else{ msg.tipo = 2; msg.gc = conta_gc(str, strlen(str)/2, strlen(str)); msgsnd(fila,&msg,sizeof(msg.gc),0); } } else{ msg.tipo = 1; msg.gc = conta_gc(str, 0,strlen(str)/2); msgsnd(fila,&msg,sizeof(msg.gc),0); } }
C
#include <stdio.h> #include <stdlib.h> #include "persona.h" #define CPAIS 6 void menu(ePersona pers[], int cant){ ePais pais[6] = {{0,"Argentina"},{1,"Uruguay"},{2,"Brasil"},{3,"Chile"},{4,"Peru"}, {5,"Paraguay"}}; int opc; do{ printf("1)Ingresar alta de una persona.\n2)Dar de baja a una persona.\n3)Mostrar todos los ingresados.\n"); printf("4)Ordenarlos por edad.\n5)Modificar datos de una persona.\n6)Salir.\n\nOpcion: "); scanf("%d",&opc); switch(opc){ case 1: system("cls"); alta(pers, pais, cant, 6); break; case 2: system("cls"); baja(pers, cant); break; case 3: system("cls"); printf("Mostrar todos los ingresados: \n"); mostrarTodos(pers, pais, cant); printf("\n"); break; case 4: system("cls"); printf("Ordenados por edad: \n"); ordenar(pers, pais, cant); printf("\n"); break; case 5: system("cls"); modificacion(pers,cant); break; case 6: break; default: printf("Se ha ingresado una opcion incorrecta!"); } }while(opc != 6); } void inicializacion(ePersona pers[], int cant){ int i; for(i=0; i< cant; i++){ pers[i].isEmpty = 1; } } void baja(ePersona pers[], int cant){ int auxId, flag = 0, i; char confirmacion; printf("Ingrese el dni a dar de baja: "); scanf("%d",&auxId); for(i=0; i<cant;i++){ if(auxId == pers[i].dni){ printf("Datos encontrados: \n"); printf("====================================================\n"); printf("%d\t%s\t%s\t%d\t%d:%d:%d\t%d\t%d\n", pers[i].dni, pers[i].apellido, pers[i].nombre, pers[i].edad, pers[i].fechaNac.dia, pers[i].fechaNac.mes, pers[i].fechaNac.anio, pers[i].ePais, pers[i].isEmpty); printf("====================================================\n"); do{ printf("Confirma que desea borrar los datos? (S/N): "); fflush(stdin); scanf("%c",&confirmacion); toupper(confirmacion); }while(confirmacion != 's' && confirmacion != 'n'); if(confirmacion == 's'){ pers[i].isEmpty = 1; flag = 1; printf("\nLos datos se han borrado exitosamente!\n\n"); } break; } } if(flag == 0){ printf("No se ha encontrado dicho dni!\n\n"); } } void modificacion(ePersona pers[], int cant){ int auxId, flag = 0, i, opc2; char confirmacion; printf("Ingrese el dni a modificar: "); scanf("%d",&auxId); for(i=0; i<cant;i++){ if(auxId == pers[i].dni){ printf("Datos encontrados: \n"); printf("====================================================\n"); printf("%d\n%s\n%s\n%d\n%d:%d:%d\n%d\n%d\n", pers[i].dni, pers[i].apellido, pers[i].nombre, pers[i].edad, pers[i].fechaNac.dia, pers[i].fechaNac.mes, pers[i].fechaNac.anio, pers[i].ePais, pers[i].isEmpty); printf("====================================================\n"); do{ printf("Confirma que desea modificar los datos? (S/N): "); fflush(stdin); scanf("%c",&confirmacion); toupper(confirmacion); }while(confirmacion != 's' && confirmacion != 'n'); if(confirmacion == 's'){ do{ system("cls"); printf("Datos encontrados: \n"); printf("====================================================\n"); printf("%d\n%s\n%s\n%d\n%d:%d:%d\n%d\n%d\n", pers[i].dni, pers[i].apellido, pers[i].nombre, pers[i].edad, pers[i].fechaNac.dia, pers[i].fechaNac.mes, pers[i].fechaNac.anio, pers[i].ePais, pers[i].isEmpty); printf("====================================================\n\n"); printf("1) Modificar nombre.\n2) Modificar apellido.\n3) Modificar edad.\n3) Modificar F.Nac.\n"); printf("4) Modificar nacionalidad.\n5) Salir."); printf("\nOpcion: "); scanf("%d",&opc2); switch(opc2){ case 1: system("cls"); printf("Nombre: "); fflush(stdin); scanf("%s", pers[i].nombre); break; case 2: system("cls"); printf("Apellido: "); fflush(stdin); scanf("%s", pers[i].apellido); break; case 3: system("cls"); printf("Edad: "); fflush(stdin); scanf("%s", pers[i].edad); break; case 4: system("cls"); printf("Fecha Nacimiento: "); fflush(stdin); scanf("%s", pers[i].fechaNac); break; case 5: break; default: printf("Opcion Incorrecta!"); } }while(opc2 != 5); flag = 1; } break; } } if(flag == 0){ printf("No se ha encontrado dicho dni!\n\n"); } } void alta(ePersona pers[], ePais pais[], int cantidad, int id){ int i,j,flag = 0; for(i=0; i< cantidad; i++){ printf("%d",pers[i].isEmpty); printf("\n\n"); if(pers[i].isEmpty == 1){ printf("Dni: "); scanf("%d", &pers[i].dni); printf("Apellido: "); fflush(stdin); scanf("%s", pers[i].apellido); printf("Nombre: "); fflush(stdin); scanf("%s", pers[i].nombre); printf("Edad: "); scanf("%d", &pers[i].edad); printf("\n"); printf("Fecha Nacimiento\n\tDia: "); scanf("%d",&pers[i].fechaNac.dia); printf("\tmes: "); scanf("%d",&pers[i].fechaNac.mes); printf("\tanio: "); scanf("%d",&pers[i].fechaNac.anio); printf("\nIngrese nacionalidad: \n"); for(j=0;j<CPAIS;j++){ printf("\t%d %s\n",pais[j].id, pais[j].descripcion); } printf("\n"); printf("Opcion: "); scanf("%d",&pers[i].ePais); for(i=0; i<CPAIS; i++){ if(pais[i].id == pers[i].ePais){ for(j=0; j<CPAIS; j++){ if(pers[j].ePais == pers[i].ePais){ printf("%s %s",pers[j].nombre, pais[i].descripcion); } } break; } } flag = 1; pers[i].isEmpty = 0; //system("cls"); break; } } if(flag == 0){ printf("NO HAY MAS LUGAR PARA GUARDAR DATOS!!\n\n"); } } void mostrarTodos(ePersona pers[], ePais pais[], int cantidad){ int i,j; for(i=0; i< cantidad; i++){ if(pers[i].isEmpty == 0){ mostrarUno(pers[i], pais[i]); } } } void mostrarUno(ePersona pers, ePais pais){ printf("%d\t%s\t%s\t%d\t%d:%d:%d\t%d\t%d\n", pers.dni, pers.apellido, pers.nombre, pers.edad, pers.fechaNac.dia, pers.fechaNac.mes, pers.fechaNac.anio, pers.ePais, pers.isEmpty); } void ordenar(ePersona pers[], ePais pais[], int cant){ ePersona auxPer; int i,j; for(i=0;i<cant-1;i++){ for(j=i+1;j<cant;j++){ if(pers[i].edad > pers[j].edad){ auxPer = pers[i]; pers[i] = pers[j]; pers[j] = auxPer; } } } mostrarTodos(pers, pais, cant); }
C
/* MIT License Copyright (c) 2018 Viviano Riccardo Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files ((the "LICENSE")), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "llab.h" /* This function returns a lstm structure, with the big difference with the commond long short term memory * standard structure, that each weight array is size*size dimensions (you can pad) * * Inputs: * * @ int size:= the size of each hidden layer inside the lstm structure * @ int dropout_flag1:= the dropout flag for the y output of the cell * @ float dropout_threshold1:= the dropout_threshold for the y output * @ int dropout_flag2:= the dropout flag for the hidden output to the next cell * @ float dropout_threshold2:= the dropout threshold for the hidden state of the cell * @ int layer:= the vertical layer of the lstm cell * @ int window:= the number of unrolled cell in orizontal * * */ lstm* recurrent_lstm(int size, int dropout_flag1, float dropout_threshold1, int dropout_flag2, float dropout_threshold2, int layer, int window, int residual_flag, int norm_flag, int n_grouped_cell){ if(layer < 0 || size <= 0){ fprintf(stderr,"Error: the layer flag must be >= 0 and size param should be > 0\n"); exit(1); } if(window < 2){ fprintf(stderr,"Error: your window must be >= 2\n"); exit(1); } if(norm_flag == GROUP_NORMALIZATION){ if(n_grouped_cell > window || window%n_grouped_cell){ fprintf(stderr,"Error: you assumed the group normalization, but the number of grouped cells doesn't divide perfectly the number of unrolled cell during feed forward\n"); exit(1); } } int i,j; lstm* lstml = (lstm*)malloc(sizeof(lstm)); lstml->layer = layer; lstml->size = size; lstml->dropout_flag_up = dropout_flag1; lstml->dropout_flag_right = dropout_flag2; lstml->w = (float**)malloc(sizeof(float*)*4); lstml->u = (float**)malloc(sizeof(float*)*4); lstml->d_w = (float**)malloc(sizeof(float*)*4); lstml->ex_d_w_diff_grad = (float**)malloc(sizeof(float*)*4); lstml->d1_w = (float**)malloc(sizeof(float*)*4); lstml->d2_w = (float**)malloc(sizeof(float*)*4); lstml->d3_w = (float**)malloc(sizeof(float*)*4); lstml->d_u = (float**)malloc(sizeof(float*)*4); lstml->ex_d_u_diff_grad = (float**)malloc(sizeof(float*)*4); lstml->d1_u = (float**)malloc(sizeof(float*)*4); lstml->d2_u = (float**)malloc(sizeof(float*)*4); lstml->d3_u = (float**)malloc(sizeof(float*)*4); lstml->biases = (float**)malloc(sizeof(float*)*4); lstml->d_biases = (float**)malloc(sizeof(float*)*4); lstml->ex_d_biases_diff_grad = (float**)malloc(sizeof(float*)*4); lstml->d1_biases = (float**)malloc(sizeof(float*)*4); lstml->d2_biases = (float**)malloc(sizeof(float*)*4); lstml->d3_biases = (float**)malloc(sizeof(float*)*4); lstml->lstm_z = (float***)malloc(sizeof(float**)*window); lstml->lstm_hidden = (float**)malloc(sizeof(float*)*window); lstml->out_up = (float**)malloc(sizeof(float*)*window); lstml->lstm_cell = (float**)malloc(sizeof(float*)*window); lstml->dropout_mask_up = (float*)malloc(sizeof(float)*size); lstml->dropout_mask_right = (float*)malloc(sizeof(float)*size); lstml->dropout_threshold_up = dropout_threshold1; lstml->dropout_threshold_right = dropout_threshold2; lstml->residual_flag = residual_flag; lstml->norm_flag = norm_flag; lstml->n_grouped_cell = n_grouped_cell; if(norm_flag == GROUP_NORMALIZATION){ lstml->bns = (bn**)malloc(sizeof(bn*)*window/n_grouped_cell); for(i = 0; i < window/n_grouped_cell; i++){ lstml->bns[i] = batch_normalization(n_grouped_cell,size,layer,NO_ACTIVATION); } } else{ lstml->bns = NULL; } if(lstml->dropout_flag_up == NO_DROPOUT) lstml->dropout_threshold_up = 0; if(lstml->dropout_flag_right == NO_DROPOUT) lstml->dropout_threshold_right = 0; for(i = 0; i < window; i++){ lstml->lstm_z[i] = (float**)malloc(sizeof(float*)*4); lstml->lstm_hidden[i] = (float*)calloc(size,sizeof(float)); lstml->lstm_cell[i] = (float*)calloc(size,sizeof(float)); lstml->out_up[i] = (float*)calloc(size,sizeof(float)); for(j = 0; j < 4; j++){ lstml->lstm_z[i][j] = (float*)calloc(size,sizeof(float)); } } for(i = 0; i < 4; i++){ lstml->w[i] = (float*)calloc(size*size,sizeof(float)); lstml->u[i] = (float*)calloc(size*size,sizeof(float)); for(j = 0; j < size*size; j++){ lstml->w[i][j] = random_general_gaussian(0,size); lstml->u[i][j] = random_general_gaussian(0,size); } lstml->d_w[i] = (float*)calloc(size*size,sizeof(float)); lstml->ex_d_w_diff_grad[i] = (float*)calloc(size*size,sizeof(float)); lstml->d1_w[i] = (float*)calloc(size*size,sizeof(float)); lstml->d2_w[i] = (float*)calloc(size*size,sizeof(float)); lstml->d3_w[i] = (float*)calloc(size*size,sizeof(float)); lstml->d_u[i] = (float*)calloc(size*size,sizeof(float)); lstml->ex_d_u_diff_grad[i] = (float*)calloc(size*size,sizeof(float)); lstml->d1_u[i] = (float*)calloc(size*size,sizeof(float)); lstml->d2_u[i] = (float*)calloc(size*size,sizeof(float)); lstml->d3_u[i] = (float*)calloc(size*size,sizeof(float)); lstml->biases[i] = (float*)calloc(size,sizeof(float)); lstml->d_biases[i] = (float*)calloc(size,sizeof(float)); lstml->ex_d_biases_diff_grad[i] = (float*)calloc(size,sizeof(float)); lstml->d1_biases[i] = (float*)calloc(size,sizeof(float)); lstml->d2_biases[i] = (float*)calloc(size,sizeof(float)); lstml->d3_biases[i] = (float*)calloc(size,sizeof(float)); } for(i = 0; i < size; i++){ lstml->dropout_mask_up[i] = 1; lstml->dropout_mask_right[i] = 1; } lstml->window = window; return lstml; } /* This function frees the space allocated by a rlstm structure * * Inputs: * * @ lstm* rlstm:= the lstm structure that must be deallocated * * */ void free_recurrent_lstm(lstm* rlstm){ if(rlstm == NULL) return; int i,j; for(i = 0; i < rlstm->window; i++){ for(j = 0; j < 4; j++){ free(rlstm->lstm_z[i][j]); } free(rlstm->lstm_z[i]); free(rlstm->lstm_hidden[i]); free(rlstm->lstm_cell[i]); free(rlstm->out_up[i]); } for(i = 0; i < 4; i++){ free(rlstm->w[i]); free(rlstm->u[i]); free(rlstm->d_w[i]); free(rlstm->ex_d_w_diff_grad[i]); free(rlstm->d1_w[i]); free(rlstm->d2_w[i]); free(rlstm->d3_w[i]); free(rlstm->d_u[i]); free(rlstm->ex_d_u_diff_grad[i]); free(rlstm->d1_u[i]); free(rlstm->d2_u[i]); free(rlstm->d3_u[i]); free(rlstm->biases[i]); free(rlstm->d_biases[i]); free(rlstm->d1_biases[i]); free(rlstm->d2_biases[i]); free(rlstm->d3_biases[i]); free(rlstm->ex_d_biases_diff_grad[i]); } if(rlstm->norm_flag == GROUP_NORMALIZATION){ for(i = 0; i < rlstm->window/rlstm->n_grouped_cell; i++){ free_batch_normalization(rlstm->bns[i]); } free(rlstm->bns); } free(rlstm->w); free(rlstm->u); free(rlstm->d_w); free(rlstm->ex_d_w_diff_grad); free(rlstm->d1_w); free(rlstm->d2_w); free(rlstm->d3_w); free(rlstm->d_u); free(rlstm->ex_d_u_diff_grad); free(rlstm->d1_u); free(rlstm->d2_u); free(rlstm->d3_u); free(rlstm->biases); free(rlstm->d_biases); free(rlstm->ex_d_biases_diff_grad); free(rlstm->d1_biases); free(rlstm->d3_biases); free(rlstm->lstm_z); free(rlstm->lstm_hidden); free(rlstm->lstm_cell); free(rlstm->out_up); free(rlstm->dropout_mask_right); free(rlstm->dropout_mask_up); free(rlstm); } /* This function saves a lstm layer on a .bin file with name n.bin * * Input: * * @ lstm* rlstm:= the actual layer that must be saved * @ int n:= the name of the bin file where the layer is saved * * * */ void save_lstm(lstm* rlstm, int n){ if(rlstm == NULL) return; int i,j; FILE* fw; char* s = (char*)malloc(sizeof(char)*256); char* t = ".bin"; s = itoa(n,s); s = strcat(s,t); fw = fopen(s,"a+"); if(fw == NULL){ fprintf(stderr,"Error: error during the opening of the file %s\n",s); exit(1); } i = fwrite(&rlstm->residual_flag,sizeof(int),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(&rlstm->norm_flag,sizeof(int),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(&rlstm->n_grouped_cell,sizeof(int),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(&rlstm->size,sizeof(int),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(&rlstm->layer,sizeof(int),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(&rlstm->dropout_flag_up,sizeof(int),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(&rlstm->dropout_flag_right,sizeof(int),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(&rlstm->window,sizeof(int),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(&rlstm->dropout_threshold_up,sizeof(float),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(&rlstm->dropout_threshold_right,sizeof(float),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } for(j = 0; j < 4; j++){ i = fwrite(rlstm->w[j],sizeof(float)*(rlstm->size)*(rlstm->size),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(rlstm->u[j],sizeof(float)*(rlstm->size)*(rlstm->size),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(rlstm->biases[j],sizeof(float)*(rlstm->size),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } } i = fclose(fw); if(i != 0){ fprintf(stderr,"Error: an error occurred closing the file %s\n",s); exit(1); } if(rlstm->norm_flag == GROUP_NORMALIZATION){ for(j = 0; j < rlstm->window/rlstm->n_grouped_cell; j++){ save_bn(rlstm->bns[j],n); } } free(s); } /* This function saves a lstm layer on a .bin file with name n.bin * * Input: * * @ lstm* rlstm:= the actual layer that must be saved * @ int n:= the name of the bin file where the layer is saved * * * */ void heavy_save_lstm(lstm* rlstm, int n){ if(rlstm == NULL) return; int i,j; FILE* fw; char* s = (char*)malloc(sizeof(char)*256); char* t = ".bin"; s = itoa(n,s); s = strcat(s,t); fw = fopen(s,"a+"); if(fw == NULL){ fprintf(stderr,"Error: error during the opening of the file %s\n",s); exit(1); } i = fwrite(&rlstm->residual_flag,sizeof(int),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(&rlstm->norm_flag,sizeof(int),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(&rlstm->n_grouped_cell,sizeof(int),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(&rlstm->size,sizeof(int),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(&rlstm->layer,sizeof(int),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(&rlstm->dropout_flag_up,sizeof(int),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(&rlstm->dropout_flag_right,sizeof(int),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(&rlstm->window,sizeof(int),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(&rlstm->dropout_threshold_up,sizeof(float),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(&rlstm->dropout_threshold_right,sizeof(float),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } for(j = 0; j < 4; j++){ i = fwrite(rlstm->w[j],sizeof(float)*(rlstm->size)*(rlstm->size),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(rlstm->d1_w[j],sizeof(float)*(rlstm->size)*(rlstm->size),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(rlstm->d2_w[j],sizeof(float)*(rlstm->size)*(rlstm->size),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(rlstm->d3_w[j],sizeof(float)*(rlstm->size)*(rlstm->size),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(rlstm->ex_d_w_diff_grad[j],sizeof(float)*(rlstm->size)*(rlstm->size),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(rlstm->u[j],sizeof(float)*(rlstm->size)*(rlstm->size),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(rlstm->d1_u[j],sizeof(float)*(rlstm->size)*(rlstm->size),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(rlstm->d2_u[j],sizeof(float)*(rlstm->size)*(rlstm->size),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(rlstm->d3_u[j],sizeof(float)*(rlstm->size)*(rlstm->size),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(rlstm->ex_d_u_diff_grad[j],sizeof(float)*(rlstm->size)*(rlstm->size),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(rlstm->biases[j],sizeof(float)*(rlstm->size),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(rlstm->d1_biases[j],sizeof(float)*(rlstm->size),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(rlstm->d2_biases[j],sizeof(float)*(rlstm->size),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(rlstm->d3_biases[j],sizeof(float)*(rlstm->size),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } i = fwrite(rlstm->ex_d_biases_diff_grad[j],sizeof(float)*(rlstm->size),1,fw); if(i != 1){ fprintf(stderr,"Error: an error occurred saving a lstm layer\n"); exit(1); } } i = fclose(fw); if(i != 0){ fprintf(stderr,"Error: an error occurred closing the file %s\n",s); exit(1); } if(rlstm->norm_flag == GROUP_NORMALIZATION){ for(j = 0; j < rlstm->window/rlstm->n_grouped_cell; j++){ heavy_save_bn(rlstm->bns[j],n); } } free(s); } /* This function loads a lstm layer from a .bin file from fr * * Input: * * @ FILE* fr:= a pointer to a file already opened * * */ lstm* load_lstm(FILE* fr){ if(fr == NULL) return NULL; int i,j; int size = 0,layer = 0,dropout_flag_up = 0,dropout_flag_right = 0, window = 0, residual_flag = 0, norm_flag = 0, n_grouped_cell = 0; float dropout_threshold_right = 0,dropout_threshold_up = 0; float** w = (float**)malloc(sizeof(float*)*4); float** u = (float**)malloc(sizeof(float*)*4); float** biases = (float**)malloc(sizeof(float*)*4); i = fread(&residual_flag,sizeof(int),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(&norm_flag,sizeof(int),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(&n_grouped_cell,sizeof(int),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(&size,sizeof(int),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(&layer,sizeof(int),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(&dropout_flag_up,sizeof(int),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(&dropout_flag_right,sizeof(int),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(&window,sizeof(int),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(&dropout_threshold_up,sizeof(float),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(&dropout_threshold_right,sizeof(float),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } for(j = 0; j < 4; j++){ w[j] = (float*)malloc(sizeof(float)*size*size); u[j] = (float*)malloc(sizeof(float)*size*size); biases[j] = (float*)malloc(sizeof(float)*size); i = fread(w[j],sizeof(float)*(size)*(size),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(u[j],sizeof(float)*(size)*(size),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(biases[j],sizeof(float)*(size),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } } bn** bns = NULL; if(norm_flag == GROUP_NORMALIZATION){ bns = (bn**)malloc(sizeof(bn*)*window/n_grouped_cell); for(i = 0; i < window/n_grouped_cell; i++){ bns[i] = load_bn(fr); } } lstm* l = recurrent_lstm(size,dropout_flag_up,dropout_threshold_up,dropout_flag_right,dropout_threshold_right,layer, window, residual_flag,norm_flag,n_grouped_cell); for(i = 0; i < 4; i++){ copy_array(w[i],l->w[i],size*size); copy_array(u[i],l->u[i],size*size); copy_array(biases[i],l->biases[i],size); free(w[i]); free(u[i]); free(biases[i]); } if(norm_flag == GROUP_NORMALIZATION){ for(i = 0; i < window/n_grouped_cell; i++){ free(l->bns[i]); } free(l->bns); l->bns = bns; } free(w); free(u); free(biases); return l; } /* This function loads a lstm layer from a .bin file from fr * * Input: * * @ FILE* fr:= a pointer to a file already opened * * */ lstm* heavy_load_lstm(FILE* fr){ if(fr == NULL) return NULL; int i,j; int size = 0,layer = 0,dropout_flag_up = 0,dropout_flag_right = 0, window = 0, residual_flag = 0, norm_flag = 0, n_grouped_cell = 0; float dropout_threshold_right = 0,dropout_threshold_up = 0; float** w = (float**)malloc(sizeof(float*)*4); float** d1_w = (float**)malloc(sizeof(float*)*4); float** d2_w = (float**)malloc(sizeof(float*)*4); float** d3_w = (float**)malloc(sizeof(float*)*4); float** ex_d_w_diff_grad = (float**)malloc(sizeof(float*)*4); float** u = (float**)malloc(sizeof(float*)*4); float** d1_u = (float**)malloc(sizeof(float*)*4); float** d2_u = (float**)malloc(sizeof(float*)*4); float** d3_u = (float**)malloc(sizeof(float*)*4); float** ex_d_u_diff_grad = (float**)malloc(sizeof(float*)*4); float** biases = (float**)malloc(sizeof(float*)*4); float** d1_biases = (float**)malloc(sizeof(float*)*4); float** d2_biases = (float**)malloc(sizeof(float*)*4); float** d3_biases = (float**)malloc(sizeof(float*)*4); float** ex_d_biases_diff_grad = (float**)malloc(sizeof(float*)*4); i = fread(&residual_flag,sizeof(int),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(&norm_flag,sizeof(int),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(&n_grouped_cell,sizeof(int),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(&size,sizeof(int),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(&layer,sizeof(int),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(&dropout_flag_up,sizeof(int),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(&dropout_flag_right,sizeof(int),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(&window,sizeof(int),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(&dropout_threshold_up,sizeof(float),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(&dropout_threshold_right,sizeof(float),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } for(j = 0; j < 4; j++){ w[j] = (float*)malloc(sizeof(float)*size*size); d1_w[j] = (float*)malloc(sizeof(float)*size*size); d2_w[j] = (float*)malloc(sizeof(float)*size*size); d3_w[j] = (float*)malloc(sizeof(float)*size*size); ex_d_w_diff_grad[j] = (float*)malloc(sizeof(float)*size*size); u[j] = (float*)malloc(sizeof(float)*size*size); d1_u[j] = (float*)malloc(sizeof(float)*size*size); d2_u[j] = (float*)malloc(sizeof(float)*size*size); d3_u[j] = (float*)malloc(sizeof(float)*size*size); ex_d_u_diff_grad[j] = (float*)malloc(sizeof(float)*size*size); biases[j] = (float*)malloc(sizeof(float)*size); d1_biases[j] = (float*)malloc(sizeof(float)*size); d2_biases[j] = (float*)malloc(sizeof(float)*size); d3_biases[j] = (float*)malloc(sizeof(float)*size); ex_d_biases_diff_grad[j] = (float*)malloc(sizeof(float)*size); i = fread(w[j],sizeof(float)*(size)*(size),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(d1_w[j],sizeof(float)*(size)*(size),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(d2_w[j],sizeof(float)*(size)*(size),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(d3_w[j],sizeof(float)*(size)*(size),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(ex_d_w_diff_grad[j],sizeof(float)*(size)*(size),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(u[j],sizeof(float)*(size)*(size),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(d1_u[j],sizeof(float)*(size)*(size),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(d2_u[j],sizeof(float)*(size)*(size),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(d3_u[j],sizeof(float)*(size)*(size),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(ex_d_u_diff_grad[j],sizeof(float)*(size)*(size),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(biases[j],sizeof(float)*(size),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(d1_biases[j],sizeof(float)*(size),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(d2_biases[j],sizeof(float)*(size),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(d3_biases[j],sizeof(float)*(size),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } i = fread(ex_d_biases_diff_grad[j],sizeof(float)*(size),1,fr); if(i != 1){ fprintf(stderr,"Error: an error occurred loading a lstm layer\n"); exit(1); } } bn** bns = NULL; if(norm_flag == GROUP_NORMALIZATION){ bns = (bn**)malloc(sizeof(bn*)*window/n_grouped_cell); for(i = 0; i < window/n_grouped_cell; i++){ bns[i] = heavy_load_bn(fr); } } lstm* l = recurrent_lstm(size,dropout_flag_up,dropout_threshold_up,dropout_flag_right,dropout_threshold_right,layer, window, residual_flag,norm_flag,n_grouped_cell); for(i = 0; i < 4; i++){ copy_array(w[i],l->w[i],size*size); copy_array(d1_w[i],l->d1_w[i],size*size); copy_array(d2_w[i],l->d2_w[i],size*size); copy_array(d3_w[i],l->d3_w[i],size*size); copy_array(ex_d_w_diff_grad[i],l->ex_d_w_diff_grad[i],size*size); copy_array(u[i],l->u[i],size*size); copy_array(d1_u[i],l->d1_u[i],size*size); copy_array(d2_u[i],l->d2_u[i],size*size); copy_array(d3_u[i],l->d3_u[i],size*size); copy_array(ex_d_u_diff_grad[i],l->ex_d_u_diff_grad[i],size*size); copy_array(biases[i],l->biases[i],size); copy_array(d1_biases[i],l->d1_biases[i],size); copy_array(d2_biases[i],l->d2_biases[i],size); copy_array(d3_biases[i],l->d3_biases[i],size); copy_array(ex_d_biases_diff_grad[i],l->ex_d_biases_diff_grad[i],size); free(w[i]); free(d1_w[i]); free(d2_w[i]); free(d3_w[i]); free(ex_d_w_diff_grad[i]); free(u[i]); free(d1_u[i]); free(d2_u[i]); free(d3_u[i]); free(ex_d_u_diff_grad[i]); free(biases[i]); free(d1_biases[i]); free(d2_biases[i]); free(d3_biases[i]); free(ex_d_biases_diff_grad[i]); } if(norm_flag == GROUP_NORMALIZATION){ for(i = 0; i < window/n_grouped_cell; i++){ free(l->bns[i]); } free(l->bns); l->bns = bns; } free(w); free(d1_w); free(d2_w); free(d3_w); free(ex_d_w_diff_grad); free(u); free(d1_u); free(d2_u); free(d3_u); free(ex_d_u_diff_grad); free(biases); free(d1_biases); free(d2_biases); free(d3_biases); free(ex_d_biases_diff_grad); return l; } /* This function returns a lstm* layer that is the same copy of the input l * except for the temporary arrays used during the feed forward and backprop. * You have a lstm* l structure, this function creates an identical structure * with all the arrays used for the feed forward and back propagation * with all the initial states. and the same weights and derivatives in l are copied * into the new structure. d1 and d2 weights are used by nesterov and adam algorithms * * Input: * * @ lstm* l:= the lstm layer that must be copied * * */ lstm* copy_lstm(lstm* l){ if(l == NULL) return NULL; int i; lstm* copy = recurrent_lstm(l->size,l->dropout_flag_up,l->dropout_threshold_up,l->dropout_flag_right,l->dropout_threshold_right,l->layer, l->window,l->residual_flag,l->norm_flag,l->n_grouped_cell); for(i = 0; i < 4; i++){ copy_array(l->w[i],copy->w[i],l->size*l->size); copy_array(l->d_w[i],copy->d_w[i],l->size*l->size); copy_array(l->ex_d_w_diff_grad[i],copy->ex_d_w_diff_grad[i],l->size*l->size); copy_array(l->d1_w[i],copy->d1_w[i],l->size*l->size); copy_array(l->d2_w[i],copy->d2_w[i],l->size*l->size); copy_array(l->d3_w[i],copy->d3_w[i],l->size*l->size); copy_array(l->u[i],copy->u[i],l->size*l->size); copy_array(l->d_u[i],copy->d_u[i],l->size*l->size); copy_array(l->ex_d_u_diff_grad[i],copy->ex_d_u_diff_grad[i],l->size*l->size); copy_array(l->d1_u[i],copy->d1_u[i],l->size*l->size); copy_array(l->d2_u[i],copy->d2_u[i],l->size*l->size); copy_array(l->d3_u[i],copy->d3_u[i],l->size*l->size); copy_array(l->biases[i],copy->biases[i],l->size); copy_array(l->d_biases[i],copy->d_biases[i],l->size); copy_array(l->ex_d_biases_diff_grad[i],copy->ex_d_biases_diff_grad[i],l->size); copy_array(l->d1_biases[i],copy->d1_biases[i],l->size); copy_array(l->d2_biases[i],copy->d2_biases[i],l->size); copy_array(l->d3_biases[i],copy->d3_biases[i],l->size); } if(l->norm_flag == GROUP_NORMALIZATION){ for(i = 0; i < l->window/l->n_grouped_cell; i++){ copy_array(l->bns[i]->gamma,copy->bns[i]->gamma,l->bns[i]->vector_dim); copy_array(l->bns[i]->d_gamma,copy->bns[i]->d_gamma,l->bns[i]->vector_dim); copy_array(l->bns[i]->d1_gamma,copy->bns[i]->d1_gamma,l->bns[i]->vector_dim); copy_array(l->bns[i]->d2_gamma,copy->bns[i]->d2_gamma,l->bns[i]->vector_dim); copy_array(l->bns[i]->d3_gamma,copy->bns[i]->d3_gamma,l->bns[i]->vector_dim); copy_array(l->bns[i]->ex_d_gamma_diff_grad,copy->bns[i]->ex_d_gamma_diff_grad,l->bns[i]->vector_dim); copy_array(l->bns[i]->beta,copy->bns[i]->beta,l->bns[i]->vector_dim); copy_array(l->bns[i]->d_beta,copy->bns[i]->d_beta,l->bns[i]->vector_dim); copy_array(l->bns[i]->d2_beta,copy->bns[i]->d2_beta,l->bns[i]->vector_dim); copy_array(l->bns[i]->d3_beta,copy->bns[i]->d3_beta,l->bns[i]->vector_dim); copy_array(l->bns[i]->ex_d_beta_diff_grad,copy->bns[i]->ex_d_beta_diff_grad,l->bns[i]->vector_dim); } } return copy; } /* This function returns a lstm* layer that is the same copy of the input l * except for the arrays used during the ff and bp * This functions copies the weights and D and D1 and D2 into a another structure * * Input: * * @ lstm* l:= the lstm layer that must be copied * @ lstm* copy:= the lstm layer where l is copied * * */ void paste_lstm(lstm* l,lstm* copy){ if(l == NULL) return; int i; for(i = 0; i < 4; i++){ copy_array(l->w[i],copy->w[i],l->size*l->size); copy_array(l->d_w[i],copy->d_w[i],l->size*l->size); copy_array(l->ex_d_w_diff_grad[i],copy->ex_d_w_diff_grad[i],l->size*l->size); copy_array(l->d1_w[i],copy->d1_w[i],l->size*l->size); copy_array(l->d2_w[i],copy->d2_w[i],l->size*l->size); copy_array(l->d3_w[i],copy->d3_w[i],l->size*l->size); copy_array(l->u[i],copy->u[i],l->size*l->size); copy_array(l->d_u[i],copy->d_u[i],l->size*l->size); copy_array(l->ex_d_u_diff_grad[i],copy->ex_d_u_diff_grad[i],l->size*l->size); copy_array(l->d1_u[i],copy->d1_u[i],l->size*l->size); copy_array(l->d2_u[i],copy->d2_u[i],l->size*l->size); copy_array(l->d3_u[i],copy->d3_u[i],l->size*l->size); copy_array(l->biases[i],copy->biases[i],l->size); copy_array(l->d_biases[i],copy->d_biases[i],l->size); copy_array(l->ex_d_biases_diff_grad[i],copy->ex_d_biases_diff_grad[i],l->size); copy_array(l->d1_biases[i],copy->d1_biases[i],l->size); copy_array(l->d2_biases[i],copy->d2_biases[i],l->size); copy_array(l->d3_biases[i],copy->d3_biases[i],l->size); } if(l->norm_flag == GROUP_NORMALIZATION){ for(i = 0; i < l->window/l->n_grouped_cell; i++){ paste_bn(l->bns[i],copy->bns[i]); } } return; } /* This function returns a lstm* layer that is the same copy of the input l * except for the arrays used during the ff and bp * This functions copies the weights and D and D1 and D2 into a another structure * * Input: * * @ lstm* l:= the lstm layer that must be copied * @ lstm* copy:= the lstm layer where l is copied * * */ void paste_w_lstm(lstm* l,lstm* copy){ if(l == NULL) return; int i; for(i = 0; i < 4; i++){ copy_array(l->w[i],copy->w[i],l->size*l->size); copy_array(l->u[i],copy->u[i],l->size*l->size); copy_array(l->biases[i],copy->biases[i],l->size); } if(l->norm_flag == GROUP_NORMALIZATION){ for(i = 0; i < l->window/l->n_grouped_cell; i++){ paste_w_bn(l->bns[i],copy->bns[i]); } } return; } /* This function returns a lstm* layer that is the same copy for the weights and biases * of the layer l with the rule teta_i = tau*teta_j + (1-tau)*teta_i * * Input: * * @ lstm* l:= the lstm layer that must be copied * @ lstm* copy:= the lstm layer where l is copied * @ float tau:= the tau param * */ void slow_paste_lstm(lstm* l,lstm* copy, float tau){ if(l == NULL) return; int i,j; for(i = 0; i < 4; i++){ for(j = 0; j < l->size*l->size; j++){ copy->w[i][j] = tau*l->w[i][j] + (1-tau)*copy->w[i][j]; copy->d1_w[i][j] = tau*l->d1_w[i][j] + (1-tau)*copy->d1_w[i][j]; copy->d2_w[i][j] = tau*l->d2_w[i][j] + (1-tau)*copy->d2_w[i][j]; copy->d3_w[i][j] = tau*l->d3_w[i][j] + (1-tau)*copy->d3_w[i][j]; copy->ex_d_w_diff_grad[i][j] = tau*l->ex_d_w_diff_grad[i][j] + (1-tau)*copy->ex_d_w_diff_grad[i][j]; copy->u[i][j] = tau*l->u[i][j] + (1-tau)*copy->u[i][j]; copy->d1_u[i][j] = tau*l->d1_u[i][j] + (1-tau)*copy->d1_u[i][j]; copy->d2_u[i][j] = tau*l->d2_u[i][j] + (1-tau)*copy->d2_u[i][j]; copy->d3_u[i][j] = tau*l->d3_u[i][j] + (1-tau)*copy->d3_u[i][j]; copy->ex_d_u_diff_grad[i][j] = tau*l->ex_d_u_diff_grad[i][j] + (1-tau)*copy->ex_d_u_diff_grad[i][j]; if(j < l->size){ copy->biases[i][j] = tau*l->biases[i][j] + (1-tau)*copy->biases[i][j]; copy->d1_biases[i][j] = tau*l->d1_biases[i][j] + (1-tau)*copy->d1_biases[i][j]; copy->d2_biases[i][j] = tau*l->d2_biases[i][j] + (1-tau)*copy->d2_biases[i][j]; copy->d3_biases[i][j] = tau*l->d3_biases[i][j] + (1-tau)*copy->d3_biases[i][j]; copy->ex_d_biases_diff_grad[i][j] = tau*l->ex_d_biases_diff_grad[i][j] + (1-tau)*copy->ex_d_biases_diff_grad[i][j]; } } } if(l->norm_flag == GROUP_NORMALIZATION){ for(i = 0; i < l->window/l->n_grouped_cell; i++){ slow_paste_bn(l->bns[i],copy->bns[i],tau); } } return; } /* this function reset all the arrays of a lstm layer * used during the feed forward and backpropagation * You have a lstm* f structure, this function resets all the arrays used * for the feed forward and back propagation with partial derivatives D inculded * but the weights and D1 and D2 don't change * * * Input: * * @ lstm* f:= a lstm* f layer * * */ lstm* reset_lstm(lstm* f){ if(f == NULL) return NULL; int i,j,k; for(i = 0; i < 4; i++){ for(j = 0; j < f->size*f->size; j++){ f->d_w[i][j] = 0; f->d_u[i][j] = 0; if(j < f->size){ f->d_biases[i][j] = 0; if(!i){ f->dropout_mask_up[j] = 1; f->dropout_mask_right[j] = 1; } } } } for(i = 0; i < f->window; i++){ for(j = 0; j < 4; j++){ for(k = 0; k < f->size; k++){ f->lstm_z[i][j][k] = 0; f->lstm_hidden[i][k] = 0; f->lstm_cell[i][k] = 0; f->out_up[i][k] = 0; } } } if(f->norm_flag == GROUP_NORMALIZATION){ for(i = 0; i < f->window/f->n_grouped_cell; i++){ reset_bn(f->bns[i]); } } return f; } /* this function gives the number of float params for biases and weights in a lstm * * Input: * * * @ lstm* f:= the lstm layer * */ int get_array_size_params_lstm(lstm* f){ int sum = 0; int i; if(f->norm_flag == GROUP_NORMALIZATION){ for(i = 0; i < f->window/f->n_grouped_cell; i++){ sum+=f->bns[i]->vector_dim*2; } } return sum+12*f->size*f->size+6*f->size; } /* this function paste the weights and biases in a single vector * * Inputs: * * * @ lstm* f:= the lstm layer * @ float* vector:= the vector where is copyed everything * */ void memcopy_vector_to_params_lstm(lstm* f, float* vector){ int i; for(i = 0; i < 4; i++){ memcpy(f->w[i],&vector[(i*2)*f->size*f->size],f->size*f->size*sizeof(float)); memcpy(f->u[i],&vector[(i*2+1)*f->size*f->size],f->size*f->size*sizeof(float)); } for(i = 0; i < 4; i++){ memcpy(f->biases[i],&vector[8*f->size*f->size+(i)*f->size],f->size*sizeof(float)); } if(f->norm_flag == GROUP_NORMALIZATION){ for(i = 0; i < f->window/f->n_grouped_cell; i++){ memcpy(f->bns[i]->gamma,&vector[8*f->size*f->size+4*f->size+i*f->bns[i]->vector_dim],f->bns[i]->vector_dim*sizeof(float)); } for(i = 0; i < f->window/f->n_grouped_cell; i++){ memcpy(f->bns[i]->beta,&vector[8*f->size*f->size+4*f->size+(f->window/f->n_grouped_cell+i)*f->bns[i]->vector_dim],f->bns[i]->vector_dim*sizeof(float)); } } } /* this function paste the vector in the weights and biases of the lstm * * Inputs: * * * @ lstm* f:= the lstm layer * @ float* vector:= the vector where is copyed everything * */ void memcopy_params_to_vector_lstm(lstm* f, float* vector){ int i; for(i = 0; i < 4; i++){ memcpy(&vector[(i*2)*f->size*f->size],f->w[i],f->size*f->size*sizeof(float)); memcpy(&vector[(i*2+1)*f->size*f->size],f->u[i],f->size*f->size*sizeof(float)); } for(i = 0; i < 4; i++){ memcpy(&vector[8*f->size*f->size+(i)*f->size],f->biases[i],f->size*sizeof(float)); } if(f->norm_flag == GROUP_NORMALIZATION){ for(i = 0; i < f->window/f->n_grouped_cell; i++){ memcpy(&vector[8*f->size*f->size+4*f->size+i*f->bns[i]->vector_dim],f->bns[i]->gamma,f->bns[i]->vector_dim*sizeof(float)); } for(i = 0; i < f->window/f->n_grouped_cell; i++){ memcpy(&vector[8*f->size*f->size+4*f->size+(f->window/f->n_grouped_cell+i)*f->bns[i]->vector_dim],f->bns[i]->beta,f->bns[i]->vector_dim*sizeof(float)); } } } /* this function paste the dweights and dbiases in a single vector * * Inputs: * * * @ lstm* f:= the lstm layer * @ float* vector:= the vector where is copyed everything * */ void memcopy_vector_to_derivative_params_lstm(lstm* f, float* vector){ int i; for(i = 0; i < 4; i++){ memcpy(f->d_w[i],&vector[(i*2)*f->size*f->size],f->size*f->size*sizeof(float)); memcpy(f->d_u[i],&vector[(i*2+1)*f->size*f->size],f->size*f->size*sizeof(float)); } for(i = 0; i < 4; i++){ memcpy(f->d_biases[i],&vector[8*f->size*f->size+(i)*f->size],f->size*sizeof(float)); } if(f->norm_flag == GROUP_NORMALIZATION){ for(i = 0; i < f->window/f->n_grouped_cell; i++){ memcpy(f->bns[i]->d_gamma,&vector[8*f->size*f->size+4*f->size+i*f->bns[i]->vector_dim],f->bns[i]->vector_dim*sizeof(float)); } for(i = 0; i < f->window/f->n_grouped_cell; i++){ memcpy(f->bns[i]->d_beta,&vector[8*f->size*f->size+4*f->size+(f->window/f->n_grouped_cell+i)*f->bns[i]->vector_dim],f->bns[i]->vector_dim*sizeof(float)); } } } /* this function paste the vector in the dweights and dbiases of the lstm * * Inputs: * * * @ lstm* f:= the lstm layer * @ float* vector:= the vector where is copyed everything * */ void memcopy_derivative_params_to_vector_lstm(lstm* f, float* vector){ int i; for(i = 0; i < 4; i++){ memcpy(&vector[(i*2)*f->size*f->size],f->d_w[i],f->size*f->size*sizeof(float)); memcpy(&vector[(i*2+1)*f->size*f->size],f->d_u[i],f->size*f->size*sizeof(float)); } for(i = 0; i < 4; i++){ memcpy(&vector[8*f->size*f->size+(i)*f->size],f->d_biases[i],f->size*sizeof(float)); } if(f->norm_flag == GROUP_NORMALIZATION){ for(i = 0; i < f->window/f->n_grouped_cell; i++){ memcpy(&vector[8*f->size*f->size+4*f->size+i*f->bns[i]->vector_dim],f->bns[i]->d_gamma,f->bns[i]->vector_dim*sizeof(float)); } for(i = 0; i < f->window/f->n_grouped_cell; i++){ memcpy(&vector[8*f->size*f->size+4*f->size+(f->window/f->n_grouped_cell+i)*f->bns[i]->vector_dim],f->bns[i]->d_beta,f->bns[i]->vector_dim*sizeof(float)); } } }
C
/* for drawing */ /* by shindow(liuyu_200411@sina.com) */ /* 2010.4.1 setup */ #include "type.h" #include "const.h" #include "lib.h" #include "protect.h" #include "global.h" //0H--ɫ,1H--ɫ,2H--ɫ,3H--ɫ,4H--ɫ,5H--,6H--ɫ,7H--ɫ //8H--ɫ(˸),9H--ɫ(˸),AH--ɫ(˸),BH--ɫ(˸),CH--ɫ(˸) //DH--(˸),FH--ɫ(˸) //==========================жϲϷ int IsInPic(int x,int y) { if(x<0||y<0||x>320||y>200) return 0; //Ϸ else return 1; //Ϸ } //==========================һ void Draw_Pixel(int x,int y,int color) { if(!IsInPic(x,y)) return ; // set_pixel(x,200-y,color); //תy set_pixel(x,y,color); } //==========================һֱ void Draw_Line(int startX,int startY,int endX,int endY,int color) { /* int XorY=1,x=startX,y=startY; //XorYĬx,directionĬ if(Absolute(endY-startY)-Absolute(endX-startX)>0){ XorY=0; } if(endX-startX<0){ x=endX; y=endY; } Draw_Pixel(x,y,color); if(XorY){ x++; } else{ } */ //================е㻭㷨 int a,b,x,y,d,d1,d2,y_flag=0,slop_flag=0,tmp;//,бС45,ʼyյy if(startX>endX){ //жʼXǷСյ,ǵĻ tmp=startX; startX=endX; endX=tmp; tmp=startY; startY=endY; endY=tmp; } else if(startX==endX){ //ֱ if(startY<endY) b=startY; else{ b=endY; endY=startY; } for(;b<endY;b++) Draw_Pixel(startX,b,color); return ; } if(Absolute(startX-endX)<Absolute(startY-endY)) slop_flag=1; //бʴ45 if(startY>endY) y_flag=1; //ʼyСյy //===================֮ǰһЩж x=startX; y=startY; Draw_Pixel(x,y,color); if(!slop_flag){ //бС45 if(!y_flag) a=startY-endY; //aһǸ else a=endY-startY; b=endX-startX; d=2*a+b; d1=2*a; d2=2*(a+b); while(x<endX){ if(d<0){ x++; if(!y_flag) y++; else y--; d+=d2; } else{ x++; d+=d1; } Draw_Pixel(x,y,color); } } else{ //бʴ45 a=startX-endX; if(!y_flag) b=endY-startY; //bһ else b=startY-endY; d=2*a+b; d1=2*a; d2=2*(a+b); while(x<endX){ if(d<0){ x++; if(!y_flag) y++; else y--; d+=d2; } else{ if(!y_flag) y++; else y--; d+=d1; } Draw_Pixel(x,y,color); } } /* ===========Bresenham int x,y,dx,dy,i; float k,e; dx=endX-startX; dy=endY-startY; k=dy/dx; e=-0.5; x=startX; y=startY; for(i=0;i<dx;i++){ Draw_Pixel(x,y,color); x=x+1; e=e+k; if(e>=0){ y++; e--; } } */ } //==========================һ void Draw_Rectangle(int startX,int startY,int side1,int side2,int color) { Draw_Line(startX,startY,startX,startY+side2,color); Draw_Line(startX,startY,startX+side1,startY,color); Draw_Line(startX,startY+side2,startX+side1,startY+side2,color); Draw_Line(startX+side1,startY,startX+side1,startY+side2,color); } //==========================һı void Draw_Quads(int P0x,int P0y,int P1x,int P1y,int P2x,int P2y,int P3x,int P3y,int color) { } void Draw_Triangle(int P0x,int P0y,int P1x,int P1y,int P2x,int P2y,int color) { Draw_Line(P0x,P0y,P1x,P1y,color); Draw_Line(P0x,P0y,P2x,P2y,color); Draw_Line(P1x,P1y,P2x,P2y,color); } void Circle_Points(int x,int y,int X0,int Y0,int color) { Draw_Pixel(X0-x,y+Y0,color); Draw_Pixel(x+X0,y+Y0,color); Draw_Pixel(x+X0,Y0-y,color); Draw_Pixel(X0-x,Y0-y,color); Draw_Pixel(y+X0,x+Y0,color); Draw_Pixel(y+X0,Y0-x,color); Draw_Pixel(X0-y,x+Y0,color); Draw_Pixel(X0-y,Y0-x,color); } //=======================һԲ //Ȼ1/8ԲȻݶԳԻʣµ //(x,y,color) (-x,y,color) (x,-y,color) (-x,-y,color) (y,x,color) (-y,x,color) (y,-x,color) (-y,-x,color) void Draw_Circle(int X0,int Y0,int r,int color) { //㷨е㻭Բ int x,y,d; x=0;y=r;d=1-r; while(x<=y){ Circle_Points(x,y,X0,Y0,color); if(d<0){ d+=2*x+3; } else{ d+=2*(x-y)+5; y--; } x++; } }
C
/****************************************************************************** * File Name : packet_search.c * Date First Issued : 06/01/2014 * Board : PC * Description : Search packets *******************************************************************************/ #define _LARGEFILE64_SOURCE #include <sys/types.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include "packet_search.h" #include "packet_print.h" #include "sdlog.h" /****************************************************************************** * int readablock(int fd, struct LOGBLK* pblk); * @brief : Read block * @param : fd = file descriptor for read/write * @param : Pointer to buffer with requested block number set * @return : 1 = msg time < search time; * : 0 = msg time >= search time; * : -1 = Read was not 512 bytes * : -2 = Block was all zeros * : -3 = Extraction error, and not all zeros. ******************************************************************************/ int readablock(int fd, struct LOGBLK* pblk) { int readct; off64_t o_blk; off64_t o_pos; /* Position for reading. */ o_blk = pblk->blk; o_blk = o_blk << 9; // Convert block number to byte offset o_pos = lseek64(fd,o_blk,SEEK_SET); // Byte offset seek if (o_pos < 0) // In case something went awry { // Here, lseek returned an error. printf("seek error: %lld for block: %u, %llu\n",(unsigned long long)o_pos, pblk->blk, (unsigned long long)o_blk/512); return -1; } /* Read the block */ readct = read (fd, (char*)&pblk->data[0], 512); if (readct != 512) { // Here, for some reason we didn't get the length expected from an sd card. printf("Read was not 512 bytes. It was %d, pblk %d\n",readct, pblk->blk); return -1 ; } return 0; // Success } /****************************************************************************** * unsigned long long getaPID(int fd, int blk); * @brief : Read block and extract PID * @param : fd = file descriptor * @param : blk = block number * @return : n = PID + 1 * : 0 = error ******************************************************************************/ unsigned long long getaPID(int fd, int blk) { struct LOGBLK logblk; logblk.blk = blk; int ret = readablock(fd, &logblk); if (ret != 0) return 0; return (logblk.pid + 1); } /****************************************************************************** * int search_zero_end (int fd, int blkmax); * @brief : Find highest non-zero pid block number * @param : fd = file descriptor * @param : blkmax = number of blocks on SD card * @return : n = block number (0 - n) if last non-zero pid block * : 0 = error or no data ******************************************************************************/ int search_zero_end (int fd, int blkmax) { int imax = (blkmax - 1 - SDLOG_EXTRA_BLOCKS); // index of last highest blk written int imin = 0; int imid = 0; int imid_prev = -1; unsigned long long pid = getaPID(fd, 0); // Get PID of the first block if (pid <= 1) return 0; // No data on 1st block, or error pid = getaPID(fd, imax); // Get PID of the last block /* Quick wrap-around check. */ if (pid > 1) return (imax); // Return: Wraparound--Last position has non-zero PID if (pid == 0) return 0; // Return: error getting PID int ct = 0; /* Find block with the last non-zero PID. */ // Note: Here, the highest block has a zero PID. while (imin < imax) // Loop { imid = (imax + imin)/2; if (imid == imid_prev) return imid; imid_prev = imid; pid = getaPID(fd, imid); if (pid == 0) return 0; // Return: error getting PID if (pid == 1) // Was PID zero? (PID is offset by 1) imax = imid; // Yes else imin = imid; // No printf("zero ct: %d imax: %d imin: %d imid: %d pid: %llX \n",++ct,imax,imin,imid, (pid-1)); } return (imid); // Return last non-zero PID } /****************************************************************************** * int search_highest_pid (int fd, int blkmax); * @brief : Find highest pid block number * @param : fd = file descriptor * @param : blkmax = number of blocks on SD card * @return : n = block number (0 - (blkmax - 1 - SDLOG_EXTRA_BLOCKS) of block with highest PID * : 0 = error or some sort of unhappiness ******************************************************************************/ int search_highest_pid (int fd, int blkmax) { /* Setup to find the queue boundary. */ int mid_block; int delta; int low_block = 0; int high_block = blkmax-1-SDLOG_EXTRA_BLOCKS; // index of last highest blk written unsigned long long pid; unsigned long long pidx; unsigned long long id0 = getaPID(fd, low_block); // write.block.str.pid; printf("\npid start: high_block %d id0 %llX\n",low_block,(id0-1)); int ct=0; /* Go converge on the queue boundary. */ while(1==1) { delta = high_block - low_block; if(delta == 1) return (high_block); mid_block = low_block + (delta / 2); pid = getaPID(fd, high_block); //sdcard_read(mid_block, write.block.raw); if (pid == 0) return 0; // Return: error getting PID (PID is offset by 1) if(id0 >= pid) high_block = mid_block; /* Bring down the high end */ else { low_block = mid_block; /* Bring up the low end */ // ##### added code to the the sdlog.c search ######### /* Get next block. If it is higher, then the highest PID is in the half above the current high_block. */ // pidx = getaPID(fd, high_block+1); // if (pidx > pid) // high_block += delta; } pidx = getaPID(fd, mid_block); printf("pid ct: %3d high_block: %8d low_block: %8d imid: %d pid: %llX \n",++ct,high_block,low_block,mid_block, (pidx-1)); } return 0; } /****************************************************************************** * int search_rotate(int blk, int rotate, int blkmax); * @brief : Find highest pid block number * @param : blk = block number to be rotated (0 - n) * @prarm : rotate = number of blks to make highest PID blk the last * @param : blkmax = number of blocks on SD card * @return : rotated block number ******************************************************************************/ static int search_rotate(int blk, int rotate, int blkmax) { int blkr = (blk + (blkmax - rotate + 1)); // Allow for extra blocks in wrap-around if (blkr >= (blkmax - SDLOG_EXTRA_BLOCKS)) blkr -= (blkmax - SDLOG_EXTRA_BLOCKS); return blkr; } /****************************************************************************** * time_t get1stpkttime(int fd, struct LOGBLK* pblk); * @param : fd = file descriptor * @param : pblk = pointer to struct with blk number and time * @return : t = Linux time (secs) for first (going backwards) packet * : 1 = error findng first packet within the block * : 0 = read block error * Given "logical" block number (meaning highest logical block number is always * the block number of (N-1) where N is the number of blocks on the SD card), * find the physical block number. 'rotate' is the difference between the highest * block number with the highest PID, and the end of the SD card. ******************************************************************************/ time_t get1stpkttime(int fd, struct LOGBLK* pblk) { /* Read the block */ int ret = readablock(fd, pblk); if (ret != 0) return 0; /* Find the first packet in the block. */ struct PKTP pktp; ret = packet_extract_first(&pktp, (unsigned char*)pblk); if (ret != 0) return 1; /* Convert packet to CAN struct. */ struct CANRCVTIMBUF can; packet_convert(&can, &pktp); time_t t = can.U.ull >> 6; // Time in whole seconds t += PODTIMEEPOCH; // Adjust for shifted epoch /* Return the linux time (secs). */ return t; } /****************************************************************************** * int get1stpkt(int fd, struct LOGBLK* pblk, struct PKTP* pktp, struct CANRCVTIMBUF* pcan); * @param : fd = file descriptor * @param : pblk = pointer to struct with blk number and time * @param : pktp = pointers and stuff * @param : pcan = results in CAN struct format * @return : 0 = OK * : -1 = error findng first packet within the block * : -2 = read block error * Given "logical" block number (meaning highest logical block number is always * the block number of (N-1) where N is the number of blocks on the SD card), * find the physical block number. 'rotate' is the difference between the highest * block number with the highest PID, and the end of the SD card. ******************************************************************************/ int get1stpkt(int fd, struct LOGBLK* pblk, struct PKTP* pktp, struct CANRCVTIMBUF* pcan) { /* Read the block */ int ret = readablock(fd, pblk); if (ret != 0) return 0; /* Find the first packet in the block. */ ret = packet_extract_first(pktp, (unsigned char*)pblk); if (ret != 0) return 1; /* Convert packet to CAN struct. */ packet_convert(pcan, pktp); return 0; } /****************************************************************************** * struct SEARCHRESULT search_datetime (int fd, time_t datetime, int rotate, int blkmax); * @brief : Find block number for datetime that matches (whole seconds) * @param : fd = file descriptor * @param : datetime = linux time (secs) * @prarm : rotate = number of blks to make highest PID blk the last * @param : blkmax = Number of blocks number on SD card * @return : TWOINTS * : n1 = block number of something * : n2: 1 = exact match * : 0 = OK * : -1 = error getting PID * : -2 = not found ******************************************************************************/ struct SEARCHRESULT search_datetime (int fd, time_t datetime, int rotate, int blkmax) { int imax = (blkmax - 1 - SDLOG_EXTRA_BLOCKS); // Block number index of highest block int imin = 0; int imid = 0; int imid_prev = -1; struct SEARCHRESULT sr = {0,0,0}; /* Rotated blk numbers */ int rmax = search_rotate(imax, rotate, blkmax); struct LOGBLK logblk; logblk.blk = rmax; //logblk.blk = rmax; //printf("rot: imid: %d rotate: %d blkmax: %d logblk.blk: %d\n", imid, rotate, blkmax, logblk.blk); //sr.t = get1stpkttime(fd, &logblk); //printf("%d %s", rmax, ctime(&sr.t) ); //return sr; int ct = 0; while (imin < imax) // Loop { imid = (imax + imin)/2; if (imid == imid_prev) {sr.blk = imid; sr.type = 0; return sr;} imid_prev = imid; logblk.blk = search_rotate(imid, rotate, blkmax); sr.t = get1stpkttime(fd, &logblk); if (sr.t == 0) {sr.blk = -1; sr.type = -1; return sr;} // Error getting PID if (sr.t == datetime) {sr.blk = logblk.blk; sr.type = 1; return sr;} // Exact match if (sr.t > datetime) // Compare (rotated) packet time to requested time imax = imid; // Midpt time is too high else imin = imid; // Midpt time is too low printf("tim ct: %3d rmax: %d imin: %d imid: %d rmid: %9d logblk.blk %9d %s",++ct,search_rotate(imax, rotate, blkmax),imin,imid, search_rotate(imid, rotate, blkmax),logblk.blk,ctime(&sr.t)); } sr.blk = 0; sr.type = -2; return sr; }
C
#ifndef __QXWZ_SOC_H #define __QXWZ_SOC_H #include <stdlib.h> #include <stdint.h> #define QXWZ_SOCKET_DATA_CACHE_LEN 1024//socketݰС typedef int qxwz_ssize_t; typedef int8_t qxwz_soc; typedef struct { char *hostName; short port; }qxwz_soc_address;//ӵַ /** * һTCP(***ʵ***) * @return tcpͨ */ qxwz_soc qxwz_soc_create(void); /** * ӵָķ(***ʵ***) * * @param soc tcpͨ(ɵ÷qxwz_soc_create) * @param address ַ * * @return ״̬(0:ӳɹ,1:addressЧ,2:ʧ) */ int8_t qxwz_soc_connect(qxwz_soc soc,qxwz_soc_address address); /** * (***ʵ***) * * @param soc tcpͨ * @param send_buffer ͵ݻ * @param length ݵij * * @return ʵʷݵij(ʧܷ-1) */ qxwz_ssize_t qxwz_soc_send(qxwz_soc soc,char *send_buffer,size_t length); /** * յݻصյݵʱñ * ĿǰsdkȡķǣÿݰССôֱӶд治һݰˣôݰҲᱻ * @param soc tcpͨ * @param send_buffer ݻ * @param length ݵij * */ void qxwz_on_soc_data_received(qxwz_soc soc, char * buffer, size_t length); /** * رijTCP(***ʵ***) * * @param soc TCPͨ */ void qxwz_soc_close(qxwz_soc soc); /** * socketӷʱ֪ͨSDK * * @param soc TCPͨ */ void qxwz_soc_error(qxwz_soc soc); /** -------------------------------------------- ʹ첽SOCKETʱ -------------------------------------------------*/ /** * ɻص,ʹ첽socketʱʹ * * @param soc tcpͨ(ɵ÷qxwz_soc_create) * @param connect_status Ƿӳɹ(0:ӳɹ,1:addressЧ,2:ʧ) */ void qxwz_soc_connect_complete(qxwz_soc soc,int8_t connect_status); /** * ݷɻص * * @param soc tcpͨ(ɵ÷qxwz_soc_create) * @param sendLength ʵʷݵij(ʧܷ-1) */ void qxwz_soc_send_complete(qxwz_soc soc,qxwz_ssize_t send_length); /** * رijTCPӣص * * @param soc TCPͨ * @param close_status Ƿرճɹ(0:رճɹ,1:addressЧ,2:رʧ) */ void qxwz_soc_close_complete(qxwz_soc soc,int8_t close_status); #endif
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "heap.h" void HeapSort1(int *values, int dimVect) { int i; HeapVector *h = CreazaVector(values, 0, dimVect); for (i = 0; i < dimVect; i++) AdaugaValoareMinHeap(h, values[i]); for (i = 0; i < dimVect; i++) values[i] = ExtrageMinim(h); ElibereazaVector(h); } void HeapSort2(int *values, int dimVect) { int i; HeapVector *h = CreazaVector(values, dimVect, dimVect); ConstruiesteMinHeap(h); for (i = 0; i < dimVect; i++) values[i] = ExtrageMinim(h); ElibereazaVector(h); } void HeapSort3(int *values, int dimVect) { int i; HeapVector *h = CreazaVector(values, dimVect, dimVect); ConstruiesteMaxHeap(h); for (i = h->dimVect - 1; i >= 1; i--) { InterschimbaValori(h, 0, i); h->dimVect--; CoboaraValoareMaxHeap(h, 0); } memcpy(values, h->values, dimVect * sizeof(int)); ElibereazaVector(h); } int main() { int dimVect, i; int *values = NULL; printf("dimVect = "); scanf("%d", &dimVect); values = malloc(dimVect * sizeof(int)); for (i = 0; i < dimVect; i++) { printf("values[%d] = ", i); scanf("%d", &values[i]); } for (i = 0; i < dimVect; i++) printf("%d ", values[i]); printf("\n"); HeapSort3(values, dimVect); for (i = 0; i < dimVect; i++) printf("%d ", values[i]); printf("\n"); free(values); return 0; }
C
#ifndef ARRAY_H #define ARRAY_H struct Array{ unsigned int width; //size in bytes of each elem in array unsigned int nel; //number of elements in array unsigned int capacity; //total number of elements that can be stored in the array void *data; //pointer to the contents of the array }; struct Performance{ unsigned int reads; unsigned int writes; unsigned int mallocs; unsigned int frees; }; struct Performance *newPerformance(); //create new Performance structure struct Array *newArray( struct Performance *performance, unsigned int width, unsigned int capacity ); //create new Array structure, set attributes void readItem( struct Performance *performance, struct Array *array, unsigned int index, void *dest ); //copy array->width bytes from array->data (offset by the index) to *dest memeory address, and update performance void writeItem( struct Performance *performance, struct Array *array, unsigned int index, void *src ); //copy array->width bytes from memory address at src to the memory address array->data offset by index (x array->width), and update performance void contract( struct Performance *performance, struct Array *array ); //decrement array->nel by one void freeArray( struct Performance *performance, struct Array *array ); //free array->data and the structure itself, and update performance ( add one frees ) ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////** DERIVED FUNCTION PROTOTYPES : Implement those below by calling those above **/////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void appendItem( struct Performance *performance, struct Array *array, void *src ); void insertItem( struct Performance *performance, struct Array *array, unsigned int index, void *src ); //use readItem and writeITem calls to move all the elements in the array at index and over by 1, and then write given data (src) at index in the array void prependItem( struct Performance *performance, struct Array *array, void *src ); //use insertItem to insert data at position 0 (opposite of append) void deleteItem( struct Performance *performance, struct Array *array, unsigned int index ); //use readItem and writeItem calls to move all elements in the array at the position given by index+1 and higher back one, and then use contract to remove duplicate last entry //////////////////////////////////////////////////////////The Last 20%//////////////////////////////////////////////////////////////////////////// int findItem( struct Performance *performance, struct Array *array, int (*compar)(const void *, const void *), void *target ); int searchItem( struct Performance *performance, struct Array *array, int (*compar)(const void *, const void *), void *target ); #endif
C
#include "btlin_basic.h" #include <stdio.h> #include <stdlib.h> #include <math.h> #include <ctype.h> // Copy double* btlin_matrix_newcopy(double* a, int m, int n) { double *ret,*p; int i,size; size = m*n; ret = (double*)malloc(sizeof(double)*size); // Alternatives: Copy in chunks (2^n blocks) p = ret; for(i=0; i < size; i++) { (*p) = (*a); p++; a++; } //ret[i] = a[i]; return ret; } // Copy Lower triangle to upper triangle of square matrix void btlin_copylow(double* m, int n) { int i,j; for(i=0; i < n; i++) { for(j=i+1; j < n; j++) { m[j*n+i] = m[i*n+j]; } } } // Print matrix (column major) void btlin_print(double* m, int nr, int nc) { int i,j, index; printf("MATRIX %d x %d\n",nr,nc); for(i=0; i < nr; i++) { index = i; printf("[%d] ",i); for(j=0; j < nc; j++) { printf("%lf ",m[index]); index += nr; } printf("\n"); } } // Print matrix (row major) void btlin_printR(double* m, int nr, int nc) { int i,j, index; printf("MATRIX %d x %d\n",nr,nc); index=0; for(i=0; i < nr; i++) { printf("[%d] ",i); for(j=0; j < nc; j++) { printf("%lf ",m[index]); index++; } printf("\n"); } } void btlin_makeSymmetric(char uplo, double* a, int n) { int i,l,u,col,dim,colxnr; dim = n*n; uplo = tolower(uplo); colxnr = n; if (uplo == 'l') { // copies lower triangular to upper triangulr for (i=1; i < dim; i+=(n+1),colxnr+=n) { for(l=i,u=i+n-1; l < colxnr; l++, u+=n) { a[u]= a[l]; } } } else { // copy upper to lower for (i=1; i < dim; i+=(n+1),colxnr+=n) { for(l=i,u=i+n-1; l < colxnr; l++, u+=n) { a[l]= a[u]; } } } } // r = transpose(s) void btlin_transpose(double* r, double* s, int n) { int i,j; double *pr, *ps, *ps_start, temp; pr = r; ps_start = s; for(i=0; i < n; i++) { ps = ps_start; for(j=0; j < n; j++) { pr = ps; pr++; ps += n; } ps_start++; } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> void reverse (char*, int, int); void reverseStmt (char *str) { int len = strlen(str); int start = -1; int i; reverse(str, 0, len); printf("\nReversed string is %s\n", str); for (i = 0; i < len; i++) { if ( (start != -1) && (str[i] == ' ') ) { printf("i: %d, start: %d\n", i, start); reverse(&str[start], 0, i - start); printf("\n%s \n", str); while (str[i] == ' ') i++; start = i; continue; } if (start == -1 && str[i] != ' ') start = i; } } void reverse (char *str, int index, int len) { if (index == len) return; reverse(str, index + 1, len); if (index < (len/2)) return; char temp; temp = str[index]; str[index] = str[len - index - 1]; str[len - index - 1] = temp; } int main (int argc, char *argv[]) { char str[] = "Amaze"; char sentence[] = "I love programming"; printf("\nString is %s\n", str); printf("Sentence is %s\n", sentence); reverse(str, 0, strlen(str)); reverseStmt(sentence); printf("\nReversed string is %s\n", str); printf("\nReversed sentence is %s\n", sentence); return 0; }
C
#include"prototypes.h" struct node *start=NULL; int data,item,pos; struct node *last=NULL; void singly_linked_list() { system("cls"); system("COLOR F2"); while(1) { system("cls"); gotoxy(35,3); printf("\xDB\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2 SINGLY LINKED LIST MENU \xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xDB\n"); gotoxy(35,5); printf("\xDB\xDB\xDB\xDB\xB2 1. Create List"); gotoxy(35,7); printf("\xDB\xDB\xDB\xDB\xB2 2. Display"); gotoxy(35,9); printf("\xDB\xDB\xDB\xDB\xB2 3. Search"); gotoxy(35,11); printf("\xDB\xDB\xDB\xDB\xB2 4. Add to empty list / Add at beginning"); gotoxy(35,13); printf("\xDB\xDB\xDB\xDB\xB2 5. Add at end"); gotoxy(35,15); printf("\xDB\xDB\xDB\xDB\xB2 6. Add after node"); gotoxy(35,17); printf("\xDB\xDB\xDB\xDB\xB2 7. Add before node"); gotoxy(35,19); printf("\xDB\xDB\xDB\xDB\xB2 8. Delete"); gotoxy(35,21); printf("\xDB\xDB\xDB\xDB\xB2 9. Reverse"); gotoxy(35,23); printf("\xDB\xDB\xDB\xDB\xB2 *. Return to Previous Menu"); gotoxy(35,25); printf("\xDB\xDB\xDB\xDB\xB2 0. Close Application"); gotoxy(35,27); printf("\xDB\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xDB"); gotoxy(35,28); t(); gotoxy(35,29); printf("Enter your choice: "); //scanf("%d",&ch); ch=getche(); switch(ch) { case '1': start=s_create_list(start); break; case '2': s_display(start); break; case '3': printf("\n\t\t\t\t Enter the element to be searched : "); scanf("%d",&data); s_search(start,data); s_display(start); break; case '4': printf("\n\t\t\t\t Enter the element to be inserted : "); scanf("%d",&data); start=s_addatbeg(start,data); s_display(start); break; case '5': printf("\n\t\t\t\t Enter the element to be inserted : "); scanf("%d",&data); start=s_addatend(start,data); s_display(start); break; case '6': printf("\n\t\t\t\t Enter the element to be inserted : "); scanf("%d",&data); printf("\n\t\t\t\t Enter the element after which to insert : "); scanf("%d",&item); start=s_addafter(start,data,item); s_display(start); break; case '7': printf("\n\t\t\t\t Enter the element to be inserted : "); scanf("%d",&data); printf("\n\t\t\t\t Enter the element before which to insert : "); scanf("%d",&item); start=s_addbefore(start,data,item); s_display(start); break; case '8': printf("\n\t\t\t\t Enter the element to be deleted : "); scanf("%d",&data); printf("\t\t\t\t Previous"); s_display(start); start=s_del(start, data); printf("\t\t\t\t Updated"); s_display(start); break; case '9': printf("\t\t\t\t Previous"); s_display(start); start=s_reverse(start); printf("\t\t\t\t Reversed"); s_display(start); break; case '*': linked_list(); break; case '0': exit_application(); default: { system("COLOR FC"); gotoxy(30,31); printf("\aWrong Choice!!Please re-entered correct option\n"); gotoxy(30,32); system("pause"); if(ch) // OR if(ch) int case of integers singly_linked_list(); } }/*End of switch()*/ }/*End of while()*/ }/*End of singly_linked_list()*/ void circular_linked_list( ) { system("cls"); system("COLOR F2"); while(1) { system("cls"); gotoxy(35,3); printf("\xDB\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2 CIRCULAR LINKED LIST MENU \xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xDB\n"); gotoxy(35,5); printf("\xDB\xDB\xDB\xDB\xB2 1. Create List"); gotoxy(35,7); printf("\xDB\xDB\xDB\xDB\xB2 2. Display"); gotoxy(35,9); printf("\xDB\xDB\xDB\xDB\xB2 3. Add to empty list"); gotoxy(35,11); printf("\xDB\xDB\xDB\xDB\xB2 4. Add at beginning"); gotoxy(35,13); printf("\xDB\xDB\xDB\xDB\xB2 5. Add at end"); gotoxy(35,15); printf("\xDB\xDB\xDB\xDB\xB2 6. Add after"); gotoxy(35,17); printf("\xDB\xDB\xDB\xDB\xB2 7. Delete"); gotoxy(35,19); printf("\xDB\xDB\xDB\xDB\xB2 *. Return to Previous Menu"); gotoxy(35,21); printf("\xDB\xDB\xDB\xDB\xB2 0. Close Application"); gotoxy(35,23); printf("\xDB\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xDB"); gotoxy(35,24); t(); gotoxy(35,25); printf("Enter your choice: "); //scanf("%d",&ch); ch=getche(); switch(ch) { case '1': last=c_create_list(last); break; case '2': c_display(last); break; case '3': printf("\n\t\t\t\t Enter the element to be inserted : "); scanf("%d",&data); last=c_addtoempty(last,data); c_display(last); break; case '4': printf("\n\t\t\t\t Enter the element to be inserted : "); scanf("%d",&data); last=c_addatbeg(last,data); c_display(last); break; case '5': printf("\n\t\t\t\t Enter the element to be inserted : "); scanf("%d",&data); last=c_addatend(last,data); c_display(last); break; case '6': printf("\n\t\t\t\t Enter the element to be inserted : "); scanf("%d",&data); printf("\n\t\t\t\t Enter the element after which to insert : "); scanf("%d",&item); last=c_addafter(last,data,item); c_display(last); break; case '7': printf("\n\t\t\t\t Enter the element to be deleted : "); scanf("%d",&data); printf("\t\t\t\t Previous"); c_display(last); last=c_del(last,data); printf("\t\t\t\t Updated"); c_display(last); break; case '*': linked_list(); break; case '0': exit_application(); default: { system("COLOR FC"); gotoxy(30,27); printf("\aWrong Choice!!Please re-entered correct option\n"); gotoxy(30,28); system("pause"); if(ch) // OR if(ch) int case of integers circular_linked_list(); } }/*End of switch()*/ }/*End of while()*/ }/*End of circular_linked_list( )*/ void doubly_linked_list() { system("cls"); system("COLOR F2"); while(1) { system("cls"); gotoxy(35,3); printf("\xDB\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2 DOUBLY LINKED LIST MENU \xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xDB\n"); gotoxy(35,5); printf("\xDB\xDB\xDB\xDB\xB2 1. Create List"); gotoxy(35,7); printf("\xDB\xDB\xDB\xDB\xB2 2. Display"); gotoxy(35,9); printf("\xDB\xDB\xDB\xDB\xB2 3. Add to empty list"); gotoxy(35,11); printf("\xDB\xDB\xDB\xDB\xB2 4. Add at beginning"); gotoxy(35,13); printf("\xDB\xDB\xDB\xDB\xB2 5. Add at end"); gotoxy(35,15); printf("\xDB\xDB\xDB\xDB\xB2 6. Add after"); gotoxy(35,17); printf("\xDB\xDB\xDB\xDB\xB2 7. Add before"); gotoxy(35,19); printf("\xDB\xDB\xDB\xDB\xB2 8. Delete"); gotoxy(35,21); printf("\xDB\xDB\xDB\xDB\xB2 9. Reverse"); gotoxy(35,23); printf("\xDB\xDB\xDB\xDB\xB2 *. Return to Previous Menu"); gotoxy(35,25); printf("\xDB\xDB\xDB\xDB\xB2 0. Close Application"); gotoxy(35,27); printf("\xDB\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xDB"); gotoxy(35,28); t(); gotoxy(35,29); printf("Enter your choice: "); //scanf("%d",&ch); ch=getche(); switch(ch) { case '1': start=d_create_list(start); break; case '2': d_display(start); break; case '3': printf("\n\t\t\t\t Enter the element to be inserted : "); scanf("%d",&data); start=d_addtoempty(start,data); d_display(start); break; case '4': printf("\n\t\t\t\t Enter the element to be inserted : "); scanf("%d",&data); start=d_addatbeg(start,data); d_display(start); break; case '5': printf("\n\t\t\t\t Enter the element to be inserted : "); scanf("%d",&data); start=d_addatend(start,data); d_display(start); break; case '6': printf("\n\t\t\t\t Enter the element to be inserted : "); scanf("%d",&data); printf("\n\t\t\t\t Enter the element after which to insert : "); scanf("%d",&item); start=d_addafter(start,data,item); d_display(start); break; case '7': printf("\n\t\t\t\t Enter the element to be inserted : "); scanf("%d",&data); printf("\n\t\t\t\t Enter the element before which to insert : "); scanf("%d",&item); start=d_addbefore(start,data,item); d_display(start); break; case '8': printf("\n\t\t\t\t Enter the element to be deleted : "); scanf("%d",&data); printf("\t\t\t\t Previously"); d_display(start); start=d_del(start,data); printf("\t\t\t\t Updated"); d_display(start); break; case '9': printf("\t\t\t\t Previously"); d_display(start); start=d_reverse(start); printf("\t\t\t\t Reversed"); d_display(start); break; case '*': linked_list(); break; case '0': exit_application(); default: { system("COLOR FC"); gotoxy(30,31); printf("\aWrong Choice!!Please re-entered correct option\n"); gotoxy(30,32); system("pause"); if(ch) // OR if(ch) int case of integers doubly_linked_list(); } }/*End of switch()*/ }/*End of while()*/ }/*End of doubly_linked_list()*/ void linked_list() { while(1) { system("cls"); system("COLOR F1"); gotoxy(35,3); printf("\xDB\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2 LINKED LIST MENU \xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xDB\n"); gotoxy(35,5); printf("\xDB\xDB\xDB\xDB\xB2 1. Singly Linked List"); gotoxy(35,7); printf("\xDB\xDB\xDB\xDB\xB2 2. Circular Linked List"); gotoxy(35,9); printf("\xDB\xDB\xDB\xDB\xB2 3. Doubly Linked List"); gotoxy(35,11); printf("\xDB\xDB\xDB\xDB\xB2 *. Return to Main Menu"); gotoxy(35,13); printf("\xDB\xDB\xDB\xDB\xB2 0. Close Application"); gotoxy(35,15); printf("\xDB\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xDB"); gotoxy(35,16); t(); gotoxy(35,17); printf("Enter your choice: "); ch=getche(); switch(ch) { case '1': singly_linked_list(); break; case '2': circular_linked_list(); break; case '3': doubly_linked_list(); break; case '*': main_menu(); break; case '0': exit_application(); default: { system("COLOR FC"); gotoxy(30,19); printf("\aWrong Choice!!Please re-entered correct option\n"); gotoxy(30,20); system("pause"); if(ch) // OR if(ch) int case of integers linked_list(); } }/*End of switch()*/ }/*End of while()*/ }/*End of linked_list()*/
C
/* Problem Statement: Write a program to divide two numbers */ //header file for input output functions #include<stdio.h> //macro definitions #define TRUE 1 #define FALSE 0 //creating a typedef typedef int BOOL; //Function definition for dividing two numbers BOOL DivideNumbers(int num1, int num2, float *answer) { if (num2 == 0) { printf("Divide by zero error\n"); return FALSE; } *answer = (float)num1/(float)num2; return TRUE; } //main function definition int main() { //variables to hold two input numbers int no1 = 0, no2 = 0; //variable to hold result of division float ans = 0; //boolean variable to handle division by zero situation BOOL result = FALSE; //Accept first number from user printf("Enter first number: \n"); scanf("%d",&no1); //Accept second number from user printf("Enter second number: \n"); scanf("%d",&no2); //call to function result = DivideNumbers(no1, no2, &ans); //print the result upto 2 decimal places if(result == TRUE) { printf("Result of division: %0.2f\n",ans); } //return from main return 0; }
C
/* Ultrasonic Range Finder */ /* For a HC-SR04 Ultrasonic Sensor */ /* It sends a 10us pulse to start ranging (3.3V tolerant) */ /* Then it receives back a 5V pulse from 150us-38ms */ /* the distance can be calculated based on the width of */ /* the pulse. i.e. time/148 = distance in inches */ /* This program hooks it to an STM32L discovery board */ /* The pulse is sent over PB5 (disabling some segments */ /* on the LCD) using timer TIM2 in PWM one-pulse mode */ /* The length is captured using TIM4 in input capture mode*/ #include <stdint.h> #include "stm32l.h" #include "delay_lib.h" #include "lcd_lib.h" #include "num_to_string.h" static char string[7]; void convert_to_inches(int us) { int inches,feet; int length; char number[7]; inches=us/148; feet=inches/12; inches=inches%12; length=num_to_string(number,feet); if (length==1) { string[0]=' '; string[1]=number[0]; } else { string[0]=number[0]; string[1]=number[1]; } string[2]='\''; length=num_to_string(number,inches); if (length==1) { string[3]=' '; string[4]=number[0]; } else { string[3]=number[0]; string[4]=number[1]; } string[5]='\"'; } static TIM_TypeDef *tim4; static int after=0,before=0,time_interval=0; int main(void) { unsigned int lcd_buffer[16]; GPIO_TypeDef *gpiob=(GPIO_TypeDef *)GPIOB_BASE; RCC_TypeDef *rcc=(RCC_TypeDef *)RCC_BASE; TIM_TypeDef *tim3=(TIM_TypeDef *)TIM3_BASE; tim4=(TIM_TypeDef *)TIM4_BASE; NVIC_ISER_TypeDef *nvic=(NVIC_ISER_TypeDef *)NVIC_ISER_BASE; uint32_t temp; /******************/ /* configure LCD */ /******************/ lcd_clock_init(); lcd_pin_init(); lcd_config(); /*******************/ /* Configure GPIOB */ /*******************/ /* Enable GPIOB */ rcc->AHBENR |= AHBENR_GPIOBEN; /* Enable GPIOB clock */ /* Take over PB5 from LCD */ /* Set TIM4 for pins PB6 and PB7 */ temp=gpiob->MODER; temp&=~0x0000fc00; /* clear values for pin 6 */ temp|= (MODER_ALT<<(6*2)); /* Set output type to ALTERNATE */ temp|= (MODER_ALT<<(7*2)); /* Set output type to ALTERNATE */ temp|= (MODER_ALT<<(5*2)); /* Set output type to ALTERNATE */ gpiob->MODER = temp; /* Set Output mode */ gpiob->AFR[0] &= ~0xfff00000; gpiob->AFR[0] |= AFR_TIM345<<(4*5); gpiob->AFR[0] |= AFR_TIM345<<(4*6); /* Pin B6 = AF2 (TIM4) */ gpiob->AFR[0] |= AFR_TIM345<<(4*7); /* Pin B7 = AF2 (TIM4) */ /* i.e. hook up to TIM4 clock */ /* Clock Speed */ temp=gpiob->OSPEEDR&~0x0000fc00; temp|= 0x0000fc00; /* 40MHz clock speed */ gpiob->OSPEEDR=temp; /* Pull-Up/Pull-Down */ gpiob->PUPDR &=~0x0000fc00; /* No pull-up pull-down */ gpiob->PUPDR |= 1<<(7*2); /* PB7 pull up */ gpiob->PUPDR |= 1<<(5*2); /* PB7 pull up */ /* Set output type */ gpiob->OTYPER &=~0xc8; /* Push-Pull */ /******************/ /* Set up Timer 3 */ /******************/ /* Enable Clock */ rcc->APB1ENR |= RCC_APB1ENR_TIM3EN; /* MSI Clock is 2.097MHz */ /* Want PWM mode */ /* Cycle time set by ARR */ /* Duty cycle in CCR1 */ /* Divide by 2 to get 1.0485MHz */ /* 0.953us */ tim3->PSC = (2)-1; /* Pre-scalar value */ tim3->CCR2 = 11; /* Load 5 into capture/compare 1 */ /* */ tim3->ARR = 20; /* auto-reload register */ /* causes overflow after 11 cycles */ /* 10.5us */ tim3->CR1 |= TIM_CR1_OPM; /* One-pulse mode */ /* Stop after hitting ARR first time */ tim3->CCMR1 = 6<<12; /* Use PWM mode 2 */ /* chan1 low when CNT < CCR1 */ /* chan1 high when CNT > CCR1 */ tim3->CCER = TIM_CCER_CC2E; /* Enable channel 2 output */ tim3->CR1 |= TIM_CR1_CEN; /* Enable timer */ /******************/ /* Set up Timer 4 */ /******************/ /* Enable Clock */ rcc->APB1ENR |= RCC_APB1ENR_TIM4EN; /* MSI Clock is 2.097MHz */ /* Want PWM mode */ /* Cycle time set by ARR */ /* Duty cycle in CCR1 */ /* Divide by 21 to get roughly 100kHz */ /* 10us */ tim4->PSC = (21)-1; /* Pre-scalar value */ tim4->ARR = 0xffff; /* auto-reload register */ /* causes overflow after 11 cycles */ /* 10.5us */ tim4->CCMR1 = 1<<0; /* Chan1 is input, IC1 is on TI1 */ /* CC1P = 0 CC1NP=0 */ /* active rising edge */ tim4->CCMR1 |= 2<<4; /* filter for 4 cycles */ tim4->CCMR1 |=2<<8; /* Chan2 is input IC2 is on TI1 */ tim4->CCER |=1<<5; /* CC2P is 1, trigger on down edge */ tim4->CCER |= TIM_CCER_CC1E|TIM_CCER_CC2E; /* Enable Channel 1 and 2 */ /* Enable interrupts */ tim4->DIER |= TIM_DIER_CC1IE; tim4->DIER |= TIM_DIER_CC2IE; //NVIC->IP[TIM4_IRQn] = tmppriority; /* Enable TIM4 interrupt in NVIC */ nvic->ISER[TIM4_IRQn >> 0x05] = (uint32_t)0x01 << (TIM4_IRQn & (uint8_t)0x1F); /* Loop forever */ tim4->CR1 |= TIM_CR1_CEN; /* Enable timer */ for(;;) { tim3->CR1 |= TIM_CR1_CEN; /* Enable trigger */ {int i; for(i=0;i<7;i++) string[i]=' ';} // num_to_string(string,after); convert_to_inches( (time_interval)*10 ); lcd_convert(string,lcd_buffer); lcd_display(lcd_buffer); busy_delay(250000); } } static void tim4_irq_handler(void) { if (tim4->SR & TIM_SR_CC1F ) { // if update flag is set before=tim4->CCR1; } if (tim4->SR & TIM_SR_CC2F ) { // if update flag is set after = tim4->CCR2; if (before>after) { time_interval=(65536-before)+after; } else { time_interval = after - before; } } tim4->SR &= ~TIM_SR_UIF; } static void nmi_handler(void) { for(;;); } static void hardfault_handler(void) { for(;;); } static void do_nothing(void) { for(;;); } /* Vector Table */ #define STACK_TOP 0x20000800 /* CD00240193.pdf p 190 */ unsigned int *myvectors[] __attribute__ ((section("vectors"))) = { (uint32_t *) STACK_TOP, /* 0x00 stack pointer */ (uint32_t *) main, /* 0x04 code entry point */ (uint32_t *) nmi_handler, /* 0x08 NMI handler */ (uint32_t *) hardfault_handler, /* 0x0c hard fault handler */ (uint32_t *) do_nothing, /* 0x10 mem_manage */ (uint32_t *) do_nothing, /* 0x14 bus_fault */ (uint32_t *) do_nothing, /* 0x18 usage_fault */ (uint32_t *) 0, /* 0x1c reserved */ (uint32_t *) 0, /* 0x20 reserved */ (uint32_t *) 0, /* 0x24 reserved */ (uint32_t *) 0, /* 0x28 reserved */ (uint32_t *) do_nothing, /* 0x2c SVC */ (uint32_t *) do_nothing, /* 0x30 debug */ (uint32_t *) 0, /* 0x34 reserved */ (uint32_t *) do_nothing, /* 0x38 pend */ (uint32_t *) do_nothing, /* 0x3c timer tick */ /* External Interrupts */ (uint32_t *) 0, /* 0x40 Window Watchdog */ (uint32_t *) 0, /* 0x44 PVD through EXTI Line detect */ (uint32_t *) 0, /* 0x48 Tamper and Time Stamp */ (uint32_t *) 0, /* 0x4c RTC Wakeup */ (uint32_t *) 0, /* 0x50 FLASH */ (uint32_t *) 0, /* 0x54 RCC */ (uint32_t *) 0, /* 0x58 EXTI Line 0 */ (uint32_t *) 0, /* 0x5c EXTI Line 1 */ (uint32_t *) 0, /* 0x60 EXTI Line 2 */ (uint32_t *) 0, /* 0x64 EXTI Line 3 */ (uint32_t *) 0, /* 0x68 EXTI Line 4 */ (uint32_t *) 0, /* 0x6c DMA1 Channel */ (uint32_t *) 0, /* 0x70 DMA1 Channel 2 */ (uint32_t *) 0, /* 0x74 DMA1 Channel 3 */ (uint32_t *) 0, /* 0x78 DMA1 Channel 4 */ (uint32_t *) 0, /* 0x7c DMA1 Channel 5 */ (uint32_t *) 0, /* 0x80 DMA1 Channel 6 */ (uint32_t *) 0, /* 0x84 DMA1 Channel 7 */ (uint32_t *) 0, /* 0x88 ADC1 */ (uint32_t *) 0, /* 0x8c USB High Priority */ (uint32_t *) 0, /* 0x90 USB Low Priority */ (uint32_t *) 0, /* 0x94 DAC */ (uint32_t *) 0, /* 0x98 COMP through EXTI Line */ (uint32_t *) 0, /* 0x9c EXTI Line 9..5 */ (uint32_t *) 0, /* 0xa0 LCD */ (uint32_t *) 0, /* 0xa4 TIM9 */ (uint32_t *) 0, /* 0xa8 TIM10 */ (uint32_t *) 0, /* 0xac TIM11 */ (uint32_t *) 0, /* 0xb0 TIM2 */ (uint32_t *) 0, /* 0xb4 TIM3 */ (uint32_t *) tim4_irq_handler, /* 0xb8 TIM4 */ };
C
#include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include "tmm_check.h" /* This is the prototype for the function you have to pass to be called. * * Two options are available to you: * * 1) Using 2D matrices * * A, B and C are created as double-dimension arrays (float**) * where: * - A[i] is a pointer to a float* array (line i of matrix A) * - A[i][j] is the value of A(i,j) * - i = 0 to N-1, j = 0 to N-1 * - A and B are UPPER triangular (you SHOULD write down what it means * in terms of domains : which (i,j)s are valid ?) * * If you're using GPU, you should consider using linear disposition. * * 2) Using flattened matrices (linear disposition) * * A, B and C are created as single-dimension arrays (float*) * where: * - A[i] is A(0,0) * - The value of A(i,j) is accessed through A[i * N + j] * - i = 0 to N-1, j = 0 to N-1 * - A and B are UPPER triangular (you SHOULD write down what it means * in terms of domains : which (i,j)s are valid ?) * * The following TMM functions have the prototypes called by the checker. * Do NOT change them. Call your own TMM function from there. * * Remember to set in main(): * c.disposition = DISPOSITION_LINEAR or DISPOSITION_2D depending on your * implementation. * * In order to run the program, you have to run: * * LD_LIBRARY_PATH=. ./test_tmm * * A convenience command is provided for you: you can run "make run" as well. * * */ void TMM2D(long N, float** A, float** B, float** C) { struct timeval time; double elapsed_time; gettimeofday(&time, NULL); elapsed_time = (((double) time.tv_sec) + ((double) time.tv_usec)/1000000); // Call your own TMM here // gettimeofday(&time, NULL); elapsed_time = (((double) time.tv_sec) + ((double) time.tv_usec)/1000000) - elapsed_time; // timing information printf("Execution time : %lf sec.\n", elapsed_time); } void TMMlin(long N, float* A, float* B, float* C) { struct timeval time; double elapsed_time; gettimeofday(&time, NULL); elapsed_time = (((double) time.tv_sec) + ((double) time.tv_usec)/1000000); // Call your own TMM here // gettimeofday(&time, NULL); elapsed_time = (((double) time.tv_sec) + ((double) time.tv_usec)/1000000) - elapsed_time; // timing information printf("Execution time : %lf sec.\n", elapsed_time); } int main(void) { tmm_check c; c.N = 100; // Set the size you want to test against here // set according to your disposition // c.disposition = DISPOSITION_LINEAR; // c.disposition = DISPOSITION_2D; c.TMM2D = &TMM2D; c.TMMlin = &TMMlin; int ret = check_TMM(c); if(ret) printf("Check TMM FAILED!\n"); else printf("Check TMM SUCCEEDED!\n"); return ret; }
C
#include<stdio.h> int main() { int money,num=0,a=0,m; printf("请输入要买的钱数:"); scanf("%d",&money); //printf("\n请输入个m空瓶可兑换一个瓶子:"); //scanf("%d",&m); //num = money; while(money>=1) { a = money%2; //money = money/2; num += money+a; money = money/2; } printf("最多可喝到%d瓶汽水\n",num); return 0; }
C
/* Blinky with a button. An LED is attached to Pin 25 and a button is attached to Pin 1 When the button is pressed, the LED should blink */ #include "lpc111x.h" void delay(unsigned len) { while(len--); } void ConfigPins() { SYSAHBCLKCTRL |= BIT6 + BIT16; // Turn on clock for GPIO and IOCON IOCON_PIO0_2 &= ~(BIT1+BIT0); // ensure Pin 25 behaves as GPIO GPIO0DIR |= BIT2; // Make Pin 25 an output GPIO0DIR &= ~BIT8; // Make Pin 0 an input GPIO0DATA = 0; // 0 output initially } int main() { ConfigPins(); while(1) { if (GPIO0DATA & BIT8) { GPIO0DATA ^= BIT2; delay(1000000); } } }
C
#include "usart.h" void USART_Configuration(void) { USART_InitTypeDef USART_InitStructure; USART_InitStructure.USART_BaudRate = 115200; //??USART?????? USART_InitStructure.USART_WordLength = USART_WordLength_8b; //8???? USART_InitStructure.USART_StopBits = USART_StopBits_1; //??????????????? USART_InitStructure.USART_Parity = USART_Parity_No; //????? USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;//?????? USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; //???????(??????) USART_Init(USART2,&USART_InitStructure); //???USART3???? //USART_ITConfig(USART3,USART_IT_RXNE,ENABLE); //USART_ITConfig(USART2,USART_IT_TXE,ENABLE); USART_ITConfig(USART2,USART_IT_RXNE,ENABLE); USART_Cmd(USART2,ENABLE); //??USART3??; } int fputc(int ch,FILE *f) { USART_SendData(USART2,(u8)ch); while(USART_GetFlagStatus(USART1,USART_FLAG_TXE)==RESET); return ch; } void USART_Putc(char c) { USART_SendData(USART2,c); while(USART_GetFlagStatus(USART2,USART_FLAG_TXE)==RESET); } void USART_putString(char *date) { while(*date!='\0'){ //date++; USART_SendData(USART2,*date++); while(USART_GetFlagStatus(USART2,USART_FLAG_TXE)==RESET); } }
C
/** * @file: k_msg.c * @brief: kernel message passing routines * @author: Yiqing Huang * @date: 2020/10/09 */ #include "k_msg.h" #ifdef DEBUG_0 #include "printf.h" #endif /* ! DEBUG_0 */ int k_mbx_create(size_t size) { #ifdef DEBUG_0 printf("k_mbx_create: size = %d\r\n", size); #endif /* DEBUG_0 */ return 0; } int k_send_msg(task_t receiver_tid, const void *buf) { #ifdef DEBUG_0 printf("k_send_msg: receiver_tid = %d, buf=0x%x\r\n", receiver_tid, buf); #endif /* DEBUG_0 */ return 0; } int k_recv_msg(task_t *sender_tid, void *buf, size_t len) { #ifdef DEBUG_0 printf("k_recv_msg: sender_tid = 0x%x, buf=0x%x, len=%d\r\n", sender_tid, buf, len); #endif /* DEBUG_0 */ return 0; } int k_recv_msg_nb(task_t *sender_tid, void *buf, size_t len) { #ifdef DEBUG_0 printf("k_recv_msg_nb: sender_tid = 0x%x, buf=0x%x, len=%d\r\n", sender_tid, buf, len); #endif /* DEBUG_0 */ return 0; } int k_mbx_ls(task_t *buf, int count) { #ifdef DEBUG_0 printf("k_mbx_ls: buf=0x%x, count=%d\r\n", buf, count); #endif /* DEBUG_0 */ return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include <sys/time.h> #include <time.h> #define SHORT 0; #define LONG 1; #define STANDARD 2; void sampleLoadAvg(char lineBuf[256], int LB_SIZE, int iteration, int interval); //Sample the load avg int main(int argc, char* argv[]) { char repTypeName[30]; //Whether standard, long or short char lineBuf[256]; //What file is going to be inputting into struct timeval now; //to find time char c1, c2; //if there are more args than 1 int interval, duration; //duration and interval for Part D int iteration = 0; //For part D int LB_SIZE = 255; FILE* thisProcFile; //File to be opened //Determine report type int reportType = STANDARD; duration = -1; //set to -1 if part b or c interval = -1; //set to -1 if part b or c strcpy(repTypeName, "Standard"); if(argc > 1) { //if there are more than 1 arguments sscanf(argv[1], "%c%c", &c1, &c2); if(c1 != '-') { //if it's just a -, then quit and print error fprintf(stderr, "usage: observer [-s][-l int dur]\n"); exit(1); } if(c2 == 's') { //if part C reportType = SHORT; strcpy(repTypeName, "Short"); } if(c2 == 'l') { //for part D reportType = LONG; strcpy(repTypeName, "Long"); interval = atoi(argv[2]); duration = atoi(argv[3]); } } //CPU INFO char* fileName = "/proc/cpuinfo"; if((thisProcFile = fopen(fileName, "r")) == NULL) { //make sure file exists perror("fopen()\n"); return EXIT_FAILURE; } int n; n = 0; char *temp = NULL; //iterate through the file and find model name while(getline(&temp, &n, thisProcFile) > 0) { if(strstr(temp, "model name")) { printf("\nCPU Model: %s\n", temp); break; } } fclose(thisProcFile); //close file //KERNEL VERSION fileName = "/proc/version"; if((thisProcFile = fopen(fileName, "r")) == NULL) { //make sure file exists perror("fopen()\n"); return EXIT_FAILURE; } fgets(lineBuf, LB_SIZE+1, thisProcFile); //write the files of size lb_size+1 into linebuf printf("Kernel Version: %s\n", lineBuf); fclose(thisProcFile); //SYSTEM UPTIME fileName = "/proc/uptime"; if((thisProcFile = fopen(fileName, "r")) == NULL) { //make sure file exists perror("fopen()\n"); return EXIT_FAILURE; } fgets(lineBuf, LB_SIZE+1, thisProcFile); //write the files of size lb_size+1 into linebuf printf("System Uptime: %s (the first number)\n\n", lineBuf); fclose(thisProcFile); gettimeofday(&now, NULL); //get the time of day printf("Status report type %s at %s \n", repTypeName, ctime(&(now.tv_sec))); //Get the host filename and print fileName = "/proc/sys/kernel/hostname"; if((thisProcFile = fopen(fileName, "r")) == NULL) { //make sure file exists perror("fopen()\n"); return EXIT_FAILURE; } fgets(lineBuf, LB_SIZE+1, thisProcFile); //write the files of size lb_size+1 into linebuf printf("Machine hostname: %s \n", lineBuf); fclose(thisProcFile); //close the file //PART C------------------------------------------------- if(reportType == 0) { //CPU time spent in user, system, idle fileName = "/proc/stat"; if((thisProcFile = fopen(fileName, "r")) == NULL) { //make sure file exists perror("fopen()\n"); return EXIT_FAILURE; } n = 0; temp = NULL; //iterate through the file and find time while(getline(&temp, &n, thisProcFile) > 0) { if(strstr(temp, "cpu")) { printf("\nCPU times: %s", temp); printf("(1st number is user time, third is System mode, and fourth is idle.)\n"); break; } } fclose(thisProcFile); //close file //Number of read/writes fileName = "/proc/diskstats"; if((thisProcFile = fopen(fileName, "r")) == NULL) { //make sure file exists perror("fopen()\n"); return EXIT_FAILURE; } n = 0; temp = NULL; //iterate through the file and find SDA while(getline(&temp, &n, thisProcFile) > 0) { if(strstr(temp, "sda")) { printf("\nDisk Read/Writes: %s", temp); printf("(1st number AFTER sda is number total reads, fifth is # of writes.)\n"); break; } } fclose(thisProcFile); //close file //Number of Context switches fileName = "/proc/stat"; if((thisProcFile = fopen(fileName, "r")) == NULL) { //make sure file exists perror("fopen()\n"); return EXIT_FAILURE; } n = 0; temp = NULL; //iterate through the file and find SDA while(getline(&temp, &n, thisProcFile) > 0) { if(strstr(temp, "ctxt")) { printf("\nNumber of Context Switches: %s", temp); break; } } fclose(thisProcFile); //close file //Number of Processes fileName = "/proc/stat"; if((thisProcFile = fopen(fileName, "r")) == NULL) { //make sure file exists perror("fopen()\n"); return EXIT_FAILURE; } n = 0; temp = NULL; //iterate through the file and find SDA while(getline(&temp, &n, thisProcFile) > 0) { if(strstr(temp, "processes")) { printf("\nNumber of %s", temp); break; } } fclose(thisProcFile); //close file } //PART D ------------------------------------------ if(reportType = 1) { //Total number of memory fileName = "/proc/meminfo"; if((thisProcFile = fopen(fileName, "r")) == NULL) { //make sure file exists perror("fopen()\n"); return EXIT_FAILURE; } n = 0; temp = NULL; //iterate through the file and find SDA while(getline(&temp, &n, thisProcFile) > 0) { if(strstr(temp, "MemTotal")) { printf("\nNumber of %s\n", temp); break; } } fclose(thisProcFile); //close file //MEMORY availible fileName = "/proc/meminfo"; if((thisProcFile = fopen(fileName, "r")) == NULL) { //make sure file exists perror("fopen()\n"); return EXIT_FAILURE; } n = 0; temp = NULL; //iterate through the file and find SDA while(getline(&temp, &n, thisProcFile) > 0) { if(strstr(temp, "MemFree")) { printf("\nNumber of %s\n", temp); break; } } fclose(thisProcFile); //close file //Reading relevant /proc files if(interval != -1 && duration != -1) { //if not Part D just skip this while(iteration < duration) { sleep(interval); //sleep sampleLoadAvg(lineBuf, LB_SIZE, iteration, interval); //get avg and print iteration += interval; } } } exit(0); } void sampleLoadAvg(char lineBuf[256], int LB_SIZE, int iteration, int interval) { //Sample the load avg FILE* thisProcFile1 = fopen("/proc/loadavg", "r"); //open file fgets(lineBuf, LB_SIZE+1, thisProcFile1); //get the avg printf("Iteration #%d (time%d): %s", iteration, iteration * interval, lineBuf); //print it }
C
#include "imu.h" /** * @brief * * @param x * @param y * @param z * @param samples */ void avg_mag(float *x, float *y, float *z, char samples) { float tx,ty,tz; *x =0; *y=0; *z=0; float fsamp = (float)samples; for (char i = 0; i < samples; i++) { read_mag(&tx,&ty,&tz); *x = *x + (tx/fsamp); *y = *y + (ty/fsamp); *z = *z + (tz/fsamp); } }
C
/* Write a program which accept one number from user and check whether 9th or 12th bit is on or off. Input : 257 Output : TRUE iMask1: 0000 0000 0000 0000 0000 0001 0000 0000 0X00000100 iMask2: 0000 0000 0000 0000 0000 1000 0000 0000 0X00000800 */ #include<stdio.h> typedef int BOOL; #define TRUE 1 #define FALSE 0 BOOL CheckBit(int iNo) { int iMask1 = 0X00000100; int iMask2 = 0X00000800; if((iNo&iMask1==iMask1) || (iNo&iMask2==iMask2)) { return TRUE; } else { return FALSE; } } int main() { int iNum = 0; BOOL bRet = FALSE; printf("Enter a number: \n"); scanf("%d",&iNum); bRet = CheckBit(iNum); if(bRet==TRUE) { printf("TRUE"); } else { printf("FALSE"); } return 0; }