language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include<stdio.h> #include<stdlib.h> #define MAX_LIST_SIZE 100 typedef int element; typedef struct { int list[MAX_LIST_SIZE]; int length; }ArrayListType; void init(ArrayListType *L){ L->length =0; } int is_empty(ArrayListType *L){ return L->length == 0; } int is_full(ArrayListType *L){ return L->length == MAX_LIST_SIZE; } void add(ArrayListType *L,int position,element item){ if(!is_full(L)&&(position >=0)&&(position<=L->length)){ int i; for(i=(L->length-1);i>=position;i--){ L->list[i+1]=L-> list[i]; } L->list[position]=item; L->length++; } } element delete (ArrayListType *L,int position){ int i; element item; if(position<0||position >=L->length){ // error("ġ "); } item=L-> list[position]; for(i=position;i<(L->length-1);i++){ L->list[i]=L-> list[i+1]; } L->length--; return item; } void display(ArrayListType *L){ int i; for(i=0;i<L->length; i++){ printf("%d\n",L-> list[i]); } } //void error(char *message){ // fprintf(stderr,"%s\n",message); // exit(1); //} main(){ ArrayListType list1; ArrayListType *plist; init(&list1); add(&list1,0,10); add(&list1,0,20); add(&list1,0,30); display(&list1); }
C
#include <stdio.h> //iki sayıyı karşılaştır ve büyük olan çift mi tek mi kontrol et int main() { int sayi1, sayi2; printf("birinci sayiyi giriniz :"); scanf("%d", &sayi1); printf("ikinci sayiyi giriniz :"); scanf("%d", &sayi2); if(sayi1 > sayi2) { if (sayi1%2 == 0) printf("birinci sayı büyük ve çifttir. \n"); else printf("birinci sayı büyük ve tektir. \n"); } else { if (sayi2> sayi1) printf("ikinci sayı büyük ve çifttir. \n"); else printf("ikiinci sayı büyük ve tektir. \n"); } return 0; }
C
#include "option.h" option *option_new( const char *short_opt, const char *long_opt, const char *description ) { option *opt = NULL; opt = malloc(sizeof(option)); if (!opt) return NULL; opt->short_opt = short_opt; opt->long_opt = long_opt; opt->description = description; opt->argument = NULL; opt->accepts_arguments = false; opt->requires_arguments = false; opt->argument_delimiter = ':'; opt->present = 0; opt->next = NULL; return opt; } void option_free(option *opt) { if (opt->argument) operand_free(opt->argument); opt->argument = NULL; if (opt->next) option_free(opt->next); opt->next = NULL; free(opt); } ARGPARSEcode option_help(const option *opt, size_t padding, FILE *stream) { fprintf(stream, " "); if (opt->short_opt) fprintf(stream, "-%s", opt->short_opt); else fprintf(stream, " "); fprintf(stream, " "); if (opt->long_opt) fprintf(stream, "--%s", opt->long_opt); // TODO split long descriptions where appropriate and pad if (opt->description) { if (strlen(opt->long_opt) >= ARGPARSE_MAXLEN_LONG_OPT) fprintf(stream, "\n%*s", padding, " "); else fprintf(stream, "%*s", padding - option_padding(opt) + 2, " "); fprintf(stream, "%s", opt->description); } fprintf(stream, "\n"); return ARGPARSE_OK; } size_t option_padding(option *opt) { // 5 is the magic number for the leading two spaces to indent, the // two characters representing the short option and the space // separating the short and the long option return 5 + strlen(opt->long_opt); } option *option_find(const args *args, const char *opt) { bool short_opt = false; char *passed; if (strlen(opt) == 1) short_opt = true; option *cur = args->opts; const char *compare; while (cur) { if (short_opt && cur->short_opt) compare = cur->short_opt; else if (cur->long_opt) compare = cur->long_opt; if (compare && strcmp(opt, compare) == 0) return cur; compare = NULL; cur = cur->next; } return NULL; } ARGPARSEcode option_add_argument(option *opt, operand *op) { if (!opt || !op) return ARGPARSE_PASSED_NULL; operand *cur = opt->argument; if (!cur) { opt->argument = op; // check for modifiers, since this is the first option-argument // to be added to the option char *modifiers[] = { "false", "no", "disable" }; for (size_t i = 0; i < LENGTH(modifiers); ++i) { if (strcmp(op->string, modifiers[i]) == 0) { LOG("found modifier %s, flipping %d", modifiers[i], opt->present); opt->present *= -1; break; } } } else { while (cur->next) cur = cur->next; cur->next = op; } return ARGPARSE_OK; }
C
#include <stdio.h> #include <stdlib.h> #include <malloc.h> struct t_nodo { int valor; struct t_nodo *pai; struct t_nodo *fillo1; struct t_nodo *fillo2; }; struct t_nodo *nodo_raiz = NULL; unsigned char e_nodo_raiz(struct t_nodo *nodo) { return (!nodo->pai); } struct t_nodo *crear_nodo(int valor) { struct t_nodo *nodo = (struct t_nodo *)malloc(sizeof(struct t_nodo)); nodo->pai=NULL; nodo->fillo1=NULL; nodo->fillo2=NULL; nodo->valor = valor; return nodo; } void insertar_nodo_rec(struct t_nodo *p_nodo, int valor) { struct t_nodo *nodo_novo = NULL; //struct t_nodo *p_nodo = *p_nodo_ref; if (!p_nodo) { nodo_novo = crear_nodo(valor); p_nodo = nodo_raiz = nodo_novo; } else if (valor < p_nodo->valor) { if (!p_nodo->fillo1) { nodo_novo = crear_nodo(valor); p_nodo->fillo1=nodo_novo; nodo_novo->pai=p_nodo; } else { insertar_nodo_rec(p_nodo->fillo1, valor); } } else { if (!p_nodo->fillo2) { nodo_novo = crear_nodo(valor); p_nodo->fillo2=nodo_novo; nodo_novo->pai=p_nodo; } else { insertar_nodo_rec(p_nodo->fillo2, valor); } } } void insertar_nodo(int valor) { struct t_nodo *p_nodo = nodo_raiz; insertar_nodo_rec(p_nodo, valor); } void ler_arbol_rec(struct t_nodo *nodo) { if (!nodo) { printf("nodo nulo\n"); return; } if (nodo->fillo1) { ler_arbol_rec(nodo->fillo1); printf("%d ", nodo->valor); } else { printf("%d ", nodo->valor); } if (nodo->fillo2) { ler_arbol_rec(nodo->fillo2); } } void ler_arbol(struct t_nodo *nodo) { ler_arbol_rec(nodo); printf("\n"); } void imprimir_uso(char *nom_prog) { printf("Uso: %s <valor1 valor2 ...>\n", nom_prog); exit(1); } void liberar_memoria(struct t_nodo *nodo) { if (!nodo) return; if (nodo->fillo1) liberar_memoria(nodo->fillo1); if (nodo->fillo2) liberar_memoria(nodo->fillo2); free(nodo); } int main(int argc, char *argv[]) { int valor = 0; if (argc==1) { imprimir_uso(argv[0]); } else { for (int i = 1; i<argc; i++) { valor = atoi(argv[i]); insertar_nodo(valor); } } ler_arbol(nodo_raiz); liberar_memoria(nodo_raiz); //printf("%d %d %d\n",nodo_raiz->fillo1->valor, nodo_raiz->valor, nodo_raiz->fillo2->valor); return 0; }
C
/* to run gcc -O2 -Wall -pthread a2.c -o quicksort ./quicksort */ #include <stdio.h> #include <stdlib.h> #include <pthread.h> #define LIMIT 20 #define MESSAGES 50 #define WORK 0 #define FINISH 1 #define SHUTDOWN 2 #define THREADS 4 #define N 1000 struct message { int type; int start_pos; int end_pos; }; struct message mqueue[MESSAGES]; //queue in and out pos counters int qin = 0, qout = 0; int message_count = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t msg_in = PTHREAD_COND_INITIALIZER; pthread_cond_t msg_out = PTHREAD_COND_INITIALIZER; float random_float( float min, float max){ return ((((float) rand()) / (float) RAND_MAX)*(max - min)) + min; } void swap(double *a, double *b) { double t = *a; *a = *b; *b = t; } void inssort(double *a,int n) { int i,j; for (i=1;i<n;i++) { j = i; while ((j>0) && (a[j-1]>a[j])) { swap(&a[j-1], &a[j]); j--; } } } int partition(double *a,int n) { int first,last,middle,i,j; double p; // take first, last and middle positions first = 0; middle = n/2; last = n-1; // put median-of-3 in the middle if (a[middle]<a[first]) { swap(&a[first], &a[middle]); } if (a[last]<a[middle]) { swap(&a[middle], &a[last]); } if (a[middle]<a[first]) { swap(&a[first], &a[middle]); } // partition (first and last are already in correct half) p = a[middle]; // pivot for (i=1,j=n-2;;i++,j--) { while (a[i]<p) i++; while (p<a[j]) j--; if (i>=j) break; swap(&a[i], &a[j]); } // return position of pivot return i; } void send(int type, int start_pos, int end_pos) { pthread_mutex_lock(&mutex); while(message_count >= MESSAGES) { pthread_cond_wait(&msg_out, &mutex); } //insert message in queue mqueue[qin].type = type; mqueue[qin].start_pos = start_pos; mqueue[qin].end_pos = end_pos; qin++; //if queue counter >= queue size //then return to the start if(qin >= MESSAGES) { qin = 0; } //add message to message counter message_count++; pthread_cond_signal(&msg_in); pthread_mutex_unlock(&mutex); } void receive(int *type, int *start_pos, int *end_pos) { pthread_mutex_lock(&mutex); while(message_count < 1) { pthread_cond_wait(&msg_out, &mutex); } //take message *type = mqueue[qout].type; *start_pos = mqueue[qout].start_pos; *end_pos = mqueue[qout].end_pos; qout++; //if queue counter >= queue size //then return to the start if(qout >= MESSAGES) { qout = 0; } //remove a message from message counter message_count--; pthread_cond_signal(&msg_out); pthread_mutex_unlock(&mutex); } void *thread_func(void *params) { double *a = (double*)params; int type, start_pos, end_pos; while(1) { receive(&type, &start_pos, &end_pos); if(type == SHUTDOWN) { send(SHUTDOWN, 0, 0); break; } else if(type == FINISH) { send(FINISH, start_pos, end_pos); } else if (type == WORK) { //work load int n = end_pos - start_pos; // check if below limit // if it is sort it if(n <= LIMIT) { inssort(a+start_pos, n); send(FINISH, start_pos, end_pos); } // if it's not partition into two halves // create packages to sort halves else { int pivot = partition(a+start_pos, n); int middle = start_pos+pivot; send(WORK, start_pos, middle); send(WORK, middle, end_pos); } } } pthread_exit(NULL); } int main() { double *a; int type, start_pos, end_pos; int completed = 0; a = (double*)malloc(N*sizeof(double)); if(a == NULL) { return 1; } for(int i=0; i<N; i++) { a[i] = random_float(0.01,2.5); } //create threads pthread_t threads[THREADS]; for(int i=0; i<THREADS; i++) { if(pthread_create(&threads[i], NULL, thread_func, a) != 0) { printf("error: thread creation"); free(a); return 1; } } send(WORK, 0 , N); while(completed < MESSAGES) { receive(&type, &start_pos, &end_pos); if(type == FINISH) { completed += end_pos - start_pos; } else { send(type, start_pos, end_pos); } } send(SHUTDOWN, 0, 0); for(int i=0; i<THREADS; i++) { pthread_join(threads[i], NULL); } for(int i=0; i<N; i++) { if (i < N-1 && a[i] > a[i+1]) { printf("error: a[%d]=%f < a[%d]=%f !!!\n", i, a[i], i+1, a[i+1]); break; } } free(a); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&msg_in); pthread_cond_destroy(&msg_out); return 0; }
C
#include <stdio.h> #include <stdbool.h> int main () { int i, j, k, l, total = 0, row1, row2, col1, col2; bool err = true; printf("Length of row of array1: "); scanf("%d", &row1); printf("Length of column of array1: "); scanf("%d", &col1); int arr1[row1][col1]; printf("Arr1: \n"); for (i = 0; i < row1; i++) { for (j = 0; j < col1; j++) { printf("Arr1 [%d][%d]:", i, j); scanf("%d", &arr1[i][j]); } } printf("Length of row of array2: "); scanf("%d", &row2); printf("Length of column of array2: "); scanf("%d", &col2); if (row1 == row2 && col1 == col2) { int arr2[row2][col2]; printf("Arr2: \n"); for (i = 0; i < row2; i++) { for (j = 0; j < col2; j++) { printf("Arr2 [%d][%d]:", i, j); scanf("%d", &arr2[i][j]); } } printf("Arr1: \n"); for (i = 0; i < row1; i++) { for (j = 0; j < col1; j++) { printf("%d ", arr1[i][j]); } printf("\n"); } printf("Arr2: \n"); for (i = 0; i < row2; i++) { for (j = 0; j < col2; j++) { printf("%d ", arr2[i][j]); } printf("\n"); } for (i = 0; i < row1; i++) { for (j = 0; j < col1; j++) { if (arr1[i][j] != arr2[i][j]) { err = true; break; } else { err = false; } } } printf("\n"); if (err == false) { printf("equal\n"); } else { printf("not equal\n"); } } else { printf("not equal"); } return 0; }
C
#include <omp.h> #include <stdio.h> #include <stdlib.h> #define mSize 512 int main(int argc, char* argv[]) { double A[mSize][mSize], B[mSize][mSize], C[mSize][mSize]; int sum=0; for(int i=0;i<mSize;i++) { for(int j=0;j<mSize;j++) { A[i][j] = 1; B[i][j] = 1; C[i][j] = 0; } } double t1 = omp_get_wtime(); #pragma omp parallel for collapse(2) for(int i=0;i<mSize;i++) for(int j=0;j<mSize;j++) for(int k=0;k<mSize;k++) C[i][j] += (A[i][k] *B[k][j]); for(int i=0;i<mSize;i++) { for(int j=0;j<mSize;j++) { printf("%f ",C[i][j]); } printf("\n"); } double t2 = omp_get_wtime(); printf("\n TIME : %f",t2-t1); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> //THreading binary tree's traversal is just like the iteration edition of the normal bianry search tree's traversal. //Thread tree also makes use of the unused pointer left in the normal BST typedef struct node{ char data; int ltag; int rtag; struct node* left; struct node* right; }tree_node; tree_node* pre; int count=0; int count_cre = 0; //initialization tree_node* Initialization(){ tree_node* tree; tree = (tree_node*)malloc(sizeof(tree_node)); if(!tree){ printf("Error in initialization\n"); return NULL; } else{ tree->data = '\0'; tree->ltag = 0; tree->rtag = 0; tree->left = NULL; tree->right = NULL; printf("success\n"); return tree; } } //create a tree_node void CreateNode(char e, tree_node* node){ node->data = e; node->ltag = 0; node->rtag = 0; node->left = NULL; node->right = NULL; return; } //insert the element into the tree void TreeInsert(char e, tree_node* root){ tree_node* temp; tree_node* parent; temp = (tree_node*)malloc(sizeof(tree_node)); parent = (tree_node*)malloc(sizeof(tree_node)); parent = root; CreateNode(e, temp); if(!parent->data){ parent->data = e; return; } else{ while(1){//use the function of iteration to insert the tree node. Or you could use recursion to insert tree node. if(temp->data<=parent->data&&parent->left!=NULL) parent = parent->left; else if(temp->data>parent->data&&parent->right!=NULL) parent = parent->right; else if(temp->data<=parent->data&&parent->left==NULL){ parent->left = temp; return; } else if(temp->data>parent->data&&parent->right==NULL){ parent->right = temp; return; } } } } void CreateTree(char* string, tree_node* root){ int length = strlen(string); int i; char temp; printf("The string is "); for(i = 0;i<length;i++){ temp = string[i]; printf("%c ", temp); TreeInsert(temp, root); } printf("\n"); return; } void Inorder(tree_node* root){ if(root==NULL) return; else{ Inorder(root->left); printf("%c ", root->data); Inorder(root->right); } } //create the thread binary tree based on the original binary search tree void CreateThreadTree(tree_node* root, int M){//If you want to connect the head with the last one, you could try the counter to find the last one, and then connect it to the head if(root==NULL) return; else{ CreateThreadTree(root->left, M); if(!root->left){//recursion to find the previous one root->ltag = 1; root->left = pre; } if(!pre->right){//recursion to find the next one pre->rtag = 1; pre->right = root; } count_cre++;// count_cre is used to find the last node if(count_cre==M) root->rtag=1; pre = root; CreateThreadTree(root->right, M); } } void InThreadingTraversal(tree_node* head, int M){// follow the forward order, from the first one to the last one tree_node* p; //p = (tree_node*)malloc(sizeof(tree_node)); p = head->right; // point to the root while(count<M){ while(p->ltag==0) p = p->left;// find the first node, and the first node's previous node is head.Therefore, here is the correct location //Actually, the previous step follows the inorder oreder. Go the left child. printf("%c ", p->data); count++; while(p->rtag==1){ p = p->right; printf("%c ", p->data); count++; } p = p->right;//At this time, p->rtag = 0 and the traversal follows the inorder } } void InThreadingBackwardTraversal(tree_node* head, int M){// follow the backward order, from the last one to the first one tree_node* p; p = head->right; // point to the root while(count<M){ while(p->rtag==0) {p = p->right;}// find the first node, and the first node's next node is head.Therefore, here is the correct location printf("%c ", p->data); count++; while(p->ltag==1){ p = p->left; printf("%c ", p->data); count++; } p = p->left;//At this time, p->ltag = 0 and the traversal follows the inorder } } int main(){ tree_node* root; tree_node* head;//head node which is used in the thread tree head = (tree_node*)malloc(sizeof(tree_node)); root = Initialization(); char* string = "HELLOALICE"; int length = strlen(string); CreateTree(string, root); Inorder(root); printf("\n"); CreateNode('\0', head); pre = head; CreateThreadTree(root, length); head->right = root;// add a head node in the front of the root //InThreadingTraversal(head, length); InThreadingBackwardTraversal(head, length); return 0; }
C
#include <stdio.h> int palindrome(int x) { int copyX = x , reverse = 0; while (copyX > 0) { reverse <<=1; reverse |= (copyX & 1); copyX = copyX >> 1; } if(reverse==x){ return 1; }else{ return 0; } } void main(){ int number; scanf("%d", &number); printf("%d",palindrome(number)); }
C
/* -*- Mode: C; tab-width: 8; c-basic-offset: 8; indent-tabs-mode: t; -*- */ #ifndef LIST_H #define LIST_H #include "types.h" struct list; struct list * list_new(); bool list_end(const struct list * node); void * list_data(const struct list * node); struct list * list_next(const struct list * node); struct list * list_push_front(const struct list * head, const void * data); struct list * list_pop_front(struct list * head); /** * Note: This removes the node by copying the next node over it * so be wary if you hold pointers to these nodes. */ void list_remove(struct list * node); #endif
C
/*Amanda Lara - Exercícios Lista Dia 1 14/02/2020 */ //Saque Caixa eletrônico #include <stdio.h> #include <math.h> int main(){ int reais, centavos, nota_100, nota_50, nota_20, nota_10, nota_5, nota_1, moeda_50, moeda_25, moeda_10, moeda_5, moeda_1, mod_100, mod_50, mod_20, mod_10, mod_5, mod_m50, mod_m25, mod_m10, mod_m5; printf("Digite o valor dos reais do saque: \n"); scanf( "%d", &reais); printf("Digite o valor dos centavos do saque: \n"); scanf( "%d", &centavos); nota_100 = reais / 100; mod_100 = reais % 100; nota_50 = mod_100 / 50; mod_50 = mod_100 % 50; nota_20 = mod_50 / 20; mod_20 = mod_50 % 20; nota_10 = mod_20 / 10; mod_10 = mod_20 % 10; nota_5 = mod_10 / 5; mod_5 = mod_10 % 5; nota_1 = mod_5 / 1; moeda_50 = centavos / 50; mod_m50 = centavos % 50; moeda_25 = mod_m50 / 25; mod_m25 = mod_m50 % 25; moeda_10 = mod_m25 / 10; mod_m10 = mod_m25 % 10; moeda_5 = mod_m10 / 5; mod_m5 = mod_m10 % 5; moeda_1 = mod_m5 / 1; printf("O valor de %d,%d de saque utiliza as seguintes notas e moedas: \n", reais, centavos); printf("%d notas de 100 \n", nota_100); printf("%d notas de 50 \n", nota_50); printf("%d notas de 20 \n", nota_20); printf("%d notas de 10 \n", nota_10); printf("%d notas de 5 \n", nota_5); printf("%d notas de 1 \n", nota_1); printf("%d moedas de 50 \n", moeda_50); printf("%d moedas de 25 \n", moeda_25); printf("%d moedas de 10 \n", moeda_10); printf("%d moedas de 5 \n", moeda_5); printf("%d moedas de 1 \n", moeda_1); return 0; }
C
// Copyright 2020 - 2021 - 311CA - Mihai Daniel Soare #ifndef CIRCULAR_DOUBLY_LINKED_LIST_H_ #define CIRCULAR_DOUBLY_LINKED_LIST_H_ typedef struct dll_node_t dll_node_t; struct dll_node_t { void *data; dll_node_t *prev, *next; }; typedef struct doubly_linked_list_t doubly_linked_list_t; struct doubly_linked_list_t { dll_node_t* head; unsigned int data_size; unsigned int size; }; // create a new node with a given data and its size dll_node_t *create_node(const void *new_data, unsigned int data_size); // create a list of a specified data_size doubly_linked_list_t* dll_create(unsigned int data_size); // get the node from a given position dll_node_t* dll_get_nth_node(doubly_linked_list_t* list, unsigned int n); // add a node on the nth position of the list given as a parameter void dll_add_nth_node(doubly_linked_list_t* list, unsigned int n, const void* data); // delete a node from the nth position of the list given as a parameter dll_node_t* dll_remove_nth_node(doubly_linked_list_t* list, unsigned int n); // free the memory allocated from a list void dll_free(doubly_linked_list_t** pp_list); // print a list that contains int datas void dll_print_int_list(doubly_linked_list_t* list); // move a node in the first position void dll_move_first(dll_node_t **head, dll_node_t *new_node); #endif // CIRCULAR_DOUBLY_LINKED_LIST_H_
C
#ifndef __UART_PLL011_C__ #define __UART_PLL011_C__ #include <common.h> #include <uart.h> #include <gpio.h> /* Global instance */ static peripheral_ctx_t uart0; static rx_call_back uart_recv_cb; static pthread_t thread_id; void uart_set_baudrate(unsigned int baudrate) { double baud_value = 0.0; unsigned int cr_value = 0; unsigned short int_value = 0x00; unsigned short fractional_value = 0x00; /* 4)//(48000000 / (16 * 115200) = 26.0416 //(0.0416 * 64 + 0.5) = 3 3)//(48000000 / (16 * 9600)) = 312.5 = IBRD=312 //(0.5 * 64 + 0.5) = 32 */ baud_value = (48000000 / (baudrate * 16.0)); int_value = (unsigned short)baud_value; /*Four digits after decimal*/ fractional_value = ((baud_value - int_value) * 64) + 0.5; #if 0 cr_value = UART0_GET32(CR); printf("CR value is %X\n", cr_value); cr_value &= ~CR_UARTEN; /*Disable the UART*/ UART0_PUT32(CR, cr_value); printf("int_value %d fractional_value %d baud_value is %f\n", int_value, fractional_value, baud_value); #endif UART0_PUT32(IBRD, int_value); UART0_PUT32(FBRD, fractional_value); #if 0 UART0_PUT32(LCRH, (LCRH_WLEN8 |LCRH_FEN)); /*Enabling the UART*/ cr_value = UART0_GET32(CR); cr_value |= CR_UARTEN; UART0_PUT32(CR, cr_value); #endif }/*uart_set_baudrate*/ void uart_register_cb(void (*Fn)(unsigned char *rsp_ptr, unsigned int len)) { unsigned int rc = 0; /*Initializing call back*/ uart_recv_cb = Fn; /*Creating the Thread for receiving the response from UART*/ rc = pthread_create(&thread_id, (void *)0, poll_receiver, (void *)0); }/*uart_register_cb*/ int uart_memmap(void) { peripheral_ctx_t *pi3b_uart = &uart0; if ((pi3b_uart->mem_fd = open("/dev/mem", O_RDWR | O_SYNC)) < 0) { fprintf(stderr, "Failed to open mem device\n"); return -1; } /* Mapping GPIO Physical memeory into virtual memory */ pi3b_uart->map = mmap(NULL, /*Let the Kernel decisides for us*/ BLOCK_SIZE, (PROT_READ | PROT_WRITE), /*The Mapped region is protected*/ MAP_SHARED, /*Shared accross Process*/ pi3b_uart->mem_fd, /*File Descriptor of mapped region*/ UART_BASE); if (pi3b_uart->map == MAP_FAILED) { perror("mmap"); return -1; } /* Virtual Address mapped by Kernel */ pi3b_uart->base_addr = (volatile unsigned int *)pi3b_uart->map; return 0; }/*memmap*/ void UART0_PUT32(unsigned int reg, unsigned int value) { *(uart0.base_addr + reg) = value; }/*UART0_PUT32*/ unsigned int UART0_GET32(unsigned int reg) { return(*(uart0.base_addr + reg)); }/*UART0_GET32*/ void disable_uart(void) { unsigned int data = 0x00; data = UART0_GET32(CR); data &= ~(CR_UARTEN); UART0_PUT32(CR, data); }/*disable_uart*/ void enable_uart(void) { unsigned int data = 0x00; data = UART0_GET32(CR); /*Clear the bit0 first*/ data &= ~(CR_UARTEN); /*set the bit0 now*/ data |= CR_UARTEN; UART0_PUT32(CR, data); }/*disable_uart*/ void enable_tx(void) { unsigned int data = 0x00; data = UART0_GET32(CR); data &= ~(CR_TXE); data |= CR_TXE; UART0_PUT32(CR, data); }/*enable_tx*/ void enable_rx(void) { unsigned int data = 0x00; data = UART0_GET32(CR); data &= ~(CR_RXE); data |= CR_RXE; UART0_PUT32(CR, data); }/*enable_rx*/ void disable_tx(void) { unsigned int data = 0x00; data = UART0_GET32(CR); data &= ~(CR_TXE); UART0_PUT32(CR, data); }/*disable_tx*/ void disable_rx(void) { unsigned int data = 0x00; data = UART0_GET32(CR); data &= ~(CR_RXE); UART0_PUT32(CR, data); }/*disable_rx*/ void flush_fifo(void) { unsigned int data = 0x00; data = UART0_GET32(LCRH); data &= ~(LCRH_FEN); UART0_PUT32(LCRH, data); }/*flush_fifo*/ void enable_fifo(void) { unsigned int data = 0x00; data = UART0_GET32(LCRH); data &= ~(LCRH_FEN); data |= LCRH_FEN; UART0_PUT32(LCRH, data); }/*enable_fifo*/ void uart_write(unsigned char *data_ptr, unsigned char data_len) { unsigned int idx = 0; while(idx < data_len) { uart_putc(data_ptr[idx]); idx++; } }/*uart_write*/ void uart_putc(unsigned char c) { unsigned int data = 0; while(1) { /*Wait Until TX-FIFO has a room for new byte*/ if((UART0_GET32(FR) & FR_TXFF) == 0) break; } //data = UART0_GET32(DR); //data &= ~(DR_DATA); data = c; UART0_PUT32(DR, data); } void uart_init(void) { unsigned int data = 0; /*Disable the UART*/ UART0_PUT32(CR, 0); data = GPIO_GET32(GPFSEL1); data &= ~(7<<12); //gpio14 data |= 4<<12; //alt0 data &= ~(7<<15); //gpio15 data |= 4<<15; //alt0 GPIO_PUT32(GPFSEL1, data); GPIO_PUT32(GPPUD, 0); for(data = 0; data < 150; data++) { asm volatile("nop"); } GPIO_PUT32(GPPUDCLK0, ((1 << 14) | (1 << 15))); for(data = 0; data < 150; data++) { asm volatile("nop"); } GPIO_PUT32(GPPUDCLK0, 0); UART0_PUT32(ICR,0x7FF); /*1)//(3000000 / (16 * 115200) = 1.627 ==> IBRD=1 //(0.627*64)+0.5 = 40 ==> FBRD=40 //int 1 frac 40 2)//(3000000 / (16 * 9600)) = 19.2 ==> IBRD=19 //(0.53125 * 64 + 0.5) = 34.5 ==>FBRD=34.5 UART_CLK is 48MHz, look for the Kernel command line argument by dmesg tailf 3)//(48000000 / (16 * 9600)) = 312.5 = IBRD=312 //(0.5 * 64 + 0.5) = 32 4)//(48000000 / (16 * 115200) = 26.0416 //(0.0416 * 64 + 0.5) = 3 */ uart_set_baudrate(9600); //UART0_PUT32(IBRD, 312); //UART0_PUT32(FBRD, 32); /*8Bits word no Parity and no stop bits*/ UART0_PUT32(LCRH, (LCRH_WLEN8 |LCRH_FEN)); //UART0_PUT32(LCRH, 0x60); UART0_PUT32(CR, (CR_TXE |CR_RXE |CR_UARTEN)); }/*uart_init*/ void *poll_receiver(void *thread_arg) { (void) thread_arg; unsigned char rsp_byte; FILE *fp = NULL; fp = fopen("./recv_char.txt", "w"); while(1) { /*Wait until RX-FIFO is not empty*/ if(!(UART0_GET32(FR) & FR_RXFE)) { rsp_byte = UART0_GET32(DR) & 0xFF; //fprintf(stderr, "0x%0.2X .... %c \n", rsp_byte, rsp_byte); //fwrite(rsp_byte, 1, 1, fp); fprintf(fp, "0x%0.2X...%c\n", rsp_byte, rsp_byte); uart_recv_cb((unsigned char *)&rsp_byte, 1); } }/*while(1)*/ fclose(fp); }/*poll_receiver*/ #endif /*__UART_PLL011_C__*/
C
#define SUB_STR_PTR(s, start, len) ({ \ char* __ss__ = malloc((len + 1) * sizeof(char)); \ memcpy(__ss__, &s[start], len); \ __ss__[len] = '\0'; \ __ss__; \ }) #define MIN(X,Y) ((X) < (Y) ? (X) : (Y)) char* longestPalindrome(char* s){ const int sLen = strlen(s); if (sLen <= 1) return s; const int size = 2 * sLen + 1; char t[size]; for (int i = 0; i < sLen; ++i) { const int j = 2 * i; t[j] = '\0'; t[j + 1] = s[i]; } t[size - 1] = '\0'; int pLens[size], c = 0, r = 0, maxPLen = 0, idx = 0; for (int i = 0; i < size; ++i) { const int j = 2 * c - i; int pLen = (r > i ? MIN(r - i, pLens[j]) : 0); for (int incrPLen = pLen + 1, posLeft = i - incrPLen, posRight = i + incrPLen; 0 <= posLeft && posRight < size && t[posLeft] == t[posRight]; --posLeft, ++posRight) ++pLen; const int newR = i + (pLens[i] = pLen); if (newR > r) { c = i; r = newR; } if (pLen > maxPLen) { maxPLen = pLen; idx = i; } } const int start = (idx - maxPLen) / 2; return SUB_STR_PTR(s, start, maxPLen); }
C
/* This is a program thst uses a switch statement and asks the user to enter a character from the keyboard and displays a message whether the character is a vowel (a, e, i, o, u) or not. Author: Daniel Tilley Date: 14/10/14 */ #include <stdio.h> main() { char letter; printf("Please enter a character from the keyboard\n"); scanf("%1s",&letter); flushall(); switch(letter) { case'a': case'A': { printf("\n%c is a vowel",letter); break; }//end case 'a' case'e': case'E': { printf("\n%c is a vowel",letter); break; }//end case 'e' case'i': case'I': { printf("\n%c is a vowel",letter); break; }//end case 'i' case'o': case'O': { printf("\n%c is a vowel",letter); break; }//end case 'o' case'u': case'U': { printf("\n%c is a vowel",letter); break; }//end case 'u' default: { printf("\n%c is not a vowel",letter); break; }//end default }//end switch getchar(); }//end main
C
#include "sock.h" #include <signal.h> #include <errno.h> #include <poll.h> #include <sys/wait.h> int Poll(struct pollfd *client, nfds_t nfds, int timeout) { int nready; while(1){ nready = poll(client, nfds, timeout); if(nready == -1 && errno != EINTR){ perror("poll() error"); exit(0); } else if(nready == -1 && errno == EINTR) continue; else if(nready > 0) return nready; } }
C
//reader-writer using mutex #include<stdio.h> #include<stdlib.h> //#include<semaphore.h> #include<pthread.h> //sem_t var1, var2; pthread_mutex_t LOCK, CC; int rc=0; void *reader() { //sem_wait(&var1); pthread_mutex_lock(&LOCK); rc = rc+1; if(rc==1) pthread_mutex_lock(&CC); //sem_post(&var1); pthread_mutex_unlock(&LOCK); printf("\nReader entered critical section. Number of readers: %d", rc); //sem_wait(&var1); pthread_mutex_lock(&LOCK); rc = rc - 1; if(rc==0) pthread_mutex_unlock(&CC); //sem_post(&var2); //sem_post(&var1); pthread_mutex_unlock(&LOCK); printf("\nReader has exited the critical section"); } void *writer() { //sem_wait(&var2); pthread_mutex_lock(&CC); printf("\nWriter has entered the critical section"); //sem_post(&var2); pthread_mutex_unlock(&CC); printf("\nWriter has exited the critical section"); } int main() { //sem_init(&var1, 0, 0); //sem_init(&var2, 0, 0); pthread_mutex_init(&LOCK, NULL); pthread_mutex_init(&CC, NULL); pthread_t thread_readers[50], thread_writers[50]; int N; printf("\nEnter Number of People Trying to access the Critical Section: "); scanf("%d", &N); for(int i=0; i<N; i++) { pthread_create(&thread_readers[i], 0, reader, 0); pthread_create(&thread_writers[i], 0, writer, 0); } for(int i=0; i<N; i++) { pthread_join(thread_writers[i],NULL); pthread_join(thread_readers[i],NULL); } //sem_destroy(&var1); //sem_destroy(&var2); pthread_mutex_destroy(&LOCK); pthread_mutex_destroy(&CC); }
C
#include <stdio.h> int main() { int numArr[10] = { 0, }; // 迭 Ҹ 0 ʱȭ printf("%d\n", numArr[0]); // 0: 迭 ù °(ε 0) printf("%d\n", numArr[5]); // 0: 迭 °(ε 5) printf("%d\n", numArr[9]); // 0: 迭 °(ε 9) return 0; }
C
#include <stdio.h> int main() { int i, n, max, min; int smax, smin, t; int a[10]; scanf("%d", &n); for (i = 0; i < n; i++) { scanf("%d", &a[i]); } max = a[0]; min = a[0]; for (i = 0; i < n; i++) { if (a[i] < min) { min = a[i]; smin = i; } if (a[i] > max) { max = a[i]; smax = i; } } t = a[smax]; a[smax] = a[n - 1]; a[n - 1] = t; t = a[smin]; a[smin] = a[0]; a[0] = t; for (i = 0; i < n; i++) { if (i == 0) printf("%d", a[i]); else printf(" %d", a[i]); } return 0; }
C
#include<stdio.h> int[][2] go() { int m[2][2] = {1,2,3,4}; return m; } int main() { int m[2][2]; m = go(); for(int i = 0 ; i < 2 ; i++) { for (int j = 0; j < 2; j++) { printf(" %d ",m[i][j]); } printf("\n"); } }
C
/** ################################################################################# # Grupo 1 - SSC5723 - 1/2021 # # Implementação de buffer de tamanho limitado e utilizando fila # ################################################################################# */ #include "buffer.h" // Criar Buffer de tamanho 'size' ou BUFFER_SIZE se 'size' 0 ou negativo Buffer* criarBuffer(int size) { Buffer* b = (Buffer*)malloc(sizeof(Buffer)); b->buf = createQueue(); b->tamanho_atual = 0; b->tamanho_limite = size; return b; } // Quantidade de slots livres no buffer int slotsLivres(Buffer* b) { return b->tamanho_limite - b->tamanho_atual; } // Quantidade de slots ocupados no buffer int slotsOcupados(Buffer* b) { return b->tamanho_atual; } // Insere item no buffer, se não estiver cheio // true - Valor inserido // false - Buffer cheio bool inserirNoBuffer(Buffer* b, item_type i) { if (b->tamanho_atual == b->tamanho_limite) { // Buffer cheio return false; } enQueue(b->buf,i); b->tamanho_atual++; return true; } bool retirarDoBuffer(Buffer* b, item_type* i) { if(b->tamanho_atual == 0) { //Buffer vazio. return false; } *i = b->buf->front->item; deQueue(b->buf); b->tamanho_atual--; return true; } // Estatisticas do buffer void stats(Buffer* b) { printf("\nTamanho do Buffer: %d \n", b->tamanho_limite); printf("Slots disponíveis: %d \n", slotsLivres(b)); printf("Slots ocupados: %d \n\n", slotsOcupados(b)); }
C
// Absolute Beginner's Guide to C, 3rd Edition Kindle // sample program from Chapter18_2 // File chapter18_2.c // This program is nothing more than a simple demonstration of the getchar() function. // getchar() is defined in stdio.h, but string.h is needed for the strlen() function #include <stdio.h> #include <string.h> int main(void) { int i; char msg[25]; printf("Type up to 25 characters and then press Enter...\n"); for (i = 0;i < 25;i++) { msg[i] = getchar(); if (msg[i] == '\n') { i--; break; } } putchar('\n'); // One line break after the loop is done. for (;i >= 0;i--) { putchar(msg[i]); } putchar('\n'); return 0; }
C
/* * Smart terminal output routine. * Uses curses to display the object. */ #include <signal.h> #include <curses.h> #include <varargs.h> #define STATUSLINE 22 #define INPUTLINE 23 static int inputready; static void gotinput(); extern void ttywrite(); /* * Open the terminal and enable for detecting terminal input. */ ttyopen() { struct sgttyb s; initscr(); signal(SIGINT, gotinput); /* * Get terminal modes. */ ioctl(2, TIOCGETP, &s); /* * Set the modes to the way we want them. */ s.sg_flags |= CBREAK; s.sg_flags &= ~(ECHO|XTABS); ioctl(2, TIOCSETN, &s); return 0; } static void gotinput() { signal(SIGINT, gotinput); inputready = 1; } /* * Close the terminal. */ void ttyclose() { refresh(); endwin(); } /* * Test to see if a keyboard character is ready. * Returns nonzero if so (and clears the ready flag). */ ttycheck() { int result; result = inputready; inputready = 0; return result; } /* * Print a formatted string to the terminal. * The string length is limited to 256 characters. */ void ttyprintf(char *fmt, ...) { va_list ap; static char buf[256]; va_start(ap, fmt); vsprintf(buf, fmt, ap); va_end(ap); addstr(buf); } /* * Print a status line, similar to printf. * The string length is limited to 256 characters. */ void ttystatus(char *fmt, ...) { va_list ap; static char buf[256]; va_start(ap, fmt); vsprintf(buf, fmt, ap); va_end(ap); move(STATUSLINE, 0); addstr(buf); clrtobot(); move(0, 0); refresh(); } void ttywrite(cp, len) char *cp; { while (len-- > 0) { addch(*cp); cp++; } } void ttyhome() { move(0, 0); } void ttyeeop() { clrtobot(); } void ttyflush() { refresh(); } /* * Return a NULL terminated input line (without the final newline). * The specified string is printed as a prompt. * Returns nonzero (and an empty buffer) on EOF or error. */ ttyread(prompt, buf, buflen) char *prompt; char *buf; { int c; char *cp; move(INPUTLINE, 0); addstr(prompt); clrtoeol(); cp = buf; for (;;) { refresh(); c = fgetc(stdin); switch (c) { case EOF: buf[0] = '\0'; move(INPUTLINE, 0); clrtoeol(); move(0, 0); refresh(); return -1; default: *cp++ = c; addch(c); if (cp < buf + buflen - 1) break; /* fall through... */ case '\n': case '\r': *cp = 0; move(INPUTLINE, 0); clrtoeol(); move(0, 0); refresh(); return 0; case '\b': if (cp == buf) break; --cp; addch('\b'); clrtoeol(); break; } } } /* END CODE */
C
/* =================== push ==================== Inserts node into linked list stack. Pre pStack is pointer to valid stack header Post dataIn inserted Return true if successful false if underflow */ bool push (STACK* pStack, int dataIn) { // Local Declarations STACK_NODE* pNew; bool success; // Statements pNew = (STACK_NODE*)malloc(sizeof (STACK_NODE)); if (!pNew) success = false; else { pNew->data = dataIn; pNew->link = pStack->top; pStack->top = pNew; pStack->count++; success = true; } // else return success; } // push
C
# include "filestream.h" # define BUFFER_SIZE 1024 /* ->readcontainsdir(char*) fonction lisant le contenu d'un répertoire donné en paramètre. */ void readcontainsdir (char *name){ DIR * dir; struct dirent* dirent; if( (dir = opendir(name) ) == NULL ) return; while((dirent = readdir(dir)) != NULL) { fprintf(stdout,"%s/ ",dirent->d_name); } if (closedir(dir) == -1) { return; } } /* ->cat( char* ) La fonction affiche le contenu du fichier présent dans le repertoire. */ int cat (char* nom) { FILE *from; char buffer[BUFFER_SIZE]; int n; int exit_status = EXIT_SUCCESS; if (NULL == (from = fopen(nom ,"rb"))) { return -1; } while ((n = fread(buffer,sizeof(char),BUFFER_SIZE,from)) != 0) { if (fwrite(buffer,sizeof(char),n,stdout) != n) { break; } } if (ferror(from)) { perror("read"); clearerr(from); exit_status = EXIT_FAILURE; } if (ferror(stdout)){ perror("write"); clearerr(stdout); exit_status = EXIT_FAILURE; } fclose(from); exit(exit_status); }
C
/********************************************************************************* Description: Controls stepper motor from debounced buttons Uses: DSX Experimenter board and SMPM Connections: Port C - stepper motor via the SMPM Author: Dinuka Abeywardena/Kyle Alvarez Note: Do note that this is only a test file and is not a proper header/source file pair Feel free to use this as a starting point for SPI communication Although I expect when you use it in your project, you will appropriately convert this into its respective source/header pair **********************************************************************************/ #include "SPI.h" #include "common.h" void setupSPI(void){ //PortB TRISB = 0b00000000; SSPSTAT = 0b01000000; SSPCON = 0b00100000; TRISC = 0b11010000; PORTC |= 0b00000011; } //Transfers data through SPI using SSPBUF unsigned char spi_transfer(unsigned char data){ unsigned char temp = 0; SSPIF = 0; SSPBUF = data; while (SSPIF == 0); temp = SSPBUF; SSPIF = 0; return temp; } void setToMotorCW(){ //Set full step and motor CW unsigned char controlByte = 0b00001001; spi_transfer(controlByte); currentDirection = 1; } void setToMotorCCW(){ //Set full step and motor CCW unsigned char controlByte = 0b00001011; spi_transfer(controlByte); currentDirection = 0; }
C
#include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> static const int dx[] = {0,-1,1,0}; static const int dy[] = {-1,0,0,1}; struct unit { int class; int hp; int attack; size_t x, y; }; struct map { char **data; size_t height; size_t width; size_t dsize; struct unit *units; size_t ucount; size_t usize; size_t elves; size_t goblins; int **dist; }; static void map_free(struct map *g) { if (g) { free(g->units); while (g->height-- > 0) { free(g->dist[g->height]); free(g->data[g->height]); } free(g->dist); free(g->data); free(g); } } static struct map *map_copy(const struct map *g) { struct map *c = calloc(1, sizeof(*c)); if (c) { c->dsize = c->height = g->height; c->width = g->width; c->usize = c->ucount = g->ucount; c->elves = g->elves; c->goblins = g->goblins; c->data = calloc(c->dsize, sizeof(c->data[0])); c->dist = calloc(c->dsize, sizeof(c->dist[0])); c->units = calloc(c->usize, sizeof(c->units[0])); if (!c->data || !c->dist || !c->units) { map_free(c); return NULL; } memmove(c->units, g->units, c->ucount * sizeof(c->units[0])); for (size_t i = 0; i < c->height; i++) { c->data[i] = strdup(g->data[i]); c->dist[i] = malloc(c->width * sizeof(c->dist[0][0])); if (!c->data[i] || !c->dist[i]) { map_free(c); return NULL; } memmove(c->dist[i], g->dist[i], c->width * sizeof(c->dist[0][0])); } } return c; } static void map_bfs(struct map *g, struct unit *u) { /* reset the map */ for (size_t y = 0; y < g->height; y++) { for (size_t x = 0; x < g->width; x++) { g->dist[y][x] = INT_MAX; } } struct pos { size_t x, y; } queue[1024]; size_t wi = 0, ri = 0; queue[wi++ & 1023] = (struct pos){u->x, u->y}; g->dist[u->y][u->x] = 0; while (wi != ri) { struct pos p = queue[ri++ & 1023]; for (int i = 0; i < 4; i++) { size_t x = p.x + dx[i]; size_t y = p.y + dy[i]; if (g->data[y][x] != '.') { continue; } if (g->dist[y][x] == INT_MAX) { g->dist[y][x] = g->dist[p.y][p.x] + 1; if (wi-ri == 1024) { abort(); } queue[wi++ & 1023] = (struct pos){x, y}; } } } } static void map_move_unit(struct map *g, struct unit *u) { /* check if an enemy is already in range */ int enemy = u->class == 'E' ? 'G' : 'E'; for (int i = 0; i < 4; i++) { if (g->data[u->y + dy[i]][u->x + dx[i]] == enemy) { return; } } /* find a destination to move the unit to */ map_bfs(g, u); int min = INT_MAX; size_t tx, ty; for (struct unit *e = g->units; e < g->units + g->ucount; e++) { if (u->class == e->class || e->hp <= 0) { continue; } for (int i = 0; i < 4; i++) { size_t x = e->x + dx[i]; size_t y = e->y + dy[i]; if (min > g->dist[y][x]) { min = g->dist[y][x]; tx = x; ty = y; } } } /* no suitable destination found */ if (min == INT_MAX) { return; } /* walk the path back until we find the place to move to */ for (;;) { size_t mx = tx; size_t my = ty; for (int i = 0; i < 4; i++) { size_t x = tx + dx[i]; size_t y = ty + dy[i]; if (min > g->dist[y][x]) { min = g->dist[y][x]; my = y; mx = x; } } if (mx == u->x && my == u->y) { break; } tx = mx; ty = my; } /* update the map and the unit position */ g->data[u->y][u->x] = '.'; g->data[ty][tx] = u->class; u->x = tx; u->y = ty; } static int map_attack_unit(struct map *g, struct unit *u) { int minhp = INT_MAX; struct unit *target = NULL; for (int i = 0; i < 4; i++) { for (struct unit *e = g->units; e < g->units + g->ucount; e++) { /* don't attack friends or dead units */ if (e->class == u->class || e->hp <= 0) { continue; } if (u->x + dx[i] == e->x && u->y + dy[i] == e->y && minhp > e->hp) { minhp = e->hp; target = e; } } } if (target) { target->hp -= u->attack; if (target->hp <= 0) { g->data[target->y][target->x] = '.'; return 1; } } return 0; } static int unit_cmp(const void *pa, const void *pb) { const struct unit *a = pa; const struct unit *b = pb; if (a->y != b->y) { return a->y - b->y; } return a->x - b->x; } static int map_points(struct map *g) { int count = 0; for (struct unit *u = g->units; u < g->units + g->ucount; u++) { if (u->hp > 0) { count += u->hp; } } return count; } static void map_print(struct map *g) { size_t i = 0; for (size_t y = 0; y < g->height; y++) { printf("%s", g->data[y]); for (; i < g->ucount && g->units[i].y == y; i++) { if (g->units[i].hp > 0) { printf(" %c(%d)", g->units[i].class, g->units[i].hp); } } printf("\n"); } } static int map_simulate(struct map *g, int retearly) { int rounds = 0; for (rounds = 0; ; rounds++) { /* sort the units */ qsort(g->units, g->ucount, sizeof(g->units[0]), unit_cmp); /* play a round */ for (struct unit *u = g->units; u < g->units + g->ucount; u++) { if (u->hp <= 0) { continue; } map_move_unit(g, u); if (map_attack_unit(g, u)) { if (u->class == 'G') { if (retearly || --g->elves == 0) { return rounds; } } else if (--g->goblins == 0) { return rounds; } } } } } static struct map *map_load(FILE *input) { struct map *g = calloc(1, sizeof(*g)); if (!g) { return NULL; } char *line = NULL; size_t linesize = 0; while (getline(&line, &linesize, input) != -1) { for (char *t = line; *t; t++) { int class; switch(*t) { case 'G': class = *t; g->goblins++; break; case 'E': class = *t; g->elves++; break; case '\n': g->width = (size_t)(t - line); *t = 0; continue; default: continue; } if (g->ucount == g->usize) { size_t newsize = g->usize ? g->usize * 2 : 2; struct unit *newunits = realloc(g->units, newsize * sizeof(*newunits)); if (newunits == NULL) { map_free(g); return NULL; } g->usize = newsize; g->units = newunits; } g->units[g->ucount].hp = 200; g->units[g->ucount].attack = 3; g->units[g->ucount].class = class; g->units[g->ucount].x = (size_t)(t - line); g->units[g->ucount].y = g->height; g->ucount++; } if (g->height == g->dsize) { size_t newsize = g->dsize ? g->dsize * 2 : 2; char **newdata = realloc(g->data, newsize * sizeof(*newdata)); if (newdata == NULL) { map_free(g); return NULL; } g->dsize = newsize; g->data = newdata; int **newdist = realloc(g->dist, newsize * sizeof(*newdist)); if (newdist == NULL) { map_free(g); return NULL; } g->dist = newdist; } g->data[g->height] = strdup(line); g->dist[g->height] = malloc(g->width * sizeof(int)); if (g->data[g->height] == NULL || g->dist[g->height] == NULL) { free(g->dist[g->height]); free(g->data[g->height]); map_free(g); return NULL; } g->height++; } free(line); return g; } int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "Usage: %s <filename>\n", argv[0]); return 1; } FILE *input = fopen(argv[1], "rb"); if (!input) { fprintf(stderr, "Cannot open %s\n", argv[1]); return 1; } struct map *g = map_load(input); fclose(input); printf("Read a map of size %zu,%zu, units %zu\n", g->width, g->height, g->ucount); printf("Answer1:\n"); struct map *c = map_copy(g); int rounds = map_simulate(c, 0); map_print(c); int points = map_points(c); printf("Rounds %d, points %d\n", rounds, points); printf("Outcome of the battle %d with attack level = 3\n", rounds * points); map_free(c); /* find the minimum attack level by bisecting */ int low = 4, high = 200; while (low < high) { int attack = low + (high - low) / 2; printf("Trying with attack level %d...\n", attack); c = map_copy(g); for (struct unit *u = c->units; u < c->units + c->ucount; u++) { if (u->class == 'E') { u->attack = attack; } } map_simulate(c, 1); if (c->goblins) { low = attack + 1; } else { high = attack; } map_free(c); } for (struct unit *u = g->units; u < g->units + g->ucount; u++) { if (u->class == 'E') { u->attack = high; } } rounds = map_simulate(g, 0); map_print(g); points = map_points(g); printf("Minimum attack level: %d\n", high); printf("Rounds %d, points %d\n", rounds, points); printf("Outcome of the battle %d with attack level = %d\n", rounds * points, high); map_free(g); return 0; }
C
#include <assert.h> #include <limits.h> #include <math.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> // Complete the hourglassSum function below. int hourglassSum(long long int a[6][6]) { long long int sum = 0; long long int max_sum; max_sum=a[0][0]+a[0][1]+a[0][2]+a[1][1]+a[2][0]+a[2][1]+a[2][2]; for(int i = 0; i< 4; i++) { for(int j = 0; j<4; j++) { sum=a[i][j]+a[i][j+1]+a[i][j+2]+a[i+1][j+1]+a[i+2][j]+a[i+2][j+1]+a[i+2][j+2]; // printf("%d %d %d %d %d %d %d \n",a[i][j],a[i][j+1],a[i][j+2],a[i+1][j+1],a[i+2][j],a[i+2][j+1],a[i+2][j+2]); if(sum > max_sum) { max_sum = sum; } sum = 0; } } printf("%lld",max_sum); return 0; } int main() { long long int arr[6][6]; for(int i=0; i< 6; i++) { for(int j=0; j<6; j++) { scanf("%lld",&arr[i][j]); } } // for(int i=0; i< 6; i++) // { // for(int j=0; j<6; j++) // { // printf("%d ",arr[i][j]); // } // printf("\n"); // } hourglassSum(arr); return 0; }
C
#include "gpio_rw.h" #include "verbose.h" #include <sys/stat.h> #include <sys/types.h> int cGPIO_export(int pin) { char buffer[BUFFER_MAX]; ssize_t bytes_written; int fd; fd = open("/sys/class/gpio/export", O_WRONLY); if (-1 == fd) { verbose(V_NORMAL, stderr, BLUE "[%s]" NONE " Failed to open export for writing!", __FUNCTION__); return (-1); } bytes_written = snprintf(buffer, BUFFER_MAX, "%d", pin); write(fd, buffer, bytes_written); close(fd); return (0); } int cGPIO_unexport(int pin) { char buffer[BUFFER_MAX]; ssize_t bytes_written; int fd; fd = open("/sys/class/gpio/unexport", O_WRONLY); if (-1 == fd) { verbose(V_NORMAL, stderr, BLUE "[%s]" NONE " Failed to open unexport for writing!", __FUNCTION__); return (-1); } bytes_written = snprintf(buffer, BUFFER_MAX, "%d", pin); write(fd, buffer, bytes_written); close(fd); return (0); } int cGPIO_direction(int pin, int dir) { static const char s_directions_str[] = "in\0out"; char path[DIRECTION_MAX]; int fd; snprintf(path, DIRECTION_MAX, "/sys/class/gpio/gpio%d/direction", pin); fd = open(path, O_WRONLY); if (-1 == fd) { verbose(V_NORMAL, stderr, BLUE "[%s]" NONE " Failed to open gpio direction for writing!", __FUNCTION__); return (-1); } if (-1 == write(fd, &s_directions_str[GPIO_IN == dir ? 0 : 3], GPIO_IN == dir ? 2 : 3)) { verbose(V_NORMAL, stderr, BLUE "[%s]" NONE " Failed to set direction!", __FUNCTION__); return (-1); } close(fd); return (0); } int cGPIO_read(int pin) { char path[VALUE_MAX]; char value_str[3]; int fd; snprintf(path, VALUE_MAX, "/sys/class/gpio/gpio%d/value", pin); fd = open(path, O_RDONLY); if (-1 == fd) { verbose(V_NORMAL, stderr, BLUE "[%s]" NONE " Failed to open gpio value for reading!", __FUNCTION__); return (-1); } if (-1 == read(fd, value_str, 3)) { verbose(V_NORMAL, stderr, BLUE "[%s]" NONE " Failed to read value!", __FUNCTION__); return (-1); } close(fd); return (atoi(value_str)); } int cGPIO_write(int pin, int value) { static const char s_values_str[] = "01"; char path[VALUE_MAX]; int fd; snprintf(path, VALUE_MAX, "/sys/class/gpio/gpio%d/value", pin); fd = open(path, O_WRONLY); if (-1 == fd) { verbose(V_NORMAL, stderr, BLUE "[%s]" NONE " Failed to open gpio value for writing!", __FUNCTION__); return (-1); } if (1 != write(fd, &s_values_str[GPIO_LOW == value ? 0 : 1], 1)) { verbose(V_NORMAL, stderr, BLUE "[%s]" NONE " Failed to write value!", __FUNCTION__); return (-1); } close(fd); return (0); }
C
#include <pal.h> /** Convolution on input image 'x' with a square kernel 'm' of size 'msize'. * * @param x Pointer to input image, a 2D array of size 'rows' x 'cols' * * @param m Pointer to convlution kernel * * @param r Pointer to output image * * @param rows Number of rows in input image * * @param cols Number of columns in input image * * @param msize Size of convolution kernel * * @param p Number of processor to use (task parallelism) * * @param team Team to work with * * @return None * */ void p_conv2d_f32(const float *x, float *m, float *r, int rows, int cols, int msize, int p, p_team_t team) { int i, j, k; float P, part; const float *px, *pm; float *pr; px = x; pm = m; pr = r; for (i = msize * 0.5; i < (rows - msize * 0.5); i++) { for (j = msize * 0.5; j < (cols - msize * 0.5); j++) { P = 0.0f; pm = m; for (k = 0; k < msize; k++) { p_dot_f32(px, pm, &part, msize, 0, team); P += part; px += cols; pm += msize; } *pr = P; pr++; // move image pointer one index forward compared to // the position from before `for` loop px += 1 - msize * cols; } // move image pointer to the beginning of line // beneath the current line px += (int)(msize * 0.5) * 2; } }
C
#include <stdio.h> #include "sauvegarde_descripteurs.h" int main(){ unsigned char flag; printf("init capsule");getchar(); Capsule caps = newCapsule(&flag); printf("remplissage capsule");getchar(); sds s = sdsnew("bonjour"); addElement(&caps,s); s = sdsnew("comment"); addElement(&caps,s); s = sdsnew("va"); addElement(&caps,s); s = sdsnew("1"); addElement(&caps,s); s = sdsnew("v2a"); addElement(&caps,s); printf("pointeur1:%p\t",caps.descripteurs); s = sdsnew("va3"); addElement(&caps,s); s = sdsnew("va4"); addElement(&caps,s); s = sdsnew("va5"); addElement(&caps,s); s = sdsnew("va6"); addElement(&caps,s); s = sdsnew("va7"); addElement(&caps,s); s = sdsnew("va8"); addElement(&caps,s); s = sdsnew("va9"); addElement(&caps,s); s = sdsnew("va10"); addElement(&caps,s); s = sdsnew("va11"); addElement(&caps,s); s = sdsnew("va12"); addElement(&caps,s); printf("pointeur2:%p\n",caps.descripteurs); //freeCapsule(caps); printf("sauvegarde");getchar(); saveDescripteurs(&flag,caps,"fTestDesc1.desc"); printf("affichage1");getchar(); for(unsigned int i = 0;i < caps.nbDescripteurs;i++){ printf("%u: %s\n",i,caps.descripteurs[i]); } printf("remove");getchar(); removeDescripteur(&caps,10); printf("affichage2");getchar(); for(unsigned int i = 0;i < caps.nbDescripteurs;i++){ printf("%u: %s\n",i,caps.descripteurs[i]); } printf("free");getchar(); freeCapsule(caps); printf("lecture");getchar(); caps = loadDescripteurs(&flag,"fTestDesc1.desc"); printf("fin lecture, affichage");getchar(); for(unsigned int i = 0;i < caps.nbDescripteurs;i++){ printf("%u: %s\n",i,caps.descripteurs[i]); } freeCapsule(caps); return 0; }
C
#include <stdio.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <sys/syscall.h> #include"errors.h" #if 1 int fd; void *thread(void *i) { int status; pid_t pid; pid = syscall(SYS_gettid); printf("Thread pid is %d\n", pid); if(-1 == (status = ioctl(fd, pid, 0))) { errno_abort("ioctl failed"); } read (0, &status, 4); pthread_exit(NULL); } int main(void) { pthread_t tid; int status; printf("pid is %d\n", getpid()); fd = open ("/dev/myChar", O_RDWR); if(fd < 0) { errno_abort("open failed"); } else printf("File opened Successfully %d\n", fd); if(status = pthread_create(&tid, NULL, thread, NULL)) { err_abort(status, "pthread_create() failed"); } if(-1 == (status = ioctl(fd, getpid(), 0))) { errno_abort("ioctl failed"); } printf("Thread Group Leader \n"); pthread_exit(NULL); return 0; } #endif
C
#include<stdio.h> int add(int *a, int *b) { int add; add = *a + *b; return add; } int main() { int a,b; int sum; printf("Enter first number: "); scanf("%d", &a); printf("Enter second number: "); scanf("%d", &b); sum = add(&a, &b); printf("\nThe sum of two numbers is %d", sum); return 0; }
C
#include <stdio.h> long s(long *xp, long *yp) { long x = *xp; long y = *yp; *xp = y; *yp = x; return x + y; } int main() { long a = 1; long b = 2; long sum = s(&a, &b); long diff = a - b; return 0; }
C
#include<stdio.h> #include<conio.h> #define size 10 void enqueue(int); void dequeue(); void disp(); int queue[size],front=-1,rear=-1; void main() { int value,ch; clrscr(); while(1) { printf("\n1.Insert"); printf("\n2.Delete"); printf("\n3.Display"); printf("\n4.Exit"); printf("\nEnter your choice : "); scanf("%d",&ch); switch(ch) { case 1: printf("Enter the value to be inserted : "); scanf("%d",&value); enqueue(value); break; case 2: dequeue(); break; case 3: disp(); break; case 4: exit(0); default: printf("\n Wrong choice !! Try again "); } } } void enqueue(int value) { if(rear==size-1) printf("Overflow"); else { if(front==-1) front=0; rear++; queue[rear]=value; printf("Inserted"); } } void dequeue() { if(front==rear) printf("Empty"); else { printf("Deleted : %d",queue[front]); front++; if(front==rear) front=rear=-1; } } void disp() { if(rear==-1) printf("Empty"); else { int i; printf("Queue : "); for(i=front;i<=rear;i++) printf("%d ",queue[i]); } }
C
#include <stdio.h> int comp(int x, int y) { while (x + 1 > y) { x = x - y; } return x; } int main(void) { int x; int y; printf("Bitte geben Sie zwei positive ganze Zahlen, "); printf("getrennt durch ein Leerzeichen, ein:"); scanf("%i %i", &x, &y); printf("Rückgabewert der Funktion: %d", comp(x, y)); return 0; }
C
/************** * Matan Shamir * 206960239 * 01 * ass03 **************/ #include <stdio.h> #include <string.h> #define SIZE 3 #define REPLACE_LENGTH 14 #define CHANGE_LENGTH 12 #define ADD_LENGTH 9 #define DELETE_LENGTH 10 #define SPACE ' ' #define BORDER " | " /********************************************************************************************************************* * Function name: validBackslash * Input: char str[] * Output: boolean value (0 or 1). * Function Operation: The function receives a string and counts the amount of backslashes it has, and determines whether or not the amount is valid for creating a board for a sudoku game. *********************************************************************************************************************/ int validBackslash(char str[]) { int count = 0; //this loop iterates as long as the string is, and counts every '/'. for (int i = 0; i < strlen(str); ++i) { if (str[i] == '/') count++; } //the needed amount of backslashes is the size of the board minus 1. if (count != (SIZE * SIZE) - 1) return 0; //if the amount was valid, we don't return 0 and return 1 instead. return 1; } /********************************************************************************************************************* * Function name: createBoard * Input: char board[][SIZE * SIZE], char str[] * Output: none. * Function Operation: The function receives a string and a two-dimensional array(the sudoku board) and checks if the string received is valid. if it suites the values needed to be entered to the board, the function translates it to variables or to spaces in the board and saves it. *********************************************************************************************************************/ void createBoard(char board[][SIZE * SIZE], char str[]) { //first, we check that the amount of backslashes is valid. if (!validBackslash(str)) { printf("Error\n"); return; } /*we create a pointer to the start of the string that points to different parts of it for us to know which value we need to insert at a every iteration. a second pointer points to the beginning of the array for further calculations of length.*/ char *p1 = str, *p2 = str; unsigned int length = strlen(str); //a temp board is created so we change the original board only if the string is indeed valid. char tempBoard[SIZE * SIZE][SIZE * SIZE]; //this double for loop is a matrix for us to go through every cell in the array. for (int i = 0; i < SIZE * SIZE; i++) { for (int j = 0; j < SIZE * SIZE; j++) { /*this condition tells us if a given char in the string is a char that signals blank cells. if it is, fill the amount of spaces needed and progress to next 'j' after every iteration.*/ if ((*p1 >= 'a') && (*p1 < 'a' + (SIZE * SIZE))) { for (int k = 0; k <= *p1 - 'a'; k++) { //the only case in which we dont need to enlarge 'j's value is when we only change one cell. if (k > 0) j++; tempBoard[i][j] = SPACE; } //this condition tells us if we filled to many spaces in the array and thus got an invalid string. if (j >= SIZE * SIZE) { printf("Error\n"); return; } /*the only case in which this condition works is if we receive a backslash before the end of a line, in which case we need to fill the remaining cells in the line with spaces. the condition after the logical 'OR' is if we got to the final iteration so we dont have a backslash, in which case the string has ended but still the final line needs to be filled with spaces.*/ } else if ((*p1 == '/') || ((char *) p1 - (char *) p2 == length)) { for (int k = j; k < SIZE * SIZE; k++) { tempBoard[i][j] = SPACE; j++; } //after filling the needed cells, no further action is needed so we break out of the iteration. break; /*if the pointer points to anything else but what was mentioned, it is a variable and is inserted 'as is' to the fitting cell.*/ } else { tempBoard[i][j] = *p1; } /*this condition tells us if the next char in the string after the last char in the line is not a backslash and thus invalid for being too long. it doesn't fit for the last line though.*/ if ((j == (SIZE * SIZE) - 1) && (*(p1 + 1) != '/') && (i != (SIZE * SIZE - 1))) { printf("Error\n"); return; } p1++; } p1++; } //if the function didn't stop bu now, the string was valid and temp board is copied to board. for (int i = 0; i < SIZE * SIZE; ++i) { strcpy(board[i], tempBoard[i]); } } /********************************************************************************************************************* * Function name: printBoard * Input: char board[][SIZE * SIZE] * Output: none. * Function Operation: The function receives a two-dimensional array(the sudoku board) and prints it to the user. it adds spaces and borders so it would look like a board. *********************************************************************************************************************/ void printBoard(char board[][SIZE * SIZE]) { //this double for loop is a matrix for us to go through every cell in the array. for (int i = 0; i < SIZE * SIZE; i++) { //a line drop is made when we passed to the end of a box. if ((i % SIZE == 0) && (i > 0)) printf("\n"); for (int j = 0; j < SIZE * SIZE; j++) { //if we reached the right side of the box, we print the border between the boxes. if (((j % SIZE) == 0) && (j > 0)) printf("%s",BORDER); printf("%c", board[i][j]); } printf("\n"); } printf("\n"); } /********************************************************************************************************************* * Function name: makeMove * Input: char board[][SIZE * SIZE], char move[] * Output: none. * Function Operation: The function receives a two-dimensional array(the sudoku board) and a string for which move needs to be committed, and makes it if the string is valid. if it isn't it prints 'Error', and doesn't change the board at all. *********************************************************************************************************************/ void makeMove(char board[][SIZE * SIZE], char move[]) { //the strings are made in order to make comparison and determine if the 'move' input is valid. char rep[] = "replaceAll"; char change[] = "change"; char add[] = "add"; char del[] = "delete"; //we use the rows and columns integers to have access to certain locations in the board given by the user. unsigned short int rows, columns; //if the given string is as long as the replace command: if (strlen(move) == REPLACE_LENGTH) { //this loop makes sure that the string is valid and each char of the command is right. for (int i = 0; i < strlen(rep); i++) { if (move[i] != rep[i]) { printf("Error\n"); return; } } //flag is used to mark if any changes were made in the board. if its not lit, the move isn't valid. int flag = 0; /*this condition prevents strings with invalid places or input chars from being done. if the string is fine, we go through the board and insert the given char to every cell in which it is found. if the char doesn't exist in the board, 'error' is printed and no changes are made.*/ if ((move[11] != ' ') && (move[13] != ' ') && (move[13] != ',') && (move[13] != '/') && ((move[13] < 'a') || (move[13] > 'a' + (SIZE * SIZE)))) { for (int i = 0; i < SIZE * SIZE; i++) { for (int j = 0; j < SIZE * SIZE; j++) { if (board[i][j] == move[11]) { board[i][j] = move[13]; flag = 1; } } } //in case that no changes were made, print error and return. if (flag == 0) { printf("Error\n"); return; } } else { printf("Error\n"); return; } //if the given string is as long as the change command: } else if (strlen(move) == CHANGE_LENGTH) { //this loop makes sure that the string is valid and each char of the command is right. for (int i = 0; i < strlen(change); i++) { if (move[i] != change[i]) { printf("Error\n"); return; } } /*the 'rows' and 'columns' integers are made to turn the chars from the string into accessible places from the board. the calculation is according to the 'ascii' table.*/ rows = move[7] - '0', columns = move[9] - '0'; //this condition is almost the same as the one in 'replace', besides that it checks the rows and columns. if (((rows >= 0) && (rows < SIZE * SIZE)) && ((columns >= 0) && (columns < SIZE * SIZE)) && (move[11] != '/') && (move[11] != SPACE) && (move[11] != ',') && ((move[11] < 'a') || (move[11] > 'a' + SIZE * SIZE))) { //this condition makes sure that the given place we want to change is not space. if (board[rows][columns] != SPACE) board[rows][columns] = move[11]; else { printf("Error\n"); return; } } else { printf("Error\n"); return; } //if the given string is as long as the add command: } else if (strlen(move) == ADD_LENGTH) { //again, we check that every char is indeed valid. for (int i = 0; i < strlen(add); ++i) { if (move[i] != add[i]) { printf("Error\n"); return; } } //the same translation into accessible cells is made here according to ascii. rows = move[4] - '0', columns = move[6] - '0'; //the condition is the same as the one in change. if (((rows >= 0) && (rows < SIZE * SIZE)) && ((columns >= 0) && (columns < SIZE * SIZE)) && (move[8] != '/') && (move[8] != SPACE) && (move[8] != ',') && ((move[8] < 'a') || (move[8] > 'a' + SIZE * SIZE))) { //this time, the only case in which 'add' is possible, is if the given cell is blank. if (board[rows][columns] == ' ') board[rows][columns] = move[8]; else { printf("Error\n"); return; } } else { printf("Error\n"); return; } //if the given string is as long as the delete command: } else if (strlen(move) == DELETE_LENGTH) { //again, we check that each char is valid in the string. for (int i = 0; i < strlen(del); ++i) { if (move[i] != del[i]) { printf("Error\n"); return; } } rows = move[7] - '0', columns = move[9] - '0'; //this time, the only needed condition is that the rows and columns are valid cells. if (((rows >= 0) && (rows < SIZE * SIZE)) && ((columns >= 0) && (columns < SIZE * SIZE))) { //as in change, we can only delete cells that has values in them. if (board[rows][columns] != SPACE) board[rows][columns] = SPACE; else { printf("Error\n"); return; } } else { printf("Error\n"); return; } //if the length doesn't suite any of the commands, the string isn't valid and 'error' in printed. } else { printf("Error\n"); return; } } /********************************************************************************************************************* * Function name: testBoard * Input: char board[][SIZE * SIZE] * Output: boolean value (0 or 1). * Function Operation: The function receives a two-dimensional array(the sudoku board) and determines if the board is valid according to the sudoku rules: only valid numbers and blank spaces with only one appearance for each number in a line, row and square. *********************************************************************************************************************/ int testBoard(char board[][SIZE * SIZE]) { /*'counter' is made for us to be able to compare different cells, and 'startRow' and 'startColumn' are used for us to be able to access different squares when checking them.*/ int counter = 0, startRow = 0, startColumn = 0; for (int i = 0; i < SIZE * SIZE; i++) { /*'startRow' is enlarged every 'SIZE' iterations, and thus determines from where to where the loop that each square begins.*/ if ((i % SIZE == 0) && (i != 0)) startRow += SIZE; for (int j = 0; j < SIZE * SIZE; j++) { //for 'startColumn, the same calculation is done as in startRow. if ((j % SIZE == 0) && (j != 0)) startColumn += SIZE; //'space' is a valid char, so we only check other chars comparing to others in their rows/columns/squares. if (board[i][j] != SPACE) { //the only valid chars are '1' to 'SIZE*SIZE', we add '0' to turn in to the ascii char. if ((board[i][j] < '1') || (board[i][j] > SIZE * SIZE + '0')) return 0; /*this double loop is a mini-matrix that checks there are no similar values in different cells in each squares*/ for (int k = startRow; k < startRow + SIZE; k++) { for (int l = startColumn; l < startColumn + SIZE; l++) { //the only case in which the condition isn't true is if its the same cell if ((board[i][j] == board[k][l]) && ((i != k) && (j != l))) { return 0; } } } /*this loop compares each cell to the others in its row and column using counter which grows by 1 in every iteration*/ while (counter < SIZE * SIZE) { if ((counter != j) && (board[i][counter] == board[i][j])) return 0; if ((counter != i) && (board[counter][j] == board[i][j])) return 0; counter++; } //counter is set to 0 again after every iteration because it need to go through the whole row again. counter = 0; } } /*after checking a row, startColumn is set to 0 because we shift to the most left square again, so the loop that checks the square need to start at 0.*/ startColumn = 0; } //if the test has gone by and no condition has stopped it- the board is valid and '1' is returned. return 1; } /********************************************************************************************************************* * Function name: isSameBoard * Input: char board[][SIZE * SIZE], char board1[][SIZE * SIZE] * Output: boolean value (0 or 1). * Function Operation: The function receives 2 two-dimensional arrays and determines if they are identical, by checking cell by cell that they are the same. if they aren't, '0' is returned and the first place that they dont fit is printed to the user. *********************************************************************************************************************/ int isSameBoard(char board[][SIZE * SIZE], char board1[][SIZE * SIZE]) { //this double loop allows us to go through the whole 2 sudoku boards. for (int i = 0; i < SIZE * SIZE; i++) { for (int j = 0; j < SIZE * SIZE; j++) { //we check in every cell if there is inequality between the boards. if there is, the place is printed. if (board[i][j] != board1[i][j]) { printf("Found inequality on row %d col %d.\n", i, j); return 0; } } } //if the function didn't find any inequality, it reaches this part of the code and returns 1. return 1; } /********************************************************************************************************************* * Function name: onlyOneEmpty * Input: char board[][SIZE * SIZE] * Output: boolean value (0 or 1). * Function Operation: The function receives a two-dimensional array(the sudoku board) and determines if the board has as far as one empty cell in each row, column and square. if it doesn't, '0' is returned. if it does, '1' is returned. *********************************************************************************************************************/ int onlyOneEmpty(char board[][SIZE * SIZE]) { /*the same as in the function 'testBoard', for us to be able to go check different squares, we need to set different values for startRow and startColumn to iterate.*/ int startRow = 0, startColumn = 0, counter = 0; for (int i = 0; i < SIZE * SIZE; i++) { //startRow is enlarged every 'SIZE' long iterations. if ((i % SIZE == 0) && (i != 0)) startRow += SIZE; for (int j = 0; j < SIZE * SIZE; j++) { //the same goes for startColumn. if ((j % SIZE == 0) && (j != 0)) startColumn += SIZE; /*the only case in which we need to check if there are more than one empty cell is if there is one in the first place.*/ if (board[i][j] == SPACE) { //if we found a space, we check in its box for other spaces. if another space is found, return 0. for (int k = startRow; k < startRow + SIZE; k++) { for (int l = startColumn; l < startColumn + SIZE; l++) { if ((board[k][l] == SPACE) && ((i != k) && (j != l))) { return 0; } } } /*now we check for other spaces in the cell's rows and columns using growing 'counter'. if another space is found, return 0.*/ while (counter < SIZE * SIZE) { if ((counter != j) && (board[i][counter] == SPACE)) return 0; if ((counter != i) && (board[counter][j] == SPACE)) return 0; counter++; } counter = 0; } } startColumn = 0; } //if the loop went all the way and didn't find excessive spaces, the board is valid and '1' is returned. return 1; } /********************************************************************************************************************* * Function name: completeBoard * Input: char board[][SIZE * SIZE] * Output: none. * Function Operation: The function receives a two-dimensional array(the sudoku board) and, if the board has only one empty cell in each row, column and square- it completes it according to the sudoku rules. *********************************************************************************************************************/ void completeBoard(char board[][SIZE * SIZE]) { //'option' is used for us to be able to fill each row and check if its right. char option = '1'; /*we make all changes on tempBoard and if everything passed we copy it to the original board. this loop copies each line as a string from one board to the other.*/ char tempBoard[SIZE * SIZE][SIZE * SIZE]; for (int i = 0; i < SIZE * SIZE; ++i) { strcpy(tempBoard[i], board[i]); } /*the only case in which we try to solve the board, is if the board is valid: only one empty cell in each row, column and square, and that the board only contains valid chars.*/ if (testBoard(tempBoard) && (onlyOneEmpty(tempBoard))) { for (int i = 0; i < SIZE * SIZE; i++) { for (int j = 0; j < SIZE * SIZE; j++) { //if we encounter 'space', we try to solve the board: we insert a certain option starting at '1'. if (tempBoard[i][j] == SPACE) { tempBoard[i][j] = option; /*after entering the option, we check if the board is valid. if it is, we continue to the next if it isn't, we return to the prior cell and enlarge option to try again.*/ if (!testBoard(tempBoard)) { tempBoard[i][j] = SPACE; j--; option++; } } } //here we set option back to '1' for the next line and next set of checks. option = '1'; } } else { printf("Error\n"); return; } /*if we reach this part of the code and the function didn't return it means that the board was completed and its copied back to the original board.*/ for (int i = 0; i < SIZE * SIZE; ++i) { strcpy(board[i], tempBoard[i]); } }
C
double FtoC(double temp_f) { double temp_c; temp_c = ((double)temp_f - 32.0) / 1.8; return temp_c; }
C
/****************************** * pb-test-outputs.c * v1.0 - shabaz - August 2019 * * ****************************/ #include <stdio.h> #include <stdlib.h> #include <iobb.h> #define EOA 0 char p1_array[]={2, 4, 20, 34, EOA}; char p2_array[]={2, 3, 4, 6, 8, 10, 17, 18, 19, 20, 22, 24, 33, 35, EOA}; void init_gpio(void) { int i; iolib_init(); i=0; while(p1_array[i]!=EOA) { iolib_setdir(1,p1_array[i], DigitalOut); i++; } i=0; while(p2_array[i]!=EOA) { iolib_setdir(2,p2_array[i], DigitalOut); i++; } } int main(void) { int bit; int i; char val; int del=5; init_gpio(); while(1) { for (bit=7; bit>=0; bit--) { i=0; while(p1_array[i]!=EOA) { val=p1_array[i]; if ((val & 1<<bit) || (bit==7)) { pin_high(1, val); } else { pin_low(1, val); } i++; } i=0; while(p2_array[i]!=EOA) { val=p2_array[i]; if ((val & 1<<bit) || (bit==7)) { pin_high(2, val); } else { pin_low(2, val); } i++; } iolib_delay_ms(del); } i=0; while(p1_array[i]!=EOA) { pin_low(1, p1_array[i]); i++; } i=0; while(p2_array[i]!=EOA) { pin_low(2, p2_array[i]); i++; } iolib_delay_ms(100); } // warning on next line is ok return(0); }
C
#include <stdio.h> #include <stdlib.h> int main() { float a, b, c, d, e, peso2, peso3, peso5, media; printf("Entre com o valor da primeira nota: "); scanf("%f", &a); printf("Entre com o peso da primeira nota: "); scanf("%f", &peso2); printf("Entre com o valor da segunda nota: "); scanf("%f", &b); printf("Entre com o peso da segunda nota: "); scanf("%f", &peso2); printf("Entre com o valor da terceira nota: "); scanf("%f", &c); printf("Entre com o peso da terceira nota: "); scanf("%f", &peso2); printf("Entre com o valor da quarta nota: "); scanf("%f", &d); printf("Entre com o peso da quarta nota: "); scanf("%f", &peso3); printf("Entre com o valor da quinta nota: "); scanf("%f", &e); printf("Entre com o peso da quinta nota: "); scanf("%f", &peso5); media = (a*peso2 + b*peso2 + c*peso2 + d*peso3 + e*peso5)/(peso2+peso3+peso5); printf("A media ponderada eh: %.2f \n\n", media); system("pause"); return 0; }
C
#include "fRecupClient.h" #include "GestionSauvegarde/hGestSave.h" int recupClients(ListeClients lc, char * mdpAdmin) { //recupere les clients du fichier sauvegarde. FILE* fichier = NULL; char chaine[35] = ""; fichier = fopen("clients.txt", "r"); //on ouvre le fichier en question. if (fichier == NULL) { printf("Impossible d'ouvrir le fichier clients.txt"); //on verifie si il a ete ouvert avec succes. return 1; } else { fgets(chaine, 16, fichier); *(mdpAdmin) = chaine; Personne pre = NULL; Personne actuel = NULL; while ((fgets(chaine, 35, fichier) != NULL) // On continue tant que fgets n'a pas retourné NULL (fin de fichier) { if (pre != NULL) { actuel = actuel->suivant; //si l'on est pas sur la personne "head" (precedent NULL), on passe a la personne d'apres. } actuel->precedent = pre; //la personne precedant l'actuelle dans la liste prend la valeur qu'on lui a donne. // On lit la chaine de caractères actuel->Nom = chaine; //on recupere chaque info de chaque client; fgets(chaine, 35, fichier); actuel->Prenom = chaine; fgets(chaine, 35, fichier); actuel->identifiant = chaine; fgets(chaine, 35, fichier); actuel->mdp = chaine; int i = 0; int j = 0; Ressource empr[30]; Ressource pret[30]; while (i <= 29) { //on recupere la liste des ressources empruntees. fgets(chaine, 35, fichier); if (chaine == "r") { empr[i] = NULL; } else { if (chaine == "0") { //test pour le type. (empr[i])->type = 0; } else if (chaine == "1") { (empr[i])->type = 1; } else if (chaine == "2") { (empr[i])->type = 2; } else if (chaine == "3") { (empr[i])->type = 3; } else if (chaine == "4") { (empr[i])->type = 4; } fgets(chaine, 35, fichier); if (chaine == "0") { //test pour si ressource disponible ou non. (empr[i])->disponible = 0; } else if (chaine == "1") { (empr[i])->disponible = 1; } fgets(chaine, 35, fichier); (empr[i])->Nom = chaine; fgets(chaine, 35, fichier); (empr[i])->idemprunteur = chaine; fgets(chaine, 35, fichier); (empr[i])->idproprietaire = chaine; fgets(chaine, 10, fichier); if (chaine == "n") { //on teste si la ressource a une date de debut d'emprunt ou non. (empr[i])->debut = NULL; } else { char *j = chaine; //permet de "convertir" la chaine en int pour chaque donnee de la date. ((empr[i])->debut)->jour = atoi(j); fgets(chaine, 10, fichier); char *m = chaine; ((empr[i])->debut)->mois = atoi(m); fgets(chaine, 10, fichier); char *a = chaine; ((empr[i])->debut)->annee = atoi(a); } (empr[i])->suivant = NULL; (empr[i])->precedent = NULL; } i++; } actuel->emprunts = empr; //une fois la liste des emprunts completee on la remet a la personne concernee. while (j <= 29) { //on recupere la liste des ressources pretees. fgets(chaine, 35, fichier); if (chaine == "r") { pret[j] = NULL; } else { if (chaine == "0") { (pret[j])->type = 0; } else if (chaine == "1") { (pret[j])->type = 1; } else if (chaine == "2") { (pret[j])->type = 2; } else if (chaine == "3") { (pret[j])->type = 3; } else if (chaine == "4") { (pret[j])->type = 4; } fgets(chaine, 35, fichier); if (chaine == "0") { (pret[j])->disponible = 0; } else if (chaine == "1") { (pret[j])->disponible = 1; } fgets(chaine, 35, fichier); (pret[j])->Nom = chaine; fgets(chaine, 35, fichier); (pret[j])->idemprunteur = chaine; fgets(chaine, 35, fichier); (pret[j])->idproprietaire = chaine; fgets(chaine, 10, fichier); if (chaine == "n") { //on teste si la ressource a une date de debut d'emprunt ou non. (pret[j])->debut = NULL; } else { char *j = chaine; //permet de "convertir" la chaine en int pour chaque donnee de la date. ((pret[j])->debut)->jour = atoi(j); fgets(chaine, 10, fichier); char *m = chaine; ((pret[j])->debut)->mois = atoi(m); fgets(chaine, 10, fichier); char *a = chaine; ((pret[j])->debut)->annee = atoi(a); } (pret[j])->suivant = NULL; (pret[j])->precedent = NULL; } j++; } actuel->prets = pret; //une fois la liste des emprunts completee on la remet a la personne concernee. if (pre == NULL) { //si l'on est sur la personne "head" (precedent NULL), alors on la definie comme tel dans la liste des clients. lc->head = actuel; } if (pre =! NULL) { //si l'on est pas sur la personne "head", le suivant de son precedent pointe donc vers la personne actuelle. pre->suivant = actuel; } pre = actuel; } lc->tail = actuel; //une fois la boucle achevee, on est à la fin du fichier donc des clients, la personne "tail", est donc celle qu'il nous reste. fclose(fichier); //on ferme le fichier. } return 0; }
C
#include <stdio.h> void slash(int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++){ printf(" "); } printf("\\"); printf("*"); printf("\\"); printf("\n"); } } void num_square(int n, int m){ for (int i = 0; i <= m - n; i++){ for (int j = n + i; j <= m; j++){ printf("%d", j); } for (int j = n; j < n + i; j++){ printf("%d", j); } printf("\n"); } } int calculate_whole(int n, int m){ return n / m; } int calculate_remainder(int n, int m){ return n % m; } void make_change(int n){ printf("dollars = %d\n", calculate_whole(n, 100)); n = calculate_remainder(n, 100); printf("quarters = %d\n", calculate_whole(n, 25)); n = calculate_remainder(n, 25); printf("dimes = %d\n", calculate_whole(n, 10)); n = calculate_remainder(n, 10); printf("nickels = %d\n", calculate_whole(n, 5)); n = calculate_remainder(n, 5); printf("cents = %d\n", n); } int main(void){ slash(3); slash(7); num_square(4, 9); num_square(3, 7); make_change(157); make_change(141); return 0; }
C
// cc -std=c99 -Wall -Werror -o tcp tcp.c // #define _BSD_SOURCE // originally for inet_aton; subsumed by _GNU_SOURCE #define _GNU_SOURCE // for clock_gettime #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netinet/tcp.h> #include <time.h> int main (int argc, char* argv[]) { if (argc != 5) { printf("Usage: %s ip_address port report_period max_count\n", argv[0]); goto panic; } const char* s_addr = argv[1]; const char* s_port = argv[2]; const int report_period = atoi(argv[3]); if (report_period <= 0) { printf("report_period must be positive; given %d\n", report_period); goto panic; } const int max_count = atoi(argv[4]); const int port = atoi(s_port); char s_target[32]; (void)snprintf(s_target, sizeof(s_target), "%s:%d", s_addr, port); struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(port); if (inet_aton(s_addr, &(addr.sin_addr)) == 0) { perror("inet_aton"); goto panic; } int count[2] = {0}; // ok, fail int prev_ok_count = 0; struct timespec t0; struct timespec t1; if (clock_gettime(CLOCK_MONOTONIC_RAW, &t0) != 0) { perror("clock_gettime CLOCK_MONOTONIC_RAW"); goto panic; } // If you encounter the "Cannot assign requested address" error, you have these options: // - Reduce the max_count program argument. // - Assign more IP addresses to the machine running this program. // Don't fight TIME_WAIT. // The proper solution is to assign more IP addresses. // See https://vincent.bernat.ch/en/blog/2014-tcp-time-wait-state-linux for (int i = 0; i < max_count; ++i) { if (i % report_period == 0) { if (clock_gettime(CLOCK_MONOTONIC_RAW, &t1) != 0) { perror("clock_gettime CLOCK_MONOTONIC_RAW"); goto panic; } const int total = count[0] + count[1]; const int report_con = count[0] - prev_ok_count; const long ns_per_s = 1000000000L; const long report_duration_ns = (t1.tv_sec - t0.tv_sec) * ns_per_s + (t1.tv_nsec - t0.tv_nsec); const long con_per_s = report_con * ns_per_s / report_duration_ns; printf("%s %7d / %7d done; %7d ok; %7d error; %7d total; %9ld ns duration; %6ld con/sec;\n", s_target, i, max_count, count[0], count[1], total, report_duration_ns, con_per_s); t0 = t1; prev_ok_count = count[0]; } int has_error = 0; int sfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sfd == -1) { perror("socket"); has_error = 1; goto next; } // This uses RST instead of FIN-ACK, and therefore avoids TIME_WAIT. { struct linger lin = { .l_onoff = 1, .l_linger = 0 }; if (setsockopt(sfd, SOL_SOCKET, SO_LINGER, &lin, sizeof(lin)) != 0) { perror("setsockopt SO_LINGER"); has_error = 1; goto next; } } if (connect(sfd, (struct sockaddr*)(&addr), sizeof(addr)) != 0) { perror("connect"); has_error = 1; goto next; } next: if (sfd != -1) { if (close(sfd) != 0) { perror("close"); has_error = 1; } } ++(count[has_error]); } panic: return EXIT_SUCCESS; }
C
/* * ===================================================================================== * * Filename: testExcept.c * * Description: * * Version: 1.0 * Created: 2011年06月01日 23时18分47秒 * Revision: none * Compiler: gcc * * Author: nuoerlz (nuoliu), nuoerlz@gmail.com * Company: mhtt * * CopyRight: Reserve * * ===================================================================================== */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include "except.h" Except_T Allocate_Failed = { "(& Allcation failed &)" }; char* edit(int argc, char *argv[]) { char *p = NULL; p = malloc(-1); // Force an excepttion if ( p ) return p; RAISE(Allocate_Failed); assert(0); return NULL; } int main (int argc, char *argv[]) { TRY edit(argc, argv); EXCEPT(Allocate_Failed) fprintf(stdout, "(& catch Allocate_Failed &)\n"); ELSE fprintf(stderr, "(& An internal eroor has occurred &)\n"); RERAISE; END_TRY; return 0; }
C
#include <stdio.h> #include <stdint.h> #include <stdlib.h> #include "heater.h" void heatoff(float x) { printf("heatoff %f\n", x); } void heaton(float x) { printf("heaton %f\n", x); } uint8_t temperature = 0; int main(int argc, char **argv) { while (1) { // Generate a random temperature between -50 to 100 ala // temperature = (rand() % (upper – lower + 1)) + lower temperature = (uint8_t) (rand() % (100 + 50 + 1)) - 50; step(); } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/select.h> #define BUF_SIZE 1024 #define MAX_GAME 9 #define MAX_STR 20 void error_handling(char *buf); int main(int argc, char *argv[]){ int serv_sock, clnt_sock; struct sockaddr_in serv_adr, clnt_adr; struct timeval timeout; fd_set reads, cpy_reads; socklen_t adr_sz; int fd_max, str_len, fd_num, opponent; int i, j; char buf[BUF_SIZE]; int connection[50], current = 4; if(argc!=2) { printf("Usage : %s <port>\n", argv[0]); exit(1); } serv_sock=socket(PF_INET, SOCK_STREAM, 0); memset(&serv_adr, 0, sizeof(serv_adr)); serv_adr.sin_family=AF_INET; serv_adr.sin_addr.s_addr=htonl(INADDR_ANY); serv_adr.sin_port=htons(atoi(argv[1])); if(bind(serv_sock, (struct sockaddr*) &serv_adr, sizeof(serv_adr)) == -1) error_handling("bind() error"); if(listen(serv_sock, 5)==-1) error_handling("listen() error"); FD_ZERO(&reads); FD_SET(serv_sock, &reads); fd_max=serv_sock; // init for(i = 0; i < 50; ++i){ connection[i] = -2; } while(1) { cpy_reads=reads; timeout.tv_sec=5; timeout.tv_usec=5000; if((fd_num=select(fd_max+1, &cpy_reads, 0, 0, &timeout))==-1) { break; } if(fd_num==0) { continue; } for(i=0; i<fd_max+1; i++) { if(FD_ISSET(i, &cpy_reads)) { // client connection if(i==serv_sock) { adr_sz=sizeof(clnt_adr); clnt_sock=accept(serv_sock, (struct sockaddr*)&clnt_adr, &adr_sz); FD_SET(clnt_sock, &reads); if(clnt_sock >= 50){ sprintf(buf, "CONNECTION FULL. TRY LATER"); write(clnt_sock, buf, strlen(buf)); close(clnt_sock); continue; } if(fd_max<clnt_sock) fd_max=clnt_sock; printf("connected client: %d \n", clnt_sock); if((current == clnt_sock) || (connection[current] != -1)){ sprintf(buf, "WAITING OPPONENT"); write(clnt_sock, buf, strlen(buf)); connection[clnt_sock] = -1; current = clnt_sock; } else{ connection[current] = clnt_sock; connection[clnt_sock] = current; sprintf(buf, "OPPONENT FOUND. GAME START!"); write(current, buf, strlen(buf)); write(clnt_sock, buf, strlen(buf)); current = clnt_sock; } } else { str_len=read(i, buf, BUF_SIZE); buf[str_len] = '\0'; fprintf(stdout, "Movement of %d : %s\n", i, buf); // client connection lost if(str_len <=0) { FD_CLR(i, &reads); close(i); fprintf(stdout, "closed client: %d \n", i); if(connection[i] != -1){ FD_CLR(connection[i], &reads); close(connection[i]); fprintf(stdout, "closed client: %d\n", connection[i]); connection[i] = -1; connection[connection[i]] = -1; } } // game play else { write(connection[i], buf, strlen(buf)); } } } } } close(serv_sock); return 0; } void error_handling(char *buf) { fputs(buf, stderr); fputc('\n', stderr); exit(1); }
C
#include "meeting.h" #include "calendar_t.h" #include <stdio.h> #include <stdlib.h> int main(){ int cont = 1; int option; Calendar_t* da; Meeting_t* meet; int capacity; float begin; float end; int room; int created=0; int isInsert; char* name="file"; while (cont) { printf("Choose option: \n"); printf("1: create calendar \n"); printf("2: insert meeting \n"); printf("3: remove meeting \n"); printf("4: find meeting \n"); printf("5: print calendar \n"); printf("6: load file \n"); printf("Any another number - stop \n"); scanf("%d", &option); switch (option) { case 1: printf("enter capacity:\n"); scanf("%d",&capacity); da = createDA(capacity); if(da==NULL){ printf("calendar not created:\n"); return 0; } created=1; break; case 2: if(!created){ printf("please create calendar first.\n"); break; } printf("enter begin time:\n"); scanf("%f",&begin); printf("enter end time:\n"); scanf("%f",&end); printf("enter room:\n"); scanf("%d",&room); meet = createMeeting(begin,end,room); if(meet==NULL){ printf("meeting not created:\n"); } isInsert= insertMeeting(da,meet); if(!isInsert) printf("insert not succ\n"); break; case 3: if(!created){ printf("please create calendar first.\n"); break; } printf("enter begin time:\n"); scanf("%f",&begin); removeMeeting(da,begin); break; case 4: if(!created){ printf("please create calendar first.\n"); break; } printf("enter begin time:\n"); scanf("%f",&begin); meet = findMeeting(da,begin); if(meet==NULL){ printf("not found:\n"); } else{ printf("meeting information:\n"); printf("meeting begin:%f meeting end:%f meeting room:%d \n",meet->begin,meet->end,meet->room); } break; case 5: if(!created){ printf("please create calendar first.\n"); break; } printDA(da); break; case 6: if(!created){ printf("please create calendar first.\n"); break; } loadFromFile(name,da); break; default: if(created){ saveToFile(name,da); destoryDA(da); } cont = 0; break; } } /*Meeting_t* meet1; Meeting_t* meet2; Meeting_t* meet3; Meeting_t* meet4; int capacity; Calendar_t* da; meet1=createMeeting(3.0,4.0,4); meet2=createMeeting(7.0,8.0,4); meet3=createMeeting(5.0,6.0,4); printf("enter capacity:\n"); scanf("%d",&capacity); da = createDA(capacity); if(da==NULL) return 0; insertMeeting(da, meet1); insertMeeting(da, meet2); insertMeeting(da, meet3); removeMeeting(da,meet1); meet4=findMeeting(da,meet2); printf("meeting begin:%f", meet4->begin); printDA(da);*/ return 0; }
C
#ifndef GENERATE_H #define GENERATE_H /** Inclusion des librairies necessaires **/ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> /** 64 case de l'échiquier et 8 par lignes **/ #define NUM_TILES 64 #define NUM_TILES_PER_ROW 8 /** Si WINDOWS on inclu conio pour clrscr() **/ #ifdef _WIN32 #include <conio.h> #endif /** Définition en macroprocesseur de clrscr() pour UNIX/MACOS **/ #define clrscr() printf("\e[1;1H\e[2J") /** Définition en macroprocesseur de color(param) qui permet de changer la couleur du terminal **/ #define color(param) printf("\033[1;%dm", param) #define resetColor printf("\033[0m") // Réinitialise la couleur du terminal /** Définition des couleurs **/ #define RED 31 #define GREEN 32 #define YELLOW 33 #define BLUE 34 #define MAGENTA 35 #define CYAN 36 /** Définition d'un noeud (sommet) / Une case de l'échiquier **/ typedef struct NodeListElement { int value; struct NodeListElement * next; }NodeListElement, * NodeList; /** Définition d'une liste d'adjacence **/ typedef struct AdjacencyListElement { NodeListElement * begin; }AdjacencyListElement, * AdjacencyList; /** Définition d'un graphe / Notre échiquier **/ typedef struct GraphElement { int nbVertices; AdjacencyList tabNeighbours; }GraphElement, * Graph; /** Prototypes **/ Graph newChessboardForKnight(); Graph buildKnightGraph(); NodeList addNode(int x); NodeList swapNode(NodeList n1, NodeList n2); int getLength(NodeList n); int * calculateLegalMoves(int position); int ** getAdjacencyMatrix(Graph g); bool isEmptyGraph(Graph g); bool isOutOfBounds(int x); bool isOnSameLine(int position, int candidate); bool isExclusionChessboard(int position, int candidate); bool isValidMove(int position, int candidate); void addEdge(Graph g, int src, int dest); void assignEdges(Graph g, int position); void printGraph(Graph g); void printOptimalZone(Graph g); void eraseGraph(Graph g); void free2D(int ** matrix, int nbLine); void print2D(int ** matrix, int nbLine, int nbCol); void bubbleSort(NodeList * head, int count); void graphSort(Graph g); const char * assignCase(int x); #endif
C
#include "../include/common.h" #define LEN 10 int test_array[LEN]={4,3,2,1,9,8,7,6,5,0}; /*** * 选择排序:每一次遍历,把最大的值放在数组的最右边 * 时间复杂度O(n^2) * 因为需要不断的遍历数组,每次遍历的边界向左边移动一位 * ***/ void selection_sort(int* array, int len) { if(array == NULL || len == 0) { fprintf(stderr, "invalid parameter\n"); return ; } int left_border = 0x00; int right_border = len - 1; int tmp_max = 0x00; int tmp_max_index = 0x00; int i = 0, j = 0; for(right_border = len - 1; right_border > left_border; right_border--) { /*假设最大值是最左边的值*/ tmp_max = array[ right_border ]; tmp_max_index = right_border; for(i=left_border; i<right_border; i++) { if( tmp_max < array[i] ) { tmp_max = array[i]; //当前遍历过程中,不断更新当前的最大值 tmp_max_index = i; } } /*使用异或方式来交换的时候,需要考虑到最大值与最开始的边界一致的情况*/ if(tmp_max_index ^ right_border) { /*交换最右边的值和找到的最大值*/ array[right_border] = array[right_border] ^ array[tmp_max_index]; array[tmp_max_index] = array[right_border] ^ array[tmp_max_index]; array[right_border] = array[right_border] ^ array[tmp_max_index]; } } } int main() { int i = 0; for(i=0; i<LEN; i++) { fprintf(stdout, "%d ", test_array[i]); } fprintf(stdout,"\n"); selection_sort(test_array, LEN); for(i=0; i<LEN; i++) { fprintf(stdout, "%d ", test_array[i]); } fprintf(stdout,"\n"); }
C
#include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> /* printk() */ #include <linux/fs.h> /* everything... */ #include <linux/errno.h> /* error codes */ #include <linux/types.h> /* size_t */ #include <linux/proc_fs.h> #include <linux/fcntl.h> /* O_ACCMODE */ #include <asm/uaccess.h> /* copy_from/to_user */ #include <linux/sort.h> /* sort */ MODULE_LICENSE("Dual BSD/GPL"); MODULE_AUTHOR("Jeova Pereira Gomes"); #define SUCCESS 0 #define DEVICE_NAME "memory" #define BUFFER_LENGTH 10 /* Declaração das funções memory.c */ static int memory_open(struct inode *inode, struct file *filp); static int memory_release(struct inode *inode, struct file *filp); static ssize_t memory_read(struct file *filp, char *buf, size_t count, loff_t *f_pos); static ssize_t memory_write(struct file *filp, const char *buf, size_t count, loff_t *f_pos); void memory_exit(void); int memory_init(void); static int compare(const void *a, const void *b); /* Funcao para comparar no sort */ static struct file_operations memory_fops = { .owner = THIS_MODULE, .read = memory_read, .write = memory_write, .open = memory_open, .release = memory_release }; /* Declaração das funções init and exit */ module_init(memory_init); module_exit(memory_exit); /* GLOBAL */ static char msg[BUFFER_LENGTH]; static char *msg_p; int memory_major = 0; int bytes_operated = 0; int memory_init(void) { /* Registrando o dispositivo 0, para alocação dinamica */ memory_major = register_chrdev(0, DEVICE_NAME, &memory_fops); // Falha if (memory_major < 0) { printk(KERN_ALERT "[MEMORY]: Major number nao pode ser obtido %d\n", memory_major); return memory_major; }else printk(KERN_ALERT "[MEMORY] Registrado com o Major number: %d\n", memory_major); return SUCCESS; } void memory_exit(void) { /* Liberando o major number */ unregister_chrdev(memory_major, DEVICE_NAME); printk(KERN_ALERT "[MEMORY]: Removendo o modulo\n"); } //Executado quando o disposotivo é aberto. static int memory_open(struct inode *inode, struct file *filp) { printk(KERN_DEBUG "[MEMORY]: Aberto"); msg_p = msg; return SUCCESS; } //Executado quando o disposotivo é Fechado static int memory_release(struct inode *inode, struct file *filp) { printk(KERN_DEBUG "[MEMORY]: Fechado"); return SUCCESS; } /* Parametros: filp - referência para o arquivo de device buf - local onde os dados lidos serão colocados count - quantidade de bytes lidos f_pos - Posição inicial de leitura Retorna o número de bytes lidos com sucesso. */ static ssize_t memory_read(struct file *filp, char *buf, size_t count, loff_t *f_pos) { printk(KERN_DEBUG "[MEMORY]: Executou o read %s\n\n", msg_p); if(*msg_p == '\0') return 0; bytes_operated = 0; while(count && *msg_p){ // put_user — Escreve um valor no espaco do usuario // put_user(valor, endereco) put_user(*(msg_p++), buf++); count--; bytes_operated++; } return bytes_operated; } static ssize_t memory_write( struct file *filp, const char *buf,size_t count, loff_t *posicao) { printk(KERN_DEBUG "[MEMORY]: Executou o write"); bytes_operated = 0; // Copia um bloco de dados do espaco do usuario. // Retorna o numero de bytes que nao foi copiado // Se 0, foi sucesso memset(msg_p, 0, sizeof(char)* BUFFER_LENGTH); if(copy_from_user(msg_p, buf, count)){ return -EINVAL; }else{ // Utilizando o sort, para ordenar // sort(base, quantidade, tamanho, compare, swap) sort(msg_p, count, sizeof(char), &compare, NULL); printk(KERN_DEBUG "[MEMORY3]: ordenacao, msg: %s\n", msg_p); return count; } } // Funcao auxiliar para utilizar no sort static int compare(const void *a, const void *b){ char ca = *(const char*)(a); char cb = *(const char*)(b); if(ca < cb) return -1; if(ca > cb) return 1; return 0; }
C
#include "util_adc.h" #include<libmaple/nvic.h> //#include "boards.h" #include <libmaple/dma.h> /* Interrupt function. This handles Analog watchdog and ADC1 and 2. */ extern volatile unsigned int adc_result = 0; /* Starts a single conversion in one channel previously defined. Results must be read through interrupt or polled outside this function. */ void start_single_convert(adc_dev* dev, uint8 channel) { // int pinMapADCin = PIN_MAP[analogInPin].adc_channel; adc_set_reg_seqlen(dev, 1); dev->regs->SQR3 = channel;//use channels next time. dev->regs->CR2 |= ADC_CR2_SWSTART; } /* Starts the continuous mode on one channel of the AD. Results must be read through interrupt or polled outside this function. */ void start_continuous_convert(adc_dev* dev, uint8 channel){ // int pinMapADCin = PIN_MAP[analogInPin].adc_channel; adc_set_reg_seqlen(dev, 1); dev->regs->SQR3 = channel; dev->regs->CR2 |= ADC_CR2_CONT; dev->regs->CR2 |= ADC_CR2_SWSTART; } /* Enable end of conversion interrupt on the ADC. This is for regular conversion, not injected. */ void enable_adc_irq(adc_dev* dev) {//ADC1 for now. dev->regs->CR1 |= (1U<<ADC_CR1_EOCIE_BIT); nvic_irq_enable(NVIC_ADC_1_2 ); } /* Enable the reading of the internal variables (Temperature and Vref). */ void enable_internal_reading(adc_dev *dev) { dev->regs->CR2 |= ADC_CR2_TSVREFE; } /* Read internal variables. Channels are: 16 - Temperature 17 - VrefInt Results must be read through interrupt or polled outside this function. */ void internalRead(adc_dev *dev, uint8 channel) { adc_reg_map *regs = dev->regs; adc_set_reg_seqlen(dev, 1); regs->SQR3 = channel; regs->CR2 |= ADC_CR2_SWSTART; } /* Enable the Analog Watchdog interrupt */ void enable_awd_irq(adc_dev * dev){ dev->regs->CR1 |= (1U<<ADC_CR1_AWDIE_BIT); nvic_irq_enable(NVIC_ADC_1_2 ); } /* Set Analog Watchdog Low Limit. Results must be read through interrupt or polled outside this function. */ void set_awd_low_limit(adc_dev * dev, uint32 limit) { dev->regs->LTR = limit; } /* Set Analog Watchdog High Limit. Results must be read through interrupt or polled outside this function. */ void set_awd_high_limit(adc_dev * dev, uint32 limit) { dev->regs->HTR = limit; } /* Enable the Watchdog function on the ADC. */ void set_awd_channel(adc_dev * dev, uint8 awd_channel){ dev->regs->CR1 |= (awd_channel & ADC_CR1_AWDCH); } /* Enable the Watchdog function on the ADC. */ void enable_awd(adc_dev * dev){ dev->regs->CR1 |= ADC_CR1_AWDEN; } /* Used to configure the sequence and length of the scan mode. Can be used instead of adc_set_reg_seqlen() as it sets both information The channels are not the pin numbers, but ADC channels. */ void adc_set_reg_seq_channel(adc_dev * dev, unsigned char *channels, unsigned char len){ unsigned int records[3] = {0,0,0}; unsigned char i = 0, j = 0; //run away protection if (len > 16) len = 16; //write the length records[2] |= (len - 1) << 20; //i goes through records, j goes through variables. for (i = 0, j = 0; i < len; i++) {//go through the channel list. if (i!=0 && i%6 == 0) j++;//next variable, please!! records[j] |= (channels[i] << ((i%6)*5)); } //update the registers inside with the scan sequence. dev->regs->SQR1 = records[2]; dev->regs->SQR2 = records[1]; dev->regs->SQR3 = records[0]; }; void adc_dma_disable(adc_dev * dev) { bb_peri_set_bit(&dev->regs->CR2, ADC_CR2_DMA_BIT, 0); } void adc_dma_enable(adc_dev * dev) { bb_peri_set_bit(&dev->regs->CR2, ADC_CR2_DMA_BIT, 1); } uint8 poll_adc_convert(adc_dev *dev) { return bb_peri_get_bit(dev->regs->SR, ADC_SR_EOC_BIT); } //uint8 maxSamples = 32; //uint32_t dataPoints32[maxSamples / 2]; //uint16_t *dataPoints = (uint16_t *)&dataPoints32; /* //fast interleaved mode void setADCs (uint8 analogInPin) { // const adc_dev *dev = PIN_MAP[analogInPin].adc_device; int pinMapADCin = PIN_MAP[analogInPin].adc_channel; adc_set_sample_rate(ADC1, ADC_SMPR_1_5); //=0,58uS/sample. ADC_SMPR_13_5 = 1.08uS - use this one if Rin>10Kohm, adc_set_sample_rate(ADC2, ADC_SMPR_1_5); // if not may get some sporadic noise. see datasheet. // adc_reg_map *regs = dev->regs; adc_set_reg_seqlen(ADC1, 1); ADC1->regs->SQR3 = pinMapADCin; ADC1->regs->CR2 |= ADC_CR2_CONT; // | ADC_CR2_DMA; // Set continuous mode and DMA ADC1->regs->CR1 |= ADC_CR1_FASTINT; // Interleaved mode ADC1->regs->CR2 |= ADC_CR2_SWSTART; ADC2->regs->CR2 |= ADC_CR2_CONT; // ADC 2 continuos ADC2->regs->SQR3 = pinMapADCin; } */ /* This is run inside the loop() function. It stays active and polls for the end of the transfer. */ /* void takeSamples () { // This loop uses dual interleaved mode to get the best performance out of the ADCs // unsigned long samplingTime=0; dma_init(DMA1); dma_attach_interrupt(DMA1, DMA_CH1, DMA1_CH1_Event); adc_dma_enable(ADC1); dma_setup_transfer(DMA1, DMA_CH1, &ADC1->regs->DR, DMA_SIZE_32BITS, dataPoints32, DMA_SIZE_32BITS, (DMA_MINC_MODE | DMA_TRNS_CMPLT));// Receive buffer DMA dma_set_num_transfers(DMA1, DMA_CH1, maxSamples / 2); dma1_ch1_Active = 1; // regs->CR2 |= ADC_CR2_SWSTART; //moved to setADC dma_enable(DMA1, DMA_CH1); // Enable the channel and start the transfer. //adc_calibrate(ADC1); //adc_calibrate(ADC2); samplingTime = micros(); while (dma1_ch1_Active); samplingTime = (micros() - samplingTime); dma_disable(DMA1, DMA_CH1); //End of trasfer, disable DMA and Continuous mode. // regs->CR2 &= ~ADC_CR2_CONT; } */
C
#include <stdio.h> #include <stdlib.h> int main() { char ch, file_name[25]; FILE *fp; int space=0,tab=0,new=0; fp = fopen("two.txt","r"); if( fp == NULL ) { perror("Error while opening the file.\n"); exit(0); } while( ( ch = fgetc(fp) ) != EOF ) { if(ch==' ') { space++; } else if(ch=='\n') { new++; } else if(ch=='\t') { tab++; } } printf("\n The number of spaces are %d \t",space); printf("\n The number of tabs are %d \t",tab); printf("\n The number of new lines are %d \t",new); fclose(fp); return 0; }
C
/** ****************************************************************************** * @file : ad5696.c * @brief : This file provides code for the 16-DAC ad5696 with I2C Interface * @author : Kyurkchu A. ****************************************************************************** * * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "ad5696.h" /** Transfer function: ************************************ Uout = VREF * Gain * (D/65535); ************************************ 1. VREF is the value of the external reference. VREF = 2.048 V 2. Gain is the gain of the output amplifier, Gain = 2. 3. D is the decimal equivalent of the binary code that is loaded to and 0 to 65,535 for the 16-bit AD5696. Convert function: ************************************ D = (Uout /(VREF * Gain)) * 65535; ************************************ 1. VREF is the value of the external reference. 2. Gain is the gain of the output amplifier , Gain = 2. 3. Uout is the float value of channels (A,B,C,D). */ extern I2C_HandleTypeDef hi2c2; uint8_t TXbuffer[3]; uint8_t RXbuffer[3]; //*********** INIT AD5696 AND SET INIT DATA **********************/ /** * @brief AD5696 init and set data * @retval void */ void AD5696_init(void){ if(HAL_I2C_IsDeviceReady(&hi2c2,AD5696_ADDRESSE, 2, 10)==HAL_OK) { set_value_to_channel_AD5696(COMM_WRITE_AND_UPDATE,ADDR_DAC_A,ADC_VALUE_A); // for VDDA_DAC set_value_to_channel_AD5696(COMM_WRITE_AND_UPDATE,ADDR_DAC_B,ADC_VALUE_B_MIN); // for VDDA_TRANS set_value_to_channel_AD5696(COMM_WRITE_AND_UPDATE,ADDR_DAC_C,ADC_VALUE_C_MIN); // for VDDA_PIX set_value_to_channel_AD5696(COMM_WRITE_AND_UPDATE,ADDR_DAC_D,ADC_VALUE_D); // for VMMerge_DAC } else { } } //*********** SET VALUE TO SELECT CHANNEL of AD5696 ***********/ void set_value_to_channel_AD5696(uint8_t command, uint8_t dac_channel, uint16_t data){ TXbuffer[0] = (command <<4)| dac_channel; TXbuffer[1] = (data>>8); TXbuffer[2] = data & 0xff; HAL_I2C_Master_Transmit(&hi2c2,AD5696_ADDRESSE, TXbuffer, 3,100); } //*********** WRITE AND UPDATE DATA FOR SELECTED CHANNEL AD5696 */ /** * @brief write and update data for selected channel of AD5696 * @retval void */ void write_and_update_DAC_AD5696(uint16_t data, uint8_t dac_channel) { TXbuffer[0] = (COMM_WRITE_AND_UPDATE <<4)| dac_channel; TXbuffer[1] = (data>>8); TXbuffer[2] = data & 0xff; HAL_I2C_Master_Transmit(&hi2c2,AD5696_ADDRESSE, TXbuffer, 3,100); } //*********** CONVERT FLOAT DATA TO DIGITAL DATA AD5696 ****/ /** * @brief convert float data to digital data AD5696 * @retval void */ uint16_t convert_float_to_data_DAC_AD5696(float FloatInputData) { uint16_t Dout = 0x00; Dout = (FloatInputData /( U_REF * GAIN )) * 65535; return Dout; }
C
#include <pthread.h> #include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <sys/syscall.h> int var = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pid_t gettid(void) { return syscall(SYS_gettid); } void * hilo(void *arg) { printf("soy el hilo %d, la variables es %d \n", gettid(), var); pthread_mutex_lock(&mutex); var++; pthread_mutex_unlock(&mutex); pthread_exit(NULL); } #define MAX_TH 4 int main(int argc, char **argv) { pthread_t tid[MAX_TH]; int i = MAX_TH; printf("soy el hilo de main mi pid es %d\n", getpid()); while (i--) { if (pthread_create(&tid[i], NULL, hilo, NULL)) { perror("pthread_create()"); return -1; } } for (i = 0; i < MAX_TH; i++) { pthread_join(tid[i], NULL); } printf("La variable sumada es: %d \n", var); pthread_exit(NULL); return 0; }
C
#ifndef _DATATYPES_ #define _DATATYPES_ #include "stdclibs.h" /* définitions des types de données nécessaies */ struct pt; typedef struct pt Raw_point; typedef Raw_point* ListItem; // A structure to represent an adjacency list node struct AdjListNode { ListItem item; struct AdjListNode* next; }; // A structure to represent an adjacency list typedef struct { struct AdjListNode *head; // pointer to head node of list } AdjList; struct pt { int x; int y; double key; // used for dijkstra algorithm AdjList *adjlist; // adjacency list struct pt *prev; // useful for reconstructing the path from the goal node }; typedef Raw_point* PQItem; // too many memory copies for fixup and fixdown heap operations !! typedef struct VGpt{ Raw_point *point; // pointer on polygons points and begin-end points struct VGpt *father; struct VGpt *left; struct VGpt *right; struct VGpt *rightMostSon; } VGnode; typedef struct{ Raw_point *base, *next; } VGedge; typedef struct { Raw_point *points; int size; int maxSize; } Polygon; typedef struct { Polygon *polygons; int size; int maxSize; } Obstacles; #define nb_obs_points 3 #endif
C
#include"FileRead.h" int main(int argc, char * argv[]) { if( argc < 2 ) { printf("usage : ./add-nbo file1 file2 ...\n"); exit(0); } uint32_t* arr = (uint32_t*)malloc(sizeof(uint32_t) * argc-1); uint32_t hex = 0; //printf("hex : %08x\n", hex); //printf("argc : %d\n", argc); for(int i = 1; i < argc; i++) { uint32_t temp = FileRead(argv[i]); arr[i-1] = temp; hex += temp; //printf("hex : %08x\n", hex); } //1000(0x3e8) + 500(0x1f4) = 1500(0x5dc) for(int i = 1; i < argc; i++) { printf("%d(%#04x)", arr[i-1], arr[i-1]); if( i == argc-1 ) break; printf(" + "); } printf(" = %d(%#04x)\n", hex, hex); free(arr); return 0; }
C
#pragma once #include <stddef.h> enum JsonType { jsonStringT, jsonNumberT, jsonObjectT, jsonArrayT, jsonTrueT, jsonFalseT, jsonNullT, }; struct JsonVal { enum JsonType type; union { char *string; long double number; struct { char **keys; struct JsonVal *values; int len; } object; struct { struct JsonVal *values; int len; } array; } u; }; struct JsonVal jsonParseString(const char *str, char *errorBuf, int errorBufSize); /*creates empty (top-level) object*/ struct JsonVal jsonCreateObject(); /*check type functions*/ int JsonVal_isString(const struct JsonVal *val); int JsonVal_isNumber(const struct JsonVal *val); int JsonVal_isObject(const struct JsonVal *val); int JsonVal_isArray(const struct JsonVal *val); int JsonVal_isTrue(const struct JsonVal *val); int JsonVal_isFalse(const struct JsonVal *val); int JsonVal_isNull(const struct JsonVal *val); /*add subvalues to existing values. return pointers to the newly created values.*/ struct JsonVal *JsonVal_objectAddString(struct JsonVal *val, const char *key, const char *value); struct JsonVal *JsonVal_objectAddNumber(struct JsonVal *val, const char *key, long double number); struct JsonVal *JsonVal_objectAddObject(struct JsonVal *val, const char *key); struct JsonVal *JsonVal_objectAddArray(struct JsonVal *val, const char *key); struct JsonVal *JsonVal_objectAddTrue(struct JsonVal *val, const char *key); struct JsonVal *JsonVal_objectAddFalse(struct JsonVal *val, const char *key); struct JsonVal *JsonVal_objectAddNull(struct JsonVal *val, const char *key); struct JsonVal *JsonVal_arrayAddString(struct JsonVal *val, const char *value); struct JsonVal *JsonVal_arrayAddNumber(struct JsonVal *val, long double number); struct JsonVal *JsonVal_arrayAddObject(struct JsonVal *val); struct JsonVal *JsonVal_arrayAddArray(struct JsonVal *val); struct JsonVal *JsonVal_arrayAddTrue(struct JsonVal *val); struct JsonVal *JsonVal_arrayAddFalse(struct JsonVal *val); struct JsonVal *JsonVal_arrayAddNull(struct JsonVal *val); /*access functions*/ int JsonVal_arrayLen(struct JsonVal *val); struct JsonVal *JsonVal_arrayAt(struct JsonVal* val, int index); struct JsonVal *JsonVal_getObjectValueByKey(const struct JsonVal *val, const char *key); void JsonVal_forEachArrayElement( const struct JsonVal *val, void *ctx, void (*action)(void *, const struct JsonVal *)); void JsonVal_forEachObjectElement( const struct JsonVal *val, void *ctx, void (*action)(void *, const char *key, const struct JsonVal *)); /*write functions*/ int JsonVal_write( const struct JsonVal *val, /*User context. Will be passed to the writeFunc callback.*/ void *ctx, /*user supplied write callback function.*/ int (*writeFunc)(void *ctx, void *buf, int len)); /*returns total bytes required*/ int JsonVal_writeString(const struct JsonVal *val, char *buf, int len); void JsonVal_destroy(struct JsonVal *val);
C
#include "strncat-lib.c" #include "lib/main.c" /* Copyright (C) 2000, 2003 Free Software Foundation. Ensure all expected transformations of builtin strncat occur and perform correctly. Written by Kaveh R. Ghazi, 11/27/2000. */ extern void abort (void); typedef __SIZE_TYPE__ size_t; extern char *strncat (char *, const char *, size_t); extern char *strcpy (char *, const char *); extern void *memset (void *, int, size_t); extern int memcmp (const void *, const void *, size_t); int x = 123; /* Reset the destination buffer to a known state. */ #define RESET_DST_WITH(FILLER) \ do { memset (dst, 'X', sizeof (dst)); strcpy (dst, (FILLER)); } while (0) void main_test (void) { const char *const s1 = "hello world"; const char *const s2 = ""; char dst[64], *d2; RESET_DST_WITH (s1); if (strncat (dst, "", 100) != dst || memcmp (dst, "hello world\0XXX", 15)) abort(); RESET_DST_WITH (s1); if (strncat (dst, s2, 100) != dst || memcmp (dst, "hello world\0XXX", 15)) abort(); RESET_DST_WITH (s1); d2 = dst; if (strncat (++d2, s2, 100) != dst+1 || d2 != dst+1 || memcmp (dst, "hello world\0XXX", 15)) abort(); RESET_DST_WITH (s1); d2 = dst; if (strncat (++d2+5, s2, 100) != dst+6 || d2 != dst+1 || memcmp (dst, "hello world\0XXX", 15)) abort(); RESET_DST_WITH (s1); d2 = dst; if (strncat (++d2+5, s1+11, 100) != dst+6 || d2 != dst+1 || memcmp (dst, "hello world\0XXX", 15)) abort(); RESET_DST_WITH (s1); d2 = dst; if (strncat (++d2+5, s1, 0) != dst+6 || d2 != dst+1 || memcmp (dst, "hello world\0XXX", 15)) abort(); RESET_DST_WITH (s1); d2 = dst; if (strncat (++d2+5, "", ++x) != dst+6 || d2 != dst+1 || x != 124 || memcmp (dst, "hello world\0XXX", 15)) abort(); RESET_DST_WITH (s1); if (strncat (dst, "foo", 3) != dst || memcmp (dst, "hello worldfoo\0XXX", 18)) abort(); RESET_DST_WITH (s1); if (strncat (dst, "foo", 100) != dst || memcmp (dst, "hello worldfoo\0XXX", 18)) abort(); RESET_DST_WITH (s1); if (strncat (dst, s1, 100) != dst || memcmp (dst, "hello worldhello world\0XXX", 26)) abort(); RESET_DST_WITH (s1); d2 = dst; if (strncat (++d2, s1, 100) != dst+1 || d2 != dst+1 || memcmp (dst, "hello worldhello world\0XXX", 26)) abort(); RESET_DST_WITH (s1); d2 = dst; if (strncat (++d2+5, s1, 100) != dst+6 || d2 != dst+1 || memcmp (dst, "hello worldhello world\0XXX", 26)) abort(); RESET_DST_WITH (s1); d2 = dst; if (strncat (++d2+5, s1+5, 100) != dst+6 || d2 != dst+1 || memcmp (dst, "hello world world\0XXX", 21)) abort(); /* Test at least one instance of the __builtin_ style. We do this to ensure that it works and that the prototype is correct. */ RESET_DST_WITH (s1); if (__builtin_strncat (dst, "", 100) != dst || memcmp (dst, "hello world\0XXX", 15)) abort(); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* behavior_memcpy.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: aulopez <aulopez@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/14 10:17:33 by aulopez #+# #+# */ /* Updated: 2019/07/02 14:23:06 by aulopez ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include "testing.h" #include <string.h> #include <stdlib.h> #include <signal.h> static inline int test_undefined(void *(*mem)(void *, const void *, size_t), int option) { signal(SIGSEGV, crash_expected); signal(SIGBUS, crash_expected); if (option == '3') mem("", "1", 1); if (option == '4') mem(NULL, NULL, 1); if (option == '5') mem(NULL, "1", 1); if (option == '6') mem("1", NULL, 1); if (option == '7') mem(NULL, NULL, 0); if (option == '8') mem(NULL, "1", 0); if (option == '9') mem("1", NULL, 0); return (NO_CRASH); } static inline int test_general(void *(*mem)(void *, const void *, size_t)) { char src[4096]; char sys_dst[4096]; char lib_dst[4096]; void *pc; size_t i; i = 0; pc = lib_dst; while (i < 4096) { if (i) memset(src + i - 1, (char)i, 1); memset(sys_dst, 0, i); memset(lib_dst, 0, i); memcpy(sys_dst, src, i); pc = mem(lib_dst, src, i); if (memcmp(lib_dst, sys_dst, i)) return (FAIL_1); else if (pc != lib_dst) return (FAIL_2); i++; } return (SUCCESS); } static inline int test_memory(void *(*mem)(void *, const void *, size_t)) { void *dst; void *src; size_t i; if (!(dst = protected_memory(4096))) return (ERROR); if (!(src = protected_memory(4096))) return (ERROR); i = 0; while (i++ < 4096) mem(dst + 4096 - i, src + 4096 - i, i); if (!memcmp(dst, src, 4096)) return (SUCCESS); return (FAIL_1); } static inline int test_misaligned(void *(*mem)(void *, const void *, size_t)) { char src[4096]; char sys_dst[4096]; char lib_dst[4096]; void *pc; size_t i; i = 0; pc = lib_dst; while (i < 4096) { if (i) memset(src, (char)i, 4096); memset(sys_dst, 0, i); memset(lib_dst, 0, i); memcpy(sys_dst + i, src, 4096 - i); pc = mem(lib_dst + i, src, 4096 - i ); if (memcmp(lib_dst, sys_dst, 4096 - i)) return (FAIL_1); else if (pc != lib_dst + i) return (FAIL_2); i++; } return (SUCCESS); } int main(int ac, char **av) { int option; int ret; void *function; g_av = av; if (!setup(ac, av)) return (ERROR); option = av[1][0]; function = (av[2][0] == '0') ? memcpy : ft_memcpy; if (option == '0') ret = test_general(function); else if (option == '1') ret = test_memory(function); else if (option == '2') ret = test_misaligned(function); else ret = test_undefined(function, option); return (cleanup(ret, av)); }
C
#include<stdio.h> /* void fun(); int main() { fun(); fun(); fun(); return 0; } void fun() { static int v1 = 4,v2 = 6; printf("%d %d\n",v1,v2); v1++; v2++; } */ void fun(); extern int globalval; int main() { int val; val = 10; printf("In main, Before call : %d\n",globalval); fun(val); printf("In main, After call : %d\n",globalval); return 0; }
C
#include "kernel/types.h" #include "user.h" #define INPUTBUFSZ 20 int main ( int argc, char* argv [] ) { char buf [ INPUTBUFSZ ]; printf( stdout, "Hi there!\nWhat's your name?\n" ); // memset( buf, 0, INPUTBUFSZ ); gets( buf, INPUTBUFSZ ); buf[ strlen( buf ) - 1 ] = 0; // remove newline char '\n' printf( stdout, "Pleasure to meet you %s!\n", buf ); exit(); }
C
#include <libmx.h> static void put_char(const char ch, char *string) { int l = mx_strlen(string); string[l] = ch; } static void do_print(long int n, char *string) { if (n > 9) { do_print(n / 10, string); } put_char('0' + n % 10, string); } char *mx_itoa(int number) { char *result = mx_strnew(10); long int value = number; if (value < 0) { put_char('-', result); value = -value; } do_print(value, result); return result; }
C
#include <stdio.h> #include <stdlib.h> void main() { int n=0; float x,eps,sinx,temp; printf("Nhap vao goc:"); scanf("%f",&x); printf("Nhap do chinh xac vd:0.000001 :"); scanf("%f",&eps); x = x*3.14/180; sinx = x; temp = x; while(temp > eps || temp < (-eps) ) { n++; temp = -temp*x*x/(2*n*(2*n+1)); sinx = sinx + temp; } printf("Ket qua: %f",sinx); }
C
#include <stdio.h> int fib(int n); int main() { int p; printf("Specify which term of the series you want "); scanf("%d", &p); printf("The number is %d", fib(p)); return 0; } int fib(int n) { int a; if (n == 1) { return 0; } else if (n == 2) { return 1; } else if (n >= 3) { a=fib(n - 1) + fib(n - 2); return a; } }
C
#include "stdint.h" typedef void (*constructor_t)(void); extern constructor_t _init_array_start[]; extern constructor_t _init_array_end[]; extern uint32_t bss_start; extern uint32_t bss_end; extern void PUT32(uint32_t, uint32_t); void kernel_init(void) { //initialize .bss section with zeros uint32_t addr; for (addr = bss_start; addr < bss_end; addr += 4) PUT32(addr, 0); //call all static constructors constructor_t *fn = _init_array_start; while (fn < _init_array_end) { (*fn++)(); } } void *__dso_handle = 0; int __cxa_atexit(void(*f)(void *), void *p, void *d) { return 0; } void __cxa_pure_virtual(void) { while(1){} } int __cxa_guard_acquire(unsigned char *g) { if( *g == 0 ) { *g = 1; return 1; } else { return 0; } } void __cxa_guard_release(unsigned char *g) { *g = 2; }
C
// // main.c // Practice02 // // Created by 綦 on 16/10/17. // Copyright © 2016年 PowesunHolding. All rights reserved. // /* 1.编写一个程序,从标准输入读取一些字符,并把它们写到标准输出上。它同时应该计算checksum值,并写在字符的后面。 2.编写一个程序,一行一行地读入输入行,直至到达文件尾。算出每行输入行的长度,然后把最长的那行打印出来。 */ #include <stdio.h> #include <string.h> #define MAX_ROW_LENTH 1000 #define MAX 1000 void practice03(); void practice04(); int main(int argc, const char * argv[]) { practice03(); return 0; } void practice03() { int ch; int checksum = -1; while ((ch = getchar()) != EOF) { checksum += ch; if (ch == '\n') { printf("(%i)", checksum); } putchar(ch); if (ch == '\n') { printf("(%d)", checksum); break; } } } void practice04() { int maxRowLenth = 0; int currentLenth = 0; int ch; char maxRow[MAX_ROW_LENTH]; char currentRow[MAX_ROW_LENTH]; while ((ch = getchar()) != EOF) { currentRow[currentLenth] = ch; currentLenth++; if (ch == '\n') { if (currentLenth >= maxRowLenth) { maxRowLenth = currentLenth; strncpy(maxRow + 0, currentRow + 0, currentLenth); } currentLenth = 0; } } printf("最长的行:%s", maxRow); }
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 */ /* Type definitions */ /* Variables and functions */ char* CURS_LEFT ; int /*<<< orphan*/ * CURS_RIGHT ; void* CURS_UP ; void* ENTER_BOLD ; void* ENTER_DIM ; void* ENTER_REVERSE ; void* ENTER_STANDOUT ; void* ENTER_UNDERLINE ; void* EXIT_ATTRIBUTES ; void* EXIT_STANDOUT ; void* EXIT_UNDERLINE ; void* UNDER_CHAR ; int /*<<< orphan*/ must_use_uc ; scalar_t__ tgetflag (char*) ; void* tgetstr (char*,char**) ; __attribute__((used)) static void initcap(void) { static char tcapbuf[512]; char *bp = tcapbuf; /* This nonsense attempts to work with both old and new termcap */ CURS_UP = tgetstr("up", &bp); CURS_RIGHT = tgetstr("ri", &bp); if (CURS_RIGHT == NULL) CURS_RIGHT = tgetstr("nd", &bp); CURS_LEFT = tgetstr("le", &bp); if (CURS_LEFT == NULL) CURS_LEFT = tgetstr("bc", &bp); if (CURS_LEFT == NULL && tgetflag("bs")) CURS_LEFT = "\b"; ENTER_STANDOUT = tgetstr("so", &bp); EXIT_STANDOUT = tgetstr("se", &bp); ENTER_UNDERLINE = tgetstr("us", &bp); EXIT_UNDERLINE = tgetstr("ue", &bp); ENTER_DIM = tgetstr("mh", &bp); ENTER_BOLD = tgetstr("md", &bp); ENTER_REVERSE = tgetstr("mr", &bp); EXIT_ATTRIBUTES = tgetstr("me", &bp); if (!ENTER_BOLD && ENTER_REVERSE) ENTER_BOLD = ENTER_REVERSE; if (!ENTER_BOLD && ENTER_STANDOUT) ENTER_BOLD = ENTER_STANDOUT; if (!ENTER_UNDERLINE && ENTER_STANDOUT) { ENTER_UNDERLINE = ENTER_STANDOUT; EXIT_UNDERLINE = EXIT_STANDOUT; } if (!ENTER_DIM && ENTER_STANDOUT) ENTER_DIM = ENTER_STANDOUT; if (!ENTER_REVERSE && ENTER_STANDOUT) ENTER_REVERSE = ENTER_STANDOUT; if (!EXIT_ATTRIBUTES && EXIT_STANDOUT) EXIT_ATTRIBUTES = EXIT_STANDOUT; /* * Note that we use REVERSE for the alternate character set, * not the as/ae capabilities. This is because we are modelling * the model 37 teletype (since that's what nroff outputs) and * the typical as/ae is more of a graphics set, not the greek * letters the 37 has. */ UNDER_CHAR = tgetstr("uc", &bp); must_use_uc = (UNDER_CHAR && !ENTER_UNDERLINE); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* obj_init.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dmoureu- <dmoureu-@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/03/17 12:37:49 by dmoureu- #+# #+# */ /* Updated: 2018/03/17 13:08:59 by dmoureu- ### ########.fr */ /* */ /* ************************************************************************** */ #include <scop.h> t_obj *secure_malloc_obj(void) { t_obj *obj; obj = (t_obj*)malloc(sizeof(t_obj)); if (obj == NULL) { printf("Malloc error : exit !\n"); exit(1); } return (obj); } void obj_init_color(t_obj *obj_data) { size_t i; t_vec3f *addr; float color; i = 0; while (i < obj_data->nvertices) { if (i % 3 == 0) color = (((float)(rand() % 50)) / 100.0f) + 0.1f; addr = (t_vec3f*)&obj_data->colors[i * 3]; vec3fedit(&addr[0], color, color, color); i++; } } void obj_init(t_obj *obj_data, t_tmp_obj *t) { obj_data->nvertices = list_length(t->vertex_indices); obj_data->vertices = (float*)malloc(sizeof(float) * 3 * obj_data->nvertices); obj_data->nuvs = list_length(t->uv_indices); if (obj_data->nuvs > 0) obj_data->uvs = (float*)malloc(sizeof(float) * 2 * obj_data->nuvs); obj_data->nnormals = list_length(t->normal_indices); if (obj_data->nnormals > 0) obj_data->normals = (float*)malloc(sizeof(float) * 3 * obj_data->nnormals); obj_data->tangents = (float*)malloc(sizeof(float) * 3 * obj_data->nnormals); obj_data->bitangents = (float*)malloc(sizeof(float) * 3 * obj_data->nnormals); obj_data->colors = (float*)calloc(3 * obj_data->nvertices, sizeof(float)); obj_init_color(obj_data); }
C
/* Articulation Points O(V+E) Finds all articulation points and bridges in a graph. An articulation point is a vertex whose removal would disconnect the graph. An bridge is a vertex whose removal disconnects the graph. */ vi low2, num2, parent, strongPoints; int counter2, root, rootChildren; void dfs1(Graph &g, int v) { low2[v] = num2[v] = counter2++; FORC(g.edges[v], edge) { if(num2[edge->to] == -1) { parent[edge->to] = v; if(v == root) rootChildren++; dfs1(g, edge->to); if(low2[edge->to] >= num2[v]) strongPoints[v] = true; if(low2[edge->to] > num2[v]) edge->strong = g.edges[edge->to][edge->backEdge].strong = true; low2[v] = min(low2[v], low2[edge->to]); } else if(edge->to != parent[v]) low2[v] = min(low2[v], num2[edge->to]); } } vi articulationPointsAndBridges(Graph &g) { counter2 = 0; num2 = vi(g.V, -1), low2 = vi(g.V, 0), parent = vi(g.V, -1), strongPoints = vi(g.V, 0); FOR(i, 0, g.V) if(num2[i] == -1) { root = i, rootChildren = 0; dfs1(g, i); strongPoints[root] = rootChildren > 1; } return strongPoints; }
C
#include <gst/gst.h> #include "latency.h" #include <stdio.h> guint64 src_ts = 0, sink_ts = 0; static void do_pull (Latency * self, guint64 ts, GstElement * element) { if(element && GST_IS_OBJECT(element)) { char* name = gst_element_get_name(element); if(name && strcmp(name, "sink") == 0) { printf("%s at %llu\n", name, ts); sink_ts = ts; } } } static void do_push (Latency * self, guint64 ts, GstElement * element) { if(element && GST_IS_OBJECT(element)) { char* name = gst_element_get_name(element); if(name && strcmp(name, "src")==0) { printf("%s at %llu\n",name, ts); src_ts = ts; } } } int main (int argc, char *argv[]) { GstElement *pipeline; GstBus *bus; GstMessage *msg; /* Initialize GStreamer */ gst_init (&argc, &argv); Latency* latency = latency_new(); //https://github.com/GStreamer/gstreamer/blob/master/plugins/tracers/gstlatency.c gst_tracing_register_hook (GST_TRACER (latency), "pad-push", G_CALLBACK (do_push)); gst_tracing_register_hook (GST_TRACER (latency), "pad-pull-range", G_CALLBACK (do_pull)); /* Build the pipeline */ pipeline = gst_parse_launch("videotestsrc num-buffers=100 ! x264enc ! mp4mux ! filesink location=file.mp4", NULL); /* Start playing */ gst_element_set_state (pipeline, GST_STATE_PLAYING); /* Wait until error or EOS */ bus = gst_element_get_bus (pipeline); msg = gst_bus_timed_pop_filtered (bus, GST_CLOCK_TIME_NONE, GST_MESSAGE_ERROR | GST_MESSAGE_EOS); /* Free resources */ if (msg != NULL) gst_message_unref (msg); gst_object_unref (bus); gst_element_set_state (pipeline, GST_STATE_NULL); gst_object_unref (pipeline); return 0; }
C
#include <stdio.h> #include <allegro5/allegro.h> #include <allegro5/allegro_primitives.h> #include "common.c" static void draw(void) { al_clear_to_color(al_map_rgb_f(1, 1, 1)); al_draw_line(10, 10, 190, 190, al_map_rgb_f(0, 0, 0), 0); al_draw_line(100, 10, 100, 190, al_map_rgb_f(0, 0, 0), 0); al_draw_line(10, 100, 190, 100, al_map_rgb_f(0, 0, 0), 0); al_draw_line(190, 10, 10, 190, al_map_rgb_f(0, 0, 0), 0); } int main(void) { ALLEGRO_DISPLAY *display, *ms_display; ALLEGRO_EVENT_QUEUE *queue; ALLEGRO_TIMER *timer; bool quit = false; bool redraw = true; if (!al_init()) { printf("Could not init Allegro.\n"); return 1; } al_init_primitives_addon(); al_install_keyboard(); al_set_new_display_option(ALLEGRO_SAMPLE_BUFFERS, 1, ALLEGRO_REQUIRE); al_set_new_display_option(ALLEGRO_SAMPLES, 4, ALLEGRO_SUGGEST); ms_display = al_create_display(200, 200); if (!ms_display) { printf("Multisampling not available.\n"); return 1; } al_set_window_title(ms_display, "Multisampling"); al_set_new_display_option(ALLEGRO_SAMPLE_BUFFERS, 0, ALLEGRO_REQUIRE); al_set_new_display_option(ALLEGRO_SAMPLES, 0, ALLEGRO_SUGGEST); display = al_create_display(200, 200); al_set_window_title(display, "Normal"); timer = al_create_timer(1.0 / 30.0); queue = al_create_event_queue(); al_register_event_source(queue, al_get_keyboard_event_source()); al_register_event_source(queue, al_get_display_event_source(display)); al_register_event_source(queue, al_get_display_event_source(ms_display)); al_register_event_source(queue, al_get_timer_event_source(timer)); al_start_timer(timer); while (!quit) { ALLEGRO_EVENT event; /* Check for ESC key or close button event and quit in either case. */ al_wait_for_event(queue, &event); switch (event.type) { case ALLEGRO_EVENT_DISPLAY_CLOSE: quit = true; case ALLEGRO_EVENT_KEY_DOWN: if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) quit = true; break; case ALLEGRO_EVENT_TIMER: redraw = true; break; } if (redraw && al_is_event_queue_empty(queue)) { al_set_target_backbuffer(ms_display); draw(); al_flip_display(); al_set_target_backbuffer(display); draw(); al_flip_display(); redraw = false; } } return 0; }
C
#include <stdio.h> int main(void) { int n; printf("Enter an int: "); scanf("%i", &n); // Note: You'll need to swap the body of the 'if' and the 'else' for the // output to make sense again. if ( ! (n % 2 == 0 && n < 10)) { // Whole condition negated. printf("You entered an EVEN number less than 10.\n"); // False. } else { printf("You entered an ODD number, or greater than 9.\n"); // False. } return 0; }
C
#include "library.h" #include <string.h> #include <math.h> void init_fixed_len_page(Page *page, int page_size, int slot_size) { if(page == NULL) { page = (Page *)malloc(sizeof(Page)); } page->data = malloc(sizeof(page_size)); page->page_size = page_size; page->slot_size = slot_size; //page->used_slots = 0; int capacity = fixed_len_page_capacity(page); //page->bitmapLength = 1 + ((capacity-1) / BYTE_SIZE); int bitmapLength = ceil(capacity/BYTE_SIZE); // round up (capacity / BYTE_SIZE) memset(page->data, capacity, sizeof(int)); memset(((unsigned char *)page->data + sizeof(int)), '\0', bitmapLength); //page->bitmapLength); } int fixed_len_page_capacity(Page *page) { int numer = BYTE_SIZE*(page->page_size - sizeof(int)); int denom = BYTE_SIZE * page->slot_size + 1; if(numer % denom == 0) return numer/denom; else return (numer - 8)/ denom; } int fixed_len_page_freeslots(Page *page) { //return fixed_len_page_capacity(page) - page->used_slots; int bitmapLength = } int add_fixed_len_page(Page *page, Record *r) { if(page == NULL || fixed_len_page_freeslots(page) == 0) return -1; // get the metadata of the page int capacity = fixed_len_page_capacity(page); int bitmapLength = ceil(capacity/BYTE_SIZE); // round up (capacity / BYTE_SIZE) (unsigned char *)bitmap = (unsigned char *)malloc(bitmapLength); memcpy(bitmap, ((unsigned char *)page->data + sizeof(int)), bitmapLength); // find a free slot marked by a bit 0 in the corresponding directory int i, j, slot; for(i = 0; i < bitmapLength; i++) { if(bitmap[i] != 0xff) { unsigned char value = bitmap[i]; for(j = 0; j < BYTE_SIZE && value & 0b1 != 0; j++) value = value >> 1; bitmap[i] ^= 0b1 << j; //toggle the bit slot = BYTE_SIZE * i + j; //record the slot index of the first free slot break; } } if(i >= bitmapLength) return -1; /* int tuple_size = fixed_len_sizeof(r); //get the pointer to the memory that directly points to slot for the tuple unsigned char *tuple = (unsigned char *)page->data + sizeof(int) + bitmapLength + slot * tuple_size; for(j = 0; j < r->size(); j++) { strncpy(tuple, r[j], 100); tuple = tuple + 100; } */ write_fixed_len_page(page, slot, r); return slot; } void write_fixed_len_page(Page *page, int slot, Record *r) { int tuple_size = fixed_len_sizeof(r); int capacity = fixed_len_page_capacity(page); int bitmapLength = ceil(capacity/BYTE_SIZE); //get the pointer to the memory that directly points to slot for the tuple unsigned char *tuple = (unsigned char *)page->data + sizeof(int) + bitmapLength + slot * tuple_size; for(j = 0; j < r->size(); j++) { strncpy(tuple, r[j], 100); tuple = tuple + 100; } } void read_fixed_len_page(Page *page, int slot, Record *r) { if(r == NULL) r = std::vector<V>(); int tuple_size = fixed_len_sizeof(r); int capacity = fixed_len_page_capacity(page); int bitmapLength = ceil(capacity/BYTE_SIZE); //get the pointer to the memory that directly points to slot for the tuple unsigned char *tuple = (unsigned char *)page->data + sizeof(int) + bitmapLength + slot * tuple_size; unsigned char *buffer = malloc(); for(j = 0; j < numAttribute; j++) { strncpy(buffer, tuple, lengthAttribute); r->pushback(buffer); tuple = tuple + lengthAttribute; } }
C
// TODO: Implement populate_array /* * Convert a 9 digit int to a 9 element int array. */ int populate_array(int sin, int *sin_array) { int i = 0; for (i = 8; i > -1; --i) { /* iterate all 9 digits */ if (!sin) { /* less than 9 digits */ return 1; } /* take one digit */ sin_array[i] = sin % 10; sin /= 10; } if (sin) { /* more than 9 digits */ return 1; } return 0; } // TODO: Implement check_sin /* * Return 0 (true) iff the given sin_array is a valid SIN. */ int check_sin(int *sin_array) { int result[9]; int product; int sum = 0; int i; /* iterate all 9 digits */ for (i = 0; i < 9; ++i) { if (i % 2) { /* double every other digit */ product = 2 * sin_array[i]; if (product > 9) { /* greater than 9 */ /* sum up 2 digits */ result[i] = product % 10 + product / 10; /* alternative way to get the same result */ // result[i] = product - 9; } else { result[i] = product; } } else { result[i] = sin_array[i]; } } /* sum up all 9 digits */ for (i = 0; i < 9; ++i) { sum += result[i]; } /* valid only if the sum is a multiple of 10 */ if (sum % 10) { return 1; } return 0; }
C
/* Составьте программу maxksum.c, определяющую, какие k подряд идущих элементов последовательности имеют максимальную сумму */ #include <stdio.h> #include <stdlib.h> int main() { long sum = 0, sumMax; int n,*a, firstIndexI = 0, maxIndexI = 0, k, i, x; scanf("%d", &n); scanf("%d", &k); a = (int*)malloc(k * sizeof(int)); for (i = 0; i<k ; i++) { scanf("%d", &a[i]); sum += a[i]; } sumMax = sum; for ( i = 0 ; i < n-k; i++) { scanf("%d", &x); firstIndexI++; if ((sum + x - a[(firstIndexI-1) % k]) > sumMax) { sumMax = (sum + x - a[(firstIndexI -1)% k]); maxIndexI = firstIndexI; } sum = sum + x - a[(firstIndexI-1) % k]; a[(firstIndexI-1) % k] = x; } printf("%d", maxIndexI); free(a); return 0; }
C
#include <stdio.h> #include <stdlib.h> //Prototipos de funcao void quicksort(float vetor[], int inicio, int fim); void exibirVetor(float vetor[], int tamanho); int particionar(float vetor[], int inicio, int fim, int pivo); void trocar(float *num1, float *num2); int main(){ float dados[10] = {10., 89., -5., 7.8, 5.6, .89, 9.0, 67., 2.2, 1.56}; printf("Vetor fora de ordem:\n"); exibirVetor(dados, 10); quicksort(dados, 0, 9); printf("Vetor em de ordem:\n"); exibirVetor(dados, 10); return 0; } //Definição das funções void exibirVetor(float vetor[], int tamanho){ for(int i = 0; i < tamanho; i++) printf("%i: %.2f\n", i, vetor[i]); } void quicksort(float vetor[], int inicio, int fim){ int pivo, novoPivo; if(inicio < fim){ pivo = (inicio+fim)/2; novoPivo = particionar(vetor, inicio, fim, pivo); quicksort(vetor, inicio, novoPivo-1); quicksort(vetor, novoPivo+1, fim); } } void trocar(float *num1, float *num2){ float temp = *num1; *num1 = *num2; *num2 = temp; } int particionar(float vetor[], int inicio, int fim, int pivo){ int i, j; float valor_pivo = vetor[pivo]; trocar(&vetor[pivo], &vetor[fim]); j = inicio; for(i = inicio; i < fim; i++){ if(vetor[i] <= valor_pivo){ trocar(&vetor[i], &vetor[j]); j++; } } trocar(&vetor[j], &vetor[fim]); return j; }
C
/** * @file db_create.c * @brief pictDB library: do_create implementation. * * @date 2 Nov 2015 */ #include "pictDB.h" #include <string.h> // for strncpy /********************************************************************//** * Creates the database called db_filename. Writes the header and the * preallocated empty metadata array to database file. */ int do_create(const char* file_name, struct pictdb_file* db_file) { /* Correcteur : utilisation de MAX_MAX_FILES au lieu de * header.max_files. -1pt * */ int return_value = 0; size_t number_header = 0; size_t number_metadata = 0; // Sets the DB header name strncpy(db_file->header.db_name, CAT_TXT, MAX_DB_NAME); db_file->header.db_name[MAX_DB_NAME] = '\0'; //Initialisation db_file->header.db_version = 0; db_file->header.num_files = 0; /* Correcteur : utilisation de MAX_MAX_FILES au lieu de * db_file->header.max_files et donc pas de vérification non * plus que le max_files fourni n'est pas > MAX_MAX_FILES. -0.5pt */ for(int i = 0; i < MAX_MAX_FILES; i++) { /* Correcteur : pas d'utilisation des constantes NON EMPTY/EMPTY * pour initialiser -0.5pt */ db_file->metadata[i].is_valid = 0; } db_file->fpdb = NULL; db_file->fpdb = fopen(file_name, "wb"); if(db_file->fpdb != NULL) { number_header = fwrite(&db_file->header, sizeof(struct pictdb_header), 1, db_file->fpdb); number_metadata = fwrite(db_file->metadata, sizeof(struct pict_metadata), MAX_MAX_FILES, db_file->fpdb); } if(number_header != 1 || number_metadata != MAX_MAX_FILES || db_file->fpdb == NULL) { return_value = ERR_IO; } /* Correcteur : que se passe-t-il si il y a eu erreur précédemment ? * Cette ligne ne sera pas affichée dans ce cas là. -0.5pt */ printf("%zu item(s) written\n", number_header+number_metadata); /* Correcteur : aucun fclose pour fermer db_file->fpdb. do_create * est "one shot" donc une fois qu'elle est appellée, le programme * se termine. Du coup, il faut fermer le fichier ouvert précedemment. * -1.5pt */ return return_value; }
C
#include<stdio.h> #include<conio.h> main() { int a,b,c,d,media; printf ("DIGITE O VALOR DA PRIMEIRA NOTA\n"); scanf ("%d",& a); printf ("DIGITE O VALOR DA SEGUNDA NOTA\n"); scanf ("%d",& b); printf ("DIGITE O VALOR DA TERCEIRA NOTA\n"); scanf ("%d",& c); printf ("DIGITE O VALOR DA QUARTA NOTA\n"); scanf ("%d",& d); media =(a+b+c+d)/4; if (media >=7) { printf ("VOCE FOI APROVADO SUA MEDIA FINAL E %d", media); getch(); } else { printf ("VOCE FOI REPROVADO SUA MEDIA FINAL E %d", media); getch(); } }
C
#ifndef _MEMLIST_ #define _MEMLIST_ #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <fcntl.h> #include <pthread.h> #include "constants.h" /* for naming schemes and SEGMENTSIZE */ /* This stores the information pertinent to building shared memory block * lists to be shared between the server and proxy processes. * * When one or both of the services are run with the "-o" optimization * flag, they allocate a single block of shared memory, "metanode", with * a single metanode in it. They set their own respective flag to * indicate their readiness to utilize shared memory instead of sockets * in order to communicate. * * The server will the process which initially creates the shared memory; * thus, the number of shared memory segments will be equivalent (or very * close) in number to the quantity of worker threads (1-to-1 ratio of * worker threads to shared memory segment). * * States within each shared memory segment will act as surrogate * semaphores, synchronizing access to the data held within. There are * two state indicators per segment: proxy and server. * * IDLE: No activity. * BUSY: Currently reading or writing - do not touch! * WAITING: No activity; waiting on a response before proceeding. * COMPLETE: Ready to be reset to IDLE. * * There are two possible transaction patterns: * * 1) * a. PROXY posts a request for the SERVER. * b. SERVER reads the request. * c. SERVER posts full response. * d. PROXY reads response. * * 2) * a. PROXY posts a partial request. * b. SERVER reads partial request and waits (repeat a-b until PROXY posts COMPLETE). * c. SERVER processes request, builds and posts partial response. * d. PROXY reads partial response and waits (repeat c-d until SERVER posts COMPLETE). * e. PROXY posts COMPLETE once finished reading response. Both states on * COMPLETE are reset to IDLE. * * This will also serve as a wrapper for the shared memory functionality, by * way of two functions: * * memOps_Create() * memOps_Destroy() * * Both will take care of all the space allocation, truncating, error * checking, and mapping, as well as unlinking and deleting. */ /* the flag types */ typedef enum flag { OFFLINE, ONLINE } flag; typedef enum state_t { IDLE, /* ready for use */ BUSY, /* DO NOT TOUCH - operation in progress! */ WAITING_INIT_SRVR, /* proxy is waiting for initial server contact */ WAITING_CONT_PRXY, /* server is waiting for proxy to continue read/write */ WAITING_CONT_SRVR, /* proxy is waiting for server to continue read/write */ COMPLETE /* waiting to be reset to IDLE */ } state_t; /* a singleton */ typedef struct metanode { flag serverFlag; flag proxyFlag; int numNodes; } metanode; /* a memory node */ typedef struct memnode { char mem[SEGMENTSIZE]; long int spaceUsed; state_t proxyState; state_t serverState; pthread_mutex_t mutex; pthread_cond_t condition; } memnode; /* memory list functions */ memnode* getMemList(int numNodes); memnode* findState(memnode* list, int length, state_t s); int destroyMemList(memnode* list, int length); void printMemList(memnode* list, int length); /* metanode functions */ metanode* getMetanode(void); int destroyMetanode(metanode* node); /* memory functions */ long int setMapping(memnode* node, void* data, long int dataLength); void* memOps_Create(const char* name, long int blockSize, int* exists); int memOps_Destroy(const char* name, void* mem, long int blockSize); #include "memList.c" #endif /* _MEMLIST_ */
C
#include <stdio.h> int main() { FILE *ptr = NULL; int num1, num2, num3; ptr = fopen("intizers.txt", "r"); fscanf(ptr, "%d %d %d", &num1, &num2, &num3); printf("The first intizer in the file is %d\n", num1); printf("The second intizer in the file is %d\n", num2); printf("The third intizer in the file is %d\n", num3); return 0; }
C
#include"render.h" #include<stdlib.h> static int rtk_borad_init(rtk_board_t *board,int width,int height) { board->width=width; board->height=height; board->image=malloc(sizeof(board->image[0]) * width*height ); if (board->image==NULL) { rtk_debug("board init error,memory alloc failed\n"); return RTK_MEMORY_ERR; } return 0; } int rtk_layer_init(rtk_layer_t *layer,int width,int height) { int ret=rtk_borad_init(&layer->board,width,height); vector_init(&layer->containers); return ret; } int rtk_render_init(rtk_render_t *render,int width,int height) { rtk_assert(width>=0 && height>=0); int ret=rtk_borad_init(&render->view,width,height); vector_init(&render->layers); vector_init(&render->view_stack); return ret; } void rtk_render(rtk_render_t *render) { }
C
#include "holberton.h" /** * _print_o - print an integer in octal (helper function) * @n: the integer to print * @count: a pointer to a counter for the number of bytes printed */ void _print_o(unsigned int n, int *count) { int lastRetVal; if (n > 07) _print_o(n >> 3, count); if (*count < 0) return; lastRetVal = _putchar('0' + (n & 07)); if (lastRetVal < 0) *count = (-1); else *count += lastRetVal; } /** * print_o - print an integer in octal * @args: the va_list with the integer to print as it's next element * * Return: the number of bytes printed */ int print_o(va_list args) { int count = 0; _print_o(va_arg(args, int), &count); return (count); }
C
#include "lauxlib.h" #include "lualib.h" #include "time.h" #include "lua_if.h" #include "bsp.h" static int qspi_readid(lua_State* L); static int qspi_write(lua_State* L); static int qspi_read(lua_State* L); static int qspi_erase4k(lua_State* L); void lua_qspi_RegisterFun(void) { //将指定的函数注册为Lua的全局函数变量,其中第一个字符串参数为Lua代码 //在调用C函数时使用的全局函数名,第二个参数为实际C函数的指针。 lua_register(g_Lua, "qspi_readid", qspi_readid); lua_register(g_Lua, "qspi_read", qspi_read); lua_register(g_Lua, "qspi_write", qspi_write); lua_register(g_Lua, "qspi_erase4k", qspi_erase4k); } /* ********************************************************************************************************* * 函 数 名: qspi_readid * 功能说明: 读芯片ID * 形 参: * 返 回 值: 无 ********************************************************************************************************* */ static int qspi_readid(lua_State* L) { uint32_t id; id = QSPI_ReadID(); lua_pushnumber(L, id); /* 返回值 */ return 1; } /* ********************************************************************************************************* * 函 数 名: qspi_erase4k * 功能说明: 擦除一个扇区,4KB * 形 参: * 返 回 值: 无 ********************************************************************************************************* */ static int qspi_erase4k(lua_State* L) { uint32_t addr; if (lua_type(L, 1) == LUA_TNUMBER) /* 判断第2个参数 */ { addr = luaL_checknumber(L, 1); addr = addr / 4096; addr = addr * 4096; } QSPI_EraseSector(addr); lua_pushnumber(L, 1); /* 成功 */ return 1; } /* ********************************************************************************************************* * 函 数 名: qspi_write * 功能说明: 写一包数据,小于256字节 * 形 参: * 返 回 值: 无 ********************************************************************************************************* */ static int qspi_write(lua_State* L) { size_t len; const char *data; uint32_t addr; if (lua_type(L, 1) == LUA_TNUMBER) /* 判断第2个参数 */ { addr = luaL_checknumber(L, 1); } if (lua_type(L, 2) == LUA_TSTRING) /* 判断第1个参数 */ { data = luaL_checklstring(L, 2, &len); /* 1是参数的位置, len是string的长度 */ } if (len > QSPI_PAGE_SIZE) { lua_pushnumber(L, 0); /* 出错 */ return 1; } if (QSPI_WriteBuffer((uint8_t *)data, addr, len) == 0) { lua_pushnumber(L, 0); /* 出错 */ } else { lua_pushnumber(L, 1); /* 成功 */ } return 1; } /* ********************************************************************************************************* * 函 数 名: qspi_read * 功能说明: 读一包数据,可大于256字节 * 形 参: * 返 回 值: 无 ********************************************************************************************************* */ static int qspi_read(lua_State* L) { uint32_t addr; uint32_t num; if (lua_type(L, 1) == LUA_TNUMBER) /* 判断第1个参数 */ { addr = luaL_checknumber(L, 1); /* 1是参数的位置, len是string的长度 */ } if (lua_type(L, 2) == LUA_TNUMBER) /* 判断第2个参数 */ { num = luaL_checknumber(L, 2); memset(s_lua_read_buf, 0, num); } if (num > LUA_READ_LEN_MAX) { return 0; } QSPI_ReadBuffer(s_lua_read_buf, addr, num); lua_pushlstring(L, (char *)s_lua_read_buf, num); return 1; } /***************************** 安富莱电子 www.armfly.com (END OF FILE) *********************************/
C
#ifndef _INC_ISR #define _INC_ISR 1 #include <kernel/compiler.h> #include <kernel/asm/cpustat.h> // Contains functions and utilities for registering handlers of interrupt // service routines (ISRs). These are functions that will be called when a // given interrupt - CPU, hardware, or software - is invoked. // Due to the fact that interrupts have an abnormal calling convention, // registerred ISRs must be registered via a 'handler'. A handler is a wrapper // function a given ISR. One must be defined for each ISR. // ISRs are given struct isr_params { struct cpustat cs; }; // Gets the name of the ISR handler function #define ISR_HANDLER(ISRFUNC) __handle_##ISRFUNC #define ISR_HANDLER_ATTR /* None */ // Template for ISR handler functions #define __ISR_HOOK_HANDLER_BASE(ISRFUNC, ISRBODY) \ void ISR_HANDLER_ATTR ISRFUNC(void) \ { \ ASM_VOLATILE( \ "pusha" \ ); \ { \ ISRBODY \ } \ ASM_VOLATILE( \ "popa \n\t" \ "leave \n\t" \ "iret \n\t" \ ); \ } // Standard ISR handler function // Gives the ISR an isr_params object, which contains information about the // state of the environment when the ISR was invoked. Note that this involves // a small amount of prior processing. #define ISR_DEF_HANDLER(ISRFUNC) \ __ISR_HOOK_HANDLER_BASE(ISR_HANDLER(ISRFUNC), \ { \ extern void ISRFUNC(struct isr_params params); \ struct isr_params params; \ params.cs = collect_cpustat(); \ ISRFUNC(params); \ }); // Parameterless ISR handler function // Performs no prior processing to acquire information about the ISR calling // environment. This makes it good for hardware interrupts. #define ISR_DEF_HANDLER_NOPARAMS(ISRFUNC) \ __ISR_HOOK_HANDLER_BASE(ISR_HANDLER(ISRFUNC), \ { \ extern void ISRFUNC(void); \ ISRFUNC(); \ }); // Initialise the ISR handling system, registering ISRs for all CPU exceptions int isr_init(void); // Sets the handler function for the ISR of a given number - the ISR number // being its index in the IDT, aka the interrupt number. int isr_set_handler(int isrnum, void (*handler)(void)); #endif /* _INC_ISR */
C
/* File: point_driver.c */ /* Tanggal: 30 Agustus 2016 */ /* *** Driver ABSTRACT DATA TYPE POINT *** */ #include "point.h" #include <stdio.h> int main () { POINT P1, P2; float deg; //sudut putar float deltaX, deltaY; printf("-Driver POINT-\n"); printf("Bikin point P1\n"); BacaPOINT(&P1); printf("Terbentuk P1: "); TulisPOINT(P1); printf("\n"); BacaPOINT(&P2); printf("Terbentuk P2: "); TulisPOINT(P2); printf("\n\nP1 di titik origin? "); if (IsOrigin(P1)) { printf("YA\n"); printf("Gapunya kuadran :(\n"); } else { printf("TIDAK\n"); if (!(IsOnSbX(P1) || IsOnSbY(P1))) { printf("P1 ada di kuadran %d\n", Kuadran(P1)); } } printf("\nGeser P2\n"); printf("Delta x: "); scanf("%f", &deltaX); printf("Delta y: "); scanf("%f", &deltaY); Geser(&P2, deltaX, deltaY); TulisPOINT(P2); printf(" <- P2 setelah digeser\n"); printf("\n- NextX = "); TulisPOINT(NextX(P2)); printf("\n- NextY = "); TulisPOINT(NextY(P2)); printf("\n\nJarak P2 ke 0,0 = %f\n\n", Jarak0(P2)); if (NEQ(P1,P2)) { printf("sekarang ini P1 dan P2 tidak sama\n"); } else printf("sekarang ini P1 dan P2 sama\n"); printf("Panjang P1-P2: %.2f\n\n", Panjang(P1,P2)); printf("Rotasi P1\n"); printf("Masukkan sudut = "); scanf("%f", &deg); Putar(&P1, deg); TulisPOINT(P1); printf("\nGeser P1 ke SbX > "); GeserKeSbX(&P1); TulisPOINT(P1); printf("\nGeser P2 ke SbY -> "); GeserKeSbY(&P2); TulisPOINT(P2); printf("\n\nCerminan P1 \n"); Mirror(&P1, IsOnSbY(P1)); printf(" - Dicerminkan - \n"); printf(".. sekarang P1 = "); TulisPOINT(P1); printf("\nCerminan P2 \n"); printf(" - Dicerminkan - \n"); printf(".. kalo dicerminkan, P2 = "); TulisPOINT(MirrorOf(P2, IsOnSbY(P2))); return 0; }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> #include <semaphore.h> struct shared { sem_t sem; int count; } shared; int main(int argc, char **argv) { int loopcount; struct shared *addr; pid_t pid; if(argc != 2) { printf("Usage: %s <loopcount>\n", argv[0]); exit(1); } loopcount = atoi(argv[1]); addr = (struct shared*)mmap(NULL, sizeof(shared), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); if(addr == MAP_FAILED) { perror("mmap error"); exit(1); } setbuf(stdout, NULL); sem_init(&addr->sem, 1, 1); if((pid = fork()) == 0) { /* child */ for(int i = 0; i < loopcount; ++i) { sem_wait(&addr->sem); printf("child: %d\n", addr->count++); sem_post(&addr->sem); } exit(0); } for(int i = 0; i < loopcount; ++i) { sem_wait(&addr->sem); printf("parent: %d\n", addr->count++); sem_post(&addr->sem); } exit(0); }
C
#include <stdio.h> #include <string.h> int crack(int num) { char decoded[17]; char *encoded = "Q}|u`sfg~sf{}|a3"; char *to_find = "Congratulations!"; decoded[16] = '\0'; for (int i = 0; i < 16; i++) { decoded[i] = encoded[i] ^ num; } return (strcmp(decoded, to_find) == 0 ? 1 : 0); } int main(void) { int base = 0x1337d00d; int password; for(int i = 0; i <= 22; i++) { password = base - i; if (crack(i)) { printf("Password is : %d\n", password); } } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_itoa.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: nde-maes <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/11/20 17:58:48 by nde-maes #+# #+# */ /* Updated: 2018/11/27 11:38:02 by nde-maes ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include "libft.h" /* ** `str[len--] = n_abs % 10 + 48;` before the while loop and `get_int_len` ** returning at least 1 are to handle the case of `n = 0`. In this case, we ** have to return a string with a '0' character in it (alongside the required ** terminating 0 at the end). ** ** `nb[len] = 0` sets the last byte of the array to 0 to have a string. ** ** (n1 /= n2) first apply the operation then evaluates, like ++i. ** ** `(unsigned int)-5` is still strangely still worth -5, so casting a negative ** value to an unsigned doesn't make it positive! ** ** Be mindfull of edge inputs, like the dude passing 0 as input. ** or the one passing min int. */ static int get_int_len(int n) { int len; len = 1; while (n /= 10) len++; return (len); } char *ft_itoa(int n) { char *str; int len; unsigned int n_abs; len = get_int_len(n); n_abs = (unsigned int)n; if (n < 0) { len++; n_abs = -n; } if ((str = (char*)malloc(len + 1)) == NULL) return (NULL); str[len--] = 0; str[len--] = n_abs % 10 + 48; while (n_abs >= 10) { n_abs /= 10; str[len--] = n_abs % 10 + 48; } if (n < 0) str[0] = '-'; return (str); }
C
#include <stdio.h> int main(void){ float l, w, h; scanf("%f %f %f", &l, &w, &h); printf("Volume = %.3f\n", l*w*h); }
C
/* 54. Number of Appearance */ # include <stdio.h> int real_10_power(int x); int main(){ int N, M; scanf("%d%d", &N, &M); int M_dig[7] = {0}; int N_dig[2] = {0}; /* fetch digit */ for (int i = 6; i > -1; i--){ int temp = real_10_power(i); M_dig[i] = M / temp; M -= temp * M_dig[i]; } for (int i = 1; i > -1; i--){ int temp = real_10_power(i); N_dig[i] = N / temp; N -= temp * N_dig[i]; } /* compare */ int counter = 0; for (int i = 6; i > 0; i--){ if (N_dig[1] == M_dig[i] && N_dig[0] == M_dig[i-1]) counter++; } printf("%d", counter); } int real_10_power(int x){ int y = 1; for (int i = 0; i < x; i++) y *= 10; return y; }
C
#include "image.h" GLuint loadTexture(SDL_Surface *surface) { GLuint texture; int w, h; SDL_Surface *image; SDL_Rect area; Uint32 saved_flags; Uint8 saved_alpha; /*verifica si el ancho de la imagen es potencia de 2*/ if(SE_utils_powerof2(surface->w) == 0) { printf("SE_screen: Advertencia, el ancho de la imagen no es potencia de 2\n"); fflush(stdout); } /*verifica si el alto de la imagen es potencia de 2*/ if(SE_utils_powerof2(surface->h) == 0) { printf("SE_screen: Advertencia, el alto de la imagen no es potencia de 2\n"); fflush(stdout); } w = surface->w; h = surface->h; image = SDL_CreateRGBSurface( SDL_SWSURFACE, w, h, 32, #if SDL_BYTEORDER == SDL_LIL_ENDIAN /* OpenGL RGBA masks */ 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000 #else 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF #endif ); if ( image == NULL ) { return 0; } /* Save the alpha blending attributes */ saved_flags = surface->flags&(SDL_SRCALPHA|SDL_RLEACCELOK); saved_alpha = surface->format->alpha; if ( (saved_flags & SDL_SRCALPHA) == SDL_SRCALPHA ) { SDL_SetAlpha(surface, 0, 0); } /* Copy the surface into the GL texture image */ area.x = 0; area.y = 0; area.w = surface->w; area.h = surface->h; SDL_BlitSurface(surface, &area, image, &area); /* Restore the alpha blending attributes */ if ( (saved_flags & SDL_SRCALPHA) == SDL_SRCALPHA ) { SDL_SetAlpha(surface, saved_flags, saved_alpha); } /* Create an OpenGL texture for the image */ glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, image->pixels); SDL_FreeSurface(image); /* No longer needed */ return texture; } SE_image *SE_image_load(const char *path) { SE_image *img; img = (SE_image*)malloc(sizeof(SE_image)); SDL_Surface *temp; printf("SE_image:Cargando textura: %s\n",path); if((temp = IMG_Load(path)) == NULL) { printf("SE_image:Error, no se pudo cargar la imagen\n"); } img->texture = loadTexture(temp); img->width = temp->w; img->height = temp->h; SDL_FreeSurface(temp); return img; } void SE_image_segment_draw_fx(SE_image *img,float xtex,float ytex,float wtex,float htex,float posx,float posy,float posz, float width_image,float height_image,float zoomx,float zoomy,float rotx,float roty,float rotz, float r,float g,float b,float alpha) { float width = wtex * zoomx; float height = htex * zoomy; float w = (float)img->width; float h = (float)img->height; if(w == 0)w = 1; if(h == 0)h = 1; //printf("\nhola\n"); float x1 = xtex/w; float y1 = ytex/h; float x2 = (xtex + wtex)/w; float y2 = (ytex + htex)/h; glPushMatrix(); glEnable( GL_TEXTURE_2D ); glTranslatef(width/2 ,height/2,posz); glTranslatef(posx,posy,posz); glRotatef(rotx,1,0,0); glRotatef(roty,0,1,0); glRotatef(rotz,0,0,1); glTranslatef(-width/2,-height/2,posz); glColor4f(r,g,b,alpha);/*alpha blending*/ glBindTexture(GL_TEXTURE_2D,img->texture); glBegin(GL_QUADS); glTexCoord2f(x1,y1); glVertex2f(0,0); glTexCoord2f(x2,y1); glVertex2f(width,0); glTexCoord2f(x2,y2); glVertex2f(width,height); glTexCoord2f(x1,y2); glVertex2f(0,height); glEnd(); glPopMatrix(); SE_utils_logvertices(4); } void SE_image_segment_draw_wh(SE_image *img,float xtex,float ytex,float wtex,float htex,float posx,float posy,float posz,float width,float height) { SE_image_segment_draw_fx(img,xtex,ytex,wtex,htex,posx,posy,posz,width,height,1,1,0,0,0,1,1,1,1); } void SE_image_segment_draw(SE_image *img,float xtex,float ytex,float wtex,float htex,float posx,float posy,float posz) { SE_image_segment_draw_fx(img,xtex,ytex,wtex,htex,posx,posy,posz,wtex,htex,1,1,0,0,0,1,1,1,1); } void SE_image_draw_fx(SE_image *img,float posx,float posy,float posz,float width_image,float height_image, float zoomx,float zoomy,float rotx,float roty,float rotz,float r,float g,float b,float alpha) { SE_image_segment_draw_fx(img,0,0,img->width,img->height,posx,posy,posz,width_image,height_image,zoomx,zoomy,rotx,roty,rotz,r,g,b,alpha); } void SE_image_draw_wh(SE_image *img,float posx,float posy,float posz,float width,float height) { SE_image_draw_fx(img,posx,posy,posz,width,height,1,1,0,0,0,1,1,1,1); } void SE_image_draw(SE_image *img,float posx,float posy,float posz) { SE_image_draw_fx(img,posx,posy,posz,img->width,img->height,1,1,0,0,0,1,1,1,1); } void SE_image_segment_draw_transf(SE_image *img,SE_transf *tr,float xtex,float ytex,float wtex,float htex) { SE_image_segment_draw_fx(img, xtex,ytex,wtex,htex, tr->x,tr->y,tr->z, tr->width,tr->height, tr->zoomx,tr->zoomy, tr->rotx,tr->roty,tr->rotz, tr->r,tr->g,tr->b, tr->alpha); } void SE_image_draw_transf(SE_image *img,SE_transf *tr) { SE_image_draw_fx(img, tr->x,tr->y,tr->z, tr->width,tr->height, tr->zoomx,tr->zoomy, tr->rotx,tr->roty,tr->rotz, tr->r,tr->g,tr->b, tr->alpha); } void SE_image_clean(SE_image *img) { free(img); printf("SE_image:se elimino puntero de imagen\n"); }
C
#include "rfos.h" #include <errno.h> #include <stdio.h> #include <string.h> void print_doc(char *bin) { fprintf(stderr,"Usage: %s <command> [<args>]\n", bin); fprintf(stderr,"\tput <key> <src>\t\t\tAdd or replace an object identified by <key> using file <src>\n"); fprintf(stderr,"\tget <key> <outpath>\t\tRetrieve the object identified by <key> and write it to <outpath>\n"); fprintf(stderr,"\tremove <key>\t\t\tRemove the object identified by <key>\n"); fprintf(stderr,"\tsearch <prefixkey> <outpath>\tSearch for objects whose key starts with <prefixkey> and write the result to <outpath>\n"); fprintf(stderr,"\tstat <key>\t\t\tRetrieve the information of an object identified by <key>\n"); } RFOS* get_proxy() { RFOS *fs_proxy = rfos_proxy_new_for_bus_sync( G_BUS_TYPE_SESSION, G_DBUS_PROXY_FLAGS_NONE, "kmitl.ce.os.RFOS", "/kmitl/ce/os/RFOS", NULL, NULL); return fs_proxy; } int handle_error(guint err_code, GError *gerror) { if (gerror != NULL) { fprintf(stderr, "%s\n", gerror->message); return EINTR; } if (err_code) { fprintf(stderr, "%s\n", strerror(err_code)); } return err_code; } int do_get(const char *key, const char *outpath) { RFOS *fs_proxy = get_proxy(); guint err_code = 0; GError *gerror = NULL; rfos_call_get_sync( fs_proxy, key, outpath, &err_code, NULL, &gerror); return handle_error(err_code, gerror); } int do_put(const char *key, const char *src) { RFOS *fs_proxy = get_proxy(); guint err_code = 0; GError *gerror = NULL; rfos_call_put_sync( fs_proxy, key, src, &err_code, NULL, &gerror); return handle_error(err_code, gerror); } int do_remove(const char *key) { RFOS *fs_proxy = get_proxy(); guint err_code = 0; GError *gerror = NULL; rfos_call_remove_sync( fs_proxy, key, &err_code, NULL, &gerror); return handle_error(err_code, gerror); } int do_search(const char *key, const char *outpath) { RFOS *fs_proxy = get_proxy(); guint err_code = 0; GError *gerror = NULL; rfos_call_search_sync( fs_proxy, key, outpath, &err_code, NULL, &gerror); return handle_error(err_code, gerror); } int do_stat(const char *key) { RFOS *fs_proxy = get_proxy(); guint err_code = 0; GError *gerror = NULL; guint obj_size = 0; gint64 atime = -1; rfos_call_stat_sync( fs_proxy, key, &obj_size, &atime, &err_code, NULL, &gerror); err_code = handle_error(err_code, gerror); if (err_code) { return err_code; } fprintf(stdout, "%s %u %s", key, obj_size, ctime(&atime)); return 0; } int main (int argc, char *argv[]) { if (argc < 2) { print_doc(argv[0]); return EINVAL; } if (strncmp(argv[1],"put",3) == 0) { if (argc < 4) { print_doc(argv[0]); return EINVAL; } const char *key = argv[2]; const char *src = argv[3]; return do_put(key, src); } else if (strncmp(argv[1], "get", 3) == 0) { if (argc < 4) { print_doc(argv[0]); return EINVAL; } const char *key = argv[2]; const char *outpath = argv[3]; return do_get(key, outpath); } else if (strncmp(argv[1], "remove", 6) == 0) { if (argc < 3) { print_doc(argv[0]); return EINVAL; } const char *key = argv[2]; return do_remove(key); } else if (strncmp(argv[1], "search", 6) == 0) { if (argc < 4) { print_doc(argv[0]); return EINVAL; } const char *key = argv[2]; const char *outpath = argv[3]; return do_search(key, outpath); } else if (strncmp(argv[1], "stat", 4) == 0) { if (argc < 3) { print_doc(argv[0]); return EINVAL; } const char *key = argv[2]; return do_stat(key); } else { print_doc(argv[0]); return EINVAL; } return 0; }
C
//Name: Augustus Crosby #include "sem.h" #define SIZE_BUFF 10 struct sem* empty; struct sem* full; int buff[SIZE_BUFF]; int in = 0; int out = 0; void buffStart() { for(int i = 0; i < SIZE_BUFF; i++){ buff[i] = 0; } return; } void producer1() { for(;;) { P(empty); buff[in] = 1; in = (in + 1) % SIZE_BUFF; printf("Producer 1:\nBUFFER:"); for (int i = 0; i < SIZE_BUFF; i++) { printf("\n1: %d", buff[i]); } printf("\n"); sleep(1); V(full); return; } } void producer2() { for(;;) { P(empty); buff[in] = 1; in = (in + 1) % SIZE_BUFF; printf("Producer 2:\nBUFFER:"); for (int i = 0; i < SIZE_BUFF; i++) { printf("\n1: %d", buff[i]); } printf("\n"); sleep(1); V(full); return; } } void consumer1() { for(;;) { P(full); buff[out] = 0; out = (out + 1) % SIZE_BUFF; printf("Consumer 1:\nBUFFER:"); for (int i = 0; i < SIZE_BUFF; i++) { printf("\n1: %d", buff[i]); } printf("\n"); sleep(1); V(empty); } } void consumer2() { for(;;) { P(full); buff[out] = 0; out = (out + 1) % SIZE_BUFF; printf("Consumer 2:\nBUFFER:"); for (int i = 0; i < SIZE_BUFF; i++) { printf("\n1: %d", buff[i]); } printf("\n"); sleep(1); V(empty); } } //method 2 int main() { full = (struct sem*) malloc(sizeof(struct sem)); empty = (struct sem*) malloc(sizeof(struct sem)); RunQ = (struct queue*) malloc(sizeof(struct queue)); InitQueue(RunQ); InitSem(empty, SIZE_BUFF); InitSem(full, 0); buffStart(); start_thread(producer1); start_thread(producer2); start_thread(consumer1); start_thread(consumer2); run(); return 0; }
C
#include <stdio.h> #include "lenght.h" #include "weight.h" #include "temperature.h" int main(int argc, const char * argv[]) { printf("\n**** Lenght Conversions ****"); centimeter_inche(5); inche_centimeter(8); meter_feet(35); feet_meter(56); kilometer_mile(4); mile_kilometer(7); printf("\n\n**** Weight Conversions ****"); pound_kilogram(10); kilogram_pound(6); gram_ounce(8); ounce_gram(1); printf("\n\n**** Temperature Conversions ****"); celsius_fahrenheit(37); fahrenheit_celsius(32); celsius_kelvin(100); kelvin_celsius(273); kelvin_fahrenheit(273); fahrenheit_kelvin(212); printf("\n\n"); return 0; }
C
#include <stdio.h> int main(void) { long int a; printf("Enter a number: "); scanf("%ld", &a); printf("%ld ", a); return 0; }
C
#include<stdio.h> #include"header.h" void maketree(struct tree *father,struct tree *child,int x,int count) { child->data=x; if(count%2==0) father->left=child; else father->right=child; }
C
#include<stdio.h> #define MAXLINE 1000 int get_line(char line[],int maxline); void copy(char to[],char from[]); main() { char line[MAXLINE],longest[MAXLINE]; int len,max=0,i=0,c; while((len=get_line(line,MAXLINE))>0) { if(len>max) { max=len; copy(longest,line); } } if(max>0) { printf("\n LONGEST LINE:\n"); printf("%s",longest); while(longest[i]!='\0') { ++i; } if(longest[i]=='\n'||longest[i]==EOF) { printf("\n length of longest line %d\n",i-2); } else//longest line greater than 1000 characters { printf("\n length of longest line %d\n",i-1); } } return 0; } void copy(char to[],char from[]) { int i=0; while((to[i]=from[i])!='\0') ++i; } int get_line(char line[],int maxline) { int c,i; for(i=0;i<maxline-1 && (c=getchar())!=EOF&&c!='\n';++i) { line[i]=c; } if(c=='\n') { line[i]=c; ++i; } line[i]='\0'; return i; }
C
/* */ /* Program Name: setlocal.c */ /* */ #include <locale.h> #include <stdio.h> void main( void ) { printf( "Old locale was %s\n", setlocale( LC_MONETARY, "C" ) ); } 
C
#include <stdio.h> #include <stdlib.h> struct node { //Basic building block int data; struct node *next; }; void push (struct node **head, int new_data) { //Add new node to first position (to head of linked list) struct node *newnode = (struct node *)malloc(sizeof(struct node)); newnode->data = new_data; newnode->next = *head; *head = newnode; } void reverse(struct node **head) { //reverses given list struct node *back = NULL; struct node *curr = *head; struct node *front = curr->next; while (front != NULL) { curr->next = back; back = curr; curr = front; front = front->next; } curr->next = back; *head = curr; } void printList(struct node *n) { //print linked list while(n!=NULL) { printf("%d\n", n->data); n = n->next; } printf("\n"); } int main() { struct node *head = (struct node *)malloc(sizeof(struct node)); head->next = NULL; head->data = 7; push(&head, 1); push(&head, 5); push(&head, 3); push(&head, 2); push(&head, 4); push(&head, 6); push(&head, 7); push(&head, 8); printList(head); reverse(&head); printList(head); }
C
#ifndef _EWF_HASHTABLE_H_ #define _EWF_HASHTABLE_H_ #ifndef _GNU_SOURCE #define _GNU_SOURCE 1 #endif #include <search.h> /*! * \file ewf_hastable.h * \brief Functions dealing with hash tables. * \author Raphael HUCK */ /*! Structure representing a hash table. */ typedef struct hsearch_data ewf_hashtable_t; /*! Create a hash table. * \note This function will take care of allocating memory for the hash table so you don't need to. * \param htab pointer to return the created hash table * \param size size (in number of entries) of the hash table to create * \return * - \b EWF_SUCCESS if the hash table was successfully created * - \b EWF_ERROR otherwise */ int ewf_hashtable_create(ewf_hashtable_t **htab, size_t size); /*! Destroy a hash table. * \note This function will take care of freeing the memory for the hash table so you don't need to. * \param htab pointer to the hash table to destroy * \return * - \b EWF_SUCCESS if the hash table was successfully destroyed * - \b EWF_ERROR otherwise */ int ewf_hashtable_destroy(ewf_hashtable_t **htab); /*! Insert an entry in the hash table. * \param htab pointer to the hash table to insert into * \param key key to identify the entry to insert * \param data pointer to the entry to insert * \return * - \b EWF_SUCCESS if the entry was successfully inserted * - \b EWF_ERROR otherwise */ int ewf_hashtable_insert(ewf_hashtable_t **htab, const char *key, void **data); /*! Find an entry in the hash table. * \param htab pointer to the hash table where to find the entry * \param key key of the entry to find * \param data pointer to return the found entry * \return * - \b EWF_SUCCESS if the entry was successfully found * - \b EWF_ERROR otherwise */ int ewf_hashtable_find(ewf_hashtable_t **htab, const char *key, void **data); #endif /* _EWF_HASHTABLE_H_ */