language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* Parking charges for four wheeler is 30 rupees for first three hours and after every hour it is 5 rupees. Accept number of hours and calculate total amount. Input : 2 Output : 30 Input : 7 Output : 50 */ #include"stdio.h" #define FIRST3 30 #define AFTER3 5 void totalRent(int); void totalRent(int hrs){ int icost = 0,tcost = 0; if(hrs < 4){ tcost =FIRST3; } else { icost =((hrs - 3) *AFTER3); tcost = icost + FIRST3; } printf("Output: %d",tcost); } void main(){ int hrs; printf("Input:"); scanf("%d",&hrs); totalRent(hrs); }
C
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <string.h> #include <unistd.h> #include "fighters-map.h" /*************************************************** * function name: create_table * * function parameters: int size * * function description: create table for map * ****************************************************/ struct table *create_table(int size) { struct table *t = (struct table*)malloc(sizeof(struct table)); t->size = size; t->list = (struct node**)malloc(sizeof(struct node*)*size); int i; for(i=0;i<size;i++) t->list[i] = NULL; return t; } /*************************************************** * function name: hash_code * * function parameters: struct table *t,int key * * function description: generate hash code * ****************************************************/ int hash_code(struct table *t,int key) { if(key < 0) return -(key%t->size); return key%t->size; } /*************************************************** * function name: insert * * function parameters: struct table *t,int key, * * char *name, char health * * function description: insert node to map * ****************************************************/ void insert(struct table *t,int key,char *name, char health) { int pos = hash_code(t,key); struct node *list = t->list[pos]; struct node *newNode = (struct node*)malloc(sizeof(struct node)); struct node *temp = list; while(temp) { if(temp->key == key) { temp->name = name; temp->health = health; return; } temp = temp->next; } newNode->key = key; newNode->name = name; newNode->health = health; newNode->next = list; t->list[pos] = newNode; } /*************************************************** * function name: lookup * * function parameters: struct table *t,int key * * function description: find node into map * ****************************************************/ struct node *lookup(struct table *t,int key) { int pos = hash_code(t,key); struct node *list = t->list[pos]; struct node *temp = list; while(temp) { if(temp->key==key) { return temp; } temp = temp->next; } return NULL; } /*************************************************** * function name: delete * * function parameters: struct table *t,int key * * function description: find and delete node * ****************************************************/ int delete(struct table *t,int key) { int pos = hash_code(t,key); struct node *list = t->list[pos]; struct node **temp = &list; struct node *to_free; while(*temp) { to_free = *temp; if(to_free->key==key) { *temp = to_free->next; free(to_free); return 1; } temp = &((*temp)->next); } return 0; } /*************************************************** * function name: read_fighters_from_file * * function parameters: char *file_name * * function description: read nodes from file * ****************************************************/ int read_fighters_from_file(char *file_name) { printf("in readFightersFromFile1\n"); int key = 0; char *name = NULL; char health = 0; int fd = open(file_name, O_RDONLY); printf("in readFightersFromFile\n"); if(fd < 0) return -1; while(read(fd, &key, sizeof(int)) > 0) { if(!(read(fd, name, sizeof(char) * 50) > 0)) return -1; if(!(read(fd, &health, sizeof(char)) > 0)) return -1; key=0; memset(name, ' ', sizeof(char) * 50); health=0; } }
C
#include "monty.h" /** * rotl - rotates to the left * @stack: monty stack * @line_number: line number */ void rotl(stack_t **stack, unsigned int line_number) { stack_t *tmp; int firstVal; UNUSED(line_number); tmp = *stack; if (tmp) firstVal = tmp->n; while (tmp != NULL) { if (tmp->next) tmp->n = tmp->next->n; else tmp->n = firstVal; tmp = tmp->next; } }
C
/* ** free_child.c for free_child in /home/ozouf_h//42sh/src/parsing ** ** Made by harold ozouf ** Login <ozouf_h@epitech.net> ** ** Started on Sat May 12 14:52:06 2012 harold ozouf ** Last update Wed May 16 17:52:12 2012 harold ozouf */ #include <stdlib.h> #include "tree.h" void free_node(t_node *nd) { t_child *tmp; if (nd) { if (nd->content) free(nd->content); while (nd->child) { tmp = nd->child; if (tmp->nd) free_node(tmp->nd); nd->child = nd->child->next; if (tmp) free(tmp); } free(nd); nd = NULL; } } void free_token(t_token *t) { t_token *tmp; while (t) { tmp = t; if (t->content) free(t->content); t = t->next; free(tmp); } }
C
// Representation of graph in Adjacency List #include <stdio.h> #include <stdlib.h> struct AdjListNode { int dest; struct AdjListNode* next; }; struct AdjList { struct AdjListNode *head; }; struct Graph { int V; struct AdjList* array; }; struct AdjListNode* newAdjListNode(int dest) { struct AdjListNode* newNode = (struct AdjListNode*) malloc(sizeof(struct AdjListNode)); newNode->dest = dest; newNode->next = NULL; return newNode; } struct Graph* createGraph(int V) { struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph)); graph->V = V; graph->array = (struct AdjList*) malloc(V * sizeof(struct AdjList)); int i; for (i = 0; i < V; ++i) graph->array[i].head = NULL; return graph; } void addEdge(struct Graph* graph, int src, int dest) { src -= 1, dest -= 1; struct AdjListNode* newNode = newAdjListNode(dest); newNode->next = graph->array[src].head; graph->array[src].head = newNode; newNode = newAdjListNode(src); newNode->next = graph->array[dest].head; graph->array[dest].head = newNode; } void main(){ struct Graph *adjGraph = createGraph(6); addEdge(adjGraph, 1, 2); addEdge(adjGraph, 1, 3); addEdge(adjGraph, 2, 4); addEdge(adjGraph, 2, 5); addEdge(adjGraph, 3, 4); addEdge(adjGraph, 3, 5); addEdge(adjGraph, 4, 6); addEdge(adjGraph, 4, 5); addEdge(adjGraph, 5, 6); for (int i = 0; i < adjGraph->V; ++i) { struct AdjListNode* curr = adjGraph->array[i].head; printf("Vertex %d ", i+1); while (curr) { printf("-> %d ", curr->dest + 1); curr = curr->next; } printf("\n"); } }
C
#include <avr/io.h> #include <avr/interrupt.h> #include <util/delay.h> unsigned char ADC_Conversion(unsigned char); unsigned char ADC_Value1; unsigned char ADC_Value2; unsigned int str[12]; unsigned int k1,k2,k; void config() { cli(); //ADC pin configuration DDRA = 0x00; //set PORTA direction as input PORTA = 0x00; //set PORTA pins floating DDRC=0x0F; DDRB=0X0F; TCCR1A=0xA1; TCCR1B=0x05; OCR1A=180; //Left Motor PWM OCR1B=180; //Right Motor PWM DDRD=0x30; //Declaring PD4,PD5 as output //Function to Initialize ADC ADCSRA = 0x00; ADMUX = 0x20; //Vref=5V external --- ADLAR=1 --- MUX4:0 = 0000 ACSR = 0x80; ADCSRA = 0x86; //ADEN=1 --- ADIE=1 --- ADPS2:0 = 1 1 0 sei(); } //This Function accepts the Channel Number and returns the corresponding Analog Value unsigned char ADC_Conversion(unsigned char Ch) { unsigned char a; Ch = Ch & 0x07; ADMUX= 0x20| Ch; ADCSRA = ADCSRA | 0x40; //Set start conversion bit while((ADCSRA&0x10)==0); //Wait for ADC conversion to complete a=ADCH; ADCSRA = ADCSRA|0x10; //clear ADIF (ADC Interrupt Flag) by writing 1 to it return a; } int main(void) { config(); unsigned int a,ma,mb,m1,m2,m3,m4,x,y; PORTC=0x0F; _delay_ms(5000); PORTC=0x00; _delay_ms(1000); // For white line readings str[0]= ADC_Conversion(0); str[1]= ADC_Conversion(1); str[2]= ADC_Conversion(2); str[3]= ADC_Conversion(3); str[4]= ADC_Conversion(4); str[5]= ADC_Conversion(5); PORTC=0x0F; _delay_ms(5000); PORTC=0x00; // For Black line readings str[6]= ADC_Conversion(0); str[7]= ADC_Conversion(1); str[8]= ADC_Conversion(2); str[9]= ADC_Conversion(3); str[10]= ADC_Conversion(4); str[11]= ADC_Conversion(5); k1=((str[0]+str[1]+str[2]+str[3]+str[4]+str[5])/6); // Taking average for white line k2=((str[6]+str[7]+str[8]+str[9]+str[10]+str[11])/6); // Taking average for black line k=((k1+k2)/2); // taking average of both _delay_ms(1000); for(a=0;a<=20;a++) { PORTC=0x01; _delay_ms(k); PORTC=0x00; _delay_ms(k); } while(1) { if(ADC_Conversion(1) > k) { m1=1; } else if(ADC_Conversion(1) < k) { m1=0; } if(ADC_Conversion(2) > k) { m2=10; } else if(ADC_Conversion(2) < k) { m2=0; } if(ADC_Conversion(3) > k) { m3=100; } else if(ADC_Conversion(3) < k) { m3=0; } if(ADC_Conversion(4) > k) { m4=1000; } else if(ADC_Conversion(4) < k) { m4=0; } if(ADC_Conversion(0) > k) { ma=1; } else if(ADC_Conversion(0) < k) { ma=0; } if(ADC_Conversion(5) > k) { mb=10; } else if(ADC_Conversion(5) < k) { mb=0; } x=(m1+m2+m3+m4); if((ADC_Conversion(0) > k) & (ADC_Conversion(5) > k)) { PORTC=0x00; switch(x) { case 1110: //right case 1100: PORTB=0x08; break; case 1000: //cright case 0101: case 0100: case 1101: PORTB=0x08; break; //left case 110: case 1: case 0: case 1011: case 1010: PORTB=0x02; break; case 10: //cleft case 11: case 111: PORTB=0x02; break; //straight case 1001: case 1111: PORTB=0x0A; break; } } else if((ADC_Conversion(0) < k) & (ADC_Conversion(5) < k)) { PORTC=0x0F; switch(x) { case 1110: //right case 1100: PORTB=0x02; break; case 1000: //cright case 0101: case 0100: case 0: PORTB=0x02; break; case 1101: PORTB=0x06; break; //left case 110: case 1: case 1011: case 1010: PORTB=0x08; break; case 10: //cleft case 11: case 111: PORTB=0x08; break; //straight case 1001: case 1111: PORTB=0x0A; break; } } else if((ADC_Conversion(0) < k) & (ADC_Conversion(5) > k)) { //straight PORTC=0x00; PORTC=0x0F; } else if((ADC_Conversion(0) > k) & (ADC_Conversion(5) < k)) { //straight PORTC=0x00; PORTC=0x0F; } } }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX_NUM 8 /** * Note: The returned array must be malloced, assume caller calls free(). */ int* twoSum(int* nums, int numsSize, int target, int* returnSize){ int *answer; //int j; int i, eclass; int diff; int hash_size; int mask; struct Node { int index; struct Node* next; }; struct Head { struct Node *start; struct Node *end; }; struct Head *hashtable; struct Node *temp = NULL; struct Node *membuf; struct Node *memptr; int *numsptr, *numstart; answer = malloc(2 * sizeof(int)); hash_size = 1 << (31 - __builtin_clz(numsSize)); mask = hash_size - 1; hashtable = calloc(hash_size, sizeof(struct Head)); memptr = membuf = malloc(numsSize * sizeof(struct Node)); //initialize hash table for(numstart = numsptr = &nums[0]; numsptr < &nums[numsSize]; numsptr++) { eclass = *numsptr & mask; if (hashtable[eclass].start == NULL) { hashtable[eclass].end = hashtable[eclass].start = memptr++; } else { hashtable[eclass].end = hashtable[eclass].end->next = memptr++; } hashtable[eclass].end->index = (int) (numsptr - numstart); // index = i hashtable[eclass].end->next = NULL; } //look for target sums for (i=0; i<numsSize; i++) { diff = target - nums[i]; eclass = diff & mask; // check each item in bucket temp = hashtable[eclass].start; while(temp != NULL) { if (temp->index != i && nums[temp->index] == diff) { //match goto finish; } temp = temp->next; } } finish: answer[0] = i; answer[1] = temp->index; free(membuf); free(hashtable); * returnSize = 2; return answer; } int main(int argc, char* argv[]) { int numsSize = MAX_NUM; int nums[MAX_NUM] = {3,2,4,1,9,6,3,8}; int target = 9; int returnSize; int *yes; yes = twoSum( nums, numsSize, target, &returnSize); if(yes == NULL) { printf("nothing found\n"); return -1; } printf("main yes[0] %d\n", yes[0]); printf("main yes[1] %d\n", yes[1]); free(yes); return 0; }
C
#include <stdio.h> #include <stdlib.h> int secondes (int s){ int h,m; h = s / 3600; s = s - (h * 3600); m = s / 60 ; s = s - (m * 60); // on a maintenant h qui est en heures , m en minutes , et s en secondes // return EXIT_SUCCESS; } int main(void) { int h,m,s; printf("entrez le temps en secondes : "); scanf("%d", &s); h = s / 3600; s = s - (h * 3600); m = s / 60 ; s = s - (m * 60); printf ("il est %02d %02d %02d ", h, m ,s ); return EXIT_SUCCESS; }
C
#include "BHeap.h" #include <stdlib.h> #include <stdio.h> #define hijoi(i) (2*(i)+1) #define hijod(i) (2*(i)+2) #define padre(i) (((i)-1)/2) #define nelems(h) (h)->nelems #define data(h, i) (h)->data[i] BHeap *bheap_create() { BHeap *ret = malloc(sizeof(BHeap)); nelems(ret)=0; return ret; } int bheap_minimum(BHeap *heap) { if(nelems(heap) == 0) { printf("error: heap vacio\n"); return -1; } else return data(heap,0); } BHeap *bheap_erase_minimum(BHeap *heap) { int i; /* si ya estaba vacio */ if(nelems(heap) == 0) return heap; /* subo el ultimo elemento */ data(heap,0) = data(heap, nelems(heap) - 1); nelems(heap)--; /* hundir */ i = 0; while(hijoi(i) < nelems(heap)) { int minpos = i; if(data(heap, hijoi(i)) < data(heap, minpos)) minpos = hijoi(i); if(2*i + 2 < nelems(heap)) if(data(heap, hijod(i)) < data(heap, minpos)) minpos = hijod(i); if(minpos != i) { int t; t = data(heap, i); data(heap, i) = data(heap, minpos); data(heap, minpos) = t; i = minpos; } else break; } return heap; } BHeap *bheap_erase_minimum2(BHeap *heap) { int i; /* si ya estaba vacio */ if(nelems(heap) == 0) return heap; /* subo el ultimo elemento */ data(heap,0) = data(heap, nelems(heap) - 1); nelems(heap)--; /* hundir */ i = 0; while(hijoi(i) < nelems(heap)) { int minpos = i; if(data(heap, hijoi(i)) > data(heap, minpos)) minpos = hijoi(i); if(2*i + 2 < nelems(heap)) if(data(heap, hijod(i)) > data(heap, minpos)) minpos = hijod(i); if(minpos != i) { int t; t = data(heap, i); data(heap, i) = data(heap, minpos); data(heap, minpos) = t; i = minpos; } else break; } return heap; } BHeap *bheap_insert(BHeap *heap, int data) { int i; /* si ya esta lleno */ if (nelems(heap) == MAX_HEAP) { printf("error: heap lleno\n"); return heap; } /* agrego al final */ data(heap,nelems(heap)) = data; nelems(heap)++; /* flotar */ i = nelems(heap) - 1; while(i != 0 && data(heap,padre(i)) > data(heap, i)) { int t; t = data(heap, i); data(heap, i) = data(heap,padre(i)); data(heap, padre(i)) = t; i = padre(i); } return heap; } BHeap *bheap_insert2(BHeap *heap, int data) { int i; /* si ya esta lleno */ if (nelems(heap) == MAX_HEAP) { printf("error: heap lleno\n"); return heap; } /* agrego al final */ data(heap,nelems(heap)) = data; nelems(heap)++; /* flotar */ i = nelems(heap) - 1; while(i != 0 && data(heap,padre(i)) < data(heap, i)) { int t; t = data(heap, i); data(heap, i) = data(heap,padre(i)); data(heap, padre(i)) = t; i = padre(i); } return heap; } void bheap_print(BHeap *heap) { int i; for(i = 0; i < nelems(heap); ++i) printf("%d ", data(heap, i)); printf("\n"); } void bheap_destroy(BHeap *heap) { free(heap); } int bheap_is_empty(BHeap *arbolito){ if (arbolito == NULL) return 1/0; return !(arbolito->nelems); }
C
/* ************************************************************************ * Description: Common routines for matrix multiplication **************************************************************************/ #ifndef _MATRIX_COMMON_H_ #define _MATRIX_COMMON_H_ /* ************************************************************************ * Routine: Initialize * Description: Initializes all elements in matrix. **************************************************************************/ void Initialize(float *A, int fil, int col); /* ************************************************************************ * Routine: InitializeI * Description: Initializes each square submatrix in matrix A to the * identity I. **************************************************************************/ void InitializeI(float *A, int fil, int col); /* ************************************************************************ * Routine: display * Description: Displays a matrix A to stdout. **************************************************************************/ void display(float *A, int fil, int col); /* ************************************************************************ * Routine: Compare * Description: Returns 1 if matrices are identical **************************************************************************/ int Compare(float *A, float *B, int fil, int col); /* ************************************************************************ * Routine: matmul_seq * Description: Matrix multiplication **************************************************************************/ void matmul_seq(float *C, float *A, float *B, int N); #endif
C
#include <stdio.h> #include "dbg.h" int i = 1; int *pi = &i; void Call_by_value(int i) { i++; log_info("i inside Call_by_value: %d", i); } void Call_by_reference(int *pi) { *pi = 2; log_info("i insde Call_by_reference: %d", *pi); } int main() { log_info("i in global scope euaqls: %d", i); Call_by_value(i); log_info("i after beign call by value: %d", i); log_info("i in global scope euaqls: %d", i); Call_by_reference(pi); log_info("i eqals after beign call by reference: %d", i); return 0; }
C
#include "forth.h" #include <assert.h> void test_forth_init(void); void test_forth_push_pop(void); void test_forth_init(void) { struct forth f; forth_init(&f, 10, 10, 0); assert(f.sp0 != 0); assert(f.sp != 0); assert(f.stack == 10); forth_free(&f); } void test_forth_push_pop(void) { struct forth f; cell c; forth_init(&f, 1, 0, 0); forth_push(&f, -3); assert(f.sp - f.sp0 == 1); c = forth_pop(&f); assert(f.sp == f.sp0); assert(c == -3); }
C
/*Exercise 5−1. As written, getint treats a + or − not followed by a digit as a valid representation of zero.Fix it to push such a character back on the input.*/ #include<stdio.h> #include<ctype.h> #define SIZE 5 #define BUFSIZE 100 char buf[BUFSIZE]; int bufp = 0; int getch(void) { return (bufp > 0)? buf[--bufp] : getchar(); // If the value of 'bufp'>0 than it will overwrite the value at bufp else will get new characte } void ungetch(int c) { if(bufp >= BUFSIZE) // It is used for checking buffer overflowing printf("ungetch: too many characters\n"); else buf[bufp++]=c; // It will store the character in buf array at position 'bufp' than increments the value of 'bufp' } int getint(int *pn) { int c,sign; while(isspace(c=getch())) // It will continue the loop if the ‘ ‘ occurs else will terminate the loop ; if(!isdigit(c) && c !=EOF && c!='+' && c!='-') // If entered character c is not a EOF and is not a digit and not a ‘+’ and not a '-' than it will terminate { ungetch(c); // it's not a number return -1; // -1 will end the program directly } sign = (c == '-') ? -1 : 1; // To store the sign of the number if(c=='+' || c=='-') // If the value of c is ‘+’ or ‘-‘ the it will get new character c = getch(); // This avoids to treat a '+' or '-' not followed by a digit as a valid representation of zero if( !isdigit( c ) ) // If not a number than returns 0 return 0; for(*pn = 0; isdigit(c);c=getch()) // To get the consecutive digits of a number to form a number and will store it at given location *pn = 10 * *pn + (c-'0'); *pn *= sign; if(c!=EOF) //checks for c!=EOF ungetch(c); return c; } int main(void) { int n,s,array[SIZE]; for(n=0;n<SIZE && getint(&array[n]) !=EOF; n++ ) // To store the inputs at consecutive array position { printf("storing in n = %d, getint %d\n", n, array[n]); } printf("The array is: "); for(s=0;s<n; s++) //To print the value of array printf("%d ",array[s]); printf("\n"); return 0; } /* Output:- 1 Storing in n = 0, getint 1 2 Storing in n = 1, getint 2 3 Storing in n = 2, getint 3 -4 Storing in n = 3, getint -4 5 Storing in n = 4, getint 5 The array is: 1 2 3 -4 5 */
C
/* * algorithm.c * * Created on: May 1, 2011 * Author: infinoid */ #include <stdio.h> #include <stdlib.h> #include "algorithm.h" #include "pretty.h" void mask_box(board_t *this, myint_t mask, myint_t x, myint_t y) { myint_t new, prev = __sync_fetch_and_and(&this->per_unit[y][x], mask); token_t found; if(prev == (prev & mask)) /* No change, don't bother. */ return; new = prev & mask; if(!new) { /* This indicates a logic error, or an unsolvable puzzle. */ print(this); die("Either a logic error occurred, or this puzzle is unsolvable.\n" "(Attempt to apply mask 0x%x to grid unit (%d,%d) (prev 0x%x) resulted in 0.)\n", mask, x, y, prev); } if(!(new & (new-1))) { /* Found another solution. Add it to the queue. */ DEC(this->remaining); found = (sizeof(new)<<3) - CLZ(new); this->results[y][x] = found; this->links[y][x].next = this->pending; this->pending = &this->links[y][x]; } } void mark_done(board_t *this, myint_t x, myint_t y); void mark_done(board_t *this, myint_t x, myint_t y) { myint_t i, j, boxx, boxy, mask; mask = ~(1<<(this->results[y][x]-1)); for(i = 0; i < NUM_TOKENS; i++) { /* Mark the row */ if(i != y) mask_box(this, mask, x, i); /* Mark the column */ if(i != x) mask_box(this, mask, i, y); } boxx = x - (x % BOX_SIDE_LEN); boxy = y - (y % BOX_SIDE_LEN); /* Mark the box */ for(i = boxx; i < boxx + BOX_SIDE_LEN; i++) for(j = boxy; j < boxy + BOX_SIDE_LEN; j++) if(i != x || j != y) mask_box(this, mask, i, j); } int mark_pending(board_t *board) { myint_t count = 0; link_t *this = board->pending; while(this) { count++; board->pending = this->next; mark_done(board, this->address[0], this->address[1]); this = board->pending; } if(count) fprintf(stderr, "mark_pending: handled %d pending completions.\n", count); return count; } /* Given a board_t that's memsetted to 0, and then results[][] populated * with preexisting data, initialize the rest of board_t. */ int annotate(board_t *this) { myint_t x, y, count = NUM_TOKENS*NUM_TOKENS; /* First pass, initialize masks and generate count. */ for(y = 0; y < NUM_TOKENS; y++) for(x = 0; x < NUM_TOKENS; x++) { myint_t v = this->results[y][x]; if(v) { count--; this->per_unit[y][x] = 1 << (v - 1); } else { this->per_unit[y][x] = (1 << NUM_TOKENS) - 1; } this->links[y][x].address[0] = x; this->links[y][x].address[1] = y; } this->remaining = count; /* Second pass, update empty-cell masks with full-cell data. */ for(y = 0; y < NUM_TOKENS; y++) for(x = 0; x < NUM_TOKENS; x++) if(this->results[y][x]) { mark_done(this, x, y); } return count; } static inline myint_t count_unresolved_flags(board_t *this, myint_t bx, myint_t by, myint_t sx, myint_t sy, myint_t m) { myint_t x, y, rv = 0; myint_t flag = 1<<m; for(x = bx; x < bx+sx; x++) for(y = by; y < by+sy; y++) { if(this->results[y][x] == m+1) return -1; if(this->per_unit[y][x] & flag) rv++; } return rv; } static inline myint_t last_one_standing_in_line(board_t *this) { myint_t n, i, flag, rv = 0; for(i = 0; i < NUM_TOKENS; i++) { flag = 1<<i; for(n = 0; n < NUM_TOKENS; n++) { if(count_unresolved_flags(this, 0, n, NUM_TOKENS, 1, i) == 1) { /* There's only one possible "i" for this row. */ myint_t x; printf("Only one %d in row %d.\n", i+1, n); for(x = 0; x < NUM_TOKENS; x++) { if(this->per_unit[n][x] & flag) { mask_box(this, flag, x, n); rv++; break; } } } if(count_unresolved_flags(this, n, 0, 1, NUM_TOKENS, i) == 1) { /* There's only one possible "i" for this column. */ myint_t y; printf("Only one %d in column %d.\n", i+1, n); for(y = 0; y < NUM_TOKENS; y++) { if(this->per_unit[y][n] & flag) { mask_box(this, flag, n, y); rv++; break; } } } } } return rv; } static inline myint_t last_one_standing_in_box(board_t *this) { myint_t i, flag, bx, by, rv = 0; for(i = 0; i < NUM_TOKENS; i++) { flag = 1<<i; for(bx = 0; bx < NUM_TOKENS; bx += BOX_SIDE_LEN) for(by = 0; by < NUM_TOKENS; by += BOX_SIDE_LEN) { if(count_unresolved_flags(this, bx, by, BOX_SIDE_LEN, BOX_SIDE_LEN, i) == 1) { /* There's only one possible "i" for this box. */ myint_t x, y; printf("Only one %d in box at (%d,%d).\n", i+1, bx, by); for(x = bx; x < bx + BOX_SIDE_LEN; x++) for(y = by; y < by + BOX_SIDE_LEN; y++) { if(this->per_unit[y][x] & flag) { mask_box(this, flag, x, y); rv++; break; } } } } } return rv; } /* Note: the following searches are only done when the algorithm is * somewhat desperate, as matches don't necessarily ensure forward * progress. */ static inline myint_t box_items_form_a_line(board_t *this) { myint_t i, l, n, boxcount, bx, by, flag, rv = 0; for(i = 0; i < NUM_TOKENS; i++) { flag = 1<<i; for(bx = 0; bx < NUM_TOKENS; bx += BOX_SIDE_LEN) for(by = 0; by < NUM_TOKENS; by += BOX_SIDE_LEN) { boxcount = count_unresolved_flags(this, bx, by, BOX_SIDE_LEN, BOX_SIDE_LEN, i); if(boxcount < 0) continue; for(l = 0; l < BOX_SIDE_LEN; l++) { if(boxcount == count_unresolved_flags(this, bx, by+l, BOX_SIDE_LEN, 1, i)) { for(n = 0; n < NUM_TOKENS; n++) { if(n < bx || n >= bx + BOX_SIDE_LEN) { if(!this->results[by+l][n] && this->per_unit[by+l][n] & flag) { printf("The %d's in box at (%d,%d) form a horizontal line, which rules out (%d,%d).\n", i+1, bx, by, n, by+l); rv++; mask_box(this, ~flag, n, by+l); } } } } if(boxcount == count_unresolved_flags(this, bx+l, by, 1, BOX_SIDE_LEN, i)) { for(n = 0; n < NUM_TOKENS; n++) { if(n < by || n >= by + BOX_SIDE_LEN) { if(!this->results[n][bx+l] && this->per_unit[n][bx+l] & flag) { printf("The %d's in box at (%d,%d) form a vertical line, which rules out (%d,%d).\n", i+1, bx, by, bx+l, n); rv++; mask_box(this, ~flag, bx+l, n); } } } } } } } return rv; } static inline myint_t line_items_are_in_a_box(board_t *this) { myint_t i, j, k, l, bx, by, flag, rv = 0; for(l = 0; l < NUM_TOKENS; l++) { flag = 1<<l; for(i = 0; i < NUM_TOKENS; i++) { int row_count = 0, col_count = 0; for(j = 0; j < NUM_TOKENS; j++) { if(this->per_unit[i][j] & flag) row_count++; if(this->per_unit[j][i] & flag) col_count++; } for(k = 0; k < NUM_TOKENS; k += BOX_SIDE_LEN) { int box_row_count = 0, box_col_count = 0; for(j = 0; j < BOX_SIDE_LEN; j++) { if(this->per_unit[i][j+k] & flag) box_row_count++; if(this->per_unit[j+k][i] & flag) box_col_count++; } if(row_count == box_row_count) { for(by = i - (i % BOX_SIDE_LEN); by < i - (i % BOX_SIDE_LEN) + BOX_SIDE_LEN; by++) { if(by == i) continue; for(bx = k; bx < k + BOX_SIDE_LEN; bx++) { if(this->per_unit[by][bx] & flag) { printf("The %d's in line (%d,*) are in a box, which rules out (%d,%d).\n", l+1, i, bx, by); rv++; mask_box(this, ~flag, bx, by); } } } } if(col_count == box_col_count) { for(bx = i - (i % BOX_SIDE_LEN); bx < i - (i % BOX_SIDE_LEN) + BOX_SIDE_LEN; bx++) { if(bx == i) continue; for(by = k; by < k + BOX_SIDE_LEN; by++) { if(this->per_unit[by][bx] & flag) { printf("The %d's in column (*,%d) are in a box, which rules out (%d,%d).\n", l+1, i, bx, by); rv++; mask_box(this, ~flag, bx, by); } } } } } } } return rv; } static inline myint_t inductive_exclusion_n(board_t *this, myint_t bx, myint_t by, myint_t sx, myint_t sy, myint_t N) { /* Given a subset of the space where exclusion is enforced, find * matched tuples of possibilities for which inductive closure excludes * those possibilities from existing anywhere else in the set. * * In other words, if N is 2, and two cells of the box both have 2 and * 6 as options, and they can't be anything else, then some third box * which has 2, 6 and 9 as options can't be a 2 or 6 after all. * * In a more interesting example, if N is 3, and three cells of the * box have possibilities [2,6], [6,9], and [2,9], then the * possibilities 2, 6, and 9 must be in those cells, and can't be * elsewhere in the box. */ /* "elements" is a scalar value for the number of elements under * consideration. We only consider the elements whose values are not * yet known. 0 <= elements <= NUM_TOKENS. * * idx[N] is the current permutation. There are N indices in the * permutation, each index is in the range of 0 to elements-1, are * unique within this list, and are in strictly ascending order. If * N is 3, the search space starts at [0,1,2] and terminates at * [NUM-3,NUM-2,NUM-1]. * * X[NUM_TOKENS] and Y[NUM_TOKENS] map the values in idx[] to positions * in the board matrix. They are declared with NUM_TOKENS entries, but * only indices 0 through elements-1 are populated. */ myint_t elements = 0, idx[N], X[NUM_TOKENS], Y[NUM_TOKENS], i, rv = 0; /* Set up initial set of indices */ for(i = 0; i < N; i++) idx[i] = i; /* Set up coordinate tables */ for(i = 0; i < NUM_TOKENS - 1; i++) { /* Calculate the coordinates for every element */ X[elements] = i % sx + bx; Y[elements] = i / sx + by; /* ...but only hold onto the unresolved elements */ if(CPOP(this->per_unit[Y[elements]][X[elements]]) > 1) elements++; } /* There must be at least N entries in the unresolved set to achieve * inductive closure, and there must be at least N+1 entries for there * to be anything else to exclude based on that. If we don't have that * many elements, don't bother trying. */ if(elements < N+1) return rv; /* Consider all the permutations. */ while(idx[0] <= elements - N) { myint_t mask = 0; /* find the union of all possibilities across the current * permutation. */ for(i = 0; i < N; i++) mask |= this->per_unit[Y[idx[i]]][X[idx[i]]]; if(CPOP(mask) == N) { /* the union has N bits set, look for things it can exclude */ myint_t ix, iy; for(iy = by; iy < sy + by; iy++) { for(ix = bx; ix < sx + bx; ix++) { myint_t skip = 0; for(i = 0; i < N; i++) { if(X[idx[i]] == ix && Y[idx[i]] == iy) { /* don't consider elements in the current * permutation */ skip = 1; break; } } if(skip) continue; if(!(this->per_unit[iy][ix] & mask)) continue; /* found one! */ printf("Set "); for(i = 0; i < N; i++) printf("%s[%d,%d]", i ? ", " : "", X[idx[i]], Y[idx[i]]); printf(" of size %d with %d possibilities excludes [%d,%d].\n", N, N, ix, iy); mask_box(this, ~mask, ix, iy); rv++; } } } /* Find the next permutation. */ for(i = N-1; i >= 0; i--) { if(idx[i] < (elements-(N-i))) { myint_t j; idx[i]++; for(j = i + 1; j < N; j++) { idx[j] = idx[j-1] + 1; } break; } else if(!i) idx[0] = elements; /* done */ } } return rv; } static inline myint_t inductive_exclusion(board_t *this) { myint_t i, j, n, rv = 0; for(n = 2; n < NUM_TOKENS-1; n++) { for(i = 0; i < NUM_TOKENS; i += BOX_SIDE_LEN) for(j = 0; j < NUM_TOKENS; j += BOX_SIDE_LEN) rv += inductive_exclusion_n(this, i, j, BOX_SIDE_LEN, BOX_SIDE_LEN, n); for(i = 0; i < NUM_TOKENS; i++) { rv += inductive_exclusion_n(this, i, 0, 1, NUM_TOKENS, n); rv += inductive_exclusion_n(this, 0, i, NUM_TOKENS, 1, n); } if(rv) return rv; } return rv; } int chew(board_t *this) { myint_t count = 0, rv; while((rv = mark_pending(this))) { count += rv; } if(!this->remaining) return rv; /* last one in box standing */ rv += last_one_standing_in_box(this); /* last one in line standing */ rv += last_one_standing_in_line(this); if(rv) return rv; /* items in box form a line */ rv += box_items_form_a_line(this); /* items in line are within a box */ rv += line_items_are_in_a_box(this); if(rv) return rv; /* inductive exclusion */ rv += inductive_exclusion(this); return rv; }
C
#include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include "common.h" void* loadfile(char* name, unsigned int* buflen) { char* buf; FILE* fin = fopen(name, "rb"); if (!fin) { printf("loadfile(): Could not open the file.\n"); return NULL; } fseek(fin, 0, SEEK_END); *buflen = ftell(fin); fseek(fin, 0, SEEK_SET); buf = malloc(*buflen); if(!buf) { fclose(fin); printf("loadfile(): Out of memory!\n"); return NULL; } fread(buf, 1, *buflen, fin); fclose(fin); return buf; } int writefile(char* name, void* buf, unsigned int buflen) { FILE* fout = fopen(name, "wb"); if (!fout) { printf("writefile(): Could not open the file.\n"); return 0; } fwrite(buf, 1, buflen, fout); fclose(fout); return 1; } int isFileExist(char* name) { FILE* f = fopen(name, "r"); if (f) { fclose(f); return 1; } else { return 0; } } //expected function behaviours: //* int clearPathIfOccupied(const char* path) //path parameter is an absolute path //no file/folder exists: return 1 //file and folder is present: attempt delete either //if folder: delete recursively //failure to delete: return 0 // //* int isPathRelative(const char* path) //self-explanatory // //* int retrieveWorkingPath(unsigned int nBufferLength, char* lpBuffer) //lpBuffer is destination buffer //nBufferLength is max buffer length(including null) //if fail: return 0 //otherwise: return number of characters written to buff, without null // Fully qualified name of the directory being deleted, without trailing backslash #ifdef _WIN32 #include <windows.h> /* int clearPathIfOccupied(const char* path) { DWORD attr; attr = GetFileAttributesA(path); if (attr != INVALID_FILE_ATTRIBUTES) { SHFILEOPSTRUCTA file_op = { NULL, FO_DELETE, path, "", FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT, FALSE, 0, "" }; return !SHFileOperationA(&file_op); } return 1; } int isPathRelative(const char* path) { return PathIsRelativeA(path); } int retrieveWorkingPath(unsigned int nBufferLength, char* lpBuffer) { return GetCurrentDirectoryA(nBufferLength, lpBuffer); } */ int makeDir(const char *path) { return mkdir(path); } #else /* int clearPathIfOccupied(const char* path) { //TODO return 0; } int isPathRelative(const char* path) { return *path != '/'; } int retrieveWorkingPath() { //TODO return 0; } */ int makeDir(const char *path) { return mkdir(path, 0777); } #endif
C
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <assert.h> #include <stdlib.h> #include <math.h> int D[2]; int pipeError,forkError; int main(){ char bb[] = "Hello, World!\n"; char out[sizeof(bb)/sizeof(bb[0])]; pipeError = pipe(D); assert(pipeError >= 0); forkError = fork(); assert(forkError!=-1); if(forkError != 0){ close(D[0]); write(D[1], bb, sizeof(bb)); exit(0); } else{ close(D[1]); read(D[0], out, sizeof(out)); printf("out string is: %s\n", out); } return 0; }
C
#include <stdio.h> #include <string.h> #include <ctype.h> typedef enum { VOWEL_HEAVY, CONSONANT_HEAVY, BALANCED } classifier_t; classifier_t classifier(const char* sntnc) { int i = -1; int vowels = 0; int consonants = 0; //printf("Enter a sentence.\n"); //gets(str); while(sntnc[i] != '\0'){ if(sntnc[i] == 'a' || sntnc[i] == 'e' || sntnc[i] == 'i' || sntnc[i] == 'o' || sntnc[i] == 'u' || sntnc[i] == 'A' || sntnc[i] == 'E' || sntnc[i] == 'I' || sntnc[i] == 'O' || sntnc[i] == 'U') { vowels++; } else { consonants++; } i++; } if(vowels > consonants) { return VOWEL_HEAVY; } else if (consonants > vowels) { return CONSONANT_HEAVY; } else { return BALANCED; } } void print(classifier_t sentence) { if (sentence == CONSONANT_HEAVY) { printf("The sentence is consonant heavy"); } if (sentence == VOWEL_HEAVY) { printf("The sentence is vowel heavy"); } if (sentence == BALANCED) { printf("The sentence is balanced"); } } int main() { char str[100]; fgets(str,100,stdin); classifier_t sentence = classifier(str); print(sentence); return 0; }
C
/* Author: lsong013 * Partner(s) Name: Reuben D'cunha * Lab Section: * Assignment: Lab # Exercise # * Exercise Description: [optional - include for your own benefit] * * I acknowledge all content contained herein, excluding template or example * code, is my own original work. */ #include <avr/io.h> #include "io.h" #include <avr/interrupt.h> #include <util/delay.h> volatile unsigned char TimerFlag = 0; unsigned long _avr_timer_M = 1; unsigned long _avr_timer_cntcurr = 0; void TimerOn() { TCCR1B = 0x0B; OCR1A = 125; TIMSK1 = 0x02; TCNT1 = 0; _avr_timer_cntcurr = _avr_timer_M; SREG |= 0x80; } void TimerOff() { TCCR1B = 0x00; } void TimerISR() { TimerFlag = 1; } ISR(TIMER1_COMPA_vect) { _avr_timer_cntcurr--; if (_avr_timer_cntcurr == 0) { TimerISR(); _avr_timer_cntcurr = _avr_timer_M; } } void TimerSet(unsigned long M) { _avr_timer_M = M; _avr_timer_cntcurr = _avr_timer_M; } void set_PWM(double f) { static double frequency; if (f != frequency) { if(!f) TCCR3B &= 0x08; else TCCR3B |= 0x03; if(f < 0.954) OCR3A = 0xFFFF; else if (f > 31250) OCR3A = 0x0000; else OCR3A = (short)(8000000 / (128 * f)) - 1; TCNT3 = 0; frequency = f; } } void PWM_on() { TCCR3A = (1 << COM3A0); TCCR3B = (1 << WGM32) | (1 << CS31) | (1 << CS30); set_PWM(0); } void PWM_off() { TCCR3A = 0x00; TCCR3B = 0x00; } static unsigned char tled = 0; static unsigned char oled = 0; enum tstates {start, zero, one, two} tstates; void ttick() { switch(tstates) { case start: tstates = zero; break; case zero: tstates = one; break; case one: tstates = two; break; case two: tstates = zero; break; default: tstates = start; break; } switch(tstates) { case start: break; case zero: tled = 0x01; break; case one: tled = 0x02; break; case two: tled = 0x04; break; default: break; } } enum ostates {ostart, three, off} ostates; void otick() { switch(ostates) { case ostart: ostates = three; break; case three: ostates = off; break; case off: ostates = three; break; default: break; } switch(ostates) { case ostart: break; case three: oled = 0x08; break; case off: oled = 0x00; break; default: break; } } unsigned long telapsed = 0; unsigned long oelapsed = 0; unsigned long selapsed = 0; const unsigned short tperiod = 300; const unsigned short operiod = 1000; const unsigned short speriod = 20; unsigned char sp_freq = 0x00; enum Speaker {sp_start, sp_on, sp_off} Speaker_state; void sp_tick() { switch(Speaker_state) { case sp_start: Speaker_state = sp_on; break; case sp_off if ((~PINA & 0x04) == 0x04) Speaker_state = sp_on; break; case sp_on: if ((~PINA & 0x04) != 0x00) Speaker_state = sp_off; break; default: break; } switch(Speaker_state) { case sp_start: case sp_on: speaker_temp = 0x01; break; case sp_off: speaker_temp = 0x00; break; default: break; } } void main() { PORTA = 0xFF; DDRA = 0x00; PORTB = 0x00; DDRB = 0xFF; TimerSet(100); TimerOn(); tstates = start; while(1) { telapsed += 100; oelapsed += 100; if (telapsed >= tperiod) { ttick(); telapsed = 0; } if (oelapsed >= operiod) { otick(); oelapsed = 0; } if (selapsed >= speriod) { sp_tick(); selapsed = 0; } PORTB = tled | oled; while(!TimerFlag); TimerFlag = 0; } }
C
#include<stdio.h> void add( int a,int b) { int c=a+b; printf("sum of %d and %d is %d",a,b,c); } int main() { add(10,100); getch(); return 0; }
C
#include <stdio.h> int main() { char title[61]; char artist[61]; int tracks; /* number of tracks on the CD */ char type; /* used to read in album/single info */ int album; /* boolean - is the CD an ALBUM? */ float price; printf("Welcome to the CD database.\n\n"); /* * First, the title */ printf("Please enter the details of the CD...\n"); printf("Title? "); scanf("%[^\n]", title); /* * Next, the artist */ printf("Artist? "); fflush(stdin); scanf("%[^\n]", artist); /* * Next, the number of tracks */ printf("Number of tracks? "); fflush(stdin); scanf("%d", &tracks); /* * Next, Album/single */ for (;;) { printf("Album or single (a for album, s for single)? "); fflush(stdin); scanf("%c", &type); if (type == 'a' || type == 's') break; printf("Error - only 'a' or 's' are allowed\n"); } album = type == 'a'; /* if we get here it must be 'a' or 's' */ /* * Next, the price */ printf("Retail price (e.g. 4.65)? "); fflush(stdin); scanf("%f", &price); /* * Output the CD details */ printf("\nThe CD details you entered are:\n"); printf("============================\n"); printf("Title: %s\n", title); printf("Artist: %s\n", artist); printf("Number of tracks: %d\n", tracks); if (album) printf("Album\n"); else printf("Single\n"); printf("Price: %.2f\n", price); printf("============================\n"); /* * A user-friendly exit of the program */ printf("\nPress ENTER to exit the program: "); fflush(stdin); return 0; }
C
#include <stdio.h> #include<math.h> #include<float.h> #include<stdlib.h> #include<time.h> void de_lat(void); void de_lon(void); #define int main() { int sv[104]={}; de_lat(); de_lon(); de_alt(); //NICʱ4bits //A/G state 2bits //horizontal velocityˮƽٶ horizontal_v(); // latitude decoding void de_lat() { register int i; int lat_d=0; float lat,lsb=2.1457672*pow(10,-5); float accuracy;//γȱʱһ srand((unsigned)time(NULL)); accuracy=(rand()/(double)(RAND_MAX)-0.5)*lsb; // translate to dec printf("the latitude is: "); for (i=0;i<23:i++) { if(sv[i]) lat_d=lat_d+pow(2,22-i); } // whether is N pole or South pole if(lat_d=pow(2,22)) printf("pole\n"); else // not pole { if(sv[0]=0) { lat = lat_d*lsb+accuracy ; printf("north "); printf("%.5f",lat); } else { lat=(pow(2,23)-lat_d)*lsb+accuracy; printf("south "); printf("%.5f",lat); } } } //longitude encoding void de_lon() { register int i; int lon_d=0; float lon,lsb=2.1457672*pow(10,-5); float accuracy; srand((unsigned)time(NULL)); accuracy=(rand()/(double)(RAND_MAX)-0.5)*lsb; printf("\nthe longitude is :"); for (i=23;i<47:i++) { if(sv[i]) lon_d=lon_d+pow(2,46-i); } if(sv[24]=0) { printf("east "); lon=lon_d*lsb+accuracy; printf("%.5f",lon); } else { printf("west "); lon=(pow(2,24)-lat_d)*lsb+accuracy; printf("%.5f",lon); } } //߶ȱ void de_alt() { register int i; int alt_d; int alt; float accuracy; srand((unsigned)time(NULL)); accuracy=rand()/((double)(RAND_MAX)/25)-12.5; // altitude type if(sv[47]) printf("\ngeometric altitude"); else printf("\npressure altitude"); //altitude 12bits for (i=48;i<60:i++) { if(sv[i]) alt_d=alt_d+pow(2,59-i); } if(alt_d) { alt=alt_d*25-1025+accuracy;//feet printf("\nthe altitude is :"); printf("%d",alt); } else printf("\naltitude imformation is unavailable"); } // horizontal velocity //ٶȱǰһreseved void horizontal_v() { register int i; int NS_velocity_d=0; int NS_velocity; float accuracy; srand((unsigned)time(NULL)); accuracy=rand()/(double)(RAND_MAX)-0.5; //A/G state //0 if((sv[64]==0)&&(sv[65]==0)) { //NSvelocity //airborne subsonic 1kt //жϷ if(sv[66]) printf("\nthe direction is south"); else printf("\nthe direciton is north"); // velocity С10bits for(i=67;i<77;i++) { if(sv[i]) NS_velocity_d= NS_velocity_d+pow(2,59-i); } if( NS_velocity_d==0) printf("\nthe N/S velocity is available"); else { if(NS_velocity_d==1023) printf("\nthe N/S velocity is bigger than 1021.5knots"); else { NS_velocity=NS_velocity_d-1+accuracy; printf("\nthe N/S velocity is %.5f",NS_velocity); } } } //1
C
#include <stdio.h> #include <stdlib.h> long calculateBuffSize(long fileSize){ long res = 0; while(res < fileSize){ res += (16 * sizeof(char)); } return res; } void hexdump(FILE *input, FILE *output) { fseek(input, 0, SEEK_END); long fileSize = ftell(input); long buffSize = calculateBuffSize(fileSize); rewind(input); char *arr = (char *) malloc(buffSize); for(int i=0; i < buffSize; i++) //fill buffer with 0s arr[i] = 0; fread(arr, 1, fileSize, input); //read text from file into buffer fclose(input); for(int i = 0; i < buffSize; i+=16){ fprintf(output, "%06x : ", i); for(int j = 0; j < 16; j++){ if(i+j >= fileSize){ fprintf(output, " "); } else{ fprintf(output, "%02x ", (unsigned char) arr[i+j]); } } fprintf(output, " "); for(int k = i; k < i+16; k++){ if(k < fileSize){ if(arr[k] < 32 || arr[k] > 126) fprintf(output, "."); else{ fprintf(output, "%c", arr[k]); } } } fprintf(output, "\n"); } free(arr); return; }
C
#include <stdio.h> int main(){ int N=0,a=0,b=0; scanf("%d",&N); for(int i=0;i<N;i++){ scanf("%d %d",&a,&b); printf("You get %d piece(s) and your dad gets %d piece(s).\n",a/b,a%b); } return 0; }
C
/* Debounce Each time the input pin goes from LOW to HIGH (e.g. because of a push-button press), the output pin is toggled from LOW to HIGH or HIGH to LOW. There's a minimum delay between toggles to debounce the circuit (i.e. to ignore noise). The circuit: - LED attached from pin 13 to ground - pushbutton attached from pin A1 to ground - Note: On most Arduino boards, there is already an LED on the board connected to pin 13, so you don't need any extra components for this example. created 21 Nov 2006 by David A. Mellis modified 30 Aug 2011 by Limor Fried modified 28 Dec 2012 by Mike Walters modified 30 Aug 2016 by Arturo Guadalupi This example code is in the public domain. http://www.arduino.cc/en/Tutorial/Debounce */ // constants won't change. They're used here to set pin numbers: const int buttonPin = 4; // the number of the pushbutton pin // Variables will change: int buttonState; // the current reading from the input pin int lastButtonState = HIGH; // the previous reading from the input pin // the following variables are unsigned longs because the time, measured in // milliseconds, will quickly become a bigger number than can be stored in an int. unsigned long lastDebounceTime = 0; // the last time the output pin was toggled unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers void setup_button() { pinMode(buttonPin, INPUT_PULLUP); } void loop_button() { // read the state of the switch into a local variable: int reading = digitalRead(buttonPin); // check to see if you just pressed the button // (i.e. the input went from LOW to HIGH), and you've waited long enough // since the last press to ignore any noise: // If the switch changed, due to noise or pressing: if (reading != lastButtonState) { // reset the debouncing timer lastDebounceTime = millis(); } if ((millis() - lastDebounceTime) > debounceDelay) { // whatever the reading is at, it's been there for longer than the debounce // delay, so take it as the actual current state: // if the button state has changed: if (reading != buttonState) { buttonState = reading; } } // save the reading. Next time through the loop, it'll be the lastButtonState: lastButtonState = reading; }
C
/* ** parsing.c for parsing in /home/nicolaspolomack/psu/PSU_2016_my_printf/ ** ** Made by Nicolas Polomack ** Login <nicolas.polomack@epitech.eu> ** ** Started on Fri Nov 18 10:06:59 2016 Nicolas Polomack ** Last update Wed Nov 23 10:37:13 2016 Nicolas Polomack */ #include "my.h" char *get_flags(char *str, t_flags *flags, va_list ap, int *count) { if ((*str == '-') || (*str == '+') || (*str == '0') || (*str == '#') || (*str == ' ')) flags->hold = *(str++); if (*str >= '0' && *str <= '9') while (*str >= '0' && *str <= '9') flags->width = flags->width * 10 + (*(str++) - '0'); else if (*str == '*') flags->width += va_arg(ap, int) + *(str++) * 0; else flags->width = -1; if (*str == '.') { if (*(++str) >= '0' && *str <= '9') while (*str >= '0' && *str <= '9') flags->precision = flags->precision * 10 + (*(str++) - '0'); else if (*str == '*') flags->precision += va_arg(ap, int) + *(str++) * 0; } else str += (flags->precision = ((*str == '.') ? 0 : -1)) + 1; if (*str == 'h' || *str == 'l') flags->length = *(str++); flags->format = *str; str = check_parse(str, flags, count); return (str); } char *check_parse(char *str, t_flags *flags, int *count) { int c1; int c2; c1 = 0; c2 = 0; if (flags->format == 'd' || flags->format == 'i' || flags->format == 'p' || flags->format == 'X' || flags->format == 'x' || flags->format == 'o' || flags->format == 'u' || flags->format == 'b' || flags->format == '%' || flags->format == 'd' || flags->format == 'i' || flags->format == 'S' || flags->format == 's' || flags->format == 'c') return (str); else while (*(flags->backup) != flags->format) my_putchar_printf(*(flags->backup++), count); my_putchar_printf(flags->format, count); return (str); }
C
#include<stdio.h> #include<string.h> void preencher(FILE* f, char* c){ fwrite(c, sizeof(char), strlen(c), f); } int main (void){ char str[26]; FILE* f = fopen("/home/ime/Área de Trabalho/arq.jota.txt", "w"); for(int i=0; i<10; i++){ printf("Frase: "); scanf("%s", str); preencher(f, str); } fclose(f); return 0; }
C
#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int numero =0; printf("Escribe un numero \n"); scanf("%d",&numero); fflush(stdin); if(numero>0){ printf("el cuadrado de %d es: %d",numero,(numero*numero)); }else{ printf("ERROR,el numero debe ser mayor que cero"); } return 0; }
C
#include "/players/eurale/closed/ansi.h" #include "room.h" /* this constant should be 1 for virgin Mud's */ /* #define FOODS = 5 */ #define Level this_player()->query_level() #define Name this_player()->query_name() #define Speak(s)\ write("Innkeeper says: "+s+"\n") int cm,mm,rmm; string last_eater; #undef EXTRA_RESET #define EXTRA_RESET\ cm = 30;\ mm = 25;\ rmm = 20;\ if(arg) return;\ items=({"menu","The menu looks like this"}); ONE_EXIT("players/eurale/Druid/df10.c","south", BOLD+GRN+"Druid Eatery"+NORM, "You are in the Druid Eatery. Here you can buy food to still your\n"+ "hunger, but only a limited selection is available and only in\n"+ "limited quantities. There is a menu posted on the wall.\n", 1) init() { add_action("buy","buy"); add_action("buy","order"); ::init(); } long(s) { ::long(s); show_menu(); } show_menu() { write("\n"); if(!(cm||mm||rmm)) Speak("We have completely sold out...come back later."); else { write("1: Twice-baked potato ");write(cm);write(" at 210 gp\n"); write("2: Leak soup ");write(mm);write(" at 300 gp\n"); write("3: Beef stew ");write(rmm);write(" at 350 gp\n"); write("4: A Mug of Beer ");write(" ");write(" 10 gp\n"); write("\n"); write("Use 'buy <number>' to buy the desired Food. The food will\n"+ "be consumed at once. Good appetite.\n\n"); } return; } no_food() { Speak("Sorry - we have sold out of that."); if(cm||mm||rmm) Speak("Why don't you try something else ?"); else Speak("Why don't you come back later ?"); return 1; } pays(n) { if(this_player()->query_money()<n) { Speak("You cannot afford that."); return 0; } this_player()->add_money(-n); return 1; } tease(n) { if(Name==last_eater) Speak("My - Are we hungry today."); last_eater=Name; this_player()->heal_self(n); return 1; } buy(s) { if(!s) { Speak("What do you want to buy ?"); return 1; } /* baked potato, price 210, heals 15 times 14 per pt */ if(s=="1"||s=="<1>") { if(!cm) return no_food(); if(!pays(210)) return 1; write("You are served a twice-baked potato - very nourishing\n"); say(Name+" orders a twice-baked potato\n"); call_other(this_player(),"eat_food",10); cm=cm-1; return tease(15); } /* Leak soup, price 300, heals 25 times 12 per pt */ if(s=="2"||s=="<2>") { if(!mm) return no_food(); if(!pays(300)) return 1; write("You are served a bowl of leak soup - very good\n"); say(Name+" orders a bowl of leak soup\n"); call_other(this_player(),"eat_food",12); mm=mm-1; return tease(25); } /* Beef stew, price 350, heals 35 times 10 per pt */ if(s=="3"||s=="<3>") { if(!rmm) return no_food(); if(!pays(350)) return 1; write("You are served a plate of beef stew - very delicious\n"); say(Name+" orders a plate of beef stew\n"); call_other(this_player(),"eat_food",14); rmm=rmm-1; return tease(35); } if(s=="4"||s=="<4>"||s=="mug"||s=="beer") { if(!pays(10)) return 1; if(!this_player()->drink_alcohol(2)) { Speak("You look a little too drunk for that..let me take it back."); this_player()->add_money(10); return 1; } write("You drink a mug of first class beer - That feels good.\n"); say(Name+" drinks a beer.\n"); return 1; } Speak("We have no such number on the menu, try 1, 2 or 3."); return 1; } eat_ok(arg) { if (!call_other(this_player(), "eat_food", arg)) { Speak("You look like your full.\n"); return 0; } return 1; }
C
/* * DES Key Setup * D.P.Mitchell 83/06/30. */ #include "crypt.h" int subkeys[128]; int pc1_c[] = { 57,49,41,33,25,17, 9, 1,58,50,42,34,26,18, 10, 2,59,51,43,35,27, 19,11, 3,60,52,44,36, }; int pc1_d[] = { 63,55,47,39,31,23,15, 7,62,54,46,38,30,22, 14, 6,61,53,45,37,29, 21,13, 5,28,20,12, 4, }; int shifts[] = { 1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1, }; int pc2_c[] = { 14,17,11,24, 1, 5, 3,28,15, 6,21,10, 23,19,12, 4,26, 8, 16, 7,27,20,13, 2, }; int pc2_d[] = { 41,52,31,37,47,55, 30,40,51,45,33,48, 44,49,39,56,34,53, 46,42,50,36,29,32, }; key_setup(key, decrypting) Block *key; int decrypting; { register round, j, k; register int *kl, *kh; int temp; int c[28], d[28]; int keybits[64]; /* * unpack 64-bit key block */ for (j = 0; j < 64; j++) if (j > 31) keybits[j] = ((key->right & (1 << (j - 32))) != 0); else keybits[j] = ((key->left & (1 << j)) != 0); /* * first permuted choice of 56 bits */ for (j = 0; j < 28; j++) { c[j] = keybits[pc1_c[j]-1]; d[j] = keybits[pc1_d[j]-1]; } /* * funny rotation of the 28-bit halves */ for (round = 0; round < 16; round++) { for (k = 0; k < shifts[round]; k++) { temp = c[0]; for (j = 0; j < 27; j++) c[j] = c[j + 1]; c[27] = temp; temp = d[0]; for (j = 0; j < 27; j++) d[j] = d[j + 1]; d[27] = temp; } /* * second permuted choice of 48 bits */ if (decrypting) { kl = &subkeys[8 * (15 - round)]; kh = &subkeys[8 * (15 - round) + 4]; } else { kl = &subkeys[8 * round]; kh = &subkeys[8 * round + 4]; } for (j = 0; j < 24; j += 6) { *kl++ = c[pc2_c[j + 0] - 1] + (c[pc2_c[j + 1] - 1] << 1) + (c[pc2_c[j + 2] - 1] << 2) + (c[pc2_c[j + 3] - 1] << 3) + (c[pc2_c[j + 4] - 1] << 4) + (c[pc2_c[j + 5] - 1] << 5); *kh++ = d[pc2_d[j + 0] - 29] + (d[pc2_d[j + 1] - 29] << 1) + (d[pc2_d[j + 2] - 29] << 2) + (d[pc2_d[j + 3] - 29] << 3) + (d[pc2_d[j + 4] - 29] << 4) + (d[pc2_d[j + 5] - 29] << 5); } } }
C
#ifndef LAB_13_MY_LIST_H #define LAB_13_MY_LIST_H #include "structures.h" #define FILTER_GENDER 0 #define FILTER_AGE 21 void push_standard_list(struct Student **list, struct Student *element); int pop_standard_list(std_t *list, int index); void print_standard_list(std_t stud); void free_standard_list(std_t *list); std_t list_i(std_t list, int i); int list_size(std_t list); void push_berkeley_sorted(std_t stud, struct list_head *head, int field, int (*cmp)(std_t, std_t)); void push_berkeley_all(std_t stud, struct list_head **sort, struct list_head **filter); void pop_berkeley_all(std_t stud); void print_berkeley_sort(struct list_head **array_of_lists, int field); void print_berkeley_filter(struct list_head **array_of_lists, int field); void null_berkeley(struct list_head **arr_sort, struct list_head **arr_filter); #endif //LAB_13_MY_LIST_H
C
int main() { int i,j,k,n,t=0; char s[100]; gets(s); k=strlen(s); for(i=0;i<k;i++) { if(s[i]==' ') { if(s[i+1]==' ') { t=t+1; for(n=i;n>=t-1;n--) { s[n+1]=s[n]; } } } } for(j=t;j<k;j++) printf("%c",s[j]); return 0; }
C
#include <stdio.h> #include <dirent.h> int main(int argc, char *argv[]) { DIR *dp; struct dirent *dirp; printf("Directory content:\n"); if ((dp = opendir(".")) != NULL) { while ((dirp = readdir(dp)) != NULL) { if (strcmp(dirp->d_name, ".") == 0 || strcmp(dirp->d_name, "..") == 0) continue; printf("%s\n", dirp->d_name); } closedir(dp); } else fprintf(stderr, "Can't open current directory\n"); }
C
#include <stdio.h> /** * main - entry point in c * * Return: 0 if successful */ int main(void) { long a = 1; long b = 2; int n = 3; printf("%li, ", a); printf("%li, ", b); while (n < 50) { long fib = a + b; printf("%li, ", fib); a = b; b = fib; n++; } while (n == 50) { long fib = a + b; printf("%li\n", fib); a = b; b = fib; n++; } return (0); }
C
// 編號:19-0401N0v0L2_Array-Exercise_For.c // 程式類別:C語言 // 基礎題:陣列 ( 難度 ** ) // 題目:陣列重組 // 時間:NULL ( 不限 ) //最佳 1s內 // 內存大小:128MB // 創建一個SIZE為10的Arr字元陣列, // 並初始化Arr陣列內容:A~J; // 隨機輸入0~9範圍內10個編號, // 輸出根據編號所輸入的英文順序。 // ( 請參考 Input 和 Output 格式 ) // 輸出格式: // printf(“Arr[%d] = %d\n”, ??); //問號為自定變數 // *注意: // 1、不可以使用printf直接表達,必須將內容存入到Arr中, // 再將整個Arr輸出。 // 2、請不要重複輸入0~9的編號 // 3、編號1~9 表示 A~I // 4、編號 0 表示 J // *提示: // 將輸入的編號存入Key陣列中,再用for循環挨個讀取 // 並輸出 //注意:需使用到雙重for循環。 // Input: // 5438791206 //隨機輸入10筆0~9的資料 // Output: // Arr[0] = E //Arr0號中根據Key內容為5,所以是E // Arr[1] = D // Arr[2] = C // Arr[3] = H // Arr[4] = G // Arr[5] = I // Arr[6] = A // Arr[7] = B // Arr[8] = J // Arr[9] = F #include<stdio.h> #define SIZE 10 int main(void){ /*變量宣告*/ int i,j; //循環用參數 int Keyi; //保存Key編號 int Key[SIZE]; //保存編號 char Arr[SIZE] = {'A','B','C','D','E','F','G','H','I','J'}; //初始化內容 char Arr2[SIZE]; //暫存 Key編號中所對應的Arr內容 /*輸入Key編號*/ for(i=0; i<SIZE; i++){ scanf("%d", &Key[i]); } /*將Key編號對應的Arr內容取出並存入Arr2中*/ for(i=0; i<SIZE; i++){ Keyi = Key[i]; //取出Key陣列中所保存的編號 並存入Keyi中 Arr2[i] = Arr[Keyi]; //將Arr所對應的Keyi編號內容存入 Arr2中 } /*將Arr2中的內容覆蓋\轉存 回Arr中*/ for(i=0; i<SIZE; i++){ Arr[i] = Arr2[i]; } /*輸出Arr*/ for(i=0; i<SIZE; i++){ printf("Arr[%d] = %c\n", i, Arr[i]); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> void dump(char* text, const char* arr, int n) { puts(text); int i = 0; while (n > 0) { printf("%2c:%2d,", *(arr + i), *(arr + i)); n--; i++; } puts(""); } void throw_error(const char *str, const char *a, const char *b) { printf("ERROR on %s : \"%s\" != \"%s\"\n", str, a, b); exit(1); } void compare(const char *str, const char *a, const char *b) { printf("COMPARE on %s : \"%s\" == \"%s\"\n", str, a, b); if(strcmp(a, b)) { throw_error(str, a, b); } } #define ENOMEM 12 #define EINVAL 22 int str_cat(char **dst, const char *src) { if (!dst) #if defined(EINVAL) return EINVAL; #else return EXIT_FAILURE; #endif size_t dst_len = 0, src_len = 0, len = 0; int overlap = 0; char *new = NULL; const char *dst_tmp = *dst, *src_tmp = src; if (dst_tmp && *dst_tmp) while (*++dst_tmp); if (src_tmp && *src_tmp) while (*++src_tmp); if (!(new = ( overlap = (dst_tmp > src_tmp ? dst_tmp : src_tmp) - (*dst < src ? *dst : src) <= ( len = (dst_len = dst_tmp - *dst) + (src_len = src_tmp - src) ) ) ? calloc(len + 1, 1) : realloc(*dst, len + 1)) || (overlap && !memcpy(new, *dst, dst_len)) || !memcpy(new + dst_len, src, src_len)) #if defined(ENOMEM) return ENOMEM; #else return EXIT_FAILURE; #endif if (overlap) free(*dst); *dst = new; return EXIT_SUCCESS; } int str_cpy(char **dst, const char *src) { if (!dst) #if defined(EINVAL) return EINVAL; #else return EXIT_FAILURE; #endif size_t src_len = 0; char *new = NULL; const char *tmp = src; if (src && *src) while (*++tmp); if (!(new = calloc((src_len = tmp - src) + 1, 1)) || !memcpy(new, src, src_len)) #if defined(ENOMEM) return ENOMEM; #else return EXIT_FAILURE; #endif free(*dst); *dst = new; return EXIT_SUCCESS; } void str_printf(char **a, const char *b, const char *c){} void str_free(char **a){} // http://thecodeil.com/5min_challenge_ru.html /* Copyright (C) Hola 2012, 2013 * * Welcome to TheCodeIL.com Challenge! */ void testing() { char *s = NULL; str_cpy(NULL, NULL); str_cat(NULL, NULL); str_cpy(&s, "Hola Hola"); compare("str_cpy(&s, \"Hola Hola\");", s, "Hola Hola"); str_cpy(&s, s+5); compare("str_cpy(&s, s+5);", s, "Hola"); str_cat(&s, " World"); compare("str_cat(&s, \" World\");", s, "Hola World"); str_cat(&s, s+5); compare("str_cat(&s, s+5);", s, "Hola WorldWorld"); s = NULL; str_cpy(&s, s); compare("s = NULL; str_cpy(&s, s);", s, ""); str_cat(&s, "a"); compare("str_cat(&s, \"a\");", s, "a"); s = NULL; str_cat(&s, s); compare("s = NULL; str_cat(&s, s);", s, ""); str_cpy(&s, "a"); compare("str_cpy(&s, \"a\");", s, "a"); s = NULL; str_cat(&s, ""); compare("s = NULL; str_cat(&s, \"\");", s, ""); str_cat(&s, "Hola Hola"); compare("str_cat(&s, \"Hola Hola\");", s, "Hola Hola"); s = NULL; str_cpy(&s, ""); compare("s = NULL; str_cpy(&s, \"\");", s, ""); str_cpy(&s, "Hola Hola"); compare("str_cpy(&s, \"Hola Hola\");", s, "Hola Hola"); } int main(int argc, char *argv[]) { testing(); char *s = NULL; str_cpy(&s, "Hola Hola"); str_cpy(&s, s+5); str_cat(&s, " World"); str_printf(&s, "%s!", s); puts(s); /* result: "Hola World!" */ str_free(&s); return 0; }
C
#include <linux/init.h> #include <linux/module.h> #include <linux/interrupt.h> #include <linux/kernel.h> #include <linux/fs.h> #include <linux/cdev.h> #include <linux/device.h> #include <linux/slab.h> // kmalloc(), kfree() #include <asm/uaccess.h> // copy_to_user() MODULE_AUTHOR("Jakub Werner"); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("A dummy driver"); MODULE_SUPPORTED_DEVICE("none"); #define MAJORNUM 121 #define NUMDEVICES 2 #define DEVNAME "t12tasklet" #define TASKLET_CALLED "My Tasklet Was Called" static struct cdev *cdev = NULL; static struct class *dev_class; static struct device *device; static int is_open = 0; static atomic_t v; static ssize_t driver_open(struct inode *inode, struct file* file); static ssize_t driver_close(struct inode *inode, struct file* file); static struct file_operations fops = { .owner= THIS_MODULE, .open = driver_open, .release = driver_close, }; static char tasklet_called[] = "my tasklet was called"; static void tasklet_function(unsigned long data); DECLARE_TASKLET(tasklet, tasklet_function,(unsigned long) &tasklet_called); static void tasklet_function(unsigned long data) { printk("%s\n", (char *)data); } static int __init mod_init(void) { dev_t major_nummer = MKDEV(MAJORNUM, 0); atomic_set(&v, -1); if (register_chrdev_region(MKDEV(MAJORNUM, 0), NUMDEVICES, DEVNAME)) { pr_warn("Device number 0x%x not available ...\n" , MKDEV(MAJORNUM, 0)); return -EIO ; } pr_info("Device number 0x%x created\n", MKDEV(MAJORNUM, 0)); cdev = cdev_alloc(); if (cdev == NULL) { pr_warn("cdev_alloc failed!\n"); goto free_devnum; } kobject_set_name(&cdev->kobj, DEVNAME); cdev->owner = THIS_MODULE; cdev_init(cdev, &fops); if (cdev_add(cdev, MKDEV(MAJORNUM,0), NUMDEVICES)) { pr_warn("cdev_add failed!\n"); goto free_cdev; } device = device; dev_class = class_create(THIS_MODULE, DEVNAME); device = device_create (dev_class, NULL, major_nummer, NULL, DEVNAME); return 0; free_cdev: kobject_put(&cdev->kobj); cdev = NULL; free_devnum: unregister_chrdev_region(MKDEV(MAJORNUM,0), NUMDEVICES); return -1; } static ssize_t driver_open(struct inode *inode, struct file* file) { tasklet_schedule(&tasklet); is_open++; try_module_get(THIS_MODULE); pr_debug("Module fops:device %s was opened from device with minor no %d \n", DEVNAME , iminor(inode)); return 0; } static ssize_t driver_close(struct inode *inode, struct file* file) { is_open--; module_put(THIS_MODULE); pr_debug("Module fops:device %s was closed \n", DEVNAME); return 0; } static void __exit mod_exit(void) { if (cdev) { cdev_del(cdev); } device_destroy(dev_class, MKDEV(MAJORNUM, 0)); class_destroy(dev_class); tasklet_kill(&tasklet); tasklet_disable(&tasklet); unregister_chrdev_region(MKDEV(MAJORNUM, 0), NUMDEVICES); printk(KERN_ALERT "Goodbye, cruel world\n"); } module_init(mod_init); module_exit(mod_exit);
C
#include <stdio.h> #include <stdlib.h> #include <math.h> // TC: era richiesto: sqrt(x1^2+x2^2+...+xn^2) void sqrtsum(int* a, int size){ int i = 0; int sum = 0; for(; i < size; ++i){ int pot = a[i] * a[i]; sum = sum + pot; double value = sqrt(sum); printf("%f\n", value); } } int main(){ int a[10]; int size = sizeof(a) / sizeof(int); int i = 0; for(; i < size; ++i){ a[i] = 6 * (i + 1); } sqrtsum(a, size); return EXIT_SUCCESS; }
C
/* Character analysis operators Examples using the character analysis operators. Send any byte and the sketch will tell you about it. created 29 Nov 2010 modified 2 Apr 2012 by Tom Igoe This example code is in the public domain. */ #include <stdlib.h> #include <stdio.h> void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } // send an intro: Serial.println("send any byte and I'll tell you everything I can about it"); Serial.println(); } void loop() { // get any incoming bytes: if (Serial.available() > 0) { int thisChar = Serial.read(); // say what was sent: Serial.print("You sent me: \'"); Serial.write(thisChar); Serial.print("\' ASCII Value: "); Serial.println(thisChar); // analyze what was sent: if(isAlphaNumeric(thisChar)) { Serial.println("it's alphanumeric"); } if(isAlpha(thisChar)) { Serial.println("it's alphabetic"); } if(isAscii(thisChar)) { Serial.println("it's ASCII"); } if(isWhitespace(thisChar)) { Serial.println("it's whitespace"); } if(isControl(thisChar)) { Serial.println("it's a control character"); } if(isDigit(thisChar)) { Serial.println("it's a numeric digit"); } if(isGraph(thisChar)) { Serial.println("it's a printable character that's not whitespace"); } if(isLowerCase(thisChar)) { Serial.println("it's lower case"); } if(isPrintable(thisChar)) { Serial.println("it's printable"); } if(isPunct(thisChar)) { Serial.println("it's punctuation"); } if(isSpace(thisChar)) { Serial.println("it's a space character"); } if(isUpperCase(thisChar)) { Serial.println("it's upper case"); } if (isHexadecimalDigit(thisChar)) { Serial.println("it's a valid hexadecimaldigit (i.e. 0 - 9, a - F, or A - F)"); } // add some space and ask for another byte: Serial.println(); Serial.println("Give me another byte:"); Serial.println(); } }
C
#include<stdio.h> int main() { float x,i,y=0; int s=0; for(i=0;i<6;i++){ scanf("%f",&x); if(x>0){ s++; y+=x; } } printf("%d valores positivos\n",s); printf("%.1f\n",y/s); return 0; }
C
#include <stdio.h> #include <string.h> typedef struct Radix4Node{ struct Radix4Node* children[4]; int flag;//Ϊ1ַĽβ }Redix4Node,* Redix4ptr; typedef struct Statistic{ int mem; int cmpnum; int nodeNum; }Statistic; Statistic global_stats; void* bupt_malloc(size_t ); Redix4ptr newNode(); Redix4ptr Redix4Insert(Redix4ptr,int); Redix4ptr Find(Redix4ptr ptr, int key); Redix4ptr Find(Redix4ptr ptr, int key){ return ptr->children[key]; } Redix4ptr newNode(){ global_stats.nodeNum++; Redix4ptr node = (Redix4ptr)bupt_malloc(sizeof(Redix4Node)); for (int i = 0; i < 4; i++){ node->children[i] =NULL; } node->flag = 0; return node; } Redix4ptr Redix4Insert(Redix4ptr ptr, int key){ if (!ptr->children[key]){ ptr->children[key] = newNode(); } return ptr->children[key]; } void* bupt_malloc(size_t size){ if (size <= 0) { return NULL; } global_stats.mem += size; return malloc(size); } int main(){ global_stats.cmpnum = 0; global_stats.mem = 0; global_stats.nodeNum = 0; FILE *fp; Redix4ptr head = newNode(); if ((fp = fopen("./patterns-127w.txt", "r")) == NULL){ return -1; } int flag = 0; while (!feof(fp)){ char strLine[100] = { '\0' }; fgets(strLine, 100, fp); int i = 0; Redix4ptr pos = head; while (strLine[i] != '\n'&&strLine[i] != '\0'){ int bit1 = (strLine[i] & 192)>>6; pos = Redix4Insert(pos, bit1); int bit2 = (strLine[i] & 48) >>4; pos = Redix4Insert(pos, bit2); int tmp = strLine[i] << 4; int bit3 = (strLine[i] &12) >> 2; pos = Redix4Insert(pos, bit3); int bit4 = strLine[i] &3; pos = Redix4Insert(pos, bit4); i++; } pos->flag = 1; } fclose(fp); printf("ڵ:%d\n", global_stats.nodeNum); if ((fp = fopen("./words-98w.txt", "r")) == NULL){ return -1; } int wordsNum = 0; int wordsSuccessNum = 0; while (!feof(fp)){ wordsNum++; char strLine[100] = { '\0' }; fgets(strLine, 100, fp); //ַתΪint int i = 0; Redix4ptr pos = head; int length = 0; while (strLine[length] != '\n'&&strLine[length] != '\0'){ length++; } while (strLine[i] != '\n'&&strLine[i] != '\0'){ int bit1 = (strLine[i] & 192) >> 6; pos = Find(pos, bit1); global_stats.cmpnum++; if (!pos) break; int bit2 = (strLine[i] & 48) >> 4; pos = Find(pos, bit2); global_stats.cmpnum++; if (!pos) break; int bit3 = (strLine[i] & 12) >> 2; pos = Find(pos, bit3); global_stats.cmpnum++; if (!pos) break; int bit4 = strLine[i] & 3; pos = Find(pos, bit4); global_stats.cmpnum++; if (!pos) break; i++; } if (i == length && pos->flag){ wordsSuccessNum++; } } fclose(fp); printf("ṹռڴ%d\n", global_stats.mem); printf("wordsܸ%d\n", wordsNum); printf("ɹwordܸ%d\n", wordsSuccessNum); printf("ַȽϴ %d\n", global_stats.cmpnum / 1000); printf("\n"); }
C
#include<stdio.h> int graph[50][50]; int minfn(int x, int y); int Dijkstra(int v) { int vertex[v+1]; for(int i=0;i<v+1;i++) { vertex[i]=0; } int vertex_visited[v+1]; int shortest_path[v]; int count = 1; int min = 999; int temp = 0; printf("\nStep\t"); for(int i=2;i<=v;i++) { printf("V=%d\t",i);} printf("N\n----------------------------------------------------------------------------------"); //Initializations printf("\n0\t"); vertex_visited[1] = 1; count = 2; vertex[1]=1; int D[v+1][v+1]; int P[v+1][v+1]; for(int i=2;i<=v;i++) { D[1][i-1]= graph[1][i]; P[1][i-1] = 1; printf("%d,%d\t",D[1][i-1],P[1][i-1]); if(D[1][i-1]<min) { min = D[1][i-1]; temp = i; } } printf("%d\t",vertex_visited[1]); vertex[temp]=1; shortest_path[temp] = min; // printf("\nShortest path from source to vertex %d = %d\n",temp,min); printf("\n"); for(int iteration=2;iteration<=v;iteration++) { printf("%d\t",iteration-1); vertex_visited[count] = temp; count++; min = 999; for(int dpvertex=1;dpvertex<v;dpvertex++) { if(vertex[dpvertex+1] == 0){ D[iteration][dpvertex]=minfn(D[iteration-1][dpvertex],D[iteration-1][vertex_visited[count-1]-1]+graph[vertex_visited[count-1]][dpvertex+1]); if(minfn(D[iteration-1][dpvertex],D[iteration-1][vertex_visited[count-1]-1]+graph[vertex_visited[count-1]][dpvertex+1])==D[iteration-1][dpvertex]) { P[iteration][dpvertex]=P[iteration-1][dpvertex]; } else { P[iteration][dpvertex]=vertex_visited[count-1]; } if(D[iteration][dpvertex]<min) { min = D[iteration][dpvertex]; temp = dpvertex+1; } printf("%d,%d\t",D[iteration][dpvertex],P[iteration][dpvertex]); } else { printf("----\t"); } } for(int m=1;m<=count-1;m++) printf("%d,",vertex_visited[m]); if(min!=999) { shortest_path[temp] = min; } // printf("\nShortest path from source to vertex %d = %d\n",temp,min); printf("\n"); vertex[temp]=1; } for(int i=2;i<=v;i++) { printf("Shortest path from vertex 1 to %d is %d\n",i,shortest_path[i]); } } int minfn(int x, int y) { int min; if(x<=y) { min = x; } else min = y; return min; } int inputgraph(int v) { printf("Enter the adjacency matrix : \n"); for(int i=1;i<=v;i++) { for(int j=1;j<=v;j++) { printf("Enter edge between %d and %d",i,j); scanf("%d",&graph[i][j]); } } Dijkstra(v); return 0; } int main() { int v; printf("Enter the no of vertices : "); scanf("%d",&v); int graph[v+1][v+1]; inputgraph(v); }
C
/*링 버퍼 구조: 원하는 만큼 데이터를 무한하게 입력하는데, 저장되는 건 최근의 MAX개. 아이디어: 입력할 때: 인덱스를 input++ % MAX로 설정. 이 값은 절대 MAX를 넘을 수 없다. 이때 주목할 점은 input++ % MAX의 값은 MAX를 넘을 수 없지만, input의 값은 계속 누적되어 충분히 넘을 수 있다는 것. input은 말 그대로 입력한 원소의 수다. 핵심 아이디어: i = input - MAX; if(i<0) i = 0; 입력한 숫자의 개수: input 몇 번째 입력한 정수인가?: i + 1부터 input까지 출력 해당(남아있는) 값은?: buffer[i % MAX] 출력*/ #include <stdio.h> #define MAX 10 int main(void) { int retry; int buffer[MAX]; int input = 0, i; printf("정수를 입력하세요.\n"); do { printf("%d번째 정수: ", input + 1); scanf("%d", &buffer[input++ % MAX]); printf("계속할까요?[Yes: (1) / No: (0)]: "); scanf("%d", &retry); } while (retry == 1); //input++ % MAX를 거쳤기 때문에, input++ % MAX 자체의 값은 MAX를 초과할 수 없으나, //input은 얼마든지 초과할 수 있다. i = input - MAX; //MAX보다 적게 입력했다면, i를 다시 0으로 초기화 if (i < 0) i = 0; for (; i < input; i++) { printf("%d번째 정수: %d\n", i + 1, buffer[i % MAX]); } //정수가 몇 번째 입력인지 알려면, i가 아니라, i+1부터 조회해야 한다. //저장은 buffer[0 == input]부터 하는데, "번 째"는 1 == input + 1부터 세기 때문에 return 0; }
C
#include<stdio.h> int main(){ int n1,rem,rev=0,n; printf("Enter A Number : "); scanf("%d",&n); n1=n; while(n>0){ rem=n%10; rev=rev*10+rem; n/=10; } if(n1==rev){ printf("It's a Palindrome"); printf("\n%d",rev); } else{ printf("Not a Palindrome"); printf("\n%d",rev); } return 0; }
C
/* Copyright (c) 2012, Matthew E. Cross <matt.cross@gmail.com> * * Permission to use, copy, modify, and/or distribute this software * for any purpose with or without fee is hereby granted, provided * that the above copyright notice and this permission notice appear * in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* bst.c - Binary search tree - currently implemented as an AA Tree * (or Andersson Tree). See: http://en.wikipedia.org/wiki/AA_tree */ #include "mec-lib/bst.h" #include "mec-lib/util.h" /* This is used internally by the implementation, but may be useful for external code that wants to walk the tree manually. */ const struct bst_node bst_nil_node = { .parent = NULL, .left = (struct bst_node *)&bst_nil_node, .right = (struct bst_node *)&bst_nil_node, .level = 0, }; struct bst_node *bst_nil = (struct bst_node *)&bst_nil_node; /* Initalize a BST. */ void bst_init(struct bst *bst, struct bst_ops *ops) { bst->root = bst_nil; bst->ops = ops; } /* The AA tree skew operation - repair a left horizontal link. */ static struct bst_node *bst_skew(struct bst *bst, struct bst_node *n) { if ((n == bst_nil) || (n->left == bst_nil)) { return n; } else if (n->left->level == n->level) { /* Horizontal left link - do a left rotate to eliminate it. */ struct bst_node *l = n->left; l->parent = n->parent; if (n->parent == NULL) bst->root = l; else if (n->parent->left == n) l->parent->left = l; else l->parent->right = l; n->left = l->right; if (n->left != bst_nil) n->left->parent = n; l->right = n; n->parent = l; return l; } else { return n; } } /* The AA tree split operation - repair a dual horizontal right link. */ static struct bst_node *bst_split(struct bst *bst, struct bst_node *n) { if ((n == bst_nil) || (n->right == bst_nil) || (n->right->right == bst_nil) ) { return n; } else if (n->level == n->right->right->level) { /* We have two horizontal right links - repair it by popping the middle node up a level. */ struct bst_node *r = n->right; r->parent = n->parent; if (n->parent == NULL) bst->root = r; else if (n->parent->left == n) r->parent->left = r; else r->parent->right = r; n->right = r->left; if (n->right != bst_nil) n->right->parent = n; r->left = n; n->parent = r; r->level++; return r; } else { return n; } } /* Insert an item into a BST. Returns 0 on success, non-zero on error. */ int bst_insert(struct bst *bst, struct bst_node *n) { void *k = bst->ops->get_key(n); struct bst_node *cur; /* Initialize n as a leaf node. */ n->level = 1; n->left = n->right = bst_nil; /* Handle insertion into an empty tree. */ if (bst->root == bst_nil) { n->parent = NULL; bst->root = n; return 0; } /* Find the proper place in the tree to insert this node as a leaf. */ cur = bst->root; while (1) { void *cur_key = bst->ops->get_key(cur); int comparison = bst->ops->compare(k, cur_key); if (comparison < 0) { if (cur->left == bst_nil) { cur->left = n; n->parent = cur; break; } else { cur = cur->left; } } else if (comparison > 0) { if (cur->right == bst_nil) { cur->right = n; n->parent = cur; break; } else { cur = cur->right; } } else { /* Two items with the same key not allowed! */ return 1; } } /* Now walk back up the tree to repair any temporary damage. */ while (n) { n = bst_skew(bst, n); n = bst_split(bst, n); n = n->parent; } return 0; } /* Remove an item from a BST. Returns 0 on success, non-zero on error. */ int bst_delete(struct bst *bst, struct bst_node *n) { struct bst_node *r; struct bst_node *cur; /* If the node to be deleted is a leaf node, then just remove it. */ if ((n->left == bst_nil) && (n->right == bst_nil)) { if (n->parent == NULL) bst->root = bst_nil; else if (n->parent->left == n) n->parent->left = bst_nil; else n->parent->right = bst_nil; cur = n->parent; } else { /* This is a non-leaf node. Find a leaf node below this one and unlink it from the tree so that when we walk back up we can replace 'n' with 'r'. */ if (n->left == bst_nil) r = bst_next(bst, n); else r = bst_prev(bst, n); if (r->parent->left == r) r->parent->left = bst_nil; else r->parent->right = bst_nil; cur = r->parent; } /* Walk back up the tree rebalancing as we go. If we find 'n', then substitute 'r' in its place. */ while (cur) { if (cur == n) { /* Put the node 'r' here. */ r->parent = cur->parent; if (cur->parent == NULL) bst->root = r; else if (cur->parent->left == cur) r->parent->left = r; else r->parent->right = r; r->left = cur->left; if (r->left != bst_nil) r->left->parent = r; r->right = cur->right; if (r->right != bst_nil) r->right->parent = r; r->level = cur->level; cur = r; } /* Fix up the level of this node if necessary. */ if (cur->level > (MEC_MIN(cur->left->level, cur->right->level) + 1)) { cur->level = MEC_MIN(cur->left->level, cur->right->level) + 1; if (cur->right->level > cur->level) cur->right->level = cur->level; } /* Handle rebalancing. */ cur = bst_skew(bst, cur); bst_skew(bst, cur->right); bst_skew(bst, cur->right->right); cur = bst_split(bst, cur); bst_split(bst, cur->right); cur = cur->parent; } /* Clean up the node we just deleted. */ n->level = 0; n->parent = n->left = n->right = NULL; return 0; } /* Find an item in a BST. Returns a pointer to the node, or NULL if item was not found. */ struct bst_node *bst_find(struct bst *bst, void *key) { struct bst_node *cur; cur = bst->root; while (cur != bst_nil) { void *cur_key = bst->ops->get_key(cur); int comparison = bst->ops->compare(key, cur_key); if (comparison < 0) cur = cur->left; else if (comparison > 0) cur = cur->right; else return cur; } return NULL; } /* Find the smallest item in a BST whose key is greater than or equal to 'key'. Returns NULL if no such item is found. */ struct bst_node *bst_find_smallest_gte(struct bst *bst, void *key) { struct bst_node *cur; cur = bst->root; while (cur != bst_nil) { void *cur_key = bst->ops->get_key(cur); int comparison = bst->ops->compare(key, cur_key); if (comparison < 0) { if (cur->left == bst_nil) return cur; cur = cur->left; } else if (comparison > 0) { if (cur->right == bst_nil) return bst_next(bst, cur); cur = cur->right; } else return cur; } return NULL; } /* Find the largest item in a BST whose key is less than or equal to 'key'. Returns NULL if no such item is found. */ struct bst_node *bst_find_largest_lte(struct bst *bst, void *key) { struct bst_node *cur; cur = bst->root; while (cur != bst_nil) { void *cur_key = bst->ops->get_key(cur); int comparison = bst->ops->compare(key, cur_key); if (comparison < 0) { if (cur->left == bst_nil) return bst_prev(bst, cur); cur = cur->left; } else if (comparison > 0) { if (cur->right == bst_nil) return cur; cur = cur->right; } else return cur; } return NULL; } /* Given a node, return a pointer to the node in the tree with the next highest key. If NULL is passed in, returns a pointer to the node in the tree with the smallest key. If no more nodes exist, returns NULL. */ struct bst_node *bst_next(struct bst *bst, struct bst_node *n) { struct bst_node *cur; if (n == NULL) { if (bst->root == bst_nil) return NULL; cur = bst->root; while (cur->left != bst_nil) cur = cur->left; return cur; } else { if (n->right != bst_nil) { /* The next node is the left most child of our right subtree. */ cur = n->right; while (cur->left != bst_nil) cur = cur->left; return cur; } else { /* Walk up the tree until we walk up a left link; when we do that is the next node. */ cur = n; while (cur->parent) { if (cur->parent->left == cur) return cur->parent; cur = cur->parent; } return NULL; } } } /* Given a node, return a pointer to the node in the tree with the next lowest key. If NULL is passed in, returns a pointer to the node in the tree with the largest key. If no more nodes exist, returns NULL. */ struct bst_node *bst_prev(struct bst *bst, struct bst_node *n) { struct bst_node *cur; if (n == NULL) { if (bst->root == bst_nil) return NULL; cur = bst->root; while (cur->right != bst_nil) cur = cur->right; return cur; } else { if (n->left != bst_nil) { /* The next node is the right most child of our left subtree. */ cur = n->left; while (cur->right != bst_nil) cur = cur->right; return cur; } else { /* Walk up the tree until we walk up a right link; when we do that is the next node. */ cur = n; while (cur->parent) { if (cur->parent->right == cur) return cur->parent; cur = cur->parent; } return NULL; } } } /* Local Variables: */ /* mode: c */ /* c-basic-offset: 8 */ /* indent-tabs-mode: nil */ /* fill-column: 120 */ /* c-backslash-max-column: 120 */ /* End: */
C
#include <avr/io.h> #include <util/delay.h> #include <stdio.h> #include <avr/interrupt.h> #define BAUD 9600 #include <util/setbaud.h> /* cpp FILE * uart_str; static int uart_putchar(char c , FILE *stream); static int uart_getchar(FILE *stream); */ #define MYUBRR F_CPU/16/BAUD-1 //c 328p void init_uart(void) { UBRRH = (uint8_t)(MYUBRR>>8); UBRRL = (uint8_t)MYUBRR; #if USE_2X UCSRA |= _BV(U2X); #else UCSRA &= ~(_BV(U2X)); #endif UCSRC = (1<<URSEL) | (3<<UCSZ0); // 8-bit data UCSRB = (1<<RXEN) | (1<<TXEN); // Enable RX and TX } void uart_putchar(char c, FILE *stream) { if (c == '\n') { uart_putchar('\r', stream); } loop_until_bit_is_set(UCSRA, UDRE); UDR = c; } char uart_getchar(FILE *stream) { loop_until_bit_is_set(UCSRA, RXC); // Wait until data exists. return UDR; } /* void init_uart(void) { UBRRH = UBRRH_VALUE;//(unsigned char)(ubrr>>8); UBRRL = UBRRL_VALUE;//(unsigned char)ubrr; UCSRB = (1<<RXEN)|(1<<TXEN); UCSRC = (1<<URSEL)|(1<<USBS)|(3<<UCSZ0); } */ static int uart_putchar32(char c, FILE *stream) { if(c == '\n') uart_putchar('\r', stream); while( !(UCSRA & (1<<UDRE)) ) ; UDR = c; return 0; } static int uart_getchar32(FILE *stream) { while( !(UCSRA & (1<<RXC)) ) ; char data = UDR; if(data == '\r') data = '\n'; uart_putchar(data, stream); return data; } //FILE uart_output = FDEV_SETUP_STREAM(uart_putchar, NULL, _FDEV_SETUP_WRITE); //FILE uart_input = FDEV_SETUP_STREAM(NULL, uart_getchar, _FDEV_SETUP_READ); //FILE uart_io = FDEV_SETUP_STREAM(uart_putchar, uart_getchar, _FDEV_SETUP_RW);
C
#include <stdio.h> int main() { char variable1, variable2; printf("enter the tow alphabate for ascii value variable1 or variable2 :"); scanf("%c %c",&variable1,&variable2); printf("ASCII values of these are %d or %d \n",variable1,variable2); //compaire if(variable1>variable2) printf("\nYou are in if"); else printf("\nYou are in else"); return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <stdint.h> #include <stdbool.h> #include "bitmapUtils.h" //#define DEBUG_PRINT int encodebitmap1(char* name, int x, int y, uint8_t* map){ printf("Opening output %s\n",name); FILE* fd_out = fopen(name,"wb"); if (fd_out==NULL){ printf("Cannot open output file\n"); return __LINE__; } // calculate size with padding uint32_t line_length = x; if ( (x % 32) != 0) line_length += (32 - (line_length % 32)); #ifdef DEBUG_PRINT printf("x=%d, linelength=%d\n",x,line_length); #endif // read in the file header struct bmp_file_header file_header; memset(&file_header,0,sizeof(struct bmp_file_header)); file_header.type[0] = 'B'; file_header.type[1] = 'M'; file_header.size = sizeof(struct bmp_file_header) + sizeof(struct bmp_dib_header) + 8 + ((line_length*y)/8); file_header.start = sizeof(struct bmp_file_header) + sizeof(struct bmp_dib_header) + 8; size_t bytes_written = fwrite(&file_header,1,sizeof(struct bmp_file_header),fd_out); printf("Out write %lu\n", bytes_written); // read in the dib header struct bmp_dib_header dib_header; memset(&dib_header,0,sizeof(struct bmp_dib_header)); dib_header.size = sizeof(struct bmp_dib_header); dib_header.x = x; dib_header.y = y; dib_header.a = 1; dib_header.b = 1; bytes_written = fwrite(&dib_header,1,sizeof(struct bmp_dib_header),fd_out); #ifdef DEBUG_PRINT printf("Out write %lu\n", bytes_written); #endif uint8_t junk[8] = {0,0,0,0,0xff,0xff,0xff,0}; bytes_written = fwrite(junk,1,8,fd_out); #ifdef DEBUG_PRINT printf("Out write %lu\n", bytes_written); #endif uint8_t* map_ptr = map; for (int iy=0; iy<y; ++iy){ for (int ix=0; ix<(int)line_length; ix+=8){ int xleft = x - ix; uint8_t tmp = 0; if (xleft>0) { if(*map_ptr==1) tmp |= 0x80; map_ptr++;} if (xleft>1) { if(*map_ptr==1) tmp |= 0x40; map_ptr++;} if (xleft>2) { if(*map_ptr==1) tmp |= 0x20; map_ptr++;} if (xleft>3) { if(*map_ptr==1) tmp |= 0x10; map_ptr++;} if (xleft>4) { if(*map_ptr==1) tmp |= 0x08; map_ptr++;} if (xleft>5) { if(*map_ptr==1) tmp |= 0x04; map_ptr++;} if (xleft>6) { if(*map_ptr==1) tmp |= 0x02; map_ptr++;} if (xleft>7) { if(*map_ptr==1) tmp |= 0x01; map_ptr++;} bytes_written = fwrite(&tmp,1,1,fd_out); } } printf("Closing output %s\n",name); fclose(fd_out); return 0; } int encodebitmap24(char* name, int x, int y, uint8_t* map, int scale){ printf("Opening output %s\n",name); FILE* fd_out = fopen(name,"wb"); if (fd_out==NULL){ printf("Cannot open output file\n"); return __LINE__; } // calculate size with padding uint16_t line_length = x*3; if ( (line_length % 4) != 0) line_length += (4 - (line_length % 4)); uint16_t padding = (line_length - (x*3)); #ifdef DEBUG_PRINT printf("x=%d, linelength=%d, padd=%d bytes\n",x,line_length,padding); #endif // read in the file header struct bmp_file_header file_header; memset(&file_header,0,sizeof(struct bmp_file_header)); file_header.type[0] = 'B'; file_header.type[1] = 'M'; file_header.size = sizeof(struct bmp_file_header) + sizeof(struct bmp_dib_header) + ((line_length*y)); file_header.start = sizeof(struct bmp_file_header) + sizeof(struct bmp_dib_header); size_t bytes_written = fwrite(&file_header,1,sizeof(struct bmp_file_header),fd_out); #ifdef DEBUG_PRINT printf("Out write %lu\n", bytes_written); #endif // read in the dib header struct bmp_dib_header dib_header; memset(&dib_header,0,sizeof(struct bmp_dib_header)); dib_header.size = sizeof(struct bmp_dib_header); dib_header.x = x; dib_header.y = y; dib_header.a = 1; dib_header.b = 24; bytes_written = fwrite(&dib_header,1,sizeof(struct bmp_dib_header),fd_out); #ifdef DEBUG_PRINT printf("Out write %lu\n", bytes_written); #endif uint8_t* map_ptr = map; for (int iy=0; iy<y; ++iy){ for (int ix=0; ix<x; ++ix){ int xleft = x - ix; uint8_t tmp[3]; if (xleft>0) { uint8_t value = scale * *map_ptr; tmp[0] = value; tmp[1] = value; tmp[2] = value; map_ptr++; } bytes_written = fwrite(&tmp,1,3,fd_out); // on last write in line add padding if (xleft==1 && padding) { uint8_t pad[4] = {0}; bytes_written = fwrite(&pad,1,padding,fd_out); } } } printf("Closing output %s\n",name); fclose(fd_out); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_vector.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: obamzuro <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/06/09 17:09:11 by obamzuro #+# #+# */ /* Updated: 2019/06/07 17:09:30 by obamzuro ### ########.fr */ /* */ /* ************************************************************************** */ #include "taskmaster_daemon.h" void init_ftvector(t_ftvector *vec) { if (!vec) return ; vec->capacity = 2; vec->len = 0; vec->elem = (void **)malloc(vec->capacity * sizeof(void *)); } void free_ftvector(t_ftvector *vec) { unsigned int i; i = -1; while (++i < vec->len) free(vec->elem[i]); free(vec->elem); } void push_ftvector(t_ftvector *vec, void *line) { void **temp; unsigned int i; if (!vec || !line) return ; if (vec->capacity < vec->len + 1) { vec->capacity *= 2; temp = (void **)malloc(vec->capacity * sizeof(void *)); i = -1; while (++i < vec->len) temp[i] = vec->elem[i]; free(vec->elem); vec->elem = temp; } vec->elem[vec->len] = line; ++vec->len; }
C
#include "function.h" #include <stdlib.h> Node* createList(int *a, int size) { Node *root; Node **now = &root; for (int i = 0; i < size; i++) { *now = malloc(sizeof(Node)); (*now)->data = a[i]; (*now)->next = NULL; now = &(*now)->next; } return root; } void push_front(Node** head, int val) { Node *root = malloc(sizeof(Node)); root->data = val; root->next = *head; *head = root; } void deleteElementByIdx(Node** head, int idx) { Node **now = head; while (idx--) { now = &(*now)->next; if (*now == NULL) return; } Node *del = *now; *now = del->next; free(del); } Node* copyList(Node* head) { Node *root; Node **now = &root; Node *onow = head; while (onow != NULL) { *now = malloc(sizeof(Node)); (*now)->data = onow->data; (*now)->next = NULL; now = &(*now)->next; onow = onow->next; } return root; } void SwapElementByIdx(Node** head, int idx1, int idx2) { if (idx1 > idx2) { int tmp = idx1; idx1 = idx2; idx2 = tmp; } Node *now = *head; for (int i = 0; i < idx1; i++) { now = now->next; if (now == NULL) return; } Node *n1 = now; for (int i = idx1; i < idx2; i++) { now = now->next; if (now == NULL) return; } Node *n2 = now; int tmp = n1->data; n1->data = n2->data; n2->data = tmp; }
C
#include "holberton.h" #include <stdio.h> /** * append_text_to_file - appends text to a file * @filename: file to append to, if NULL, return -1 * @text_content: content to append, if NULL, do not append * Return: 1 on success, -1 on failure */ int append_text_to_file(const char *filename, char *text_content) { int append_file, len, wr_stat; if (filename == NULL) return (-1); append_file = open(filename, O_WRONLY | O_APPEND); if (append_file == -1) return (-1); if (text_content == NULL) return (1); for (len = 0; text_content[len]; len++) ; wr_stat = write(append_file, text_content, len); close(append_file); return (wr_stat == -1 ? -1 : 1); }
C
#include <stdio.h> #include <stdlib.h> int main() { /*O comando do-while: Permite executar, repetidamente e ao menos uma vez um conjunto de comandos de acordo com uma condição //Forma geral: do { conjunto de comandos } while(condicao); */ int a, b; printf("Digite dois valor inteiros: "); scanf("%d %d", &a, &b); do { printf("%d\n", a); a++; } while(a < b); /*Risco de Loop Infinito do { printf("%d\n", a); a--; //A condicao sempre sera verdadeira } while(a < b); */ //Condicoes mais complexas do { printf("%d\n", a); a++; } while(a < b && a > 0); //do-while tambem pode ser utilizado para exibir menus int i; do { printf("Escolha uma opcao:\n"); printf("(1) Opcao 1\n"); printf("(2) Opcao 2\n"); printf("(3) Opcao 3\n"); scanf("%d, &i"); } while( (i < 1) || (i > 3) ); printf("Voce escolheu a Opcao %d\n", i); printf("Fim do programa.\n"); system("pause"); return 0; }
C
#include <stdio.h> // main int main(){ int i, j; i = 0; while ( i < 8 ){ if ( i % 2 != 0 ){ printf(" "); }// end if j = 0; while ( j < 8 ){ printf("* "); j++; }// end while printf("\n"); i++; }// end while }// end main
C
/** * Copyright (c) 2020, Evgeniy Morozov * All rights reserved. * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #ifndef RAY_TRACING_ONE_WEEK_RT_RAY_H #define RAY_TRACING_ONE_WEEK_RT_RAY_H typedef struct ray_s { point3_t origin; vec3_t direction; double time; } ray_t; static inline ray_t ray_init(vec3_t origin, vec3_t direction, double time) { ray_t result = {origin, direction, time}; return result; } static inline point3_t ray_at(ray_t ray, double t) { return vec3_sum(ray.origin, vec3_scale(ray.direction, t)); } #endif // RAY_TRACING_ONE_WEEK_RT_RAY_H
C
#include <stdio.h> #include <stdlib.h> int main() { int max, min, numbers[5]; while(1) { for(int i = 0; i < 5; i++) { printf("пJƦr%d=", (i+1)); scanf("%d", &numbers[i]); } printf("=======================\n"); max=numbers[0]; for(int i = 1; i < 5; i++) { if (numbers[i] > max) max = numbers[i]; } printf("̤j=%d\n\n", max); } return 0; }
C
#include<stdio.h> void main() { int n1,n2,n3; printf("enter the three number:\n"); scanf("%d%d%d",&n1,&n2,&n3); if(n1>=n2&&n1>=n3) printf("%d is the largest number.",n1); if(n2>=n1&&n2>=n3) printf("%d is the largest number.",n2); if(n3>=n1&&n3>=n2) printf("%d is the largest number.",n3); }
C
#include<stdio.h> int main() { int t; scanf("%d",&t); int i; for(i=0;i<t;++i){ int n; scanf("%d",&n); int num=0; int j; for(j=2;j<=n/2;j++){ if(!(n%j)&&n/j%2==1){ num++; } } printf("case #%d:\n",i); printf("%d\n",num); } return 0; }
C
#include <signal.h> /** * sigset_init - initializes a sigset * @set: a signal set * @signals: 0 terminated array of signals * Return: 0 on success, -1 on error */ int sigset_init(sigset_t *set, int *signals) { int check_ret, signb; check_ret = sigemptyset(set); if (check_ret) return (-1); while ((signb = *signals++) != 0) { check_ret = sigaddset(set, signb); if (check_ret) return (-1); } return (0); }
C
#include "InternalBdsLib.h" #include <Guid/ByoGlobalVariable.h> /** Get the Option Number that wasn't used. @param OrderVariableName Could be L"BootOrder", L"DriverOrder" or L"KeyOrder". @param FreeOptionNumber To receive the minimal free option number. @retval EFI_SUCCESS The option number is found @retval EFI_OUT_OF_RESOURCES There is no free option number that can be used. @retval EFI_INVALID_PARAMETER FreeOptionNumber is NULL **/ EFI_STATUS GetFreeOptionNumber ( IN CHAR16 *OrderVariableName, OUT UINT16 *FreeOptionNumber, IN EFI_GUID *VendorGuid ) { UINTN OptionNumber; UINTN Index; UINT16 *OptionOrder; UINTN OptionOrderSize; UINT16 *BootNext; if (FreeOptionNumber == NULL) { return EFI_INVALID_PARAMETER; } OptionOrder = EfiBootManagerGetVariableAndSize ( OrderVariableName, VendorGuid, &OptionOrderSize ); BootNext = NULL; if (*OrderVariableName == L'B') { BootNext = GetEfiGlobalVariable (L"BootNext"); } for (OptionNumber = 0; OptionNumber < OptionOrderSize / sizeof (UINT16) + ((BootNext != NULL) ? 1 : 0); OptionNumber++ ) { // // Search in OptionOrder whether the OptionNumber exists // for (Index = 0; Index < OptionOrderSize / sizeof (UINT16); Index++) { if (OptionNumber == OptionOrder[Index]) { break; } } // // We didn't find it in the ****Order array and it doesn't equal to BootNext // Otherwise, OptionNumber equals to OptionOrderSize / sizeof (UINT16) + 1 // if ((Index == OptionOrderSize / sizeof (UINT16)) && ((BootNext == NULL) || (OptionNumber != *BootNext)) ) { break; } } if (OptionOrder != NULL) { FreePool (OptionOrder); } if (BootNext != NULL) { FreePool (BootNext); } // // When BootOrder & BootNext conver all numbers in the range [0 ... 0xffff], // OptionNumber equals to 0x10000 which is not valid. // ASSERT (OptionNumber <= 0x10000); if (OptionNumber == 0x10000) { return EFI_OUT_OF_RESOURCES; } else { *FreeOptionNumber = (UINT16) OptionNumber; return EFI_SUCCESS; } } /** Create the Boot#### or Driver#### variable from the load option. @param LoadOption Pointer to the load option. @retval EFI_SUCCESS The variable was created. @retval Others Error status returned by RT->SetVariable. **/ EFI_STATUS EFIAPI EfiBootManagerLoadOptionToVariable ( IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *Option ) { UINTN VariableSize; UINT8 *Variable; UINT8 *Ptr; CHAR16 OptionName[sizeof ("Driver####")]; CHAR16 *Description; CHAR16 NullChar; if ((Option->OptionNumber == LoadOptionNumberUnassigned) || (Option->FilePath == NULL) || (Option->OptionType >= LoadOptionTypeMax) ) { return EFI_INVALID_PARAMETER; } // // Convert NULL description to empty description // NullChar = L'\0'; Description = Option->Description; if (Description == NULL) { Description = &NullChar; } /* UINT32 Attributes; UINT16 FilePathListLength; CHAR16 Description[]; EFI_DEVICE_PATH_PROTOCOL FilePathList[]; UINT8 OptionalData[]; TODO: FilePathList[] IS: A packed array of UEFI device paths. The first element of the array is a device path that describes the device and location of the Image for this load option. The FilePathList[0] is specific to the device type. Other device paths may optionally exist in the FilePathList, but their usage is OSV specific. Each element in the array is variable length, and ends at the device path end structure. */ VariableSize = sizeof (Option->Attributes) + sizeof (UINT16) + StrSize (Description) + GetDevicePathSize (Option->FilePath) + Option->OptionalDataSize; Variable = AllocatePool (VariableSize); ASSERT (Variable != NULL); Ptr = Variable; *(UINT32 *) Ptr = Option->Attributes; Ptr += sizeof (Option->Attributes); *(UINT16 *) Ptr = (UINT16) GetDevicePathSize (Option->FilePath); Ptr += sizeof (UINT16); CopyMem (Ptr, Description, StrSize (Description)); Ptr += StrSize (Description); CopyMem (Ptr, Option->FilePath, GetDevicePathSize (Option->FilePath)); Ptr += GetDevicePathSize (Option->FilePath); CopyMem (Ptr, Option->OptionalData, Option->OptionalDataSize); UnicodeSPrint ( OptionName, sizeof (OptionName), (Option->OptionType == LoadOptionTypeBoot) ? L"Boot%04x" : L"Driver%04x", Option->OptionNumber ); return gRT->SetVariable ( OptionName, &gEfiGlobalVariableGuid, EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE, VariableSize, Variable ); } /** This function will register the new boot#### or driver#### option. After the boot#### or driver#### updated, the BootOrder or DriverOrder will also be updated. @param Option Pointer to load option to add. @param Position Position of the new load option to put in the ****Order variable. @retval EFI_SUCCESS The boot#### or driver#### have been successfully registered. @retval EFI_INVALID_PARAMETER The option number exceeds 0xFFFF. @retval EFI_ALREADY_STARTED The option number of Option is being used already. Note: this API only adds new load option, no replacement support. @retval EFI_OUT_OF_RESOURCES There is no free option number that can be used when the option number specified in the Option is LoadOptionNumberUnassigned. @retval EFI_STATUS Return the status of gRT->SetVariable (). **/ EFI_STATUS EFIAPI EfiBootManagerAddLoadOptionVariable ( IN EFI_BOOT_MANAGER_LOAD_OPTION *Option, IN UINTN Position ) { EFI_STATUS Status; UINT16 OptionNumber; if (Option == NULL) { return EFI_INVALID_PARAMETER; } // // Get the free option number if the option number is unassigned // if (Option->OptionNumber == LoadOptionNumberUnassigned) { Status = GetFreeOptionNumber ( Option->OptionType == LoadOptionTypeBoot ? L"BootOrder" : L"DriverOrder", &OptionNumber, &gEfiGlobalVariableGuid ); if (EFI_ERROR (Status)) { return Status; } Option->OptionNumber = OptionNumber; } if (Option->OptionNumber >= LoadOptionNumberMax) { return EFI_INVALID_PARAMETER; } Status = AddOptionNumberToOrderVariable ( Option->OptionType == LoadOptionTypeBoot ? L"BootOrder" : L"DriverOrder", (UINT16) Option->OptionNumber, Position, &gEfiGlobalVariableGuid ); if (!EFI_ERROR (Status)) { // // Save the Boot#### or Driver#### variable // Status = EfiBootManagerLoadOptionToVariable (Option); } return Status; } /** This function will register the new boot#### or driver#### option. After the boot#### or driver#### updated, the BootOrder or DriverOrder will also be updated. @param Option Pointer to load option to add. @retval EFI_SUCCESS The boot#### or driver#### have been successfully registered. @retval EFI_INVALID_PARAMETER The option number exceeds 0xFFFF. @retval EFI_ALREADY_STARTED The option number of Option is being used already. Note: this API only adds new load option, no replacement support. @retval EFI_OUT_OF_RESOURCES There is no free option number that can be used when the option number specified in the Option is LoadOptionNumberUnassigned. @retval EFI_STATUS Return the status of gRT->SetVariable (). **/ EFI_STATUS EFIAPI EfiBootManagerModifyOptionVariable ( IN EFI_BOOT_MANAGER_LOAD_OPTION *Option ) { EFI_STATUS Status; if (Option == NULL) { return EFI_INVALID_PARAMETER; } // // Get the free option number if the option number is unassigned // if (Option->OptionNumber == LoadOptionNumberUnassigned) { return EFI_INVALID_PARAMETER; } if (Option->OptionNumber >= LoadOptionNumberMax) { return EFI_INVALID_PARAMETER; } // // Save the Boot#### or Driver#### variable // Status = EfiBootManagerLoadOptionToVariable (Option); return Status; } EFI_STATUS AddOptionNumberToOrderVariable ( IN CHAR16 *OrderVariableName, IN UINT16 OptionNumber, IN UINTN Position, IN EFI_GUID *VendorGuid ) { EFI_STATUS Status; UINTN Index; UINT16 *OptionOrder; UINT16 *NewOptionOrder; UINTN OptionOrderSize; // // Update the option order variable // OptionOrder = EfiBootManagerGetVariableAndSize ( OrderVariableName, VendorGuid, &OptionOrderSize ); Status = EFI_SUCCESS; for (Index = 0; Index < OptionOrderSize / sizeof (UINT16); Index++) { if (OptionOrder[Index] == OptionNumber) { Status = EFI_ALREADY_STARTED; break; } } if (!EFI_ERROR (Status)) { Position = MIN (Position, OptionOrderSize / sizeof (UINT16)); NewOptionOrder = AllocatePool (OptionOrderSize + sizeof (UINT16)); CopyMem (NewOptionOrder, OptionOrder, Position * sizeof (UINT16)); CopyMem (&NewOptionOrder[Position + 1], &OptionOrder[Position], OptionOrderSize - Position * sizeof (UINT16)); NewOptionOrder[Position] = OptionNumber; Status = gRT->SetVariable ( OrderVariableName, VendorGuid, EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE, OptionOrderSize + sizeof (UINT16), NewOptionOrder ); ASSERT_EFI_ERROR (Status); FreePool (NewOptionOrder); } if (OptionOrder != NULL) { FreePool (OptionOrder); } return Status; } /** Sort the load option. The DriverOrder or BootOrder will be re-created to reflect the new order. @param OptionType Load option type @param Comparator The comparator **/ VOID EFIAPI EfiBootManagerSortLoadOptionVariable ( EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType, EFI_BOOT_MANAGER_LOAD_OPTION_COMPARATOR Comparator ) { EFI_BOOT_MANAGER_LOAD_OPTION *LoadOption; EFI_BOOT_MANAGER_LOAD_OPTION TempOption; UINTN LoadOptionCount; UINTN IndexI; UINTN IndexJ; UINT16 *OptionOrder; UINTN Start; DEBUG((EFI_D_INFO, "%a()\n", __FUNCTION__)); LoadOption = EfiBootManagerGetLoadOptions (&LoadOptionCount, OptionType); Start = 0; // // Always put the BootNext as the first // if ((LoadOptionCount > 0) && LoadOption[0].BootNext) { Start = 1; } // // Insertion sort algorithm // for (IndexI = Start + 1; IndexI < LoadOptionCount; IndexI++) { // // for IndexI, find a proper position in [Start .. IndexI) // for (IndexJ = Start; IndexJ < IndexI; IndexJ++) { if (Comparator (&LoadOption[IndexI], &LoadOption[IndexJ])) { CopyMem (&TempOption, &LoadOption[IndexI], sizeof (EFI_BOOT_MANAGER_LOAD_OPTION)); CopyMem (&LoadOption[IndexJ + 1], &LoadOption[IndexJ], (IndexI - IndexJ) * sizeof (EFI_BOOT_MANAGER_LOAD_OPTION)); CopyMem (&LoadOption[IndexJ], &TempOption, sizeof (EFI_BOOT_MANAGER_LOAD_OPTION)); break; } } } // // Create new ****Order variable // OptionOrder = AllocatePool ((LoadOptionCount - Start) * sizeof (UINT16)); for (IndexI = Start; IndexI < LoadOptionCount; IndexI++) { OptionOrder[IndexI - Start] = (UINT16) LoadOption[IndexI].OptionNumber; } gRT->SetVariable ( OptionType == LoadOptionTypeBoot ? L"BootOrder" : L"DriverOrder", &gEfiGlobalVariableGuid, EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE, (LoadOptionCount - Start)* sizeof (UINT16), OptionOrder ); FreePool (OptionOrder); EfiBootManagerFreeLoadOptions (LoadOption, LoadOptionCount); } /** Initialize the load option. @param OptionNumber Point to option number and NULL requests to auto-generate the option number **/ EFI_STATUS EFIAPI EfiBootManagerInitializeLoadOption ( IN OUT EFI_BOOT_MANAGER_LOAD_OPTION *Option, IN UINTN OptionNumber, IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType, IN UINT32 Attributes, IN CHAR16 *Description, IN EFI_DEVICE_PATH_PROTOCOL *FilePath, IN UINT8 *OptionalData, OPTIONAL IN UINT32 OptionalDataSize ) { if ((Option == NULL) || (Description == NULL) || (FilePath == NULL)) { return EFI_INVALID_PARAMETER; } if (((OptionalData != NULL) && (OptionalDataSize == 0)) || ((OptionalData == NULL) && (OptionalDataSize != 0))) { return EFI_INVALID_PARAMETER; } ZeroMem (Option, sizeof (EFI_BOOT_MANAGER_LOAD_OPTION)); Option->OptionNumber = OptionNumber; Option->OptionType = OptionType; Option->Attributes = Attributes; Option->Description = AllocateCopyPool (StrSize (Description), Description); Option->FilePath = DuplicateDevicePath (FilePath); if (OptionalData != NULL) { Option->OptionalData = AllocateCopyPool (OptionalDataSize, OptionalData); Option->OptionalDataSize = OptionalDataSize; } return EFI_SUCCESS; } /** Return the index of the load option in the load option array. The function compares the OptionType, Attributes, Description, FilePath, OptionalData. **/ INTN EFIAPI EfiBootManagerFindLoadOption ( IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *Key, IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *Array, IN UINTN Count ) { UINTN Index; for (Index = 0; Index < Count; Index++) { if ((Key->OptionType == Array[Index].OptionType) && (Key->Attributes == Array[Index].Attributes) && (StrCmp (Key->Description, Array[Index].Description) == 0) && (CompareMem (Key->FilePath, Array[Index].FilePath, GetDevicePathSize (Key->FilePath)) == 0) && (Key->OptionalDataSize == Array[Index].OptionalDataSize) && (CompareMem (Key->OptionalData, Array[Index].OptionalData, Key->OptionalDataSize) == 0)) { return (INTN) Index; } } return -1; } /** Return the index of the load option in the load option array. The function compares the OptionType, Attributes, Description, FilePath, OptionalData. **/ INTN EFIAPI ByoEfiBootManagerFindLoadOption ( IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *Key, IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *Array, IN UINTN Count, IN OUT UINTN *OptionNumber ) { UINTN Index; *OptionNumber = 0xffff; for (Index = 0; Index < Count; Index++) { if((StrCmp (Key->Description, Array[Index].Description) == 0) && ((StrCmp (Key->Description, L"Internal EDK Shell") == 0) || (StrCmp (Key->Description, L"Boot Device List") == 0) || (StrCmp (Key->Description, L"Enter Setup") == 0))) { *OptionNumber = Index; } if ((Key->OptionType == Array[Index].OptionType) && (Key->Attributes == Array[Index].Attributes) && (StrCmp (Key->Description, Array[Index].Description) == 0) && (CompareMem (Key->FilePath, Array[Index].FilePath, GetDevicePathSize (Key->FilePath)) == 0) && (Key->OptionalDataSize == Array[Index].OptionalDataSize) && (CompareMem (Key->OptionalData, Array[Index].OptionalData, Key->OptionalDataSize) == 0)) { return (INTN) Index; } } return -1; } EFI_STATUS DeleteOptionVariable ( IN CHAR16 *OptionOrderVariable, IN UINT16 OptionNumber, IN EFI_GUID *VendorGuid ) { UINT16 *OptionOrder; UINTN OptionOrderSize; EFI_STATUS Status; UINTN Index; Status = EFI_NOT_FOUND; OptionOrder = EfiBootManagerGetVariableAndSize ( OptionOrderVariable, VendorGuid, &OptionOrderSize ); for (Index = 0; Index < OptionOrderSize / sizeof (UINT16); Index++) { if (OptionOrder[Index] == OptionNumber) { OptionOrderSize -= sizeof (UINT16); CopyMem (&OptionOrder[Index], &OptionOrder[Index + 1], OptionOrderSize - Index * sizeof (UINT16)); Status = gRT->SetVariable ( OptionOrderVariable, VendorGuid, EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE, OptionOrderSize, OptionOrder ); ASSERT_EFI_ERROR (Status); break; } } if (OptionOrder != NULL) { FreePool (OptionOrder); } return Status; } /** Update the BootOrder or DriverOrder according to the OptionType to delete OptionNumber . @param OptionNumber Indicate the option number of load option @param OptionType Indicate the type of load option @retval EFI_INVALID_PARAMETER OptionType or OptionNumber is invalid. @retval EFI_NOT_FOUND The load option cannot be found @retval EFI_SUCCESS The load option was deleted **/ EFI_STATUS EFIAPI EfiBootManagerDeleteLoadOptionVariable ( IN UINTN OptionNumber, IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType ) { if ((OptionType >= LoadOptionTypeMax) || (OptionNumber >= LoadOptionNumberMax)) { return EFI_INVALID_PARAMETER; } return DeleteOptionVariable ( OptionType == LoadOptionTypeBoot ? L"BootOrder" : L"DriverOrder", (UINT16) OptionNumber, &gEfiGlobalVariableGuid ); } /** Update the BootOrder or DriverOrder according to the OptionType to delete OptionNumber . @param OptionNumber Indicate the option number of load option @param OptionType Indicate the type of load option @retval EFI_INVALID_PARAMETER OptionType or OptionNumber is invalid. @retval EFI_NOT_FOUND The load option cannot be found @retval EFI_SUCCESS The load option was deleted **/ EFI_STATUS EFIAPI ByoEfiBootManagerDeleteLoadOptionVariable ( IN UINTN OptionNumber, IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType ) { if ((OptionType >= LoadOptionTypeMax) || (OptionNumber >= LoadOptionNumberMax)) { return EFI_INVALID_PARAMETER; } return DeleteOptionVariable ( OptionType == LoadOptionTypeBoot ? L"BootOrderTemp" : L"DriverOrderTemp", (UINT16) OptionNumber, &gByoGlobalVariableGuid ); } /** Convert a single character to number. It assumes the input Char is in the scope of L'0' ~ L'9' and L'A' ~ L'F' **/ UINTN CharToUint ( IN CHAR16 Char ) { if ((Char >= L'0') && (Char <= L'9')) { return (UINTN) (Char - L'0'); } if ((Char >= L'A') && (Char <= L'F')) { return (UINTN) (Char - L'A' + 0xA); } ASSERT (FALSE); return 0; } /** Build the Boot#### or Driver#### option from the VariableName. @param VariableName EFI Variable name indicate if it is Boot#### or Driver#### @retval EFI_SUCCESS Get the option just been created @retval EFI_NOT_FOUND Failed to get the new option **/ EFI_STATUS EFIAPI EfiBootManagerVariableToLoadOption ( IN CHAR16 *VariableName, IN OUT EFI_BOOT_MANAGER_LOAD_OPTION *Option ) { EFI_STATUS Status; UINT32 Attribute; UINT16 FilePathSize; UINT8 *Variable; UINT8 *TempPtr; UINTN VariableSize; EFI_DEVICE_PATH_PROTOCOL *FilePath; UINT8 *OptionalData; UINT32 OptionalDataSize; CHAR16 *Description; UINT8 NumOff; EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType; UINT16 OptionNumber; if ((VariableName == NULL) || (Option == NULL)) { return EFI_INVALID_PARAMETER; } // // Read the variable // Variable = EfiBootManagerGetVariableAndSize ( VariableName, &gEfiGlobalVariableGuid, &VariableSize ); if (Variable == NULL) { return EFI_NOT_FOUND; } // // Notes: careful defined the variable of Boot#### or // Driver####, consider use some macro to abstract the code // // // Get the option attribute // TempPtr = Variable; Attribute = *(UINT32 *) Variable; TempPtr += sizeof (UINT32); // // Get the option's device path size // FilePathSize = *(UINT16 *) TempPtr; TempPtr += sizeof (UINT16); // // Get the option's description string // Description = (CHAR16 *) TempPtr; // // Get the option's description string size // TempPtr += StrSize ((CHAR16 *) TempPtr); // // Get the option's device path // FilePath = (EFI_DEVICE_PATH_PROTOCOL *) TempPtr; TempPtr += FilePathSize; OptionalDataSize = (UINT32) (VariableSize - (UINTN) (TempPtr - Variable)); if (OptionalDataSize == 0) { OptionalData = NULL; } else { OptionalData = TempPtr; } if (*VariableName == L'B') { OptionType = LoadOptionTypeBoot; NumOff = (UINT8) (sizeof (L"Boot") / sizeof (CHAR16) - 1); } else { OptionType = LoadOptionTypeDriver; NumOff = (UINT8) (sizeof (L"Driver") / sizeof (CHAR16) - 1); } // // Get the value from VariableName Unicode string // since the ISO standard assumes ASCII equivalent abbreviations, we can be safe in converting this // Unicode stream to ASCII without any loss in meaning. // OptionNumber = (UINT16) (CharToUint (VariableName[NumOff+0]) * 0x1000) + (UINT16) (CharToUint (VariableName[NumOff+1]) * 0x100) + (UINT16) (CharToUint (VariableName[NumOff+2]) * 0x10) + (UINT16) (CharToUint (VariableName[NumOff+3]) * 0x1); Status = EfiBootManagerInitializeLoadOption ( Option, OptionNumber, OptionType, Attribute, Description, FilePath, OptionalData, OptionalDataSize ); ASSERT_EFI_ERROR (Status); FreePool (Variable); return Status; } /** Build the Boot#### or Driver#### option from the VariableName. @param VariableName EFI Variable name indicate if it is Boot#### or Driver#### @retval EFI_SUCCESS Get the option just been created @retval EFI_NOT_FOUND Failed to get the new option **/ EFI_STATUS EFIAPI ByoEfiBootManagerVariableToLoadOption ( IN CHAR16 *VariableName, IN OUT EFI_BOOT_MANAGER_LOAD_OPTION *Option ) { EFI_STATUS Status; UINT32 Attribute; UINT16 FilePathSize; UINT8 *Variable; UINT8 *TempPtr; UINTN VariableSize; EFI_DEVICE_PATH_PROTOCOL *FilePath; UINT8 *OptionalData; UINT32 OptionalDataSize; CHAR16 *Description; UINT8 NumOff; EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType; UINT16 OptionNumber; if ((VariableName == NULL) || (Option == NULL)) { return EFI_INVALID_PARAMETER; } // // Read the variable // Variable = EfiBootManagerGetVariableAndSize ( VariableName, &gByoGlobalVariableGuid, &VariableSize ); if (Variable == NULL) { return EFI_NOT_FOUND; } // // Notes: careful defined the variable of Boot#### or // Driver####, consider use some macro to abstract the code // // // Get the option attribute // TempPtr = Variable; Attribute = *(UINT32 *) Variable; TempPtr += sizeof (UINT32); // // Get the option's device path size // FilePathSize = *(UINT16 *) TempPtr; TempPtr += sizeof (UINT16); // // Get the option's description string // Description = (CHAR16 *) TempPtr; // // Get the option's description string size // TempPtr += StrSize ((CHAR16 *) TempPtr); // // Get the option's device path // FilePath = (EFI_DEVICE_PATH_PROTOCOL *) TempPtr; TempPtr += FilePathSize; OptionalDataSize = (UINT32) (VariableSize - (UINTN) (TempPtr - Variable)); if (OptionalDataSize == 0) { OptionalData = NULL; } else { OptionalData = TempPtr; } if (*VariableName == L'B') { OptionType = LoadOptionTypeBoot; NumOff = (UINT8) (sizeof (L"BootTemp") / sizeof (CHAR16) - 1); } else { OptionType = LoadOptionTypeDriver; NumOff = (UINT8) (sizeof (L"DriverTemp") / sizeof (CHAR16) - 1); } // // Get the value from VariableName Unicode string // since the ISO standard assumes ASCII equivalent abbreviations, we can be safe in converting this // Unicode stream to ASCII without any loss in meaning. // OptionNumber = (UINT16) (CharToUint (VariableName[NumOff+0]) * 0x1000) + (UINT16) (CharToUint (VariableName[NumOff+1]) * 0x100) + (UINT16) (CharToUint (VariableName[NumOff+2]) * 0x10) + (UINT16) (CharToUint (VariableName[NumOff+3]) * 0x1); Status = EfiBootManagerInitializeLoadOption ( Option, OptionNumber, OptionType, Attribute, Description, FilePath, OptionalData, OptionalDataSize ); ASSERT_EFI_ERROR (Status); FreePool (Variable); return Status; } /** Process BootOrder, or DriverOrder variables, by calling BdsLibVariableToOption () for each UINT16 in the variables. @param BdsCommonOptionList The header of the option list base on variable VariableName @param VariableName EFI Variable name indicate the BootOrder or DriverOrder @retval EFI_SUCCESS Success create the boot option or driver option list @retval EFI_OUT_OF_RESOURCES Failed to get the boot option or driver option list **/ EFI_BOOT_MANAGER_LOAD_OPTION * EfiBootManagerGetLoadOptions ( OUT UINTN *OptionCount, IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE LoadOptionType ) { EFI_STATUS Status; UINT16 *BootNext; UINT16 *OptionOrder; UINTN OptionOrderSize; UINTN Index; UINTN OptionIndex; EFI_BOOT_MANAGER_LOAD_OPTION *Option; CHAR16 OptionName[sizeof ("Driver####")]; UINT16 OptionNumber; *OptionCount = 0; BootNext = NULL; if (LoadOptionType == LoadOptionTypeBoot) { BootNext = GetEfiGlobalVariable (L"BootNext"); } // // Read the BootOrder, or DriverOrder variable. // OptionOrder = EfiBootManagerGetVariableAndSize ( (LoadOptionType == LoadOptionTypeBoot) ? L"BootOrder" : L"DriverOrder", &gEfiGlobalVariableGuid, &OptionOrderSize ); if (OptionOrder == NULL && BootNext == NULL) { return NULL; } *OptionCount = ((BootNext != NULL) ? 1 : 0) + OptionOrderSize / sizeof (UINT16); Option = AllocatePool (*OptionCount * sizeof (EFI_BOOT_MANAGER_LOAD_OPTION)); ASSERT (Option != NULL); OptionIndex = 0; for (Index = 0; Index < *OptionCount; Index++) { if (BootNext == NULL) { OptionNumber = OptionOrder[Index]; } else { OptionNumber = ((Index == 0) ? *BootNext : OptionOrder[Index - 1]); } if (LoadOptionType == LoadOptionTypeBoot) { UnicodeSPrint (OptionName, sizeof (OptionName), L"Boot%04x", OptionNumber); } else { UnicodeSPrint (OptionName, sizeof (OptionName), L"Driver%04x", OptionNumber); } Status = EfiBootManagerVariableToLoadOption (OptionName, &Option[OptionIndex]); if (EFI_ERROR (Status)) { DEBUG ((EFI_D_INFO, "[Bds] %s %r - [Delete]\n", OptionName, Status)); EfiBootManagerDeleteLoadOptionVariable (OptionNumber, LoadOptionTypeBoot); } else { ASSERT (Option[OptionIndex].OptionNumber == OptionNumber); if ((BootNext != NULL) && (*BootNext == Option[OptionIndex].OptionNumber)) { Option[OptionIndex].BootNext = TRUE; } OptionIndex++; } } if (OptionOrder != NULL) { FreePool (OptionOrder); } if (BootNext != NULL) { FreePool (BootNext); } if (OptionIndex < *OptionCount) { Option = ReallocatePool ( *OptionCount * sizeof (EFI_BOOT_MANAGER_LOAD_OPTION), OptionIndex * sizeof (EFI_BOOT_MANAGER_LOAD_OPTION), Option ); *OptionCount = OptionIndex; } return Option; } /** Process BootOrder, or DriverOrder variables, by calling BdsLibVariableToOption () for each UINT16 in the variables. @param BdsCommonOptionList The header of the option list base on variable VariableName @param VariableName EFI Variable name indicate the BootOrder or DriverOrder @retval EFI_SUCCESS Success create the boot option or driver option list @retval EFI_OUT_OF_RESOURCES Failed to get the boot option or driver option list **/ EFI_BOOT_MANAGER_LOAD_OPTION * ByoEfiBootManagerGetLoadOptions ( OUT UINTN *OptionCount, IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE LoadOptionType ) { EFI_STATUS Status; UINT16 *BootNext; UINT16 *OptionOrder; UINTN OptionOrderSize; UINTN Index; UINTN OptionIndex; EFI_BOOT_MANAGER_LOAD_OPTION *Option; CHAR16 OptionName[sizeof ("DriverTemp####")]; UINT16 OptionNumber; *OptionCount = 0; BootNext = NULL; if (LoadOptionType == LoadOptionTypeBoot) { BootNext = GetEfiGlobalVariable (L"BootNext"); } // // Read the BootOrder, or DriverOrder variable. // OptionOrder = EfiBootManagerGetVariableAndSize ( (LoadOptionType == LoadOptionTypeBoot) ? L"BootOrderTemp" : L"DriverOrderTemp", &gByoGlobalVariableGuid, &OptionOrderSize ); if (OptionOrder == NULL && BootNext == NULL) { return NULL; } DEBUG((EFI_D_ERROR, "ByoEfiBootManagerGetLoadOptions, OptionCount is 0x%x.\n", OptionOrderSize / sizeof (UINT16))); *OptionCount = ((BootNext != NULL) ? 1 : 0) + OptionOrderSize / sizeof (UINT16); Option = AllocatePool (*OptionCount * sizeof (EFI_BOOT_MANAGER_LOAD_OPTION)); ASSERT (Option != NULL); OptionIndex = 0; for (Index = 0; Index < *OptionCount; Index++) { if (BootNext == NULL) { OptionNumber = OptionOrder[Index]; } else { OptionNumber = ((Index == 0) ? *BootNext : OptionOrder[Index - 1]); } if (LoadOptionType == LoadOptionTypeBoot) { UnicodeSPrint (OptionName, sizeof (OptionName), L"BootTemp%04x", OptionNumber); } else { UnicodeSPrint (OptionName, sizeof (OptionName), L"DriverTemp%04x", OptionNumber); } Status = ByoEfiBootManagerVariableToLoadOption (OptionName, &Option[OptionIndex]); if (EFI_ERROR (Status)) { DEBUG ((EFI_D_INFO, "[Bds] %s %r - [Delete]\n", OptionName, Status)); ByoEfiBootManagerDeleteLoadOptionVariable (OptionNumber, LoadOptionTypeBoot); } else { ASSERT (Option[OptionIndex].OptionNumber == OptionNumber); if ((BootNext != NULL) && (*BootNext == Option[OptionIndex].OptionNumber)) { Option[OptionIndex].BootNext = TRUE; } OptionIndex++; } } if (OptionOrder != NULL) { FreePool (OptionOrder); } if (BootNext != NULL) { FreePool (BootNext); } if (OptionIndex < *OptionCount) { Option = ReallocatePool ( *OptionCount * sizeof (EFI_BOOT_MANAGER_LOAD_OPTION), OptionIndex * sizeof (EFI_BOOT_MANAGER_LOAD_OPTION), Option ); *OptionCount = OptionIndex; } return Option; } /** Free an EFI_BOOT_MANGER_LOAD_OPTION entry that was allocate by the library. @param Option Pointer to boot option to Free. @return EFI_SUCCESS BootOption was freed @return EFI_INVALID_PARAMETER BootOption == NULL **/ EFI_STATUS EFIAPI EfiBootManagerFreeLoadOption ( IN EFI_BOOT_MANAGER_LOAD_OPTION *LoadOption ) { if (LoadOption == NULL) { return EFI_NOT_FOUND; } if (LoadOption->Description != NULL) { FreePool (LoadOption->Description); } if (LoadOption->FilePath != NULL) { FreePool (LoadOption->FilePath); } if (LoadOption->OptionalData != NULL) { FreePool (LoadOption->OptionalData); } return EFI_SUCCESS; } /** Free an EFI_BOOT_MANGER_LOAD_OPTION array that was allocated by EfiBootManagerGetLoadOptions(). @param BootOption Pointer to boot option array to free. @param BootOptionCount Number of array entries in BootOption @return EFI_SUCCESS BootOption was freed @return EFI_NOT_FOUND BootOption == NULL **/ EFI_STATUS EFIAPI EfiBootManagerFreeLoadOptions ( IN EFI_BOOT_MANAGER_LOAD_OPTION *Option, IN UINTN OptionCount ) { UINTN Index; if (Option == NULL) { return EFI_NOT_FOUND; } for (Index = 0;Index < OptionCount; Index++) { EfiBootManagerFreeLoadOption (&Option[Index]); } FreePool (Option); return EFI_SUCCESS; } EFI_STATUS EFIAPI EfiBootManagerDeleteAllUefiBootOption( VOID ) { EFI_BOOT_MANAGER_LOAD_OPTION *NvBootOptions; UINTN NvBootOptionCount; UINTN Index; EFI_DEVICE_PATH_PROTOCOL *FilePath; NvBootOptions = EfiBootManagerGetLoadOptions (&NvBootOptionCount, LoadOptionTypeBoot); for (Index = 0; Index < NvBootOptionCount; Index++) { FilePath = NvBootOptions[Index].FilePath; if (DevicePathType(FilePath) == BBS_DEVICE_PATH) { continue; } if((NvBootOptions[Index].Attributes & LOAD_OPTION_CATEGORY) == LOAD_OPTION_CATEGORY_APP) { continue; } EfiBootManagerDeleteLoadOptionVariable(NvBootOptions[Index].OptionNumber, LoadOptionTypeBoot); } EfiBootManagerFreeLoadOptions (NvBootOptions, NvBootOptionCount); return EFI_SUCCESS; } EFI_STATUS CreateFvBootOption ( EFI_GUID *FileGuid, CHAR16 *Description, EFI_BOOT_MANAGER_LOAD_OPTION *BootOption, BOOLEAN IsBootCategory, UINT8 *OptionalData, OPTIONAL UINT32 OptionalDataSize ) { EFI_STATUS Status; EFI_DEVICE_PATH_PROTOCOL *DevicePath; EFI_LOADED_IMAGE_PROTOCOL *LoadedImage; MEDIA_FW_VOL_FILEPATH_DEVICE_PATH FileNode; EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv; UINT32 AuthenticationStatus; VOID *Buffer; UINTN Size; UINT32 Attributes; if ((BootOption == NULL) || (FileGuid == NULL) || (Description == NULL)) { return EFI_INVALID_PARAMETER; } EfiInitializeFwVolDevicepathNode (&FileNode, FileGuid); Status = gBS->HandleProtocol ( gImageHandle, &gEfiLoadedImageProtocolGuid, (VOID **) &LoadedImage ); if (!EFI_ERROR (Status)) { Status = gBS->HandleProtocol ( LoadedImage->DeviceHandle, &gEfiFirmwareVolume2ProtocolGuid, (VOID **) &Fv ); if (!EFI_ERROR (Status)) { Buffer = NULL; Size = 0; Status = Fv->ReadSection ( Fv, FileGuid, EFI_SECTION_PE32, 0, &Buffer, &Size, &AuthenticationStatus ); if (Buffer != NULL) { FreePool (Buffer); } } } if (EFI_ERROR (Status)) { return EFI_NOT_FOUND; } DevicePath = AppendDevicePathNode ( DevicePathFromHandle (LoadedImage->DeviceHandle), (EFI_DEVICE_PATH_PROTOCOL *) &FileNode ); Attributes = LOAD_OPTION_ACTIVE; if(IsBootCategory){ Attributes |= LOAD_OPTION_CATEGORY_BOOT; } else { Attributes |= LOAD_OPTION_CATEGORY_APP; } Status = EfiBootManagerInitializeLoadOption ( BootOption, LoadOptionNumberUnassigned, LoadOptionTypeBoot, Attributes, Description, DevicePath, OptionalData, OptionalDataSize ); FreePool (DevicePath); return Status; }
C
#include<stdio.h> int main() { //input do sistema int a, b, c, d; printf("Digite quatro numeros\n"); scanf("%d %d %d %d", &a, &b, &c, &d); //compilar dado double soma; soma = (a + b + c +d); // output dos dados printf("O resultado da soma de %d, %d, %d e %d é %f", a, b, c, d, soma); return 0; }
C
#if !defined(DSM_MSG_H) #define DSM_MSG_H #include <sys/types.h> #include "dsm_htab.h" /* ******************************************************************************* * Type Definitions * ******************************************************************************* */ // TYPE: All message types. (A = arbiter, S = server, D = daemon, P = process). typedef enum { MSG_MIN_VALUE = 0, MSG_GET_SESSION, // [A->D] Request for session info. MSG_SET_SESSION, // [S->D] Update as session owner. MSG_DEL_SESSION, // [S->D] Request session deletion. MSG_SET_GID, // [S->A] Arbiter must set process gid. MSG_STOP_ALL, // [S->A] Arbiter must suspend proc's. MSG_CONT_ALL, // [S->A] Arbiter may resume proc's. MSG_WAIT_DONE, // [S->A] Arbiter can release barrier. MSG_WRITE_OKAY, // [S->A] Arbiter may write. MSG_ADD_PROC, // [P->A->S] Register new process. MSG_SYNC_REQ, // [P->A->S] Request for write perms. MSG_SYNC_INFO, // [P->A->S] Sends sync info. MSG_STOP_DONE, // [A->S] Confirms all proc's paused. MSG_SYNC_DONE, // [A->S] Confirms received all data. MSG_WAIT_BARR, // [A->S] Arbiter is waiting on barrier. MSG_PRGM_DONE, // [A->S] Arbiter is exiting. MSG_MAX_VALUE } dsm_msg_t; // [Not all message types require additional data. See those that do below]. // MSG_GET_SESSION: Initialization message payload. typedef struct dsm_msg_get { char sid[DSM_SID_SIZE + 1]; // Session identifier. int nproc; // Number of expected processes. } dsm_msg_get; // MSG_SET_SESSION: Setup message payload. typedef struct dsm_msg_set { char sid[DSM_SID_SIZE + 1]; // Session identifier. unsigned int port; // Port. } dsm_msg_set; // MSG_DEL_SESSION: Delete session payload. typedef struct dsm_msg_del { char sid[DSM_SID_SIZE + 1]; // Session identifier. } dsm_msg_del; // MSG_SYNC_INFO: Sychronization message payload. typedef struct dsm_msg_sync { off_t offset; // Data offset. size_t size; // Data size. char buf[4]; // Byte buffer [TEMP]. } dsm_msg_sync; // MSG_SYNC_DONE + MSG_STOP_DONE: Data receival ack and stop ack. typedef struct dsm_msg_done { unsigned int nproc; } dsm_msg_done; // MSG_ADD_PROC + MSG_SET_GID: Send process information. typedef struct dsm_msg_proc { int pid; // Process ID. int gid; // Global process ID. } dsm_msg_proc; // UNION: Aggregate describing various message payloads. typedef union dsm_msg_payload { dsm_msg_get get; dsm_msg_set set; dsm_msg_del del; dsm_msg_sync sync; dsm_msg_done done; dsm_msg_proc proc; } dsm_msg_payload; // Structure describing message format. typedef struct dsm_msg { dsm_msg_t type; // Type. dsm_msg_payload payload; // Optional payload. } dsm_msg; // Type representing a message action function. typedef void (*dsm_msg_func) (int, dsm_msg *); /* ******************************************************************************* * Function Declarations * ******************************************************************************* */ // Links function to given message type. Returns nonzero on error. int dsm_setMsgFunc (dsm_msg_t type, dsm_msg_func func, dsm_msg_func *fmap); // Returns function for given message type. Returns NULL on error. dsm_msg_func dsm_getMsgFunc (dsm_msg_t type, dsm_msg_func *fmap); // Prints the contents of a message, depending on it's type. void dsm_showMsg (dsm_msg *mp); #endif
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #include <netdb.h> #include <arpa/inet.h> int main(int argc, char *argv[]) { if (argc < 2) { printf("usage: %s port\n", argv[0]); exit(EXIT_FAILURE); } int port = atoi(argv[1]); // Create socket int sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { perror("socket"); exit(EXIT_FAILURE); } // Bind to localhost & port struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); if (bind(sockfd, (struct sockaddr *) &addr, sizeof (addr)) < 0) { perror("bind"); close(sockfd); exit(EXIT_FAILURE); } // Prepare for new connections if (listen(sockfd, 128) < 0) { perror("listen"); close(sockfd); exit(EXIT_FAILURE); } int num_client = 0; while (1) { // Block waiting for a new connection struct sockaddr_in client_addr; socklen_t addrlen = sizeof (client_addr); int clientfd = accept(sockfd, (struct sockaddr *) &client_addr, &addrlen); if (clientfd < 0) { perror("accept"); close(sockfd); exit(EXIT_FAILURE); } // clientfd is now connected! num_client++; printf("Connection #%d from %s:%d\n", num_client, inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port)); char buf[128]; int msg_len = snprintf(buf, sizeof (buf), "Hello, you were client #%d\n", num_client); ssize_t written = write(clientfd, buf, msg_len); // This won't always be the case for streaming sockets... assert (written == msg_len); close(clientfd); } // Wait for keypress... printf("bind complete, now waiting\n"); fgetc(stdin); printf("done\n"); close(sockfd); return EXIT_SUCCESS; }
C
#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int sotiencanrut; printf ("Welcome Vu Nhat Minh come with Techcombank!\n"); printf ("Vui long nhap so tien ban can rut:"); scanf ("%d", &sotiencanrut); if (sotiencanrut%50000==0) printf ("Ban da rut tien thanh cong!"); else printf ("So tien ban rut khong phai la boi so cua 50000!\n Vui long nhap lai!"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "tuple.h" struct tuple *quotientAndRemainder(int nominator, int denominator){ int quotient = nominator / denominator; int remainder = nominator % denominator; struct tuple *t = mkTuple(); setFirst(t, quotient); setSecond(t, remainder); return t; } int main(int argc, char *argv[]) { int nominator = 13; int denominator = 5; struct tuple *t = quotientAndRemainder(nominator, denominator); int quotient = getFirst(t); int remainder = getSecond(t); printf("%d = %d * %d + %d\n", nominator, denominator, quotient, remainder); destroyTuple(t); return 0; }
C
#include "game.h" #include <stdlib.h> #include <stdio.h> #include "tetromino.h" void ResetGame(Game *game){ char name[MAX_NAME_LENGTH]; strncpy(name, game->name, MAX_NAME_LENGTH); TTF_Font *temp = game->font; TTF_Font *temp2 = game->bigFont; *game = (Game){0}; game->font = temp; game->bigFont = temp2; game->menuData.held = 1; strncpy(game->name, name, MAX_NAME_LENGTH); } void InitGame(Game *game){ ResetGame(game); game->shapeX = 5; game->font = TTF_OpenFont("joystix monospace.ttf", 25); game->bigFont = TTF_OpenFont("joystix monospace.ttf", 80); char name[] = "Player"; strncpy(game->name, name, MAX_NAME_LENGTH); } void BoardStateColor(SDL_Renderer *renderer, u8 state){ switch(state){ case STATE_CYAN: SDL_SetRenderDrawColor(renderer, 0, 255, 255, 255); break; case STATE_BLUE: SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255); break; case STATE_ORANGE: SDL_SetRenderDrawColor(renderer, 255, 165, 0, 255); break; case STATE_YELLOW: SDL_SetRenderDrawColor(renderer, 255, 255, 0, 255); break; case STATE_GREEN: SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255); break; case STATE_PURPLE: SDL_SetRenderDrawColor(renderer, 128, 0, 128, 255); break; case STATE_RED: SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255); break; default: SDL_SetRenderDrawColor(renderer, 255, 0, 255, 255); break; } } void DrawPlayArea(Game *game, SDL_Renderer *renderer){ SDL_Rect rect; rect.w = PX_PER_CELL; rect.h = PX_PER_CELL; //Board SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255); for(u8 y = 0; y < BOARD_H; y++){ rect.y = y*PX_PER_CELL; for(u8 x = 0; x < BOARD_W; x++){ rect.x = (x+1)*PX_PER_CELL; if(game->lineInfo[y].destroyTimer){ if(game->lineInfo[y].destroyTimer % 10 > 5){ SDL_SetRenderDrawColor(renderer, 0, 127, 0, 255); SDL_RenderFillRect(renderer, &rect); } } else if(game->board[x][y]){ BoardStateColor(renderer, game->board[x][y]); SDL_RenderFillRect(renderer, &rect); } } } //Shape SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255); for(u8 y = 0; y < 4; y++){ rect.y = (game->shapeY+y)*PX_PER_CELL; for(u8 x = 0; x < 4; x++){ rect.x = (game->shapeX+1+x)*PX_PER_CELL; if(game->currentShape[x][y]){ BoardStateColor(renderer, tetrominos[game->currentShapeId].boardState); SDL_RenderFillRect(renderer, &rect); } } } //Borders SDL_SetRenderDrawColor(renderer, 200, 200, 200, 255); rect.y = (GRID_H-1)*PX_PER_CELL; for(u8 x = 0; x < GRID_W; x++){ rect.x = x*PX_PER_CELL; SDL_RenderFillRect(renderer, &rect); } rect.x = 0; for(u8 y = 0; y < GRID_H; y++){ rect.y = y*PX_PER_CELL; SDL_RenderFillRect(renderer, &rect); } rect.x = (GRID_W-1)*PX_PER_CELL; for(u8 y = 0; y < GRID_H; y++){ rect.y = y*PX_PER_CELL; SDL_RenderFillRect(renderer, &rect); } //Grid SDL_SetRenderDrawColor(renderer, 180, 180, 180, 255); for(u8 x = 0; x <= GRID_W; x++){ SDL_RenderDrawLine(renderer, x*PX_PER_CELL, 0, x*PX_PER_CELL, GRID_H*PX_PER_CELL); } for(u8 y = 0; y <= GRID_H; y++){ SDL_RenderDrawLine(renderer, 0, y*PX_PER_CELL, GRID_W*PX_PER_CELL, y*PX_PER_CELL); } } void DrawTextEx(Game *game, SDL_Renderer *renderer, char* text, i32 x, i32 y, bool centered, bool big){ SDL_Color color = { 0, 0, 0 }; SDL_Surface *surface = 0; if(!big){ surface = TTF_RenderText_Solid(game->font, text, color); }else{ surface = TTF_RenderText_Solid(game->bigFont, text, color); } SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, surface); i32 texW = 0; i32 texH = 0; SDL_QueryTexture(texture, NULL, NULL, &texW, &texH); SDL_Rect dstrect = { x, y, texW, texH }; if(centered){ dstrect.x -= texW/2; } SDL_RenderCopy(renderer, texture, NULL, &dstrect); SDL_DestroyTexture(texture); SDL_FreeSurface(surface); } //Very slow void DrawText(Game *game, SDL_Renderer *renderer, char* text, i32 x, i32 y){ DrawTextEx(game, renderer, text, x, y, false, false); } void DrawUI(Game *game, SDL_Renderer *renderer){ SDL_Rect rect; char buf[32]; rect.w = PX_PER_CELL; rect.h = PX_PER_CELL; i32 ui_y = 0; i32 ui_x = 525; //Score snprintf(buf, 32, "Score: %u", game->score); DrawText(game, renderer, buf, ui_x, ui_y); ui_y += 25; snprintf(buf, 32, "Level: %u", game->level); DrawText(game, renderer, buf, ui_x, ui_y); ui_y += 25; snprintf(buf, 32, "Lines: %u", game->linesCleared); DrawText(game, renderer, buf, ui_x, ui_y); ui_y += 25; //Next shape DrawText(game, renderer, "Next shape:", ui_x, ui_y); ui_y += 50; for(u8 y = 0; y < 4; y++){ rect.y = ui_y+(y)*PX_PER_CELL; for(u8 x = 0; x < 4; x++){ rect.x = ui_x+x*PX_PER_CELL; if(tetrominos[game->nextShapeId].shape[x][y]){ BoardStateColor(renderer, tetrominos[game->nextShapeId].boardState); SDL_RenderFillRect(renderer, &rect); } } } } bool CheckCollision(Game *game, i8 shapeX, i8 shapeY){ for(i8 y = 0; y < 4; y++){ for(i8 x = 0; x < 4; x++){ if(game->currentShape[x][y]){ if(shapeY < 0){ if(shapeX+x >= BOARD_W || shapeX+x < 0){ return true; } } else if(game->board[shapeX+x][shapeY+y] || shapeX+x >= BOARD_W || shapeY+y >= BOARD_H || shapeX+x < 0){ return true; } } } } return false; } void UpdateCurrentShape(Game *game){ for(u8 y = 0; y < 4; y++){ for(u8 x = 0; x < 4; x++){ game->currentShape[x][y] = 0; } } u8 size = tetrominos[game->currentShapeId].size; for(u8 y = 0; y < size; y++){ for(u8 x = 0; x < size; x++){ u8 srcX, srcY; switch(game->currentRotation){ case 0: srcX = x; srcY = y; break; case 1: srcX = y; srcY = size-1-x; break; case 2: srcX = size-1-x; srcY = size-1-y; break; case 3: srcX = size-1-y; srcY = x; break; } game->currentShape[x][y] = tetrominos[game->currentShapeId].shape[srcX][srcY]; } } } void CompleteLine(Game *game, u8 y0){ for(u8 x = 0; x < BOARD_W; x++){ game->board[x][y0] = STATE_EMPTY; } for(u8 y = y0; y > 0; y--){ for(u8 x = 0; x < BOARD_W; x++){ game->board[x][y] = game->board[x][y-1]; } } } void SpawnTetermino(Game *game){ game->shapeY = -2; game->shapeX = BOARD_W/2-2; game->currentShapeId = game->nextShapeId; game->nextShapeId = rand() % TETREMINO_COUNT; UpdateCurrentShape(game); } void DrawMenuEntry(Game *game, SDL_Renderer *renderer, char* text, u32 *uiY, bool active){ DrawTextEx(game, renderer, text, 400, *uiY+active*5*sinf(game->frameNumber*2*M_PI*1.0f/60.0f), 1, 0); *uiY += 50; } bool ProcessMenu(Game *game, u8 *state, u8 menuMin, u8 menuMax){ if(game->menuData.input){ return true; } if(state[SDL_SCANCODE_RETURN]){ if(!game->menuData.held){ game->menuData.held = 1; return true; } }else if(state[SDL_SCANCODE_W]){ if(!game->menuData.held){ game->menuData.counter = game->menuData.counter-1; } game->menuData.held = 1; }else if(state[SDL_SCANCODE_S]){ if(!game->menuData.held){ game->menuData.counter = game->menuData.counter+1; } game->menuData.held = 1; } else{ game->menuData.held = 0; } game->menuData.counter = CLAMP(game->menuData.counter, menuMin, menuMax); return false; } bool MenuTextInput(Game *game, u8 *state, char* buf, u32 bufSize){ if(!game->menuData.input){ game->menuData.input=1; game->menuData.textCounter = strlen(buf); game->menuData.textCounter = CLAMP(game->menuData.textCounter, 0, bufSize-2); } u8 anyHeld = 0; if(state[SDL_SCANCODE_RETURN]){ if(!game->menuData.held){ buf[game->menuData.textCounter] = 0; game->menuData.input = 0; game->menuData.held = 1; return true; } anyHeld = 1; } char name[2]; name[1] = 0; for(char c = 'A'; c <= 'Z'; c++){ name[0] = c; if(!anyHeld && state[SDL_GetScancodeFromName(name)]){ if(!game->menuData.held){ buf[game->menuData.textCounter++] = c; } anyHeld = 1; } } for(char c = '0'; c <= '9'; c++){ name[0] = c; if(!anyHeld && state[SDL_GetScancodeFromName(name)]){ if(!game->menuData.held){ buf[game->menuData.textCounter++] = c; } anyHeld = 1; } } if(state[SDL_SCANCODE_SPACE]){ if(!anyHeld && !game->menuData.held){ buf[game->menuData.textCounter++] = ' '; } anyHeld = 1; } game->menuData.textCounter = CLAMP(game->menuData.textCounter, 0, bufSize-2); if(game->frameNumber % 60 > 30){ buf[game->menuData.textCounter] = '_'; } else{ buf[game->menuData.textCounter] = ' '; } if(state[SDL_SCANCODE_BACKSPACE]){ if(!game->menuData.held && game->menuData.textCounter > 0){ buf[game->menuData.textCounter] = 0; buf[--game->menuData.textCounter] = 0; } anyHeld = 1; } game->menuData.held = anyHeld; return false; } void FrameStart(Game *game, SDL_Renderer *renderer, bool *running){ game->frameNumber++; u8 *state = SDL_GetKeyboardState(NULL); if(ProcessMenu(game, state, 0, 3)){ switch(game->menuData.counter){ case 0: game->state = STATE_PLAY; break; case 1: game->state = STATE_HIGHSCORE; break; case 2: game->state = STATE_OPTIONS; break; case 3: *running = 0; break; default: break; } } SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_RenderClear(renderer); DrawTextEx(game, renderer, "FALLBLOCKS", 400, 200, 1, 1); u32 uiY = 400; DrawMenuEntry(game, renderer, "START GAME", &uiY, game->menuData.counter == 0); DrawMenuEntry(game, renderer, "HIGH SCORES", &uiY, game->menuData.counter == 1); DrawMenuEntry(game, renderer, "OPTIONS", &uiY, game->menuData.counter == 2); DrawMenuEntry(game, renderer, "EXIT", &uiY, game->menuData.counter == 3); ReadScores(&game->highscores); SDL_RenderPresent(renderer); } void FramePlay(Game *game, SDL_Renderer *renderer){ if(!game->notFirstFrame){ SpawnTetermino(game); game->notFirstFrame = 1; } u8 *state = SDL_GetKeyboardState(NULL); bool fall = false; //ROTATION if(!state[SDL_SCANCODE_Q] && !state[SDL_SCANCODE_E]){ game->rotationHeld = 0; } else{ u8 oldRotation = game->currentRotation; if(state[SDL_SCANCODE_Q] && !game->rotationHeld){ game->currentRotation = ((game->currentRotation+1) % 4); game->rotationHeld = 1; } if(state[SDL_SCANCODE_E] && !game->rotationHeld){ game->currentRotation = game->currentRotation-1; game->currentRotation = game->currentRotation % 4; game->rotationHeld = 1; } UpdateCurrentShape(game); if(CheckCollision(game, game->shapeX, game->shapeY)){ game->currentRotation = oldRotation; UpdateCurrentShape(game); } } //MOVEMENT if(game->moveCounter != 0){ game->moveCounter--; } if(state[SDL_SCANCODE_A] && game->moveCounter == 0){ if(!CheckCollision(game, game->shapeX-1, game->shapeY)){ game->shapeX -=1; } } if(state[SDL_SCANCODE_D] && game->moveCounter == 0){ if(!CheckCollision(game, game->shapeX+1, game->shapeY)){ game->shapeX +=1; } } if(!state[SDL_SCANCODE_A] && !state[SDL_SCANCODE_D]){ game->moveCounter = 0; } else{ if(game->moveCounter == 0){ game->moveCounter = 5; } } if(state[SDL_SCANCODE_S]){ if(game->forceFallCounter == 0){ fall = 1; game->forceFallCounter = 1; } else{ game->forceFallCounter--; } } else{ game->forceFallCounter = 0; } // u8 linesClearedThisFrame = 0; for(u8 y = 0; y < BOARD_H; y++){ if(game->lineInfo[y].destroyTimer){ game->lineInfo[y].destroyTimer--; if(!game->lineInfo[y].destroyTimer){ CompleteLine(game, y); linesClearedThisFrame++; } } } game->linesCleared += linesClearedThisFrame; switch(linesClearedThisFrame){ case 1: game->score += 40*(game->level+1); break; case 2: game->score += 100*(game->level+1); break; case 3: game->score += 300*(game->level+1); break; case 4: game->score += 1200*(game->level+1); break; default: break; } game->level = game->linesCleared/5; for(u8 y = 0; y < BOARD_H; y++){ if(game->lineInfo[y].destroyTimer) continue; bool rowFull = true; for(u8 x = 0; x < BOARD_W; x++){ if(!game->board[x][y]){ rowFull = false; break; } } if(rowFull){ game->lineInfo[y].destroyTimer = 40; } } //FALL game->fallCounter++; if(game->fallCounter == MAX(5, 20-game->level)){ game->fallCounter = 0; fall = true; } if(fall){ if(!CheckCollision(game, game->shapeX, game->shapeY+1)){ game->shapeY += 1; } else if(game->shapeY < 0){ game->state = STATE_END; AddScore(&game->highscores, game->name, game->score); SaveScores(&game->highscores); } else{ for(i8 y = 0; y < 4; y++){ for(i8 x = 0; x < 4; x++){ if(game->currentShape[x][y]){ game->board[game->shapeX+x][game->shapeY+y] = tetrominos[game->currentShapeId].boardState; } } } SpawnTetermino(game); } } //Pause menu if(state[SDL_SCANCODE_ESCAPE]){ game->state = STATE_PAUSE; } SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_RenderClear(renderer); DrawPlayArea(game, renderer); DrawUI(game, renderer); SDL_RenderPresent(renderer); } void FramePause(Game *game, SDL_Renderer *renderer){ game->frameNumber++; u8 *state = SDL_GetKeyboardState(NULL); if(ProcessMenu(game, state, 0, 1)){ switch(game->menuData.counter){ case 0: game->state = STATE_PLAY; break; case 1: ResetGame(game); break; default: break; } } SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_RenderClear(renderer); u32 uiY = GRID_H*PX_PER_CELL/2-100; DrawTextEx(game, renderer, "PAUSED", 400, uiY, 1, 1); uiY += 100; char buf[32]; snprintf(buf, 32, "Your score is: %u!", game->score); DrawTextEx(game, renderer, buf, 400, uiY, 1, 0); uiY += 50; DrawMenuEntry(game, renderer, "RESUME", &uiY, game->menuData.counter == 0); DrawMenuEntry(game, renderer, "MAIN MENU", &uiY, game->menuData.counter == 1); SDL_RenderPresent(renderer); } void FrameEnd(Game *game, SDL_Renderer *renderer){ game->frameNumber++; u8 *state = SDL_GetKeyboardState(NULL); if(ProcessMenu(game, state, 0, 1)){ switch(game->menuData.counter){ case 0: ResetGame(game); game->state = STATE_PLAY; break; case 1: ResetGame(game); break; default: break; } } SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_RenderClear(renderer); u32 uiY = GRID_H*PX_PER_CELL/2-100; DrawTextEx(game, renderer, "YOU LOST!", 400, uiY, 1, 1); uiY += 100; char buf[32]; snprintf(buf, 32, "Your score is: %u!", game->score); DrawTextEx(game, renderer, buf, 400, uiY, 1, 0); uiY += 50; DrawMenuEntry(game, renderer, "RETRY", &uiY, game->menuData.counter == 0); DrawMenuEntry(game, renderer, "MAIN MENU", &uiY, game->menuData.counter == 1); SDL_RenderPresent(renderer); } void FrameHighscore(Game *game, SDL_Renderer *renderer){ game->frameNumber++; u8 *state = SDL_GetKeyboardState(NULL); if(state[SDL_SCANCODE_RETURN]){ if(!game->menuData.held){ game->state = STATE_START; } game->menuData.held = 1; } else{ game->menuData.held = 0; } SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_RenderClear(renderer); u32 uiY = 60; DrawTextEx(game, renderer, "HIGHSCORES:", 400, uiY, 1, 0); uiY += 50; char buf[MAX_NAME_LENGTH+32]; for(int i = 0; i < HIGH_SCORE_MAX; i++){ snprintf(buf, MAX_NAME_LENGTH+32, "%2u. %s, %u", i+1, game->highscores.scores[i].name, game->highscores.scores[i].score); DrawTextEx(game, renderer, buf, 200, uiY, 0, 0); uiY += 50; } DrawMenuEntry(game, renderer, "BACK", &uiY, 1); SDL_RenderPresent(renderer); } void FrameOptions(Game *game, SDL_Renderer *renderer){ game->frameNumber++; u8 *state = SDL_GetKeyboardState(NULL); if(ProcessMenu(game, state, 0, 1)){ switch(game->menuData.counter){ case 0: MenuTextInput(game, state, game->name, MAX_NAME_LENGTH); break; case 1: game->state = STATE_START; break; default: break; } } SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_RenderClear(renderer); u32 uiY = 400; char buf[MAX_NAME_LENGTH+32]; snprintf(buf, MAX_NAME_LENGTH+32, "NAME:%s", game->name); DrawMenuEntry(game, renderer, buf, &uiY, game->menuData.counter == 0); DrawMenuEntry(game, renderer, "BACK", &uiY, game->menuData.counter == 1); SDL_RenderPresent(renderer); } void Frame(Game* game, SDL_Renderer *renderer, bool *running){ switch(game->state){ case STATE_START: FrameStart(game, renderer, running); break; case STATE_PLAY: FramePlay(game, renderer); break; case STATE_PAUSE: FramePause(game, renderer); break; case STATE_END: FrameEnd(game, renderer); break; case STATE_HIGHSCORE: FrameHighscore(game, renderer); break; case STATE_OPTIONS: FrameOptions(game, renderer); break; default: game->state = STATE_START; break; } }
C
#include "../system.h" s32int_t strlen(str_t); s32int_t strcmp(str_t, str_t); s32int_t strlen(str_t str) { int i=0; int len=0; while (str[i]) { len++; i++; } return len; } s32int_t strcmp(str_t x, str_t y) { int i=0; while(x[i]||y[i]) { if(x[i]!=y[i]) return 1; i++; } return 0; }
C
/* Emma Yaffe Random Testing Quiz The testme function requires a specific set of actions to happen in order to produce the error. First, it must sequentially be passed the following characters: '[', '(', '{', ' ', 'a', 'x', '}', ')', ']' When it receives one of these characters in the correct order, it increments the state integer. That is, state starts at 0. The first time it receives '[', state is incremented to 1. If it receives another '[', nothing happens. If it then receives '(' while the state is 1, state is incremented again. This continues until the state is 9 -- after it receives every one of those characters in order. Second, it must receive the string 'reset\0'. In order to produce the error, the state must be at 9 when it receives the 'reset\0'. With this in mind, I implemented the inputChar() and inputString() to randomly generate test inputs. For inputChar(), I created an array that held one of each of the possible characters that would trigger a state change. I did not include all characters due to limitations of time and of my machine, in order to make the test complete in a resonable amount of time. I randomly chose one of the items in the array and returned value. For inputString(), I created array that held the letters of reset: ('r', 'e', 's', 't'). I randomly chose from those characters to generate the string. I hard-coded the last character of the string to be '\0' to avoid errors. It needs to have the null terminating character last in order to run correctly. To compile, type: make To run, type: testme To remove file, type: make clean */
C
#include<stdio.h> #include<time.h> int main() { char *arr = ""; time_t tvar; time(&tvar); arr = ctime(&tvar); printf("user time: %s", arr); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <pthread.h> #define BUFFER_SIZE 4 #define ASC_a 97 #define ASC_A 65 int buffer_a[BUFFER_SIZE]; int buffer_b[BUFFER_SIZE]; int in_a; int in_b; int out_a; int out_b; typedef struct { int value; pthread_mutex_t mutex; pthread_cond_t cond; }semaphore; void semaphore_init(semaphore *sema, int value) { sema->value = value; pthread_mutex_init(&sema->mutex, NULL); pthread_cond_init(&sema->cond, NULL); } void semaphore_wait(semaphore *sema) { pthread_mutex_lock(&sema->mutex); sema->value--; while(sema->value < 0) pthread_cond_wait(&sema->cond, &sema->mutex); pthread_mutex_unlock(&sema->mutex); } void semaphore_signal(semaphore *sema) { pthread_mutex_lock(&sema->mutex); sema->value++; pthread_cond_signal(&sema->cond); pthread_mutex_unlock(&sema->mutex); } int buffer_is_empty(int input,int output) { return input == output; } int buffer_is_full(int input,int output) { return (input + 1) % BUFFER_SIZE == output; } int get_item_a() { int item; item = buffer_a[out_a]; out_a = (out_a + 1) % BUFFER_SIZE; return item; } int get_item_b() { int item; item = buffer_b[out_b]; out_b = (out_b + 1) % BUFFER_SIZE; return item; } void put_item_a(int item) { buffer_a[in_a] = item; in_a = (in_a + 1) % BUFFER_SIZE; } void put_item_b(int item) { buffer_b[in_b] = item; in_b = (in_b + 1) % BUFFER_SIZE; } semaphore mutex_sema_a; semaphore mutex_sema_b; semaphore empty_buffer_sema_a; semaphore empty_buffer_sema_b; semaphore full_buffer_sema_a; semaphore full_buffer_sema_b; #define COUNT (BUFFER_SIZE * 2) void *consume(void *arg) { int i; int item; for(i = 0; i < COUNT; ++i) { semaphore_wait(&full_buffer_sema_b); semaphore_wait(&mutex_sema_b); item = get_item_b(); semaphore_signal(&mutex_sema_b); semaphore_signal(&empty_buffer_sema_b); printf("\t\tconsume item: %c\n", item); } return NULL; } void *calculater(void *arg) { int i; int item; for(i = 0; i < COUNT; ++i) { semaphore_wait(&full_buffer_sema_a); semaphore_wait(&mutex_sema_a); item = get_item_a(); printf("\ttest: %c\n", item); semaphore_signal(&mutex_sema_a); semaphore_signal(&empty_buffer_sema_a); semaphore_wait(&empty_buffer_sema_b); semaphore_wait(&mutex_sema_b); item = item - (ASC_a - ASC_A); put_item_b(item); semaphore_signal(&mutex_sema_b); semaphore_signal(&full_buffer_sema_b); printf("\tcalculator item: %c\n", item); } return NULL; } void produce() { int i; int item; for (i = 0; i < COUNT; i++) { semaphore_wait(&empty_buffer_sema_a); semaphore_wait(&mutex_sema_a); item = i + 'a'; put_item_a(item); semaphore_signal(&mutex_sema_a); semaphore_signal(&full_buffer_sema_a); printf("produce item: %c\n", item); } } int main(int argc, char const *argv[]) { /* code */ //semaphore pro,cal,con; pthread_t consume_tid,calculater_pid; semaphore_init(&mutex_sema_a, 1); semaphore_init(&mutex_sema_b, 1); semaphore_init(&empty_buffer_sema_b, BUFFER_SIZE - 1); semaphore_init(&empty_buffer_sema_a, BUFFER_SIZE - 1); semaphore_init(&full_buffer_sema_a, 0); semaphore_init(&full_buffer_sema_b, 0); pthread_create(&consume_tid, NULL, consume, NULL); pthread_create(&calculater_pid, NULL, calculater, NULL); produce(); sleep(1); return 0; }
C
#include <stdio.h> #include <stdlib.h> int update_line_col(char c); void insert_spaces(int num); void insert_tab(int num); void insert_tab_stop(int col, int m, int n, int num, void (*insert_tabstop)(int num)); int get_m_n(int argc,char **argv, int *m, int *n); int get_tab_stops(int *tabstops, int maxstops, int argc, char *argv[]); void insert_tab_stop_list(int col, int *stops, int len, int num, void (*insert_tabstop)(int num)); #define MAX_TABS_STOPS 80 #define NUMSPACES 4 void detab(int m, int n, int *stops, int stopslen) { int c; const int tabsize = NUMSPACES; int count = 0; int col = 0; while((c = getc(stdin)) != EOF) { col = update_line_col(c); insert_tab_stop(col, m, n, tabsize, insert_spaces); insert_tab_stop_list(col, stops, stopslen, tabsize, insert_spaces); if(c == '\t') { count++; } else { insert_spaces(count*tabsize); putc(c, stdout); count = 0; } } } int main(int argc,char **argv) { int m, n; int tabstops[MAX_TABS_STOPS]; int lenstops = 0; if(!get_m_n(argc, argv, &m, &n)) { detab(m, n, tabstops, lenstops); } else { lenstops = get_tab_stops(tabstops, MAX_TABS_STOPS, argc, argv); detab(m, n, tabstops, lenstops); } //printf("m = %d. n = %d\n", m, n); }
C
/* ============================================================================ Name : Nuestras.c Author : Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <commons/string.h> #include <commons/collections/list.h> #include <parser/parser.h> #include <parser/metadata_program.h> #include <stdint.h> int main(void) { /*PCB_DATA pcb; t_metadata_program *metadata = metadata_desde_literal(script); pcb.pid = 0; pcb.contPags_pcb = 1; pcb.contextoActual = -1; pcb.exitCode = 0; pcb.indiceCodigo = metadata->instrucciones_serializado; pcb.cantidadDeInstrucciones = metadata->instrucciones_size; pcb.indiceEtiquetas = metadata->etiquetas; //string_append(&(pcb.indiceEtiquetas),"\0"); pcb.cantidadDeEtiquetas = metadata->cantidad_de_etiquetas; pcb.indiceStack = malloc(sizeof(t_entrada)); pcb.indiceStack->argumentos = list_create(); pcb.indiceStack->variables = list_create(); pcb.cantidadDeEntradas = 0; pcb.programCounter = metadata->instruccion_inicio; void* pcbSerializado = serializarPCB(&pcb); PCB_DATA *pcb2 = deserializarPCB(pcbSerializado); imprimirPCB(pcb2); printf("%d\n",pcb.pid); global = pruebaSerializarPCB(); ((t_variable*)list_get(global->indiceStack[3].argumentos, 1))->ID = 'k'; otraPrueba(global);*/ //imprimirPCB(global); } /* void copiar(char * ruta){ char * comando = string_new(); string_append(&comando, "cp -R src/laGranBiblioteca/ "); string_append(&comando, ruta); string_append(&comando, "/src/"); system(comando); } void copiarEnProyecto(char * proyecto){ char * comando = string_new(); string_append(&comando, "../"); string_append(&comando, proyecto); copiar(comando); puts("Proceso terminado maquinola"); } int main(void) { copiarEnProyecto("Kernel"); copiarEnProyecto("Consola"); copiarEnProyecto("CPU"); copiarEnProyecto("Memoria"); copiarEnProyecto("FileSystem"); */ /* printf("Hace algun tiempo, este codigo era lo mas ranciamente hermoso que podiamos haber esperado del gran programadior, G.H.S\nSal2.\n\n\n"); return EXIT_SUCCESS; } */
C
#include <stdio.h> void new_line() { printf("666666\n"); } void three_line() { int i = 0; for (i = 1; i < 3; i++) { new_line(); } } int main() { three_line(); return 0; }
C
#include <stdio.h> #include <stdlib.h> long long k, p; long long ** multiply(long long **one, long long **two) { //int pp, q; long long **rez, i, t, j; rez = malloc(k * sizeof(long long*)); for(i = 0; i < k; i++) rez[i] = malloc(k * sizeof(long long)); for(i = 0; i < k; i++) for(j = 0; j < k; j++) rez[i][j] = 0; // printf("%d\n", p); for(t = 0; t < k; t++) { for(i = 0; i < k; i++) { for(j = 0; j < k; j++) { // printf("%d\n", p); //printf("%d\n", rez[t][i]); //rez[t][i] += ((one[t][j] % p) * (two[j][i] % p)) % p; rez[t][i] = (rez[t][i] % p + ((one[t][j] % p) * (two[j][i] % p)) % p) % p; } } } return rez; } int main(void) { long long **matrix, **tmp, *mas_k; long long n, pow = 0, sum = 0; long long i, j; scanf("%lld%lld%lld", &k, &n, &p); matrix = malloc(k * sizeof(long long *)); mas_k = malloc(k * sizeof(long long)); for(i = 0; i < k; i++) { scanf("%lld", &mas_k[i]); matrix[i] = malloc(k * sizeof(long long)); } for(i = 0; i < k; i++) scanf("%lld", &matrix[0][i]); for(i = 1; i < k; i++) for(j = 0; j < k; j++) if ((i - j) == 1) matrix[i][j] = 1; else matrix[i][j] = 0; pow = n - k; tmp = malloc(k * sizeof(long long*)); for(i = 0; i < k; i++) tmp[i] = malloc(k * sizeof(long long)); for (i = 0; i < k; i++) for(j = 0; j < k; j++) if (i == j) tmp[i][j] = 1; else tmp[i][j] = 0; /* for(i = 0; i < k; i++) for(j = 0; j < k; j++) if (j == k - 1) printf("%d\n", tmp[i][j]); else printf("%d ", tmp[i][j]);*/ /* for(i = 0; i < k; i++) for(j = 0; j < k; j++) if (j == k - 1) printf("%d\n", matrix[i][j]); else printf("%d ", matrix[i][j]); puts("umnojenie");*/ while(pow > 1) { if (pow % 2) { pow--; tmp = multiply(matrix, tmp); /*printf("%lld\n", pow); for(i = 0; i < k; i++) for(j = 0; j < k; j++) if (j == k - 1) printf("%d\n", tmp[i][j]); else printf("%d ", tmp[i][j]);*/ } else { /* for(i = 0; i < k; i++) for(j = 0; j < k; j++) if (j == k - 1) printf("%d\n", matrix[i][j]); else printf("%d ", matrix[i][j]); printf("\n");*/ pow /= 2; matrix = multiply(matrix, matrix); /* for(i = 0; i < k; i++) for(j = 0; j < k; j++) if (j == k - 1) printf("%d\n", matrix[i][j]); else printf("%d ", matrix[i][j]);*/ } } matrix = multiply(matrix, tmp); /*for(i = 0; i < k; i++) for(j = 0; j < k; j++) if (j == k - 1) printf("%d\n", matrix[i][j]); else printf("%d ", matrix[i][j]);*/ /*for(i = 0; i < k; i++) for(j = 0; j < k; j++) if (j == k - 1) printf("%d\n", matrix[i][j]); else printf("%d ", matrix[i][j]); */ for(i = 0; i < k; i++) sum = (sum % p + ((mas_k[k - i - 1] % p) * (matrix[0][i] % p)) % p ) % p; if (n > k) printf("%lld", sum); else printf("%lld", mas_k[n - 1] % p); return 0; }
C
#include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <errno.h> #include <string.h> #include <signal.h> #include <termios.h> #include <unistd.h> #include <linux/limits.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <pwd.h> #define CMD_LEN 1024 #define ARGV_NUM 64 pid_t shell_pid, shell_pgid; int shell_terminal; /* A process is a single process. */ typedef struct process { struct process *next; /* next process in pipeline */ char *command, *argv[ARGV_NUM]; /* for exec */ pid_t pid; /* process ID */ int status; /* reported status value */ bool first, last; char *infilename, *outfilename; } process; /* A job is a pipeline of processes. */ typedef struct job { struct job *next; /* next active job */ char *command; /* command line, used for messages */ process *first_process; /* list of processes in this job */ pid_t pgid; /* process group ID */ int stdin, stdout, stderr; /* standard i/o channels */ } job; /* The active jobs are linked into a list. This is its head. */ job *first_j = NULL; bool prompt(void) { struct passwd *pw = getpwuid(getuid()); char *prompt_username, *prompt_sign; char prompt_cwd[PATH_MAX]; if (pw->pw_uid!= 0) { prompt_username = pw->pw_name; prompt_sign = "$"; } else { prompt_username = "root"; prompt_sign = "#"; } if (getcwd(prompt_cwd, PATH_MAX)==NULL) perror("getcwd"); printf("%s$@%s %s ", prompt_username, prompt_cwd, prompt_sign); fflush(stdout); return true; } void init_process(process *p) { p->next = NULL; p->pid = 0; p->first = p->last = false; p->infilename = p->outfilename = NULL; } job *parse_cmd(char* cmd_str) { int i; process *first_p, *current_p; job *j; char *current_cmd; j = (job *)malloc(sizeof(job)); current_cmd = strtok(cmd_str, "|\n"); current_p = first_p = (process *)malloc(sizeof(process)); init_process(current_p); current_p->command = current_cmd; current_p->first = true; i = 0; while ((current_cmd=strtok(NULL,"|\n"))!=NULL) { current_p->next = (process *)malloc(sizeof(process)); current_p = current_p->next; init_process(current_p); current_p->command = current_cmd; i++; } current_p->last = true; current_p = first_p; while (current_p!=NULL) { current_p->command = strtok(current_p->command, "<"); if ((current_p->infilename=strtok(NULL, "<"))!=NULL) { current_p->infilename = strtok(current_p->infilename, " "); } current_p->command = strtok(current_p->command, ">"); if ((current_p->outfilename=strtok(NULL, ">"))!=NULL) { current_p->outfilename = strtok(current_p->outfilename, " "); } i = 0; (current_p->argv)[0] = strtok(current_p->command, " \t\n"); i++; while (((current_p->argv)[i]=strtok(NULL, " \t\n"))!=NULL) { i++; if (i==ARGV_NUM-1) { fputs("Too many tokens.\n", stderr); break; } } (current_p->argv)[i] = NULL; current_p = current_p->next; } j->first_process = first_p; j->pgid=0; return j; } bool run_simple(char *cmd, pid_t *child_group, bool first) { char *argv[ARGV_NUM]; int iter; pid_t child = 0; iter = 0; argv[0] = strtok(cmd, " \t\n"); iter++; while ((argv[iter]=strtok(NULL, " \t\n"))!=NULL) { iter++; if (iter==ARGV_NUM-1) { fputs("Too many tokens.\n", stderr); return false; } } argv[iter] = NULL; if ((child=fork())==-1) { perror("fork"); return false; } if (child==0) { // child if(first) setpgid(0, 0); execvp(argv[0], argv); } else { // parent if (first) { *child_group = child; } else { setpgid(child, *child_group); } } return true; } void run_process(process *p, pid_t pgid, int infile, int outfile) { signal(SIGINT, SIG_DFL); signal(SIGQUIT, SIG_DFL); signal(SIGTSTP, SIG_DFL); signal(SIGTTIN, SIG_DFL); signal(SIGTTOU, SIG_DFL); signal(SIGCHLD, SIG_DFL); setpgid(0, pgid); if (infile!=STDIN_FILENO) { dup2(infile, STDIN_FILENO); close(infile); } if (outfile!=STDOUT_FILENO) { dup2(outfile, STDOUT_FILENO); close(outfile); } execvp(p->argv[0], p->argv); perror("execvp"); exit(1); return; } void run_job(job *j) { process *p; pid_t child_pid; int mypipe[2], infile, outfile; int child_num; int status; p = j->first_process; infile = STDIN_FILENO; if (p->infilename!=NULL) infile = open(p->infilename, O_RDONLY); j->pgid = 0; child_num = 0; while (p!=NULL) { if (p->next) { if (pipe(mypipe)<0) { perror("pipe"); exit(1); } outfile = mypipe[1]; } else { outfile = STDOUT_FILENO; if (p->outfilename!=NULL) outfile = open(p->outfilename, O_WRONLY|O_CREAT, 0666); } child_pid = fork(); if (child_pid==0) { run_process(p, j->pgid, infile, outfile); } else if (child_pid<0) { perror("fork"); } else { if(p->first) j->pgid = child_pid; child_num++; } if (infile!=STDIN_FILENO) close(infile); if (outfile!=STDOUT_FILENO) close(outfile); infile=mypipe[0]; p = p->next; } if (tcsetpgrp(STDIN_FILENO, j->pgid) == -1) { perror("tcsetpgrp"); exit(1); } while (child_num!=0) { wait(&status); child_num--; } if (tcsetpgrp(STDIN_FILENO, shell_pgid) == -1) { perror("tcsetpgrp"); exit(1); } return; } void clean_job(job *j) { process *p, *n; p = j->first_process; while (p->next) { n = p->next; free(p); p = n; } free(p); free(j); } bool run_cmd(char *cmd) { char *cmd_buff = (char *)malloc(CMD_LEN); pid_t child_group; int child_num; int status; FILE *tty; if ((tty=fopen("/dev/tty", "w"))==NULL) { perror("fopen"); } sprintf(cmd_buff, cmd); child_num = 1; run_simple(cmd_buff, &child_group, true); if (tcsetpgrp(fileno(tty), child_group) == -1) { perror("tcsetpgrp"); return false; } while (child_num!=0) { wait(&status); child_num--; } if (tcsetpgrp(fileno(tty), getpgid(0)) == -1) { perror("tcsetpgrp"); return false; } free(cmd_buff); return true; } void ignore_signal(int sig) { return; } char *get_cmd(char* cmd_str) { prompt(); if (fgets(cmd_str, CMD_LEN, stdin)==NULL) return NULL; return cmd_str; } void init_shell(void) { signal(SIGINT, SIG_IGN); signal(SIGQUIT, SIG_IGN); signal(SIGTSTP, SIG_IGN); signal(SIGTTIN, SIG_IGN); signal(SIGTTOU, SIG_IGN); signal(SIGCHLD, SIG_IGN); shell_terminal = STDIN_FILENO; shell_pid = getpid(); if (setpgid(shell_pid, shell_pgid) < 0) { perror("setpgid"); exit(1); } shell_pgid = shell_pid; tcsetpgrp(shell_terminal, shell_pgid); } int main(int argc, char *argv[]) { //struct passwd *pw = getpwuid(getuid()); char *cmd_str; //chdir(pw->pw_dir); init_shell(); cmd_str = (char *)malloc(CMD_LEN); while ((get_cmd(cmd_str))!=NULL) { first_j = parse_cmd(cmd_str); run_job(first_j); clean_job(first_j); } free(cmd_str); printf("\n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #define BUF_SZ 32 int buf[BUF_SZ] = { 0x5555aaaa, 0x5555aaaa, 0x5555aaaa, 1,4, 0x5555aaab, 0x5555aaac, 0x5555aaad, 0x55555555, // 55550000 0x5555aaaa, 2,3, 0x5555aaaa, 0x5555aaaa, 0xaaaa5555, // ffffffff 0x5555aaaa, 0x5555aaaa, 3,2, 0x44444444, 0x88888888, // cccccccc 0x5555aaaa, 4,2, 4,4, // 00000010 0x5555aaaa, 0,2, 0x5555aaaa, 0xaaaa5555, // ffffffff 0x5555aaaa // 0x5555aaaa, 0x5555aaaa, 0x5555aaaa, 0x5555aaaa }; int main(int argc, char *argv[]) { int i; int number = 4; int seed = 7; int n; for (i=0; i<BUF_SZ; i++) { n = buf[i]; fwrite(&n, sizeof(int), 1, stdout); } return(0); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> char * revstr(char s[]); void recurRevstr(char *s); void recurRevstr(char *s) { if (*s == 0) return; else { // s = s+1; // printf("%c", *s); recurRevstr(s+1); printf("%c", *s); } } char * revstr(char s[]) { char *rev = (char *)malloc(sizeof(strlen(s)+1)); rev[strlen(s)] = 0; int i=0; while (s[i] != '\0') { rev[strlen(s)-i-1] = s[i]; i++; } return rev; } void main() { char str[] = "I am a string"; // printf("%s", c); // c[0] = 'i'; // printf("\n%s\n", c); // char *p = NULL; // p = c; // while (*p != '\0') { // printf("%c", *p); // p++; // } // char revStr[strlen(str)+1]; // revStr[strlen(str)] = '\0'; // int i=0; // while (str[i] != '\0') { // revStr[strlen(str)-i-1] = str[i]; // i++; // } // printf("%s ", str); // printf("%s\n", revStr); // char *rev = revstr(str); // i = 0; // while(rev[i] != 0) { // printf("%c", rev[i]); // i++; // } // recurRevstr(str); char c = '+'; int a=10, b=5; int res = a c b; printf("%d", res); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> //#include <file.h> //using namespace::std; typedef struct customer{ unsigned long inTime; unsigned long lineId; char* name; unsigned int items; } Customer; typedef struct node{ Customer *customer; struct node* next; } Node; typedef struct queue{ Node* front; Node* back; }Queue; #define QUEUES 12 #define MAX_NAME_LEN 10 #define MAX_IN_TIME 2000000000 #define MAX_ITEMS 100 #define cout fout Customer *createCustomer(unsigned long time, unsigned long line, char *name, unsigned int items); void enqueue(Queue *pQueue, Customer *pCustomer); int queueEmpty(Queue queue); void runSimulation(Queue *pQueue, FILE *pFile); Customer *getNextCustomer(Queue *pQueue, unsigned long *currTime); void checkoutCustomer(Customer *pCustomer, unsigned long *currTime); Customer *getCustomerWithMinInTime(Queue *pQueue); Customer *getCustomerWithinTimeWithMinItems(Queue *pQueue, unsigned long currTime); int main() { char* inputFile = "in.txt"; char* outFile = "out.txt"; Queue queues[QUEUES]; for(int i=0; i<QUEUES; i++){ queues[i].front = NULL; queues[i].back = NULL; } FILE *fin = fopen(inputFile, "r"); FILE *fptr = fopen(outFile, "w"); int testcases; fscanf(fin, "%d", &testcases); while(testcases > 0){ int customers; fscanf(fin, "%d", &customers); for(int i=0; i<customers; i++) { unsigned long inTime; unsigned long line; char* name = (char*) malloc(MAX_NAME_LEN * sizeof(char)); unsigned int items; fscanf(fin, "%lu %lu %s %d\n", &inTime, &line, name, &items); line--; enqueue(queues, createCustomer(inTime, line, name, items)); } runSimulation(queues, fptr); // clearAllQueues(queues); testcases--; } fclose(fptr); return 0; } void runSimulation(Queue *pQueue, FILE *pFile) { unsigned long currentTime = 0; Customer *c = getNextCustomer(pQueue, &currentTime); while(c != NULL){ checkoutCustomer(c, &currentTime); fprintf(pFile, "%s from line %lu checks out at time %lu.\n", c->name, c->lineId+1, currentTime); free(c->name); c->name = NULL; free(c); c = NULL; c = getNextCustomer(pQueue, &currentTime); } } void checkoutCustomer(Customer *pCustomer, unsigned long *currTime) { *currTime += 30 + (pCustomer->items * 5); printf("%s from line %lu checks out at time %lu.\n", pCustomer->name, pCustomer->lineId+1, *currTime); } Customer *getNextCustomer(Queue *pQueue, unsigned long *currTime) { Customer *c = getCustomerWithinTimeWithMinItems(pQueue, *currTime); if(c == NULL) { c = getCustomerWithMinInTime(pQueue); if (c != NULL && c->inTime > *currTime) *currTime = c->inTime; } return c; } Customer *getCustomerWithinTimeWithMinItems(Queue *pQueue, unsigned long currTime) { int minIdx = -1; int minItems = MAX_ITEMS + 10; int found = 0; for(int i=0; i<QUEUES; i++){ if(pQueue[i].front != NULL && pQueue[i].front->customer->inTime <= currTime && pQueue[i].front->customer->items < minItems){ minItems = pQueue[i].front->customer->items; minIdx = i; found = 1; } } if(!found) return NULL; Node* n = pQueue[minIdx].front; if(pQueue[minIdx].front == pQueue[minIdx].back){ pQueue[minIdx].front = NULL; pQueue[minIdx].back = NULL; } else { pQueue[minIdx].front = pQueue[minIdx].front->next; } n->next = NULL; Customer *c = n->customer; n->customer = NULL; free(n); return c; } Customer *getCustomerWithMinInTime(Queue *pQueue) { int minIdx; unsigned long minInTime = MAX_IN_TIME; int found = 0; for(int i=0; i<QUEUES; i++){ if(pQueue[i].front != NULL && pQueue[i].front->customer->inTime < minInTime){ minInTime = pQueue[i].front->customer->inTime; minIdx = i; found = 1; } } if(!found) return NULL; Node* n = pQueue[minIdx].front; if(pQueue[minIdx].front == pQueue[minIdx].back){ pQueue[minIdx].front = NULL; pQueue[minIdx].back = NULL; } else { pQueue[minIdx].front = pQueue[minIdx].front->next; } n->next = NULL; Customer *c = n->customer; n->customer = NULL; free(n); return c; } void enqueue(Queue *pQueue, Customer *pCustomer) { Node* n = (Node*) malloc(sizeof(Node)); n->customer = pCustomer; n->next = NULL; if(queueEmpty(pQueue[pCustomer->lineId])){ pQueue[pCustomer->lineId].front = n; pQueue[pCustomer->lineId].back = n; } else{ pQueue[pCustomer->lineId].back->next = n; pQueue[pCustomer->lineId].back = n; } } int queueEmpty(Queue queue) { return (queue.front == NULL && queue.back == NULL); } Customer *createCustomer(unsigned long time, unsigned long line, char *name, unsigned int items) { Customer *c = (Customer*) malloc(sizeof(Customer)); c->inTime = time; c->lineId = line; c->name = (char*) malloc(MAX_NAME_LEN * sizeof(char)); sprintf(c->name, "%s", name); c->items = items; return c; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <openssl/des.h> #include <openssl/evp.h> #include "util.h" void error(const char *err) { fprintf(stderr, "%s\n", err); exit(1); } void usage(char *name) { printf("Usage: %s [options]\n", name); printf(" -c Use client mode: Act as master.\n"); printf(" -s Use server mode: Act as backdoor. [default]\n"); printf(" -h Show this help listing.\n"); printf(" -i <arg> Remote host address for client mode. [default=127.0.0.1]\n"); printf(" -w <arg> Folder to watch. [default=/root]\n"); printf(" -x [und] Covert channel to use. [default=udp]\n"); printf(" EXAMPLES:\t %s -c -i 192.168.0.1\n", name); printf(" EXAMPLES:\t %s -s -i 192.168.0.2 -x n\n", name); exit(0); } uint64 get_sec() { struct timeval curr_time; uint64 result; gettimeofday(&curr_time, NULL); result = ((uint64) curr_time.tv_sec) << 32; result += curr_time.tv_usec; return result; } FILE* open_file(char* fname, uint8 writeMode) { FILE *file; if (writeMode) { if ( (file = fopen(fname, "wb")) == NULL) error("Error opening open input file."); } else { if ( (file = fopen(fname, "rb")) == NULL) error("Error opening open output file."); } return file; } void encrypt(char *key, char *msg, int size) { static char* result; int n = 0; DES_cblock key2; DES_key_schedule schedule; result = (char*)malloc(size); // Prepare the key for use with DES_cfb64_encrypt memcpy(key2, key, 8); DES_set_odd_parity(&key2); DES_set_key_checked(&key2, &schedule); // Encryption occurs here DES_cfb64_encrypt((unsigned char*)msg, (unsigned char*)result, size, &schedule, &key2, &n, DES_ENCRYPT); memcpy(msg, result, size); free(result); } void decrypt(char *key, char *msg, int size) { static char* result; int n = 0; DES_cblock key2; DES_key_schedule schedule; result = (char*)malloc(size); // Prepare the key for use with DES_cfb64_encrypt memcpy(key2, key, 8); DES_set_odd_parity(&key2); DES_set_key_checked(&key2, &schedule); // Decryption occurs here DES_cfb64_encrypt((unsigned char*)msg, (unsigned char*)result, size, &schedule, &key2, &n, DES_DECRYPT); memcpy(msg, result, size); free(result); } void calc_md5(const void *content, ssize_t len, char* md5) { EVP_MD_CTX mdctx; unsigned char md_value[EVP_MAX_MD_SIZE]; unsigned int md_len; EVP_DigestInit(&mdctx, EVP_md5()); EVP_DigestUpdate(&mdctx, content, (size_t) len); EVP_DigestFinal_ex(&mdctx, md_value, &md_len); EVP_MD_CTX_cleanup(&mdctx); for (int i = 0; i < 4; ++i) md5[i] = md_value[i]; } char* buildTransmission(char *data, int *len, char type) { char *buff; char *ptr; char md5[MD5_LEN]; int pass_len; int tot_len; int data_len; pass_len = strlen(HDR_KEY); data_len = *len; tot_len = data_len + pass_len; // Allocate buffer for transmission buff = malloc(FRAM_SZ + tot_len); // First byte: Command type buff[0] = type; // Three bytes: Total length buff[1] = tot_len >> 16; buff[2] = tot_len >> 8; buff[3] = tot_len; // Copy pass key and data to transmission buffer ptr = buff + FRAM_SZ; memcpy(ptr, HDR_KEY, pass_len); ptr += pass_len; memcpy(ptr, data, data_len); // Calculate MD5 ptr = buff + FRAM_SZ; calc_md5(ptr, tot_len, md5); ptr = buff + 4; memcpy(ptr, md5, MD5_LEN); // Update len *len = tot_len + FRAM_SZ; return buff; } char* getTransmission(char *packet, int *len, char *type) { char *data; char *ptr; char md5[MD5_LEN]; int pass_len; int tot_len; int data_len; // unsigned char l1, l2, l3; pass_len = strlen(HDR_KEY); // Check Password ptr = packet + FRAM_SZ; if (memcmp(ptr, HDR_KEY, pass_len) != 0) return NULL; // Get Length tot_len = (((uint8)packet[1]) << 16) + (((uint8)packet[2] << 8)) + ((uint8)packet[3]); data_len = tot_len - pass_len; // Check MD5 ptr = packet + FRAM_SZ; calc_md5(ptr, tot_len, md5); ptr = packet + 4; if (memcmp(ptr, md5, MD5_LEN) != 0) return NULL; // Get TX Type *type = packet[0]; // Get Data ptr = packet + FRAM_SZ + pass_len; data = malloc(data_len); memcpy(data, ptr, data_len); // Update len *len = data_len; return data; }
C
#include <stdio.h> #include <signal.h> #include <unistd.h> #include <time.h> #include <string.h> int maxTermCount = 3; /*enum signals{ SIGHU = 1, SIGINT_, SIGQUIT, SIGILL_, SIGTRAP, SIGABRT_, SIGBUS, SIGFPE_, SIGKILL, SIGUSR1, SIGSEGV_, SIGUSR2, SIGPIPE, SIGALRM, SIGTERM_, SIGSTKFLT, SIGCHLD, SIGCONT, SIGSTOP, SIGTSTP, SIGTTIN, SIGTTOU, SIGURG, SIGXCPU, SIGXFSZ, SIGVTALRM, SIGPROF, SIGWINCH, SIGIO, SIGPWR, SIGSYS, SIGRTMIN, SIGRTMIN1, SIGRTMIN2, SIGRTMIN3, SIGRTMIN4, SIGRTMIN5, SIGRTMIN6, SIGRTMIN7, SIGRTMIN8, SIGRTMIN9, SIGRTMIN10, SIGRTMIN11, SIGRTMIN12, SIGRTMIN13, SIGRTMIN14, SIGRTMIN15, SIGRTMAX14, SIGRTMAX13, SIGRTMAX12, SIGRTMAX11, SIGRTMAX10, SIGRTMAX9, SIGRTMAX8, SIGRTMAX7, SIGRTMAX6, SIGRTMAX5, SIGRTMAX4, SIGRTMAX3, SIGRTMAX2, SIGRTMAX1, SIGRTMAX };*/ static char csignals[64][12] = { "HU", "INT", "QUIT", "ILL", "TRAP", "ABRT", "BUS", "FPE", "KILL", "USR1", "SEGV", "USR2", "PIPE", "ALRM", "TERM", "STKFLT", "CHLD", "CONT", "STOP", "TSTP", "TTIN", "TTOU", "URG", "XCPU", "XFSZ", "VTALRM", "PROF", "WINCH", "IO", "PWR", "SYS", "RTMIN", "RTMIN+1", "RTMIN+2", "RTMIN+3", "RTMIN+4", "RTMIN+5", "RTMIN+6", "RTMIN+7", "RTMIN+8", "RTMIN+9", "RTMIN+10", "RTMIN+11", "RTMIN+12", "RTMIN+13", "RTMIN+14", "RTMIN+15", "RTMAX-14", "RTMAX-13", "RTMAX-12", "RTMAX-11", "RTMAX-10", "RTMAX-9", "RTMAX-8", "RTMAX-7", "RTMAX-6", "RTMAX-5", "RTMAX-4", "RTMAX-3", "RTMAX-2", "RTMAX-1", "RTMAX" }; int termCount = 0; int sigCount = 0; void sighandler(int sig) { //add to termcount if(sig == SIGTERM) { termCount++; } else { termCount = 0; } sigCount++; //report signal caught printf("SIG%s caught at %d\n", csignals[sig-1], time(NULL)); //reset signal signal(sig, sighandler); } int main(int argc, char** argv) { //process command line if(argc < 2) { fprintf(stderr, "INSUFFICIENT ARGUMENTS\n"); } int sigSize = argc - 1; int sig[sigSize]; int keepLooping = 1; int i; int j; for(i = 1; i < argc; i++) { for(j = 1; j < 64; j++) { if(strcmp(csignals[j-1], argv[i]) == 0) { sig[i-1] = j; //printf("%d\n", sig[i-1]); break; } } } //register handler for each arg for(i = 0; i < sigSize; i++) { signal(sig[i], sighandler); } //report pid to stderr fprintf(stderr, "catcher: $$ = %d\n", getpid()); while(keepLooping) { //pause pause(); //printf("yeet"); //if 3 successive SIGTERM, terminate loop if(termCount >= maxTermCount) { break; } } //final status report fprintf(stderr, "catcher: Total signals count = %d\n", sigCount); return 0; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_4__ TYPE_2__ ; typedef struct TYPE_3__ TYPE_1__ ; /* Type definitions */ struct TYPE_4__ {char* name; int /*<<< orphan*/ chksum; } ; struct TYPE_3__ {int /*<<< orphan*/ magic; } ; typedef TYPE_1__ HD_USTAR ; typedef TYPE_2__ HD_TAR ; /* Variables and functions */ int BLKMULT ; int /*<<< orphan*/ OCT ; int /*<<< orphan*/ TMAGIC ; scalar_t__ TMAGLEN ; scalar_t__ asc_ul (int /*<<< orphan*/ ,int,int /*<<< orphan*/ ) ; scalar_t__ strncmp (int /*<<< orphan*/ ,int /*<<< orphan*/ ,scalar_t__) ; scalar_t__ tar_chksm (char*,int) ; int tar_id(char *blk, int size) { HD_TAR *hd; HD_USTAR *uhd; if (size < BLKMULT) return(-1); hd = (HD_TAR *)blk; uhd = (HD_USTAR *)blk; /* * check for block of zero's first, a simple and fast test, then make * sure this is not a ustar header by looking for the ustar magic * cookie. We should use TMAGLEN, but some USTAR archive programs are * wrong and create archives missing the \0. Last we check the * checksum. If this is ok we have to assume it is a valid header. */ if (hd->name[0] == '\0') return(-1); if (strncmp(uhd->magic, TMAGIC, TMAGLEN - 1) == 0) return(-1); if (asc_ul(hd->chksum,sizeof(hd->chksum),OCT) != tar_chksm(blk,BLKMULT)) return(-1); return(0); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #define NUMBER_US 3 #define NUMBER_CS 3 #define NUMBER_MOTORS 5 struct Ultrasonic_Sensor { char* name; int echo; int trig; float value; // cm } typedef Ultrasonic_Sensor; struct Colour_Sensor { char* name; int pin; int value; } typedef Colour_Sensor; struct Motor { char* name; int enable; int a; int b; int value; } typedef Motor; struct Wheels { Motor left; Motor right; } typedef Wheels; struct Arm { Motor first; Motor second; Motor claw; } typedef Arm; Ultrasonic_Sensor us[] = { {"left", 1, 2, 3}, {"centre", 4, 5, 6}, {"right", 7, 8, 9} }; Colour_Sensor cs[] = { {"left", 1, 0}, {"centre", 4, 5}, {"right", 7, 8} }; Motor motors[] = { {"left", 5, 1, 2, 0}, {"right", 6, 7, 8, 0}, {"first", 7, 1, 2, 0}, {"second", 8, 1, 2, 0}, {"claw", 9, 1, 2, 0} }; Wheels wheels; Arm arm; void setup_pins() { /* iterate over motors */ /* iterate over colour sensors */ /* interate over ultrasonic sensors */ } void setup_motors() { for (int i = 0; i < NUMBER_MOTORS; i ++) { // digital write a and b to be 0 motors[i].value = 0 /* analogWrite(motors[i].enable,motors[i].value); */ } } void print_cs() { static int i; for (i = 0; i < NUMBER_CS; i ++) { printf("NAME: %s PIN: %d VALUE: %d \n", cs[i].name, cs[i].pin, cs[i].value); } } void print_us() { static int i; for (i = 0; i < NUMBER_US; i ++) { printf("NAME: %s ECHO: %d TRIG: %d VALUE: %d \n", us[i].name, us[i].echo, us[i].trig, us[i].value); } } // -- POLL SENSORS -- // void poll_cs() { static int i; for (i = 0; i < NUMBER_CS; i ++) { /* just randomly generating */ us[i].value = rand() % 1000; } } void poll_us() { static int i; for (i = 0; i < NUMBER_US; i ++) { /* just randomly generating */ us[i].value = rand() % 100; } } float get_us(char* name) { /* sequential search */ static int i; for (i = 0; i < NUMBER_US; i ++) { if (strcmp(us[i].name, name) == 0) { return us[i].value; } } return -1; } int get_cs(char* name) { /* sequential search */ static int i; for (i = 0; i < NUMBER_CS; i ++) { if (strcmp(cs[i].name, name) == 0) { return cs[i].value; } } return -1; } int get_button() { return 1; } void drop_arm() { /* full extend te motors, for the second motor wait until button is pressed */ } void raise_arm() { } /* sets motor speed and a/b pins */ void set_motor() { } void move_forward(int speed) { /* make a and b high for both motors */ /* analogwrite on the pins */ } int main(int argc, char** argv) { /* seed RNG */ srand(time(0)); char buffer[1024]; wheels.left = motors[0]; wheels.right = motors[1]; arm.first = motors[2]; arm.second = motors[3]; arm.claw = motors[4]; poll_cs(); while (1) { poll_us(); poll_cs(); printf("> "); fgets(buffer, 1024, stdin); if ((strcmp(buffer, "ultra\n") == 0)) { print_us(); } else if ((strcmp(buffer, "colour\n") == 0)) { print_cs(); } else if ((strcmp(buffer, "motor\n") == 0)) { } } return 0; }
C
#include<stdio.h> #include<conio.h> void main() { int i; printf("Enter the number:\n"); clrscr(); scanf("%d",&i); if(i%2==0) { printf("No is even"); } else { printf("No is odd"); } getch(); }
C
#include <stdio.h> typedef struct table{ int data; int link; }table; int place=0; int R=10; table dataTable[10]; void hash(int x) { place=x%11; if(dataTable[place].data==-1) dataTable[place].data=x; else { collision(x); } } void collision(int x) { if(dataTable[R].data==-1) { dataTable[place].link=R; dataTable[R].data=x; R--; } else { R--; collision(x); } } int main() { int i; for(i=0;i<11;i++) { dataTable[i].data=-1; dataTable[i].link=-1; } hash(27); hash(18); hash(29); hash(28); hash(39); hash(13); hash(16); printf("Data Link\n"); for(i=0;i<11;i++) { printf("%d ", dataTable[i].data); printf("%d\n", dataTable[i].link); } return 0; }
C
// Machine Problem 2 // CS3050 // Saab // /* Dylan Lade William Givens Claire Hough */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #define MAX_VERT 20 typedef struct{ int visited; int magnitude; int adj[MAX_VERT]; } Vert; typedef struct{ int top; int elements[MAX_VERT]; } Stack; typedef struct{ int outDegree; int index; int components[MAX_VERT]; } GraphSCC; void build_array(int s, int d, Vert* vert, int max); void push(int v, Stack* stack, int max); int pop(Stack* stack); void dfs(int v, int transpose, Vert vert[], Stack* stack, int max, GraphSCC graphSCC[]); void reset_visited(int max, Vert vert[]); void order_pass(int max, Vert vert[], Stack* stack, GraphSCC graphSCC[]); void scc_pass(Stack* stack, Vert vert[], int max, GraphSCC graphSCC[]); int main (int argc, char* argv[]) { //Check for input file if (argc != 2) { printf("Please Check input!\n"); printf("Correct Input: ./a.out <inputFile>.txt\n"); return 0; } char* inputFile = argv[1]; int** input = malloc(sizeof(int*) * 6969); int max = 0; int index = 0; //Read in input file into input printf("File input: \n"); FILE *inptr = fopen(inputFile, "r"); while (0 == 0) { if (feof(inptr)) { break; } *(input + index) = malloc(sizeof(int*)); fscanf(inptr,"%d", *(input + index)); //Calculate max number of vertices if (max < **(input + index)) { max = **(input + index); } printf("%d ", **(input + index)); ++index; } printf("Max: %d", max); printf("\n"); printf("%d\n", index); Vert vertices[max]; Stack* stack = malloc(sizeof(stack)); printf("Create Stack pointer\n"); stack->top = -1; printf("Initialize top\n"); for(int i = 0; i <= max + 1; i++){ stack->elements[i] = ' '; } printf("Stack init works\n"); for(int i = 0; i < max; i++){ vertices[i].visited = 0; vertices[i].magnitude = 0; for(int j = 0; j < MAX_VERT; j++){ vertices[i].adj[j] = ' '; } // printf("Visited: %d Magnitude: %d Index: %d\n", vertices[i].visited, vertices[i].magnitude, i); } printf("Vert init works\n"); index = 0; while((*(input+index)) != NULL){ if(index == 0 || index % 2 == 0){ int source = **(input+index); int dest = **(input+index+1); build_array(source, dest, vertices, max); printf("s: %d | d: %d\n", source, dest); } index++; } // printf("After build_array Loop\n"); // int temp = 43434213; // for(index = 0; index < max; index++) { // for(int i = 0; i < vertices[index].magnitude; i++) { // if(abs(vertices[index].adj[i]) > abs(vertices[index].adj[i+1])) { // temp = vertices[index].adj[i]; // vertices[index].adj[i] = vertices[index].adj[i+1]; // vertices[index].adj[i+1] = vertices[index].adj[i]; // } // } // } int i = 0; for(index = 0; index < max; index++) { printf("v: %d | ", index + 1); i = 0; while(vertices[index].adj[i] != ' ') { printf("%d ", vertices[index].adj[i]); i++; } printf("\n"); } GraphSCC graphSCC[max]; for(index = 0; index < max; index++){ graphSCC[index].index = 0; graphSCC[index].outDegree = 0; for(int j = 0; j < max; j++){ graphSCC[index].components[j] = 0; } } order_pass(max, vertices, stack, graphSCC); reset_visited(max, vertices); scc_pass(stack, vertices, max, graphSCC); fclose(inptr); free(input); printf("\n"); return 0; } void build_array (int s, int d, Vert* vert, int max) { int i = 0; int temp; vert[s-1].magnitude++; vert[d-1].magnitude++; //printf("mag: %d | ", vert[s-1].magnitude); //printf(". "); while(vert[s-1].adj[i] != ' '){ i++; } vert[s-1].adj[i] = d; int j = 0; while(vert[d-1].adj[j] != ' '){ j++; } vert[d-1].adj[j] = -s; printf("pos: %d | neg: %d \n", vert[s-1].adj[i], vert[d-1].adj[j]); } void push(int v, Stack* stack, int max){ stack->top++; // printf("Stack Top: %d ", stack->top); if(stack->top < max){ stack->elements[stack->top] = v; } else{ printf("Stack is full\n"); exit(1); } } int pop(Stack* stack){ return stack->top < 0 ? -1 : stack->elements[stack->top--]; } void dfs(int v, int transpose, Vert vert[], Stack* stack, int max, GraphSCC graphSCC[]){ int i, c ,n; vert[v].visited = 1; for(i = 0, c = vert[v].magnitude; i < c; ++i){ n = vert[v].adj[i]*transpose; if(n > 0){ if(!vert[n-1].visited){ dfs(n-1, transpose, vert, stack, max, graphSCC); } // else{ // printf("v: %d\n", vert); // } } } if (transpose < 0){ push(v, stack, max); } else{ printf("%d ", v + 1); } } void reset_visited(int max, Vert vert[]){ for(int i = 0; i < max; ++i){ // printf("Reset visited to 0 "); vert[i].visited = 0; } printf("\n"); } void order_pass(int max, Vert vert[], Stack* stack, GraphSCC graphSCC[]){ for(int i = 0; i < max; ++i){ if(!vert[i].visited){ <<<<<<< HEAD dfs(i , -1, vert, stack, max, graphSCC); ======= // printf("Ordered Pass DFS "); dfs(i , -1, vert, stack, max); >>>>>>> c92bc44a79aa5ca9460b6c4a784a8f9a34379b2f } } printf("\n"); } void scc_pass(Stack* stack, Vert vert[], int max, GraphSCC graphSCC[]){ int i = 0, v; while((v = pop(stack)) != -1){ //printf("v: %d\n", v); if(!vert[v].visited){ printf("scc %d: ", ++i); graphSCC[i].index = i; dfs(v, 1, vert, stack, max, graphSCC); printf("\n"); } } } /* New Program Flow: Build the graph and create the adjacency list search the graph for the SCC turn the SCC into one component build the graph with that find the out degree of the SCC */
C
/* * Roey Shushan - 312577919 * Bar Pinian - 313347585 */ #include <stdio.h> // For the printing. #include <unistd.h> // For reading and closing the file. #include <fcntl.h> // For the file opening. #include <string.h> // For the strcpy. #define MAX_PKT_SIZE 1024 // Constant size for the path of the file. /* Our user program main function. */ int main(int argc, char** argv) { int fd; // Integer representation for our file opening. char buff[MAX_PKT_SIZE]; // Our buffer. char devicePath[100]; // The path of the created file by our kobject within the driver. strcpy(devicePath, "/sys/kernel/keylogger/data_attr"); // Initialization of the file path. fd = open(devicePath, O_RDONLY); // Opening the file (our keylogger file). if(fd == -1) // If error was returned by the file opening. { printf("error file open"); // Printing error message. return -1; // Returning the integer representation of the error. } read(fd,buff,sizeof(buff)); // Reading from the file (our keylogger file). printf("The keylogger file content: \n%s\n", buff); // Printing the content within the keylogger file. close(fd); // Closing the opened file. }
C
#include "test.h" #include "jlvm.h" #include "jlvm.c" #define NUMARGS(...) (sizeof((long[]){__VA_ARGS__})/sizeof(long)) #define LIST(...) (list_(NUMARGS(__VA_ARGS__), __VA_ARGS__)) #define I(i) (i << NSHIFT) int listcmp(pair x, pair y) { for(pair a = (pair) x, b = (pair) y; a != NIL || b != NIL; a = (pair) cdr(a), b = (pair) cdr(b)) { if(IS_CONS(car(a)) && IS_CONS(car(b))) { return listcmp((pair) car(a), (pair) car(b)); } if(car(a) != car(b)) { return 1; } } return 0; } #define listeq(x, y) if (listcmp(x, y) != 0) {\ printf("expected: "); \ print_val((long) x); \ printf("\ngot: "); \ print_val((long) y); \ printf("\n"); \ fail; \ } void print_val(long v) { if(IS_INT(v)) { printf("INT<%d>", v >> NSHIFT); } else if ((v & BITMASK) == T_SYM) { printf("SYM<%s>", v - T_SYM); } else if (IS_CONS(v)) { pair p = (pair) v; if(p != NIL) { printf("("); print_val(car(p)); printf(" . "); print_val(cdr(p)); printf(")"); } else { printf("'()"); } } else if (IS_FUN(v)) { pair c = (pair) ((long) v - T_FUN + T_CONS); printf("FUN<frees: "); print_val((long) cdr(c)); printf(" code: %p", car(c)); putchar('>'); } else { printf("?<0x%x>", v); } } // list constructor accepting whatever cons we want to use (tagged, untagged, reversed, etc) pair list_(int n, ...) { va_list l; va_start(l, n); pair p = cons(va_arg(l, long), (long) NIL); pair c = p; for(int i = 0; i < (n - 1); i++) { cdr_(c) = (long) cons(va_arg(l, long), (long) NIL); c = (pair) cdr_(c); } va_end(l); return p; } void reset() { S = NIL; E = NIL; C = NIL; D = NIL; } void t1() { E = LIST((long) cons(I(1), (long) NIL)); C = LIST(LD, (long) cons(0, 0)); eval(); listeq(LIST(I(1)), S); } void t2() { long b[] = {LNIL, LDC, I(4), CONS}; eval_bytes(b, sizeof(b) / sizeof(long)); listeq(LIST((long) LIST(I(4))), S); } void t3() { C = LIST(LDC, I(2), SEL, (long) LIST(LDC, I(2), JOIN), (long) LIST(LNIL, JOIN), LNIL); eval(); listeq(LIST((long) NIL, I(2)), S); } void t4() { E = LIST((long) NIL, (long) NIL); C = LIST(LDF, (long) LIST( LD, (long) cons(0, 0), LD, (long) cons(0, 1), RET)); eval(); assert(IS_FUN(car(S))); } void t5() { E = LIST((long) I(3), (long) NIL); C = LIST( LDC, (long) cons(I(1), (long) cons(I(2), (long) NIL)), LDF, (long) LIST( LD, (long) cons(0, 0), LD, (long) cons(0, 1), RET), AP); eval(); listeq(LIST(I(2)), S); } void t6() { // ((lambda (x) (x)) (lambda () 1)) C = LIST(LNIL, LDF, (long) LIST(LDC, I(1), RET), CONS, LDF, (long) LIST(LNIL, LD, (long) cons(0, 0), AP, RET), AP); eval(); listeq(LIST(I(1)), S); } void t7() { // (def (a) a) C = LIST(DUM, LNIL, LDF, (long) LIST(LD, (long) cons(0, 0), RET), CONS, LDF, (long) LIST(LNIL, LDC, I(2), CONS, LD, (long) cons(0, 0), AP, RET), RAP); eval(); listeq(LIST(I(2)), S); } void t8() { E = LIST( (long) cons(I(1), (long) cons(I(2), (long) NIL)), (long) cons(I(4), (long) cons(I(8), (long) NIL)) ); C = LIST(LD, (long) cons(0, 0), LD, (long) cons(0, 1), LNIL, LD, (long) cons(1, 0), CONS, LD, (long) cons(1, 1), CONS, CDR, CAR, LDC, sym("hi"), LDC, sym("hi"), EQ); eval(); listeq(LIST(sym("t"), I(4), I(2), I(1)), S); } void t9() { C = LIST(LDC, I(1), LDC, I(2), ADD, LDC, I(5), LDC, I(3), SUB, LDC, I(4), LDC, I(2), MUL, LDC, I(12), LDC, I(2), DIV, LDC, I(12), LDC, I(5), REM, LDC, I(8), LDC, I(32), LT); eval(); listeq(LIST(sym("t"), I(2), I(6), I(8), I(2), I(3)), S); } /*void t9() { // (def (a) // (a)) C = LIST(DUM, LNIL, LDF, (long) LIST(LNIL, LD, (long) cons(1, 0), TAP), CONS, LDF, (long) LIST(LNIL, LD, (long) cons(0, 0), AP), RAP); eval(); print_val((long) S); }*/ #define CLEAN_TEST(tt) {reset(); TEST(tt)}; //TODO: assert stuff BEGIN CLEAN_TEST(t1) CLEAN_TEST(t2) CLEAN_TEST(t3) CLEAN_TEST(t4) CLEAN_TEST(t5) CLEAN_TEST(t6) CLEAN_TEST(t7) CLEAN_TEST(t8) CLEAN_TEST(t9) END
C
#include <stdlib.h> #include<stdio.h> int main() { char *x=NULL; if(x == NULL) { printf("X is NULL"); /* replace with cout and include iostream for C++ */ } x =(char *) malloc(10); printf("Hii"); x[9] = 'a'; printf("Hoooo"); return 0; }
C
/************************************************************************* > File Name: dynamic.c > Author: wangjx ************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> void dump(int *src, int len,int *record) { int index = 0; for (index = 0; index < len; index++) { if (record[index]) printf("%d ", src[index]); } printf("\n"); } int bag(int *src, int offset, int len, int *record, int res, int max) { if (offset >= len || res >= max) { dump(src, len, record); return; } memset(record + offset, 0, len - offset); bag(src, offset + 1, len, record, res, max); if (res + src[offset] <= max) { record[offset] = 1; bag(src, offset + 1, len, record, res + src[offset], max); //dump(src, len, record); return; } } void main() { int array[] = {2, 2 ,4 ,6 ,3}; int *result = malloc(sizeof(array)); memset(result, 0, sizeof(array)); bag(array, 0, 5, result, 0, 9); }
C
/* Victor Forbes - 9293394 */ #ifndef UTILS_H #define UTILS_H #define max(a, b) (a > b ? a : b) #define min(a, b) (a < b ? a : b) /* O(1) - Swaps two elements given their address and size. */ void swap(void *, void *, int); #endif
C
#include"head.h" int main(int argc,char **argv) { if(argc!=2) { printf("参数错误\n"); return -1; } int fd=open(argv[1],O_RDWR|O_CREAT,0666); if(-1==fd) { perror("open"); return -1; } int ret=ftruncate(fd,1<<20); if(ret==-1) { perror("ftruncate"); return -1; } close(fd); return 0; }
C
/* * next_prime.c * * Find the next prime number that comes after * the user's submitted n, up to 1998, whose * next prime is 1999. * * Required linked libraries: math * * author: Ryan Morehouse * license: MIT */ #include <stdio.h> #include <stdlib.h> #include <math.h> #define MIN 1 #define MAX 1998 void error_msg() { printf("Usage: next_prime.o [n]\n"); printf("[n] is a positive integer less than 1999\n"); exit(EXIT_FAILURE); } int isPrime(int number) { if(number < 2) { printf("Error in isPrime(): arg must be > 1\n"); exit(EXIT_FAILURE); } int is_prime_local = 1; if(number > 2) { double max_range = ceil(sqrt((double)number)); int i = 2; while(is_prime_local) { if(number % i == 0) is_prime_local = 0; else if(i > max_range) break; else i += 1; } } return is_prime_local; } int main(int argc, char *argv[]) { // verify there is an arg if(argc < 2) error_msg(); // verify arg is within limits int n = atoi(argv[1]); if(n < MIN || n > MAX) error_msg(); // simple cases if(n == 1) { printf("2\n"); return 0; } else if(n == 2) { printf("3\n"); return 0; } // iteration flag int prime_found = 0; // test values int test_max = n * 2; int i = n + 1; while(prime_found == 0) { if(i == test_max) { printf("There has been a fatal programming error.\n"); printf("A prime should have been found but was not.\n"); exit(EXIT_FAILURE); } prime_found = isPrime(i); if(prime_found) break; else if(i % 2 == 0) i += 1; // i is even, go to next odd else i += 2; // i is odd, go to next odd } printf("%d\n", i); return 0; }
C
/* * \file: sq_timer.h * \brief: Created by hushouguo at 18:01:13 Dec 26 2011 */ #ifndef __SQ_TIMER_H__ #define __SQ_TIMER_H__ // base on millisecond struct sq_timer { sq_time scale; unsigned int interval; sq_timer(unsigned int inter) : interval(inter) { next(); } void set(unsigned int inter); unsigned int get(); void next(); bool operator()(sq_time& current); }; #endif
C
/* * Project Euler * 35.c */ #include <stdio.h> #include <stdlib.h> #include "array.h" #include "euler.h" #include "prime.h" int* rotations_of(int x); bool is_circular_prime(int x, int* primes, int primes_len); int main() { // sieve int limit = 1000000; int primes_len; int* primes = eratosthenes(limit, &primes_len); // count circular primes int total = 0; for (int i=0; i<primes_len; i++) { if (is_circular_prime(primes[i], primes, primes_len)) { printf("%d \n", primes[i]); total++; } } // end printf("total %d \n", total); free(primes); return 0; } /** * Generates x's rotations, excluding x itself. The output array's length * is 1 less than x's total digits. * * @param x the term to evaluate * @return a heap-allocated array */ int* rotations_of(int x) { int* digits = digits_of(x); int digits_len = digit_count(x); int* rots = calloc(digits_len-1, sizeof(int)); for (int i=0; i<digits_len-1; i++) { digits = arr_shift_left(digits, digits_len); int rot = digits_to_int(digits, digits_len); rots[i] = rot; } free(digits); return rots; } /** * Returns true if x is a circular prime as described in the problem * text. * * @param x the term to test * @param primes an array of primes * @param primes_len the array's length * @return true or false */ bool is_circular_prime(int x, int* primes, int primes_len) { int* rots = rotations_of(x); int rots_len = digit_count(x)-1; int total_primes = 0; for (int i=0; i<rots_len; i++) { if (arr_bsearch(primes, primes_len, rots[i])) total_primes++; else break; } free(rots); return (total_primes == rots_len); }
C
#include<stdio.h> #include<conio.h> int a[100],i,j,temp,k,n,min,loc,count; void insert(){ printf("How Many Elements to be stored in array: "); scanf("%d",&n); printf("\nEnter array Elements: "); for(i=0;i<n;i++) { scanf("%d",&a[i]); } } void display(){ printf("\nArray Before Sorting : ->\n "); for(i=0;i<n;i++) printf(" %d ",a[i]); for(i=0;i<=n-1;i++) { min=a[i]; loc=i; count++; for(j=i+1;j<n-1;j++) { if(a[j]<min) { min=a[j]; loc=j; } } if(loc!=i) { temp=a[i]; a[i]=a[loc]; a[loc]=temp; } count++; } printf("\nComparisons Made are-> %d\n\n",count); printf("\nArray After Sorting : -> \n"); for(i=0;i<n;i++) printf("\t%d",a[i]); } main() { int choice; clrscr(); while (1) { printf("\n1.Insert \n"); printf("2.Display \n"); printf("3.Quit \n"); printf("Enter your choice : "); scanf("%d", &choice); switch(choice) { case 1: insert(); break; case 2: display(); break; case 3: exit(0); default: printf("Wrong choice \n"); } } getch(); return 0; }
C
/* Selective printing of file contents filename: Ch13Ex10.c ver 1.0 Aleksandr Kravtsov */ #include "get_str.h" #include "get_first_long.h" #include <stdio.h> #include <stdlib.h> #define MAX_LENGTH 81 #define STOP_CHAR '\n' int main(void) { char file_name[MAX_LENGTH]; FILE *file_ptr; long position; int ch; int number_of_ch = 0; /* in the open file */ fprintf(stdout, "Enter the name of the file, up to %d characters\n", MAX_LENGTH); if(get_str(file_name, MAX_LENGTH) == NULL) { fprintf(stdout, "Error: invalid file name\n"); exit(EXIT_FAILURE); } if((file_ptr = fopen(file_name, "r")) == NULL) { fprintf(stderr, "Error: can't open file \"%s\"\n", file_name); exit(EXIT_FAILURE); } while((ch = getc(file_ptr)) != EOF) number_of_ch++; fprintf(stdout, "Enter the starting position for printing from 0 to %d\n" "('< 0' to exit): ", number_of_ch); while((position = get_first_long()) >= 0) { fseek(file_ptr, position, SEEK_SET); if(position > number_of_ch) { fprintf(stdout, "Enter number from 0 to %d('< 0' to exit):", number_of_ch); continue; } while((ch = getc(file_ptr)) != STOP_CHAR && ch != EOF) putc(ch, stdout); putc('\n', stdout); fprintf(stdout, "\nEnter the starting position for printing " "from 0 to %d\n('< 0' to exit): ", number_of_ch); } if(fclose(file_ptr) != 0) { fprintf(stderr, "Error when closing file \"%s\"\n", file_name); exit(EXIT_FAILURE); } fprintf(stdout, "Program is over\n"); return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> typedef enum {CONSTANT = 50, VARIABLE, ARRAY, SUBPROC, REFERENCE} VarType; typedef struct node { char name[11]; VarType kind; int argCount; int size; int offset; int beginLineOfCode; struct node *down; int arguments[10]; } node, *table; typedef struct tablePointer { table tab; int size; struct tablePointer *parent; } *list, tablePointer; typedef struct { node *resNode; int p; int q; } coordinates; node *newNode(char _name[11], VarType _kind, int _size){ node *temp = (node *) malloc(sizeof(node)); strcpy(temp->name, _name); temp->kind = _kind; temp->size = _size; temp->down = NULL; return temp; } table newTable(){ node *a = (node *) malloc(sizeof(node)); strcpy(a->name, "112358"); a->down = NULL; return a; } table pushIdent(table top, char _name[11], VarType _kind, int _size){ node *new_node = newNode(_name, _kind, _size); if(top->down == NULL){ new_node->offset = 4; } else { new_node->offset = top->offset + top->size; } new_node->down = top; top = new_node; return top; } void printTable(table top){ int i; node *a = top; while(a != NULL){ printf("name: %s, size: %d, offset: %d, kind: %d, begin line: %d, argCount: %d arguments: ", a->name, a->size, a->offset, a->kind, a->beginLineOfCode, a->argCount); for(i = 0; i < 10; i++){ printf("%d ", a->arguments[i]); } printf("\n"); a = a->down; } } tablePointer *newTablePointer(table existTable){ tablePointer *a = (tablePointer *) malloc(sizeof(tablePointer)); a->tab = (node *) malloc(sizeof(node)); strcpy(a->tab->name, existTable->name); a->tab->kind = existTable->kind; a->tab->down = existTable->down; a->tab->size = existTable->size; a->parent = NULL; return a; } list newList(){ tablePointer *a = (tablePointer *) malloc(sizeof(tablePointer)); a->parent = NULL; return a; } list pushTable(list currentTable, table existTable){ tablePointer *newTabPointer = newTablePointer(existTable); newTabPointer->parent = currentTable; currentTable = newTabPointer; return currentTable; } void printList(list currentTable){ tablePointer *a = currentTable; while(a != NULL){ printTable(a->tab); a = a->parent; } } // node *lookupAll(list currentTable, char x[11]){ // tablePointer *a = currentTable; // while(a != NULL){ // table b = a->tab; // node *c = b; // while(c != NULL){ // if(stringcmp(c->name, x) == 0){ // return c; // } // c = c->down; // } // a = a->parent; // } // return NULL; // } coordinates *lookupAll(list currentTable, char x[11]){ tablePointer *a = currentTable; coordinates *tmp = (coordinates *) malloc(sizeof(coordinates)); tmp->p = 0; while(a != NULL){ tmp->q = 3; table b = a->tab; node *c = b; while(c != NULL){ if(stringcmp(c->name, x) == 0){ tmp->resNode = c; tmp->q = c->offset; return tmp; } c = c->down; } a = a->parent; tmp->p += 1; } return NULL; } node *lookupCurrent(list currentTable, char x[11]){ tablePointer *a = currentTable; node *b = a->tab; while(b != NULL){ if(stringcmp(b->name, x) == 0){ return b; } b = b->down; } return NULL; } int getArgCount(list currentTable){ list a = currentTable; if(a->parent->parent == NULL){ return 0; } else { return a->parent->tab->argCount; } }
C
//pathway14.c - Path through Lothwaite. Circe 5/10/04 #include <std.h> #include "../lothwaite.h" inherit TOWNPATH; void create(){ ::create(); set_long( ::query_long()+" The path continues here, leading "+ "southwest toward the ramparts or northeast into the "+ "village. A smooth, grassy dip in the valley to the north "+ "leads to two tall buildings.\n"); set_exits(([ "southwest" : PATHEXIT"pathway13", "northeast" : PATHEXIT"pathway15", "north" : PATHEXIT"grass1" ])); }
C
#include <stdio.h> #if defined(linux) /* Connects the baselibc stdio to normal POSIX stdio */ size_t write(int fd, const void *buf, size_t count); static size_t stdio_write(FILE *instance, const char *bp, size_t n) { if (instance == stdout) return write(1, bp, n); else return write(2, bp, n); } #else #error No suitable write() implementation. #endif static struct File_methods stdio_methods = { &stdio_write, NULL }; static struct File _stdout = { &stdio_methods }; static struct File _stderr = { &stdio_methods }; FILE* const stdout = &_stdout; FILE* const stderr = &_stderr;
C
/* * phOsal_NullOs_Port.h * * Created on: Feb 28, 2017 * Author: nxf18375 */ #ifndef PHOSAL_NULLOS_PORT_H_ #define PHOSAL_NULLOS_PORT_H_ #include "phDriver.h" // Kai Chen /** \defgroup phOsal_NullOs_Post NullOs_Port layer * \brief NullOs implementation needs SysTick Timer for its functionality. * This file defines functions used by the NullOs Implementation. * User should provide implementation of these in respective platforms . * @{ */ /** * * \brief Tick Timer ISR callback which will be called by ISR handler implementation in Platform Layer. * \retval None */ typedef void (*pphOsal_TickTimerISRCallBck_t)(void); /** * \brief This function Initializes the Tick Timer. * * @param[in] pTickTimerCallback Callback required to be called from the Timer-ISR * */ extern phStatus_t phOsal_InitTickTimer(pphOsal_TickTimerISRCallBck_t pTickTimerCallback); /** * \brief This function Starts the Tick Timer. * * @param[in] dwTimeMilliSecs Timer Time duration in Milli-sec. * */ extern phStatus_t phOsal_StartTickTimer(uint32_t dwTimeMilliSecs); /** * \brief This function Stops the running Tick Timer. * */ extern phStatus_t phOsal_StopTickTimer(void); /** * \brief This function if called, allows, instructions to be executed * without being interrupted by any other code flow. * */ extern void phOsal_EnterCriticalSection(void); /** * \brief This function restors the normal extecution of code flow, allows interrupts * etc. to occur. * */ extern void phOsal_ExitCriticalSection(void); /** * \brief This function put the processor to sleep * */ extern void phOsal_Sleep(void); /** * \brief This function wakesup the processor. * */ extern void phOsal_WakeUp(void); /*@}*/ #endif /* PHOSAL_NULLOS_PORT_H_ */
C
/* * Copyright (c) 2018 Integrated Solutions, Inc. * All rights reserved, worldwide. * */ #include "stm32f0xx_gpio.h" #include "stm32f0xx_usart.h" /* Scheduler include files */ #include "FreeRTOS.h" #include "semphr.h" #include "task.h" #include <string.h> #include "armtypes.h" #include "uart5.h" #include "Debug.h" #if 0 #define MAX_RBUF_SIZE 256 uint8 rbuf[MAX_RBUF_SIZE] = {0}; void modem_PrintRbuf() { debug_Printf("modem: %s", rbuf); } int modem_ResponseHasOK() { if (strstr((const char *)rbuf, "OK\r\n") != NULL) return 1; return 0; } int modem_SendATCommand(const char *pCmd, int timeout_ms) { int cmdlength,nbytes; int index=-1; int rbyte; portTickType xDelayTime = 100 / portTICK_RATE_MS; cmdlength = strlen(pCmd); // check how many characters will echo uart5_Puts(pCmd); // send to modem vTaskDelay(xDelayTime); nbytes = uart5_Read(rbuf, cmdlength, 0); // read out echo rbuf[nbytes] = 0; if (nbytes > 0 && strcmp(pCmd, (const char *)rbuf) == 0) { // it was echoed, let's wait for response index = 0; // attempt to grab first char rbuf[index] = uart5_WaitForByte(timeout_ms); if (rbuf[index] == -1) return -1; index++; while(1) { rbyte = uart5_WaitForByte(50); if (rbyte == -1) break; rbuf[index] = rbyte; index++; } rbuf[index++] = 0; // we should have a response } return index; // return num received or -1 } #endif void Modem_Init() { uart5_Init(); // CELL MODEM UART } void Modem_Test() { uart5_Puts("AT\n"); // uart5_Puts("AT+CGMI\n"); }
C
#ifndef PRACTISE_TWODIMENIONSTRING_H #define PRACTISE_TWODIMENIONSTRING_H #include <stdio.h> #include <stdlib.h> #include <string.h> //字符串封装 库函数 struct String{ char * pointer;//保存字符串的首地址 int reallyLength;//字符串的实际长度 }; typedef struct String MyString;//简写 //字符串,初始化,打印,增加(字符,字符串),删除(字符串,字符) //查找,查找字符串,查找字符 //修改字符串,(字符串替换) //尾部增加字符串,任意位置增加字符串(字符,字符串) void init(MyString *string);//原封不动初始化 void initWithLength(MyString * string,int length);//开辟长度 void initWithString(MyString *string,char * copyString);//初始化并拷贝字符串 void printString(MyString *string); void backAddCharacter(MyString *string,char c);//尾部增加字符 void backAddString(MyString *string,char *characterArray); void run(MyString *string); char * findStringFirstCharacter(MyString * string,char character); char * findStringFirstString(MyString *string,char * findString);//返回第一个找到的字符串地址 int deleteFirstCharacter(MyString *string,char deleteCharacter); int deleteFirstString(MyString *string,char * deleteString); void addCharacter(MyString *string,char character,char *position);//任意位置增加字符 void addString(MyString *myString,char * string,char * position);//任意位置增加字符串 void changeFirstCharacter(MyString *myString, const char oldCharacter, const char newCharacter);//改变字符 void changeFirstString(MyString *myString, char *const oldString,char *const newString);//改变字符串 #endif //PRACTISE_TWODIMENIONSTRING_H