language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
int *binarysearch(int A[],int target,int n){ int *low=&A[0]; int *high=&A[n]; int *mid; while(low<high){ mid=low+(high-low)/2; if(target==*mid) return mid; else if(target<*mid) high=mid; else if(target>*mid) low=mid+1; } return NULL; }
C
#include<stdio.h> #include<string.h> void main(int a, char** inp){ char * token; token = strtok(inp[0], " "); token = strtok(NULL, " "); if(strcmp(token, "-E")==0){ token = strtok(NULL, " "); while(token != NULL){ char file1[100]; strcpy(file1, token); FILE *fptr1 = fopen(file1, "r"); char line1[2000]; while(fgets(line1, sizeof(line1), fptr1)){ printf("%s\n", line1); printf("$"); } token = strtok(NULL, " "); } }else if(strcmp(token, "-n")){ token = strtok(NULL, " "); while(token != NULL){ char file1[100]; strcpy(file1, token); FILE *fptr1 = fopen(file1, "r"); char line1[2000]; int count=1; while(fgets(line1, sizeof(line1), fptr1)){ printf("%d\n", count); printf("%s\n", line1); count++; } token = strtok(NULL, " "); } } else{ while(token != NULL){ char file1[100]; strcpy(file1, token); FILE *fptr1 = fopen(file1, "r"); char line1[2000]; while(fgets(line1, sizeof(line1), fptr1)){ printf("%s\n", line1); } token = strtok(NULL, " "); } } }
C
#include <pthread.h> #include <semaphore.h> #include <stdio.h> #define N 5 //number of philosophers /* use the lpthread flag with gcc to compile this code ~$ gcc q1.c -lpthread */ /* various states of a philosopher */ #define THINKING 2 #define HUNGRY 1 #define EATING 0 /* index of left and right philosopher */ #define LEFT (philosopher_index + 4) % N #define RIGHT (philosopher_index + 1) % N int states_of_philosophers[N]; int phil[N] = { 0, 1, 2, 3, 4 }; sem_t mutex; sem_t philosophers[N]; void check(int philosopher_index) { if (states_of_philosophers[philosopher_index] == HUNGRY && states_of_philosophers[LEFT] != EATING && states_of_philosophers[RIGHT] != EATING) { states_of_philosophers[philosopher_index] = EATING; sleep(2); printf("Philosopher %d takes fork %d and %d\n", philosopher_index + 1, LEFT + 1, philosopher_index + 1); printf("Philosopher %d is Eating\n", philosopher_index + 1); // used to wake up hungry philosophers // during putfork sem_post(&philosophers[philosopher_index]); } } // take up chopsticks void acquire_fork(int philosopher_index) { sem_wait(&mutex); // indicate that the philosopher is hungry states_of_philosophers[philosopher_index] = HUNGRY; printf("Philosopher %d is Hungry\n", philosopher_index + 1); // a philosopher can only eat if its neighbours are not eating check(philosopher_index); sem_post(&mutex); //release the mutex // if unable to eat wait to be signalled sem_wait(&philosophers[philosopher_index]); sleep(1); } // put down chopsticks void release_fork(int philosopher_index){ sem_wait(&mutex); // change state of the philosopher to thinking states_of_philosophers[philosopher_index] = THINKING; printf("Philosopher %d putting fork %d and %d down\n",philosopher_index + 1, LEFT + 1, philosopher_index + 1); printf("Philosopher %d is thinking\n", philosopher_index + 1); check(LEFT); //allow philosopher at his left to eat check(RIGHT); //allow philosopher at his right to eat sem_post(&mutex); } void* philospher(void* num){ while (1) { int* i = num; sleep(1); acquire_fork(*i); sleep(0); release_fork(*i); } } int main() { int i; pthread_t threads[N]; // initialize the semaphores sem_init(&mutex, 0, 1); /* Initialize all philosophers' semaphores to 0 */ for (i = 0; i < N; i++) sem_init(&philosophers[i], 0, 0); /* Create philosophers' threads */ for (i = 0; i < N; i++) { pthread_create(&threads[i], NULL, philospher, &phil[i]); printf("Philosopher %d is thinking\n", i + 1); } /* join the created threads */ for (i = 0; i < N; i++) pthread_join(threads[i], NULL); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////// /* OUTPUT */ ////////////////////// //////////////// /* Philosopher 1 is thinking Philosopher 2 is thinking Philosopher 3 is thinking Philosopher 4 is thinking Philosopher 5 is thinking Philosopher 1 is Hungry Philosopher 2 is Hungry Philosopher 3 is Hungry Philosopher 4 is Hungry Philosopher 5 is Hungry Philosopher 5 takes fork 4 and 5 Philosopher 5 is Eating Philosopher 5 putting fork 4 and 5 down Philosopher 5 is thinking Philosopher 4 takes fork 3 and 4 Philosopher 4 is Eating Philosopher 1 takes fork 5 and 1 Philosopher 1 is Eating Philosopher 4 putting fork 3 and 4 down Philosopher 4 is thinking Philosopher 3 takes fork 2 and 3 Philosopher 3 is Eating Philosopher 5 is Hungry Philosopher 1 putting fork 5 and 1 down Philosopher 1 is thinking Philosopher 5 takes fork 4 and 5 Philosopher 5 is Eating Philosopher 4 is Hungry Philosopher 3 putting fork 2 and 3 down Philosopher 3 is thinking Philosopher 2 takes fork 1 and 2 Philosopher 2 is Eating Philosopher 1 is Hungry Philosopher 5 putting fork 4 and 5 down Philosopher 5 is thinking */
C
#include "crypto_decode.h" #include "crypto_uint8.h" #define uint8 crypto_uint8 #define p 1277 void crypto_decode(void *v,const unsigned char *s) { uint8 *f = v; uint8 x; int i; for (i = 0;i < p/4;++i) { x = *s++; *f++ = ((uint8)(x&3))-1; x >>= 2; *f++ = ((uint8)(x&3))-1; x >>= 2; *f++ = ((uint8)(x&3))-1; x >>= 2; *f++ = ((uint8)(x&3))-1; } x = *s++; *f++ = ((uint8)(x&3))-1; }
C
/* ** bufferize.c for minishell1 in /home/nicolaspolomack/shell/PSU_2016_minishell1 ** ** Made by Nicolas Polomack ** Login <nicolas.polomack@epitech.eu> ** ** Started on Mon Jan 9 10:55:14 2017 Nicolas Polomack ** Last update Sun May 21 11:49:53 2017 Arthur Knoepflin */ #include <sys/stat.h> #include "my.h" int is_right_redirect(char *str) { return (my_strcmp(str, ">") == 0 || my_strcmp(str, ">>") == 0); } int is_left_redirect(char *str) { return (my_strcmp(str, "<") == 0 || my_strcmp(str, "<<") == 0); } int is_to_fork(char c) { return (c == ';' || c == 'e' || c == 'o'); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #pragma region data_structure typedef struct _stackNode StackNode; struct _stackNode{ int value; StackNode * nextNode; }; StackNode * _head; #pragma endregion data_structure #pragma region methods_signature /************ * Constructors n Destructors *************/ StackNode * StackNode_new(void); void StackNode_delete( StackNode * node); StackNode * newNode(int value, StackNode * next); /************ * Data operations *************/ void push(int value); void pop(); void popAll(); /************ * Misc. *************/ void stackToString(); void pause(); void printMenu(); #pragma endregion methods_signature int main(){ int value = 0; do{ printf("\nInsira um numero (0 para terminar) > "); scanf("%d", &value); if(value != 0) push(value); }while(value); stackToString(); printf("\n\tTodos os numeros serao eliminados!\n"); popAll(); stackToString(); pause(); } #pragma region methods_implementation StackNode * StackNode_new(void) { StackNode * novo; if ((novo = ( StackNode*)malloc(sizeof( StackNode))) == NULL) { exit(1); } //memset(novo,0xda,sizeof( StackNode)); return novo; } void StackNode_delete( StackNode * node) { node->value = -1; //memset(node,0xdd,sizeof( StackNode)); free(node); } StackNode * newNode(int value, StackNode * next){ StackNode * newNode = StackNode_new(); newNode->value=value; newNode->nextNode = next; return newNode; } void push(int value){ StackNode * novo = newNode(value, _head); _head = novo; } void pop(){ StackNode * node; if(_head == NULL) return; node = _head; _head = _head->nextNode; StackNode_delete(node); } void popAll(){ while(_head != NULL) pop(); } void stackToString(){ StackNode * current = _head; printf("\nStack [ "); while(current != NULL){ printf("%d ",current->value); current = current->nextNode; } printf("]\n"); } void pause(){ printf("Press any key to continue . . ."); scanf("%c"); } void printMenu(){ printf("*************"); printf(" MENU "); printf(" 1.Adicionar um elemento (push) "); printf(" 2.Remover elemento do topo da pilha (pop) "); printf(" 3.Remover todos os elementos da pilha"); printf("*************"); } #pragma endregion methods_implementation
C
#include "HoareQuickSort.h" #if DEBUG #include <stdio.h> #endif // DEBUG /* nondecreasing order: type = 1 nonincreasing order: type = 0 */ void HoareQuickSort(int* a, int first, int last, int type) { if (type) { HoareQuickSortNondecreasingOrder(a, first, last); } else { HoareQuickSortNonincreasingOrder(a, first, last); } return; } void HoareQuickSortNondecreasingOrder(int* a, int first, int last) { int middle; if (first < last) { middle = HoarePartitionNondecreasingOrder(a, first, last); HoareQuickSortNondecreasingOrder(a, first, middle - 1); HoareQuickSortNondecreasingOrder(a, middle + 1, last); } return; } int HoarePartitionNondecreasingOrder(int* a, int first, int last) { int i, j, target, tmp; target = a[first]; i = first - 1; j = last + 1; while (TRUE) { while (a[--j] > target); while (a[++i] < target); if (i < j) { tmp = a[i]; a[i] = a[j]; a[j] = tmp; } else { break; } } if (a[j] != target) { i = first - 1; while (a[++i] != target); if (i <= j) { a[i] = a[j]; a[j] = target; } else { a[i] = a[++j]; a[j] = target; } } #if DEBUG else { putchar('$'); } #endif // DEBUG return j; } void HoareQuickSortNonincreasingOrder(int* a, int first, int last) { int middle; if (first < last) { middle = HoarePartitionNonincreasingOrder(a, first, last); HoareQuickSortNonincreasingOrder(a, first, middle - 1); HoareQuickSortNonincreasingOrder(a, middle + 1, last); } return; } int HoarePartitionNonincreasingOrder(int* a, int first, int last) { int i, j, target, tmp; target = a[first]; i = first - 1; j = last + 1; while (TRUE) { while (a[--j] < target); while (a[++i] > target); if (i < j) { tmp = a[i]; a[i] = a[j]; a[j] = tmp; } else { break; } } if (a[j] != target) { i = first - 1; while (a[++i] != target); if (i <= j) { a[i] = a[j]; a[j] = target; } else { a[i] = a[++j]; a[j] = target; } } #if DEBUG else { putchar('$'); } #endif // DEBUG return j; }
C
#include<stdio.h> #include<stdlib.h> #include "storage_mgr.h" #include<string.h> FILE *page; extern void initStorageManager (void){ page = NULL; } extern RC createPageFile (char *fileName) { page = fopen(fileName,"w+"); if(fileName == NULL){ return RC_FILE_NOT_FOUND; } if(page==NULL){ fclose(page); printf("Page Creation Failed"); } char *pg; pg= (char *) calloc (PAGE_SIZE , sizeof(char)); size_t wc= fwrite(pg, sizeof(char) , PAGE_SIZE, page); if (wc == PAGE_SIZE){ fclose(page); return RC_OK; } else{ fclose(page); free(pg); printf("Page Creation Failed"); } return RC_ERROR; } extern RC openPageFile(char *fileName, SM_FileHandle *fHandle){ page = fopen(fileName,"r"); if(page == NULL){ return RC_FILE_NOT_FOUND; }else{ fHandle->fileName = fileName; fseek(page,0L,SEEK_END); int size = ftell(page); rewind(page); size = size/ PAGE_SIZE; fHandle->totalNumPages = size; fHandle->mgmtInfo = page; fHandle->curPagePos = 0; return RC_OK; } } extern RC closePageFile(SM_FileHandle *fHandle){ int value = fclose((*fHandle).mgmtInfo); if(value == EOF) { return RC_ERROR; } return RC_OK; } extern RC destroyPageFile(char *fileName){ FILE *pg = fopen(fileName , "r"); if(pg==NULL) { return RC_FILE_NOT_FOUND; } int remfile= 1; remfile = remove(fileName); if(remfile == 0){ return RC_OK; } else{ return RC_FILE_REMOVE_ERROR; } } extern RC readBlock (int pageNum, SM_FileHandle *fHandle, SM_PageHandle memPage){ if(fHandle->mgmtInfo == NULL){ return RC_FILE_NOT_FOUND; } if(pageNum > fHandle->totalNumPages || pageNum < 0 ){ return RC_READ_NON_EXISTING_PAGE; } int value = fseek(fHandle->mgmtInfo, pageNum*PAGE_SIZE,SEEK_SET); if(value != 0){ return RC_ERROR; } fread(memPage,sizeof(char),PAGE_SIZE,fHandle->mgmtInfo); fHandle->curPagePos = pageNum; return RC_OK; } extern int getBlockPos(SM_FileHandle *fHandle) { int currPos = fHandle->curPagePos; if(fHandle == NULL) { return RC_FILE_HANDLE_NOT_INIT; } else{ return currPos; } } extern RC readFirstBlock(SM_FileHandle *fHandle , SM_PageHandle memPage) { if(fHandle == NULL) { return RC_FILE_HANDLE_NOT_INIT; } else{ return readBlock(0,fHandle,memPage); } } extern RC readLastBlock(SM_FileHandle *fHandle , SM_PageHandle memPage) { int tp = fHandle->totalNumPages -1; if(fHandle == NULL) { return RC_FILE_HANDLE_NOT_INIT; } else { return readBlock(tp, fHandle, memPage); } } extern RC readPreviousBlock(SM_FileHandle *fHandle , SM_PageHandle memPage) { int prev_block = getBlockPos(fHandle)-1; if(fHandle == NULL) { return RC_FILE_HANDLE_NOT_INIT; } else { return readBlock(prev_block,fHandle,memPage); } } extern RC readCurrentBlock (SM_FileHandle *fHandle, SM_PageHandle memPage) { int curr_block=fHandle->curPagePos; if(fHandle == NULL) { return RC_FILE_HANDLE_NOT_INIT; } else { return readBlock(curr_block,fHandle,memPage); } } extern RC readNextBlock (SM_FileHandle *fHandle, SM_PageHandle memPage){ int currentPage = getBlockPos(fHandle); int nextPage = currentPage+1; readBlock(nextPage,fHandle,memPage); return RC_OK; } extern RC writeBlock (int pageNum, SM_FileHandle *fHandle, SM_PageHandle memPage){ if(pageNum <0 ) { return RC_WRITE_FAILED; } page = fopen(fHandle->fileName,"r+"); if(page == NULL) { return RC_FILE_NOT_FOUND; } int value = fseek(page, pageNum*PAGE_SIZE,SEEK_SET); if(value != 0){ return RC_ERROR; } else { fwrite(memPage,sizeof(char),strlen(memPage),page); fHandle->curPagePos = pageNum; fclose(page); return RC_OK; } } extern RC writeCurrentBlock (SM_FileHandle *fHandle, SM_PageHandle memPage) { int curr_pos = fHandle->curPagePos; if(fHandle == NULL) { return RC_FILE_NOT_FOUND; } else if(memPage == NULL) { return RC_NO_SUCH_PAGE_IN_BUFF; } else { return writeBlock(curr_pos, fHandle, memPage); } } extern RC appendEmptyBlock (SM_FileHandle *fHandle){ page = fopen(fHandle->fileName,"r+"); int tp = fHandle->totalNumPages; fHandle->totalNumPages += 1; fseek(page,tp*PAGE_SIZE,SEEK_SET); char ch = 0 ; int i = 0; while(i<PAGE_SIZE){ fwrite(&ch,sizeof(ch),1,page); i++; } fclose(page); return RC_OK; } extern RC ensureCapacity(int numberOfPages, SM_FileHandle *fHandle){ int pagesToAdd = numberOfPages - fHandle->totalNumPages; int i; if(pagesToAdd > 0){ for(i = 0; i < pagesToAdd; i++) appendEmptyBlock(fHandle); } if(fHandle->totalNumPages == numberOfPages){ return RC_OK; } return RC_ERROR; }
C
/* Sample thread program to add the numbers in an array */ #include <stdio.h> #include <stdlib.h> #include <pthread.h> #define array_size 1000 #define no_processes 10 int a[array_size]; int global_index = 0; int sum = 0; pthread_mutex_t mutex1; pthread_mutex_t mutex2; void *slave(void *ignored) { int local_index, partial_sum = 0; do{ pthread_mutex_lock(&mutex1); local_index = global_index; global_index++; pthread_mutex_unlock(&mutex1); if(local_index < array_size) partial_sum += *(a + local_index); } while (local_index < array_size); pthread_mutex_lock(&mutex2); sum += partial_sum; pthread_mutex_unlock(&mutex2); /*return();*/ } main() { int i; pthread_t thread[10]; pthread_mutex_init(&mutex1,NULL); pthread_mutex_init(&mutex2,NULL); for(i=0;i<array_size;i++) a[i] = i+1; for(i=0;i<no_processes;i++) if(pthread_create(&thread[i],NULL,slave,NULL) != 0) { printf( "Pthread_create fails\n"); exit(0); } for(i=0;i<no_processes; i++) if (pthread_join(thread[i],NULL) != 0) { printf("Pthread_join fails\n"); exit(0); } printf("The sum of 1 to %d is %d\n",array_size, sum); return 0; }
C
#include<stdio.h> #define MAX 100 void crtanje(int n, int raz); int main() { int n; printf("Unesi n:\n"); scanf("%d", &n); crtanje(n, 0); printf("\n"); return 0; } void crtanje(int n, int raz) { int i; if (n == 1) { for (i = 0; i < raz; i++)printf(" "); printf("+"); } else { crtanje(n - 1, raz + 1); printf("\n"); for (i = 0; i < raz; i++)printf(" "); for (i = 0; i < n; i++)printf("+"); } }
C
#include "b-tree.h" #include <stdlib.h> #include <assert.h> /* ========================================================================== * PROTOTIPOS * ========================================================================== */ static b_node_t * b_node_new (); static b_node_t * b_node_add_nonfull (b_node_t **node, b_key_t key); static b_node_t * b_node_add_full (b_node_t **node, b_key_t key); static void b_node_replace (b_node_t *node, b_key_t key, int i); static int b_node_index (const b_node_t *node, b_key_t key); static b_node_t ** b_node_find (const b_tree_t *tree, b_key_t key); static void b_node_delete (b_node_t *node); /* ========================================================================== * FUNCIONES ÁRBOL * ========================================================================== */ b_tree_t * b_new() { b_tree_t *tree = (b_tree_t *) malloc(sizeof(b_tree_t)); tree->root = NULL; return tree; } void b_add(b_tree_t *tree, b_key_t key) { b_node_t **n = b_node_find(tree, key); if (*n == NULL) { b_node_add_nonfull(n, key); } else { int i = b_node_index(*n, key); if (i < (*n)->used_keys && key == (*n)->keys[i]) return; if ((*n)->used_keys == B_MAX_KEYS) b_node_add_full(n, key); else b_node_add_nonfull(n, key); } if (tree->root->parent != NULL) tree->root = tree->root->parent; } bool b_find(const b_tree_t *tree, b_key_t key) { b_node_t **n = b_node_find(tree, key); if (*n == NULL) return false; int i = b_node_index(*n, key); return i < (*n)->used_keys && key == (*n)->keys[i]; } void b_delete(b_tree_t *tree) { assert(tree != NULL); if (tree->root != NULL) { b_node_delete(tree->root); } free(tree); tree = NULL; } /* ========================================================================== * FUNCIONES NODOS * ========================================================================== */ static b_node_t * b_node_new() { b_node_t *node = (b_node_t *) malloc(sizeof(b_node_t)); node->used_keys = 0; for (int i = 0; i < B_MAX_KEYS; i++) { node->children[i] = NULL; node->keys[i] = 0; } node->children[B_MAX_KEYS] = NULL; node->parent = NULL; return node; } /** * Devuelve el nodo en el que se produjo la inserción. Útil para obtener * el nuevo padre en el momento en que se realiza el split. **/ static b_node_t * b_node_add_nonfull(b_node_t **node, b_key_t key) { if (*node == NULL) { *node = b_node_new(); (*node)->keys[0] = key; (*node)->used_keys = 1; } else { /** * Tengo que insertar en la posición `i`, pues esta función es llamada * sii `key` no pertenece al árbol. * Se mueven los hijos adelante, salvo por el último caso, pues o bien * esta inserción se produce sobre una hoja, o bien se produce por un * split, y en ese caso, cuando se vuelva del llamado recursivo, los hijos * serán asignados correctamente. **/ int i = b_node_index(*node, key); for (int j = (*node)->used_keys; j > i; j--) { (*node)->keys[j] = (*node)->keys[j - 1]; (*node)->children[j + 1] = (*node)->children[j]; } (*node)->keys[i] = key; (*node)->used_keys++; } return *node; } /** * Devuelve el nodo en el que se produjo la inserción. Útil para obtener * el nuevo padre en el momento en que se realiza el split. **/ static b_node_t * b_node_add_full(b_node_t **node, b_key_t key) { /** * Se guarda para el futuro, pues `b_node_replace` va a hacer que * el puntero de este hijo se pierda. **/ b_node_t *m_child = (*node)->children[B_MAX_KEYS / 2]; b_key_t up_key; if (key < (*node)->keys[B_MAX_KEYS / 2 - 1]) { up_key = (*node)->keys[B_MAX_KEYS / 2 - 1]; b_node_replace(*node, key, B_MAX_KEYS / 2 - 1); } else if (key < (*node)->keys[B_MAX_KEYS / 2]) { up_key = key; } else { up_key = (*node)->keys[B_MAX_KEYS / 2]; b_node_replace(*node, key, B_MAX_KEYS / 2); } b_node_t *new_child = b_node_new(); int split; for (split = B_MAX_KEYS / 2; split < B_MAX_KEYS; split++) { new_child->children[split - B_MAX_KEYS / 2] = (*node)->children[split]; new_child->keys[split - B_MAX_KEYS / 2] = (*node)->keys[split]; } new_child->children[split - B_MAX_KEYS / 2] = (*node)->children[split]; new_child->used_keys = B_MAX_KEYS - B_MAX_KEYS / 2; (*node)->used_keys = B_MAX_KEYS / 2; if (key > up_key) { (*node)->children[B_MAX_KEYS / 2] = m_child; /** * Evito arruinar la estructura al acomodar los padres al final, pues * este hijo es apuntado por `new_child` y a `*node`, y al modificar * a su padre el cambio repercute en `*node`, y necesito que este se * mantenga en el caso en que esté en un llamado recursivo. **/ int i = b_node_index(new_child, key); new_child->children[i] = NULL; new_child->children[i + 1] = NULL; } else { new_child->children[0] = m_child; } if ((*node)->parent == NULL || (*node)->parent->used_keys < B_MAX_KEYS) { new_child->parent = b_node_add_nonfull(& (*node)->parent, up_key); int i = b_node_index(new_child->parent, up_key); new_child->parent->children[i] = *node; new_child->parent->children[i + 1] = new_child; } else { /** * El padre está hasta las manos. Hay que romperse la cabeza. * * Casos: * 1. el valor a insertar en el padre es menor que el valor medio => * => `*node` y `n` tendrán como padre al padre de `*node`. * 2. el valor a insertar en el padre _es_ el valor medio => * => `*node` conservará a su padre y `n` tendrá como padre al nodo * creado en el llamado recursivo. * 3. el valor a insertar en el padre es mayor que el valor medio => * => `*node` y `n` tendrán como padre al nodo creado en el llamado * recursivo. **/ if (up_key < (*node)->parent->keys[B_MAX_KEYS / 2 - 1]) { /* k < keys[m - 1] */ b_node_add_full(& (*node)->parent, up_key); new_child->parent = (*node)->parent; int i = b_node_index(new_child->parent, up_key); new_child->parent->children[i] = *node; new_child->parent->children[i + 1] = new_child; } else if (up_key < (*node)->parent->keys[B_MAX_KEYS / 2]) { /* keys[m - 1] < k < keys[m] */ new_child->parent = b_node_add_full(& (*node)->parent, up_key); (*node)->parent->children[B_MAX_KEYS / 2] = *node; new_child->parent->children[0] = new_child; } else { /* keys[m] < k */ new_child->parent = b_node_add_full(& (*node)->parent, up_key); (*node)->parent = new_child->parent; int i = b_node_index(new_child->parent, up_key); new_child->parent->children[i] = *node; new_child->parent->children[i + 1] = new_child; } } b_node_t *backup = *node; for (int i = 0; i <= new_child->used_keys; i++) { if (new_child->children[i] != NULL) new_child->children[i]->parent = new_child; } *node = backup; return new_child; } /** * Reemplaza la clave de `index` por `key`, reordenando las claves y los * hijos. **/ static void b_node_replace(b_node_t *node, b_key_t key, int index) { assert(0 <= index && index < node->used_keys); int new; if (key < node->keys[index]) { for (new = index; new > 0 && key < node->keys[new - 1]; new--) { node->keys[new] = node->keys[new - 1]; node->children[new + 1] = node->children[new]; } } else { for (new = index; new < node->used_keys - 1 && key > node->keys[new + 1]; new++) { node->keys[new] = node->keys[new + 1]; node->children[new] = node->children[new + 1]; } } node->keys[new] = key; } /** * TODO: * - Fijarse si mejora con una busqueda lineal. O sea, con pocas claves, * el caché debería ser mágico acá. * - Hacer que la busqueda binaria funcione devuelve el índice de la máxima * clave menor a `key` en caso de que esta no pertenezca al nodo. **/ static int b_node_index(const b_node_t *node, b_key_t key) { #ifndef B_BINARY_SEARCH assert(node != NULL); int i; for (i = 0; i < node->used_keys && key > node->keys[i]; i++) {} return i; #else assert(node != NULL); if (node->used_keys == 0 || key < node->keys[0]) return -1; int l, u, p; l = 0; u = node->used_keys - 1; while (l <= u) { p = (l + u)/2; if (key < node->keys[p]) { u = p - 1; } else if (key == node->keys[p]) { u = p; break; } else { l = p + 1; } } return u; #endif } /** * Devuelve un puntero al nodo* donde se encuentra `key`, o donde * habría que insertarlo. **/ static b_node_t ** b_node_find(const b_tree_t *tree, b_key_t key) { assert(tree != NULL); b_node_t **n = (b_node_t **) tree; while (*n != NULL) { int i = b_node_index(*n, key); if ((i == (*n)->used_keys || key != (*n)->keys[i]) && (*n)->children[i] != NULL) { n = &(*n)->children[i]; } else { /* match concreto ó fin de la "recursión". */ break; } } return n; } /** * Libera recursivamente a los hijos, luego a si mismo, y se setea en NULL. * No se debe tocar al padre. **/ static void b_node_delete(b_node_t *node) { if (node != NULL) { for (int i = 0; i <= node->used_keys; i++) { b_node_delete(node->children[i]); } free(node); node = NULL; } }
C
#ifndef DOUBLE_LIST_H #define DOUBLE_LIST_H #include <stdlib.h> #define DOUBLE_LIST_GET_NEXT(double_list_ptr, typename) (typename *)double_list_ptr->next #define DOUBLE_LIST_GET_PREV(double_list_ptr, typename) (typename *)double_list_ptr->prev typedef struct double_list { struct double_list *next; struct double_list *prev; } double_list; int double_list_init(double_list *root) { int ret = 0; if (root == NULL) { ret = -1; goto done; } root->next = NULL; root->prev = NULL; done: return ret; } int double_list_insert_before(double_list *at, double_list *new_list_rec) { int ret = 0; if (!at || !new_list_rec) { ret = -1; goto done; } if (at->prev != NULL) { at->prev->next = new_list_rec; } new_list_rec->prev = at->prev; at->prev = new_list_rec; new_list_rec->next = at; done: return ret; } int double_list_insert_after(double_list *at, double_list *new_list_rec) { int ret = 0; if (!at || !new_list_rec) { ret = -1; goto done; } if (at->next) { at->next->prev = new_list_rec; } new_list_rec->next = at->next; at->next = new_list_rec; new_list_rec->prev = at; done: return ret; } int double_list_insert(double_list *root, unsigned int index, double_list *new_list_entry, unsigned int offset) { int ret = 0; if (root == NULL || index < -1 || new_list_entry == NULL) { ret = -1; goto done; } unsigned int i = 0; unsigned int index_lim = index-1; double_list *prev_list_entry = root; while (i < index_lim && prev_list_entry != NULL) { i++; prev_list_entry = prev_list_entry->next; } if (prev_list_entry == NULL) { ret = -2; goto done; } new_list_entry->next = prev_list_entry->next; prev_list_entry->next->prev = new_list_entry; prev_list_entry->next = new_list_entry; new_list_entry->prev = prev_list_entry - offset; done: return ret; } int double_list_insert_at_tail(double_list *root, double_list *new_tail) { int ret = 0; if (root == NULL || new_tail == NULL) { goto done; } double_list *tail = root; while (tail->next != NULL) { tail = tail->next; } tail->next = new_tail; done: return ret; } int double_list_remove(double_list *element) { int ret = 0; if (!element) { ret = -1; goto done; } if (element->next) { element->next->prev = element->prev; } if (element->prev) { element->prev->next = element->next; } done: return ret; } #endif
C
#include <stdio.h> #include <unistd.h> int main(int argc, char *argv[]){ FILE *secret = fopen("/root/root-me-challenges/app-systeme/ch5/.passwd", "rt"); char buffer[32]; fgets(buffer, sizeof(buffer), secret); printf(argv[1]); printf("\n"); printf("%s\n",buffer); printf("%x\n",buffer); printf("%p\n",buffer); fclose(secret); return 0; }
C
/* * Implementation of the null device, "null:", which generates an * immediate EOF on read and throws away anything written to it. */ #include <types.h> #include <kern/errno.h> #include <lib.h> #include <vfs.h> #include <dev.h> #include <uio.h> /* For open() */ static int nullopen(struct device *dev, int openflags) { (void)dev; (void)openflags; return 0; } /* For close() */ static int nullclose(struct device *dev) { (void)dev; return 0; } /* For d_io() */ static int nullio(struct device *dev, struct uio *uio) { /* * On write, discard everything without looking at it. * On read, do nothing, generating an immediate EOF. */ (void)dev; // unused if (uio->uio_rw == UIO_WRITE) { uio->uio_resid = 0; } return 0; } /* For ioctl() */ static int nullioctl(struct device *dev, int op, userptr_t data) { /* * No ioctls. */ (void)dev; (void)op; (void)data; return EINVAL; } /* * Function to create and attach null: */ void devnull_create(void) { int result; struct device *dev; dev = kmalloc(sizeof(*dev)); if (dev==NULL) { panic("Could not add null device: out of memory\n"); } dev->d_open = nullopen; dev->d_close = nullclose; dev->d_io = nullio; dev->d_ioctl = nullioctl; dev->d_blocks = 0; dev->d_blocksize = 1; dev->d_data = NULL; result = vfs_adddev("null", dev, 0); if (result) { panic("Could not add null device: %s\n", strerror(result)); } }
C
/* * Extracted from jstest.c developed by Vojtech Pavlik */ /* * This program can be used to test all the features of the Linux * joystick API. It is also intended to serve as an example * implementation for those who wish to learn * how to write their own joystick using applications. */ #include <sys/ioctl.h> #include <sys/time.h> #include <sys/types.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <linux/joystick.h> #define NAME_LENGTH 128 int main (int argc, char **argv) { int fd; unsigned char axes = 2; unsigned char buttons = 2; int version = 0x000800; char name[NAME_LENGTH] = "Unknown"; struct ff_effect effect, effect_weak, effect_strong; struct input_event gain, play, stop; const char * device_file_name = "/dev/input/event0"; int i; for (i=1; i<argc; ++i) { if (strncmp(argv[i], "--help", 64) == 0) { printf("Usage: %s /dev/input/eventXX\n", argv[0]); printf("Tests the force feedback driver\n"); exit(1); } else { device_file_name = argv[i]; } } /* Open device */ fd = open(device_file_name, O_RDWR); if (fd == -1) { perror("Open device file"); exit(1); } printf("Device %s opened\n", device_file_name); memset(&gain, 0, sizeof(gain)); gain.type = EV_FF; gain.code = FF_GAIN; gain.value = 0x9FFF; /* [0, 0xFFFF]) */ printf("Setting master gain to 75%% ... "); fflush(stdout); if (write(fd, &gain, sizeof(gain)) != sizeof(gain)) { perror("Error:"); } else { printf("OK\n"); } /****************************/ /* strong rumbling effect */ /****************************/ memset(&effect_strong,0,sizeof(effect)); effect_strong.type = FF_RUMBLE; effect_strong.id = -1; effect_strong.u.rumble.strong_magnitude = 0xffff; effect_strong.u.rumble.weak_magnitude = 0; effect_strong.replay.length = 900; // 900 ms effect_strong.replay.delay = 0; printf("Uploading effect # (Strong rumble, with heavy motor) ... "); fflush(stdout); if (ioctl(fd, EVIOCSFF, &effect_strong) == -1) { perror("Error"); } else { printf("OK (id %d)\n", effect_strong.id); } if (argc < 2 || argc > 3 || !strcmp("--help", argv[1])) { puts(""); puts("Usage: jstest [<mode>] <device>"); puts(""); puts(""); exit(1); } if ((fd = open(argv[argc - 1], O_RDONLY)) < 0) { perror("jstest"); exit(1); } /**************************/ /* weak rumbling effect */ /**************************/ memset(&effect_weak,0,sizeof(effect)); effect_weak.type = FF_RUMBLE; effect_weak.id = -1; effect_weak.u.rumble.strong_magnitude = 0; effect_weak.u.rumble.weak_magnitude = 0xffff; effect_weak.replay.length = 900; // 900 ms effect_weak.replay.delay = 0; printf("Uploading effect # (Weak rumble) ... "); fflush(stdout); if (ioctl(fd, EVIOCSFF, &effect_weak) == -1) { perror("Error:"); } else { printf("OK (id %d)\n", effect_weak.id); } ioctl(fd, JSIOCGVERSION, &version); ioctl(fd, JSIOCGAXES, &axes); ioctl(fd, JSIOCGBUTTONS, &buttons); ioctl(fd, JSIOCGNAME(NAME_LENGTH), name); printf("Joystick (%s) has %d axes and %d buttons. Driver version is %d.%d.%d.\n", name, axes, buttons, version >> 16, (version >> 8) & 0xff, version & 0xff); printf("Testing ... (interrupt to exit)\n"); /* * Event interface, single line readout. */ if (argc == 2 ) { int *axis; int *button; int i; struct js_event js; axis = calloc(axes, sizeof(int)); button = calloc(buttons, sizeof(char)); while (1) { if (read(fd, &js, sizeof(struct js_event)) != sizeof(struct js_event)) { perror("\njstest: error reading"); exit (1); } switch(js.type & ~JS_EVENT_INIT) { case JS_EVENT_BUTTON: button[js.number] = js.value; break; case JS_EVENT_AXIS: axis[js.number] = js.value; break; } printf("\r"); if (buttons) { printf("Buttons: "); for (i = 0; i < buttons; i++) if (i==0)effect_weak.u.rumble.strong_magnitude = 0xffff; } fflush(stdout); } } /*************/ /* Main loop */ /*************/ printf("\n\n"); for (i=1; i<16; i++) { /* Set master gain to x% if supported */ memset(&gain, 0, sizeof(gain)); gain.type = EV_FF; gain.code = FF_GAIN; gain.value = i<<12; printf("Setting master gain to %i%% ... ", i*100/16); fflush(stdout); if (write(fd, &gain, sizeof(gain)) != sizeof(gain)) { perror("Error:"); } else { printf("OK\n"); } /* Start the effect */ memset(&play,0,sizeof(play)); play.type = EV_FF; play.code = effect_strong.id; play.value = 1; if (write(fd, (const void*) &play, sizeof(play)) == -1) { perror("Play effect"); exit(1); } printf("Strong\n"); sleep(1); } for (i=1; i<16; i++) { /* Set master gain to x% if supported */ memset(&gain, 0, sizeof(gain)); gain.type = EV_FF; gain.code = FF_GAIN; gain.value = i<<12; printf("Setting master gain to %i%% ... ", i*100/16); fflush(stdout); if (write(fd, &gain, sizeof(gain)) != sizeof(gain)) { perror("Error:"); } else { printf("OK\n"); } /* Start the effect */ memset(&play,0,sizeof(play)); play.type = EV_FF; play.code = effect_weak.id; play.value = 1; if (write(fd, (const void*) &play, sizeof(play)) == -1) { perror("Play effect"); exit(1); } printf("Weak\n"); sleep(1); } /* Stop the effect */ printf("Stopping effects\n"); memset(&stop,0,sizeof(stop)); stop.type = EV_FF; stop.code = effect.id; stop.value = 0; if (write(fd, (const void*) &stop, sizeof(stop)) == -1) { perror(""); exit(1); } return -1; }
C
//////////////////////////////////////////////////////////////////////////////// // Display update //////////////////////////////////////////////////////////////////////////////// #include "display.h" #include "map_to_7segment.h" #define DISPLAY_BLINK_HALF_PERIOD 20 #define DISPLAY_SCROLL_RATE 12 static struct { uint16_t ledOn; uint16_t ledBlinking; uint8_t sevenSegs[2]; uint8_t blinkCounter; int8_t blinkState; uint8_t scrollCounter; int8_t scrollPos; int8_t scrollTimes; uint8_t activeCol; uint8_t activeRows[3]; char scrollText[50]; } display; static SEG7_DEFAULT_MAP(sevenSeg_map); void LOWERCODESIZE sevenSeg_scrollText(const char * text, int8_t times) { display.scrollTimes=times; display.scrollPos=-1; if (text) { display.scrollTimes=times; display.scrollPos=0; strcpy(&display.scrollText[1],text); strcat(display.scrollText," "); } } void LOWERCODESIZE sevenSeg_setAscii(char left, char right) { display.sevenSegs[0]=map_to_seg7(&sevenSeg_map,left); display.sevenSegs[1]=map_to_seg7(&sevenSeg_map,right); } void LOWERCODESIZE sevenSeg_setNumber(int32_t n) { n%=100; sevenSeg_setAscii('0'+(n/10),'0'+(n%10)); } int led_getOn(p600LED_t led) { uint16_t mask=1<<led; return !!(display.ledOn&mask); } int led_getBlinking(p600LED_t led) { uint16_t mask=1<<led; return !!(display.ledBlinking&mask); } void led_set(p600LED_t led, int8_t on, int8_t blinking) { uint16_t mask=1<<led; display.ledOn&=~mask; display.ledBlinking&=~mask; if (on) display.ledOn|=mask; if (blinking) display.ledBlinking|=mask; } void display_clear() { display.sevenSegs[0]=0; display.sevenSegs[1]=0; display.ledOn=0; display.ledBlinking=0; display.scrollTimes=0; } void display_init() { memset(&display,0,sizeof(display)); display.scrollText[0]=' '; } void display_update(int8_t fullUpdate) { if(fullUpdate) { uint8_t localSevenSegs[2]; // blinker display.blinkCounter++; if (display.blinkCounter>DISPLAY_BLINK_HALF_PERIOD) { display.blinkState=!display.blinkState; display.blinkCounter=0; } // scroller if(display.scrollTimes) { int8_t l,p,p2; display.scrollCounter++; l=strlen(display.scrollText); p=display.scrollPos; p2=(display.scrollPos+1)%l; localSevenSegs[0]=map_to_seg7(&sevenSeg_map,display.scrollText[p]); localSevenSegs[1]=map_to_seg7(&sevenSeg_map,display.scrollText[p2]); if (display.scrollCounter>DISPLAY_SCROLL_RATE) { display.scrollPos=p2; display.scrollCounter=0; if(p2==0 && display.scrollTimes>0) --display.scrollTimes; } } else { localSevenSegs[0]=display.sevenSegs[0]; localSevenSegs[1]=display.sevenSegs[1]; } // update one third of display at a time uint8_t b=0; switch (display.activeCol) { case 0: b=display.ledOn; if (display.blinkState) b^=display.ledBlinking; break; case 1: b=localSevenSegs[0]&0x7f; if (led_getOn(plDot)) b|=0x80; if (led_getBlinking(plDot) && display.blinkState) b^=0x80; break; case 2: b=localSevenSegs[1]&0x7f; if (led_getOn(plTune)) b|=0x80; if (led_getBlinking(plTune) && display.blinkState) b^=0x80; break; } display.activeRows[display.activeCol]=b; } BLOCK_INT { io_write(0x09,0x00); CYCLE_WAIT(1); io_write(0x08,0x10<<display.activeCol); CYCLE_WAIT(1); io_write(0x09,display.activeRows[display.activeCol]); } display.activeCol=(display.activeCol+1)%3; }
C
/************************************************************************* > File Name: switch.c > Author: wangjx > Mail: wangjianxing5210@163.com > Created Time: 2018年10月09日 星期二 14时50分20秒 ************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/time.h> #include <pthread.h> int pipes[20][3]; char buffer[10]; int running = 1; void init() { int i =20; while(i--) { if(pipe(pipes[i])<0) exit(1); pipes[i][2] = i; } } void distroy() { int i =20; while(i--) { close(pipes[i][0]); close(pipes[i][1]); } } double self_test() { int i =20000; struct timeval start, end; gettimeofday(&start, NULL); while(i--) { if(write(pipes[0][1],buffer,10)==-1) exit(1); read(pipes[0][0],buffer,10); } gettimeofday(&end, NULL); return (double)(1000000*(end.tv_sec-start.tv_sec)+ end.tv_usec-start.tv_usec)/20000; } void *_test(void *arg) { int pos = ((int *)arg)[2]; int in = pipes[pos][0]; int to = pipes[(pos + 1)%20][1]; while(running) { read(in,buffer,10); if(write(to,buffer,10)==-1) exit(1); } } double threading_test() { int i = 20; struct timeval start, end; pthread_t tid; while(--i) { pthread_create(&tid,NULL,_test,(void *)pipes[i]); } i = 10000; gettimeofday(&start, NULL); while(i--) { if(write(pipes[1][1],buffer,10)==-1) exit(1); read(pipes[0][0],buffer,10); } gettimeofday(&end, NULL); running = 0; if(write(pipes[1][1],buffer,10)==-1) exit(1); return (double)(1000000*(end.tv_sec-start.tv_sec)+ end.tv_usec-start.tv_usec)/10000/20; } int main() { init(); printf("per write and read pipe cost %6.6fus\n",self_test()); printf("per context switch cost and rw pipe cost %6.6fus\n",threading_test()); distroy(); exit(0); }
C
/** lab32.c * =========================================================== * Name: Jim Wang, 12 November 2019 * Section: T3A/4A * Project: Lab 32 * Documentation: C3C Gills helped me differentiate between tail and head recursion. * =========================================================== */ #include "lab32.h" int main() { // Exercise 1 printf("\nExercise 1:\n\n"); // The recursive function factorial() has been defined for you below. Review // the code and determine if it is tail recursive. // // For this exercise you will write a tail recursive version of factorial(), // called tail_factorial(), your function should take 2 integer parameters, the // first is the input value, the second is an accumulator. // Write your own code to test the base and recursive cases of tail_factorial() // to determine that it is working correctly. assert(tail_factorial(1, 1) == 1); // Exercise 2 printf("\nExercise 2:\n\n"); // The Collatz conjecture states that following a set of rules, you can reach 1 // starting from any other number. While this conjecture has not been proven, you // will write a tail recursive function called collatz() that accepts two integer // input parameters (the first is the starting value, the second is the accumulator) // and returns the number of steps needed to reach 1 from the starting value. // // The rules of the Collatz conjecture are: // if the current N is even, the next N = N/2 // if the current N is odd, the next N = 3*N + 1 // // The first 10 values in the number of steps required to reach 1 are below (for testing) // this is the correct output for inputs of 1, 2, 3, ... 10 // // 0, 1, 7, 2, 5, 8, 16, 3, 19, 6 // Write your own code to test the base and recursive cases of collatz() to determine // that it is working correctly assert(collatz(1, 0) == 0); // Exercise 3 printf("\nExercise 3:\n\n"); // Download the password.zip file from zyBooks. Extract this file to a new password // directory under your Lab 32 folder. There is a password hidden inside these files, // write a function decode_password() which searches these files recursively to find // the password, starting with "_.txt". // // Your decode_password() function should accept a character array input and return void. // The input is the name of a text file, without the directory, so the first call would be // decode_password("_.txt"); Use the DIRNAME constant to add the directory to the file name // inside the decode_password() fuction. You might create a character array to hold the full // name then use sprintf() to put the directory and filename together, fullName is a character // array you create, DIRNAME is a directory constant, and fname is the name you pass into the // decode_password() function. // sprintf(fullName, "%s%s", DIRNAME, fname); // // Until you reach the end of the text file, read one line of the file, if the string on that // line is of length 1, print that character (it is part of the message), otherwise the // string you read is the name of another text file which you should now search. // // NOTE: a bunch of random underscore '_' characters got thrown in with the actual message // so don't print those out when you find them. If you use fscanf(), to read the text files // remember that each line ends with a new line character. // When you submit to the ZyBook comment out any calls to decode_password(), and change the // printf() call below to the password you read from the text files. printf("https://xkcd.com/710//0//\n"); return 0; } /** ---------------------------------------------------------- * @fn int factorial(int N) * @brief Recursively calculates the factorial of N * @param N, the input parameter * @return N!, the value of the factorial of N * ---------------------------------------------------------- */ int factorial(int N) { if (N < 2) { return 1; } return N * factorial(N - 1); } /** ---------------------------------------------------------- * @fn int tail_factorial(int N, int retVal) * @brief Recursively calculates the factorial of N through tail recursion * @param N, the input parameter * @param retVal, updated every function call * @return N!, the value of the factorial of N * ---------------------------------------------------------- */ int tail_factorial(int N, int retVal) { if (N < 2) { return retVal; } return tail_factorial(N - 1, retVal * N); } /** ---------------------------------------------------------- * @fn int collatz(int N, int count) * @brief recursively finds the number of steps to reach 1 through the Collatz conjecture * @param N, input param * @param count, step count updated with each recursion * @return stepCount, the number steps needed to reach 1 * ---------------------------------------------------------- */ int collatz(int N, int count) { if (N == 1) { return count; } else if (N % 2 == 0) { return collatz(N / 2, ++count); } else { return collatz(3 * N + 1, ++count); } } /** ---------------------------------------------------------- * @fn void decode_password(char* filename) * @brief recursively searches files for password * @param filename, the file path * ---------------------------------------------------------- */ void decode_password(char* filename) { char fileCont[100]; char fullname[200]; sprintf(fullname, "%s%s", DIRNAME, filename); FILE* fp = fopen(fullname, "r"); while(!feof(fp)) { fscanf(fp, "%s", fileCont); if(strlen(fileCont) == 1) { if (strncmp(fileCont, "_", sizeof(char)) != 0){ printf("%s", fileCont); } } else { decode_password(fileCont); } } fclose(fp); }
C
#include <stdio.h> #include <stdlib.h> int main() { int a = 0, b = 1, c = 0, i = 0, answer = 0; printf("input number : "); scanf_s("%d", &answer); for (i = 1, i <= answer; i++) { printf("%d", a); c = a + b; a = b; b = c; } return 0; }
C
#ifndef OS345ARGPARSE_H_ #define OS345ARGPARSE_H_ #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "os345.h" #define MAX_ARG_LEN 256 char* bufferContents; int nextCharPos; typedef struct { int argc; char** argv; bool runInBackground; int errors; } ParsedLine; ParsedLine parseArgs(char* buffer); int parseLine(int* newArgc, char** newArgv, bool* background); int parseArg(int* newArgc, char** newArgv); int parseQuotedString(int* newArgc, char** newArgv); int parseQuoteDelimitedString(int* newArgc, char** newArgv); int parseString(int* newArgc, char** newArgv); int parseNum(char* str); int parseWhiteSpace(int* newArgc, char** newArgv); int parseAmpersand(bool* background); char peekChar(); char popChar(); bool isStringChar(char c); bool isQuote(char c); ParsedLine parseArgs(char* buffer) { debugPrint('p', 'f', "parseArgs()\n"); bufferContents = buffer; nextCharPos = 0; ParsedLine line; line.argc = 0; line.argv = malloc(MAX_ARGS * sizeof(char*)); for (int i = 1; i < MAX_ARGS; i++) line.argv[i] = NULL; line.runInBackground = FALSE; line.errors = parseLine(&line.argc, line.argv, &line.runInBackground); debugPrint('p', 'e', "finished parsing. errors:%d\n", line.errors); return line; } int parseLine(int* newArgc, char** newArgv, bool* background) { debugPrint('p', 'f', "parseLine()\n"); int errors = 0; while (peekChar() && peekChar() != '&') { errors += parseWhiteSpace(newArgc, newArgv); errors += parseArg(newArgc, newArgv); } errors += parseAmpersand(background); errors += parseWhiteSpace(newArgc, newArgv); if (peekChar() != '\0') errors++; return errors; } int parseArg(int* newArgc, char** newArgv) { debugPrint('p', 'f', "parseArg()\n"); if (isQuote(peekChar())) { return parseQuotedString(newArgc, newArgv); } else { return parseString(newArgc, newArgv); } } int parseQuotedString(int* newArgc, char** newArgv) { debugPrint('p', 'f', "parseQuotedString()\n"); if (!isQuote(peekChar())) { return 1; } else { char openQuote = popChar(); int errors = 0; errors = parseQuoteDelimitedString(newArgc, newArgv); if (!errors && openQuote == peekChar()) { popChar(); return 0; } else { return ++errors; } } } int parseQuoteDelimitedString(int* newArgc, char** newArgv) { debugPrint('p', 'f', "parseQuoteDelimitedString()\n"); char arg[MAX_ARG_LEN] = ""; char nextChar; while (peekChar() != '\0') { nextChar = peekChar(); if (isStringChar(nextChar) || isspace(nextChar)) { nextChar = popChar(); strncat(arg, &nextChar, 1); //append the new char } else if (isQuote(nextChar)) { newArgv[(*newArgc)] = malloc((strlen(arg) + 1) * sizeof(char)); strcpy(newArgv[(*newArgc)], arg); debugPrint('p', 'm', "malloced Arg %s\n", newArgv[(*newArgc)]); (*newArgc)++; return 0; } else { return 1; } } return 1; } int parseString(int* newArgc, char** newArgv) { debugPrint('p', 'f', "parseString()\n"); char arg[MAX_ARG_LEN] = ""; char nextChar; while (1) { nextChar = peekChar(); if (isStringChar(nextChar)) { nextChar = tolower(popChar()); strncat(arg, &nextChar, 1); //append the new char } else if (isspace(nextChar) || nextChar == '\0' || nextChar == '&') { newArgv[(*newArgc)] = malloc((strlen(arg) + 1) * sizeof(char)); strcpy(newArgv[(*newArgc)], arg); debugPrint('p', 'm', "malloced Arg %s\n", newArgv[(*newArgc)]); (*newArgc)++; return 0; } else { return 1; } } return 1; } int parseWhiteSpace(int* newArgc, char** newArgv) { debugPrint('p', 'f', "parsewhiteSpace()\n"); while (isspace(peekChar())) { popChar(); } return 0; } int parseAmpersand(bool* background) { debugPrint('p', 'f', "parseAmpersand()\n"); if (peekChar() != '&') { return 0; } else { popChar(); *background = TRUE; return 0; } } char peekChar() { debugPrint('p', 'p', "peeked %c\n", bufferContents[nextCharPos]); return bufferContents[nextCharPos]; } char popChar() { debugPrint('p', 'p', "popped %c\n", bufferContents[nextCharPos]); if (bufferContents[nextCharPos]) nextCharPos++; return bufferContents[nextCharPos - 1]; } bool isStringChar(char c) { if (isalpha(c)) { return 1; } else if (isdigit(c)) { return 1; } else if (c == '.') { return 1; } else if (c == ':') { return 1; } else if (isspace(c)) { return 0; } else if (c == '\0') { return 0; } else if (c == '&') { return 0; } return 1; } bool isQuote(char c) { if (c == '\'') { return 0; } else if (c == '"') { return 1; } return 0; } /* format: * 2x.. binary * 8x.. octal * 0x.. hex * .. decimal */ int parseNum(char* str) { int num; char* waste = NULL; char c = str[0]; if (isdigit(c) && str[1] == 'x') { // look for escape sequence if (c == '2') { num = strtol(&str[2], &waste, 2); } else if (c == '8') { num = strtol(&str[2], &waste, 8); } else if (c == '0') { num = strtol(&str[2], &waste, 16); } } else { num = strtol(str, &waste, 10); } if ((*waste) != '\0') { printf("%s is not a number\n", waste); num = 0; } return num; } #endif /* OS345ARGPARSE_H_ */
C
#include "client.h" /** * Function that makes the ips that will connect to the server */ void makeIp() { char *firstPart = "http://"; char *secondPartImage = "/Api/Analyze"; char* secondPartStop = "/Api/Stop"; serverImageLink = malloc(strlen(firstPart) + strlen(serverIp) + strlen(secondPartImage) + 1); serverCloseLink = malloc(strlen(firstPart) + strlen(serverIp) + strlen(secondPartStop) + 1); strcpy(serverImageLink, firstPart); strcat(serverImageLink, serverIp); strcat(serverImageLink, secondPartImage); strcpy(serverCloseLink, firstPart); strcat(serverCloseLink, serverIp); strcat(serverCloseLink, secondPartStop); free(serverIp); } /** * Function that stops the server */ int stopServer() { int res; ulfius_init_request(&requestConnection); ulfius_set_request_properties(&requestConnection, U_OPT_HTTP_VERB, "GET", U_OPT_HTTP_URL, serverCloseLink, U_OPT_NONE); ulfius_init_response(&responseConnection); res = ulfius_send_http_request(&requestConnection, &responseConnection); if (res == U_OK) { printf("Successfully stopped the server and nodes\n"); } else { printf("Failed to stop the server and nodes\n"); } ulfius_clean_response(&responseConnection); ulfius_clean_request(&requestConnection); return 0; } /** * Function that sends an image to the server */ int sendImageToServer() { int res; ulfius_init_request(&requestConnection); ulfius_set_request_properties(&requestConnection, U_OPT_HTTP_VERB, "POST", U_OPT_HTTP_URL, serverImageLink, U_OPT_JSON_BODY, jsonImage, U_OPT_NONE); ulfius_init_response(&responseConnection); res = ulfius_send_http_request(&requestConnection, &responseConnection); if (res == U_OK) { printf("Image sent server\n"); } else { printf("Failed to send image to server\n"); exit(EXIT_FAILURE); } ulfius_clean_response(&responseConnection); ulfius_clean_request(&requestConnection); return 0; }
C
bool isMatch(char* s, char* p) { int length_s, length_p, i, j; int len_flag = 0; char left, right; length_s = strlen(s); length_p = strlen(p); // unequal lenth if(length_s != length_p) { for(i = 0;i < length_p;i++) if(p[i] == '*') { len_flag = 1; break; } if(!len_flag) return false; } i = 0; j = 0; while(p[j] != '\0') { // .ֱӹ if(p[j] == '.') { i++; j++; continue; } // * *ǰĸһ else if(p[j] == '*') { // *ǰ. if(p[j - 1] == '.') { // .*ûֱַƥɹ if(p[j + 1] == '\0') return true; // else if } // һ left = p[j - 1]; right = p[j + 1]; while(s[i] == left) { i++; } j++; while(p[j] == s[i - 1]) { j++; } continue; } else if(s[i] != p[j]) { // ߲һǺ*϶*0ַ if(p[j + 1] == '*') { j = j + 2; continue; } return false; } i++; j++; } if(s[i] != p[j]) { return false; } return true; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "abm.h" int getInt(char mensaje[]) { int auxInt; printf(mensaje); scanf("%d",&auxInt); fflush(stdin); return auxInt; } float getFloat(char mensaje[]) { float auxFloat; printf(mensaje); scanf("%f",&auxFloat); fflush(stdin); return auxFloat; } char getChar(char mensaje[]) { char auxChar; printf(mensaje); scanf("%c",&auxChar); fflush(stdin); return auxChar; } void getString(char mensaje[],char cadena[]) { printf(mensaje); gets(cadena); } int validarSoloNumeros(char cadena[]) { int retorno=1; int i=0; while(cadena[i] != '\0') { if(cadena[i] < '0' || cadena[i] > '9') { retorno=0; } i++; } return retorno; } int validarSoloLetras(char cadena[]) { int retorno=1; int i=0; while(cadena[i] != '\0') { if((cadena[i] != ' ') && (cadena[i] < 'a' || cadena[i] > 'z') && (cadena[i] < 'A' || cadena[i] > 'Z')) { retorno=0; } i++; } return retorno; } int getStringNumeros(char mensaje[],char cadena[]) { int retorno=0; char auxCadena[50]; getString(mensaje,auxCadena); if(validarSoloNumeros(auxCadena)) { strcpy(cadena,auxCadena); retorno=1; } return retorno; } int getStringLetras(char mensaje[],char cadena[]) { int retorno=0; char auxCadena[50]; getString(mensaje,auxCadena); if(validarSoloLetras(auxCadena)) { strcpy(cadena,auxCadena); retorno=1; } return retorno; } void inicializarLegajoArray(int unArray[],int tam,int valor) { int i; for(i=0;i<tam;i++) { unArray[i]=valor; } } int buscarLugarLibre(int unArray[],int tam,int valor) { int retorno=-1; int i; for(i=0;i<tam;i++) { if(unArray[i] == valor) { retorno=i; } } return retorno; }
C
#include "main.h" void operatorControl() { bool btnPress = 1; int rightPower; int leftPower; while (1) { //Tank Drive rightPower = joystickGetAnalog(1, 2); leftPower = joystickGetAnalog(1, 3); if(abs(rightPower) > 15 || abs(leftPower) > 15) { motorSet(DRIVE_R, -rightPower); motorSet(DRIVE_L, leftPower); } else{ motorSet(DRIVE_R, 0); motorSet(DRIVE_L, 0); } //Lift if(joystickGetDigital(1, 5, JOY_UP)) { motorSet(LIFT_L1, 127); motorSet(LIFT_R1, -127); motorSet(LIFT_L2, 127); motorSet(LIFT_R2, -127); } else if(joystickGetDigital(1, 5, JOY_DOWN)) { motorSet(LIFT_L1, -127); motorSet(LIFT_R1, 127); motorSet(LIFT_L2, -127); motorSet(LIFT_R2, 127); } else{ motorSet(LIFT_L1, 0); motorSet(LIFT_R1, 0); motorSet(LIFT_L2, 0); motorSet(LIFT_R2, 0); } //Mogo if(joystickGetDigital(1, 7, JOY_LEFT)) { motorSet(MOGO_L, 127); motorSet(MOGO_R, -127); } else if(joystickGetDigital(1, 7, JOY_DOWN)) { motorSet(MOGO_L, -127); motorSet(MOGO_R, 127); } else{ motorSet(MOGO_R, 0); motorSet(MOGO_L, 0); } //Rollers - 4bar if(joystickGetDigital(1, 6, JOY_UP)) { motorSet(ROLLER_4BAR, -127); } else if(joystickGetDigital(1, 6, JOY_DOWN)) { motorSet(ROLLER_4BAR, 127); } else{ motorSet(ROLLER_4BAR, 0); } //Rollers - Intake if(!btnPress && joystickGetDigital(1, 8, JOY_LEFT)) { btnPress = 1; } else if(btnPress && joystickGetDigital(1, 8, JOY_UP)) { btnPress = 0; } if(joystickGetDigital(1, 8, JOY_DOWN)) { motorSet(ROLLER_CLAW, 127); } else if(joystickGetDigital(1, 8, JOY_RIGHT)) { motorSet(ROLLER_CLAW, -127); } else if(btnPress) { motorSet(ROLLER_CLAW, 25); } else{ motorSet(ROLLER_CLAW, 0); } delay(20); } }
C
#include <stdio.h> #include <stdlib.h> #include "funcion.h" int main() { char seguir='s'; int opcion; float x; float y; float resultado; int pusonumeroUno=0; int pusonumeroDos=0; while(seguir=='s') { if(pusonumeroUno==0) { printf("1- Ingresar 1er operando (A=x)\n"); } else { printf("1- Ingresar 1er operando (A=%f)\n",x); } if(pusonumeroDos==0) { printf("2- Ingresar 2do operando (B=y)\n"); } else { printf("2- Ingresar 2do operando (B=%f)\n",y); } printf("3- Calcular la suma (A+B)\n"); printf("4- Calcular la resta (A-B)\n"); printf("5- Calcular la division (A/B)\n"); printf("6- Calcular la multiplicacion (A*B)\n"); printf("7- Calcular el factorial (A!)\n"); printf("8- Calcular todas las operaciones\n"); printf("9- Salir\n\n"); printf("Ingrese opcion: "); scanf("%d",&opcion); system("cls"); switch(opcion) { case 1: x=numero(); system("cls"); printf("El numero es:%f\n\n",x); pusonumeroUno=1; break; case 2: y=numero(); system("cls"); printf("El numero es:%f\n\n",y); pusonumeroDos=1; break; case 3: resultado=suma(x,y); system("cls"); printf("El resultado de la suma es %f\n\n", resultado); break; case 4: resultado=resta (x, y); system("cls"); printf("El resultado de la resta es %f\n\n", resultado); break; case 5: if(y != 0) { resultado=division (x, y); system("cls"); printf("El resultado de la division es %f\n\n", resultado); } else { system("cls"); printf("NO se puede dividir por 0\n\n"); } break; case 6: resultado=multiplicacion (x, y); system("cls"); printf("El resultado de la multiplicacion es %f\n\n", resultado); break; case 7: if (x >= 0) { resultado=factorial(x); system("cls"); printf("El resultado del factorial de %f es %f\n\n", x, resultado); } else { system("cls"); printf("NO se puede saca el factorial de un numero negativo\n\n"); } break; case 8: resultado=suma(x,y); system("cls"); printf("El resultado de la suma es %f\n\n", resultado); resultado=resta (x, y); printf("El resultado de la resta es %f\n\n", resultado); resultado=division (x, y); printf("El resultado de la division es %f\n\n", resultado); resultado=multiplicacion (x, y); printf("El resultado de la multiplicacion es %f\n\n", resultado); resultado=factorial(x); printf("El resultado del factorial de %f es %f\n\n", x, resultado); break; case 9: seguir = 'n'; break; default: printf("Ingrese una opcion del menu\n\n"); } } }
C
/* blah_entity.c Defines functions which operate upon entities. See blah_entity.h for reference. */ #include <stdlib.h> #include <stdio.h> #ifdef BLAH_USE_GLUT #include <GL/glut.h> #endif #include <string.h> #include "blah_entity.h" #include "blah_macros.h" #include "blah_matrix.h" #include "blah_list.h" #include "blah_draw.h" #include "blah_util.h" #include "blah_error.h" /* Static Globals - Private to entity.c */ // List of those entities which were dynamically allocated, defaults to empty Blah_List blah_entity_list = { .name = "entities", .destroyElementFunction = (blah_list_element_dest_func*)Blah_Entity_destroy, }; /* Static Prototypes */ static void Blah_Entity_animate(Blah_Entity *entity); //Alters entity's location and orientation static void Blah_Entity_checkCollision(Blah_Entity *entity); //Checks if given entity is colliding against all other entities static bool Blah_Entity_processEvent(Blah_Entity *entity, Blah_Entity_Event *event); //Deals with pending event /* Main Entity Functions */ static void Blah_Entity_animate(Blah_Entity *entity) { //Alters entity's location and orientation //translate current position by velocity vector Blah_Point_translateByVector(&entity->location, &entity->velocity); //Calculate entity's orientation and update in private matrix Blah_Entity_rotateEuler(entity, entity->rotationAxisX, entity->rotationAxisY, entity->rotationAxisZ); } void blah_entity_destroyAll() { //Cleanup routine to do garbage collection for dynamically allocated entities apon exit Blah_List_destroyElements(&blah_entity_list); } void blah_entity_main() { //Main routine to process all entities blah_entity_processAll(); } void blah_entity_processAll() { Blah_List_callFunction(&blah_entity_list, (blah_list_element_func*)Blah_Entity_process); } /* Entity Function Definitions */ Blah_Entity_Object *Blah_Entity_addObject(Blah_Entity *entity, Blah_Object *object) { // Adds an object to an entity's list of composing objects Blah_Entity_Object *newEntObj = Blah_Entity_Object_new("an object",object); newEntObj->entity = entity; Blah_List_appendElement(&entity->objects, newEntObj); return newEntObj; } static void Blah_Entity_checkCollision(Blah_Entity *entity) { // Checks if given entity is colliding against all other entities. // If a collision is detected with another entity, call the collision handling function Blah_List_Element* currentElement = blah_entity_list.first; while (currentElement) { Blah_Entity* currentEntity = (Blah_Entity*)currentElement->data; if (currentEntity != entity) { // Don't check collision with itself! blah_entity_collision_func* colFunc = currentEntity->collisionFunction; Blah_Point impact; if (colFunc != NULL && currentEntity->activeCollision && Blah_Entity_checkCollisionEntity(entity, currentEntity, &impact)) { colFunc(currentEntity, entity); // call collision handler for recipient object } } currentElement = currentElement->next; } } bool Blah_Entity_checkCollisionEntity(Blah_Entity *entity1, Blah_Entity *entity2, Blah_Point *impact) { // Returns true if entity_1 is colliding with entity_2 // TODO - return impact point (void)impact; Blah_List_Element *entity1Obj = entity1->objects.first; Blah_List_Element *entity2Obj = entity2->objects.first; // Get the first object in list of each entity bool collision = false; // assume no collision yet Blah_Point collisionPoint1, collisionPoint2; while (entity1Obj && !collision) { while (entity2Obj && !collision) { if (Blah_Entity_Object_checkCollision((Blah_Entity_Object*)entity1Obj->data, (Blah_Entity_Object*)entity2Obj->data, &collisionPoint1, &collisionPoint2)) { collision = true; } else { entity2Obj = entity2Obj->next; // go through all ent2 objects } } entity2Obj = entity2->objects.first; // rewind to start of object list for ent2 entity1Obj = entity1Obj->next; // advance to next object for ent1 } return collision; } // Standard destroy routine for entity void Blah_Entity_destroy(Blah_Entity *entity) { // TODO - Only remove enity from the list if it was dynamically allocated Blah_List_removeElement(&blah_entity_list, entity); // Remove from list of entities if (entity->destroyFunction) { // call custom destroy function if there is one defined entity->destroyFunction(entity); } else { Blah_Entity_disable(entity); free(entity); } } void Blah_Entity_disable(Blah_Entity *entity) { //Disables entity. Nullifies its existence. Removes all objects and events associated with it. Blah_List_destroyElements(&entity->objects); //Destroy all objects composing entity Blah_List_destroyElements(&entity->events); //Destroy any events in the queue for the entity if (entity->entityData) {//if there is an allocated memory block for entity data free(entity->entityData); //free it } } float Blah_Entity_distanceEntity(Blah_Entity *entity1, Blah_Entity *entity2) { //Returns the distance from center of entity_1 to center of entity_2 return Blah_Point_distancePoint(&entity1->location, &entity2->location); } void Blah_Entity_draw(Blah_Entity *entity) { if (entity->drawFunction) { entity->drawFunction(entity); // Call custom draw function if it exists for entity } else { blah_draw_pushMatrix(); blah_draw_multMatrix(&entity->fakeMatrix); Blah_List_callFunction(&entity->objects, (blah_list_element_func*)Blah_Entity_Object_draw); //call Object_draw for all entity objects blah_draw_popMatrix(); } } void *Blah_Entity_getData(Blah_Entity *entity) { return entity->entityData; } // Gets entity's location in 3D space in 3 coordinates void Blah_Entity_getLocation(Blah_Entity *entity,Blah_Point *p) { Blah_Point_set(p,entity->location.x,entity->location.y,entity->location.z); } int Blah_Entity_getType(Blah_Entity *entity) { return entity->type; } // Gets entity's velocity in 3 vector float values void Blah_Entity_getVelocity(Blah_Entity *entity, Blah_Vector *v) { Blah_Vector_set(v,entity->velocity.x,entity->velocity.y,entity->velocity.z); } // Initialises a new plain entity without objects, positioned at origin void Blah_Entity_init(Blah_Entity *newEntity, char *name, int type, size_t dataSize) { newEntity->entityData = (dataSize > 0) ? malloc(dataSize) : NULL; // Allocate entity data if required blah_util_strncpy(newEntity->name, name, blah_countof(newEntity->name)); //copy name newEntity->type = type; //Set new entity type Blah_List_init(&newEntity->objects, "Objects"); Blah_List_init(&newEntity->events,"Events"); newEntity->objects.destroyElementFunction = (blah_list_element_dest_func*)Blah_Entity_Object_destroy; newEntity->activeCollision = false; Blah_Entity_setLocation(newEntity,0,0,0); //set location to origin Blah_Entity_setVelocity(newEntity,0,0,0); //going nowhere Blah_Vector_set(&newEntity->axisX, 1, 0, 0); Blah_Vector_set(&newEntity->axisY, 0, 1, 0); Blah_Vector_set(&newEntity->axisZ, 0, 0, 1); Blah_Matrix_setIdentity(&newEntity->fakeMatrix); //set matrix to identity matrix newEntity->drawFunction = NULL; newEntity->moveFunction = NULL; newEntity->collisionFunction = NULL; newEntity->destroyFunction = NULL; newEntity->rotationAxisX = newEntity->rotationAxisY = newEntity->rotationAxisZ = 0; Blah_Quaternion_setIdentity(&newEntity->orientation); } Blah_Entity *Blah_Entity_new(char* name, int type, size_t dataSize) { //constructs a new plain entity without objects, positioned at origin Blah_Entity *newEntity = (Blah_Entity*)malloc(sizeof(Blah_Entity)); if (newEntity) { Blah_Entity_init(newEntity, name, type, dataSize); Blah_List_appendElement(&blah_entity_list, newEntity); // Add to list of entities } else { blah_error_raise(errno, "Failed to allocate memory for entity '%x'", name); } return newEntity; } void Blah_Entity_process(Blah_Entity *entity) { //process entity, update position etc Blah_Entity_Event *temp_event; bool cont = true; if (entity->moveFunction != NULL) { entity->moveFunction(entity); } // If a movement control function is defined, call it Blah_Entity_animate(entity); // Animate the entity if (entity->activeCollision) { Blah_Entity_checkCollision(entity); } //If entity is actively colliding, check collisions temp_event = (Blah_Entity_Event*)Blah_List_popElement(&entity->events); while (temp_event && cont) {//Take care of all pending events cont = Blah_Entity_processEvent(entity,temp_event); //process next event_data if (cont) { temp_event = Blah_List_popElement(&entity->events); } // If it is ok to keep processing events, get the next one } } void Blah_Entity_rotateEuler(Blah_Entity *entity, float x, float y, float z) { Blah_Quaternion tempQuat; //Form a quaternion to represent all 3 euler rotations Blah_Quaternion_formatEuler(&tempQuat, x, y, z); //Multiply entity's current quaternion by new quaternion Blah_Quaternion_multiplyQuaternion(&entity->orientation, &tempQuat); //Recalculate orientation vectors in entity matrix Blah_Matrix_setRotationQuat(&entity->fakeMatrix, &entity->orientation); } void Blah_Entity_setActiveCollision(Blah_Entity *entity,bool flag) { //Sets active collision flag entity->activeCollision = flag; } void Blah_Entity_setLocation(Blah_Entity *entity, float x, float y, float z) { //Sets entity's location in 3D space given 3 coordinates Blah_Point_set(&entity->location, x, y, z); } void Blah_Entity_setRotationAxisX(Blah_Entity *entity, float x) { entity->rotationAxisX = x; } void Blah_Entity_setRotationAxisY(Blah_Entity *entity, float y) { entity->rotationAxisY = y; } void Blah_Entity_setType(Blah_Entity *entity, int type) { entity->type = type; } void Blah_Entity_setCollisionFunction(Blah_Entity* entity, blah_entity_collision_func* function) { entity->collisionFunction = function; //entity->collisionFunctionData = externData; } void Blah_Entity_setDestroyFunction(Blah_Entity* entity, blah_entity_destroy_func* function) { entity->destroyFunction = function; //entity->destroyFunctionData = externData; } void Blah_Entity_setDrawFunction(Blah_Entity* entity, blah_entity_draw_func* function) //, void *externData) { entity->drawFunction = function; //entity->drawFunctionData = externData; } void Blah_Entity_setMoveFunction(Blah_Entity* entity, blah_entity_move_func* function) //, void *externData) { entity->moveFunction = function; //entity->moveFunctionData = externData; } void Blah_Entity_setVelocity(Blah_Entity *entity, float x, float y, float z) { Blah_Vector_set(&entity->velocity, x, y, z); } /* Entity Event Functions */ // destroys an event structure void Blah_Entity_Event_destroy(Blah_Entity_Event *event) { if (event->destroyFunction) { event->destroyFunction(event); // If custom destroy function pointer exists, Call it instead to destroy the event obj } else { if (event->eventData) { free(event->eventData); } // Free event data if allocated free(event); // free event } } void *Blah_Entity_Event_getData(Blah_Entity_Event *event) { return event->eventData; } void Blah_Entity_Event_init(Blah_Entity_Event* event, const char* name, const Blah_Entity* sender, blah_entity_event_func* function, size_t dataSize) { event->eventData = (dataSize > 0) ? malloc(dataSize) : NULL; blah_util_strncpy(event->name, name, BLAH_ENTITY_EVENT_NAME_LENGTH); event->sender = sender; event->eventFunction = function; event->destroyFunction = NULL; } Blah_Entity_Event* Blah_Entity_Event_new(const char* name, const Blah_Entity* sender, blah_entity_event_func* function, size_t dataSize) { Blah_Entity_Event *newEvent = malloc(sizeof(Blah_Entity_Event)); if (newEvent) { Blah_Entity_Event_init(newEvent, name, sender, function, dataSize); } return newEvent; } static bool Blah_Entity_processEvent(Blah_Entity *entity, Blah_Entity_Event *event) { //Deals with pending event bool result = false; if (event->eventFunction) { result = event->eventFunction(entity, event); } Blah_Entity_Event_destroy(event); return result; } void Blah_Entity_sendEvent(Blah_Entity *recipient, Blah_Entity_Event *event) { Blah_List_appendElement(&recipient->events, event); //Add the new event to the entity's list }
C
#include<stdlib.h> #include<stdio.h> int main() { printf("Content-Type: text/html\n\n"); printf("<html><head><title>C Script</title></head>"); printf("<body>"); printf("<form action='a.out' method='post'><p>"); printf("<input type='submit' value='Click me!'/>"); printf("</p></form></body></html>"); return 0; }
C
# include <stdio.h> int main (void) { int i; do { printf("Please input a wind speed: \n"); scanf("%d", &i); if (i<1) printf ("If you wish to return to the start press C \n If you wish to quit, input Q \n"); fflush(stdin); scanf("%s", &q); } while(q!='Q'); return 0; }
C
/*// section pour inclure les en-tete #include <stdio.h> #include <stdlib.h> //section pour delarer les fonctions et variables globales int main(); // cette ligne est optionnelle int addition(int i, int j); // cette ligne est essentielle // variable globale int registre; //section pour delarer les fonctions // la fonction main int main(){ int a = 0; int b = 0; printf("donnez un entier ?\n"); scanf("%d",&a); printf("donnez un entier ?\n"); scanf("%d",&b); addition(a,b); printf("%d + %d = %d\n",a,b,recup); } // la fonction addition int addition(int i, int j) { return i + j; } //fonction multiplication int multiplication (int i , int j){ return i*j; } int division (int i, int j){ if (j==0){ printf("tu fais de la merde\n"); return 0; } else { return i/j; } } */ // section pour inclure les en-tete #include <stdio.h> #include <stdlib.h> #include <time.h> //section pour delarer les fonctions et variables globales #define TAILLE 1000000 int main(); void doesnotknow(); void affiche(); // variable globale int tableau[TAILLE]; //---------------------- //section pour realiser les fonctions // la fonction main int main(){ srand(time(NULL)); int i = 0; for(i = 0 ; i < TAILLE; i ++){ tableau[i] = rand(); } affiche(); doesnotknow(); affiche(); } void affiche(){ int i ; printf("DEBUT TABLEAU\n"); for(i=0;i<TAILLE;i++){ printf("[%d] = %d \n",i,tableau[i]); } printf("FIN TABLEAU\n"); } // la fonction de tri void doesnotknow() { int i = 0; int j = 0; int c = 0; int cpt =1; int compteurpermut=0; for(j=0;j< TAILLE;j++) { for(i=0;i< TAILLE-cpt;i++){ if ( tableau[i] > tableau[i+1] ) { c = tableau[i]; tableau[i] = tableau[i+1]; tableau[i+1] = c; compteurpermut++; } } if(compteurpermut==0){ j=TAILLE; } compteurpermut=0; cpt++; } }
C
#include <stdio.h> #include <stdlib.h> #define nomBin "RegistrosBin.bin" #define nomText "RegistrosText.txt" #define TAM 300 #define CON_MSJ 1 typedef struct { long dni; char apyn[36]; char sex; }t_pers; void crearBinario (char *nombre); void crearText (char *nombre); int abrirArchivo (FILE **fp, char *nombre, char *modo, int msj); void mostrarBin (FILE *fp); void mostrarText (FILE *fp); int main () { // varialbes FILE *fpABinario, *fpATexto; // programa // crearBinario(nomBin); crearText(nomText); /*if(abrirArchivo(&fpABinario, nomBin, "rb", CON_MSJ)) llenarBinario(&fpABinario);*/ if(abrirArchivo(&fpATexto, nomText, "rt", CON_MSJ)) llenarText(fpATexto); //mostrarArchivoBinario(fpABinario); mostrarArchivoTexto(fpATexto); // fin fclose(fpABinario); fclose(fpATexto); system("pause"); return 0; } void crearBinario (char *nombre) { FILE *fp = fopen(nombre, "wb"); } void crearText (char *nombre) { FILE *fp = fopen(nombre, "wt"); } int abrirArchivo (FILE **fp, char *nombre, char *modo, int msj) { if(*fp==NULL && CON_MSJ == msj) printf("Error al abrir '%s' en modo '%s'.\n", nombre, modo); return *fp!=NULL; } /* void llenarBinario (FILE **fp) { t_pers aux; long dni; printf("-----Ingreso de datos------\nDNI:0 (FIN INGRESO)\n"); printf("//--DATOS--//\n"); printf("DNI: "); scanf("%ld", dni); while (dni != 0) { aux.dni = dni; printf("NOMBRE: "); gets(aux.apyn); printf("\nSEXO: "); sscanf("%c", aux.sex); fwrite(aux, sizeof(aux), 1, fp); printf("\n//--DATOS--//\n"); printf("DNI: "); scanf("%ld", dni); } } */ void llenarText (FILE *fp) { long dni; char apyn[36]; char sex; printf("-----Ingreso de datos------\nDNI:0 (FIN INGRESO)\n"); printf("//--DATOS--//\n"); printf("DNI: "); scanf("%ld", dni); while (dni != 0) { printf("NOMBRE: "); gets(apyn); printf("\nSEXO: "); sscanf("%c", sex); fprintf(fp, "%08ld %-s %c", dni, apyn, sex); printf("\n//--DATOS--//\n"); printf("DNI: "); scanf("%ld", dni); } } //--mostrarArchivoBinario--// void mostrarArchivoBinario (FILE *fp) { t_pers aux; rewind(fp); printf("----RegistrosBinarios----\n"); while(fread(&aux, sizeof(t_pers), 1, fp)) printf("%ld %s %c\n",aux.dni, aux.apyn, aux.sex ); } //--mostrarArchivoTexto--// void mostrarArchivoTexto (FILE *fp) { char aux[TAM]; rewind(fp); printf("----RegistrosTexto----\n"); while(fgets(aux, sizeof(t_pers), fp)) printf("%s", aux); }
C
#include "nes.h" struct _ppu ppu = { .read = &nes_ppu_read_address, .write = &nes_ppu_write_address }; uint8_t nes_ppu_read_null(uint16_t address) { return 0; } void nes_ppu_write_null(uint16_t address, uint8_t value) { } uint8_t ppu_read_pattern_table(uint16_t address) { printf("READ PATTERN\n"); return 0; } void ppu_write_pattern_table(uint16_t address, uint8_t value) { printf("WROTE PATTERN\n"); } uint8_t ppu_read_name_table(uint16_t address) { printf("READ NAME\n"); return 0; } void ppu_write_name_table(uint16_t address, uint8_t value) { printf("WROTE NAME\n"); } uint8_t ppu_read_palette(uint16_t address) { printf("READ PALETTE\n"); return 0; } void ppu_write_palette(uint16_t address, uint8_t value) { printf("WROTE PALETTE\n"); } uint8_t (* nes_ppu_read[0x10])(uint16_t address) = { ppu_read_pattern_table, ppu_read_pattern_table, ppu_read_pattern_table, ppu_read_pattern_table, ppu_read_pattern_table, ppu_read_pattern_table, ppu_read_pattern_table, ppu_read_pattern_table, ppu_read_name_table, ppu_read_name_table, ppu_read_name_table, ppu_read_name_table, ppu_read_palette, ppu_read_palette, ppu_read_palette, ppu_read_palette }; void (* nes_ppu_write[0x10])(uint16_t address, uint8_t value) = { nes_ppu_write_null, nes_ppu_write_null, nes_ppu_write_null, nes_ppu_write_null, nes_ppu_write_null, nes_ppu_write_null, nes_ppu_write_null, nes_ppu_write_null, ppu_write_name_table, ppu_write_name_table, ppu_write_name_table, ppu_write_name_table, ppu_write_palette, ppu_write_palette, ppu_write_palette, ppu_write_palette }; uint8_t nes_ppu_read_address(uint16_t address) { return ppu.vram[address];//(nes_ppu_read[(address % NES_PPU_VRAM_SIZE) / 0x400])(address); } void nes_ppu_write_address(uint16_t address, uint8_t value) { ppu.vram[address] = value; (nes_ppu_write[(address % NES_PPU_VRAM_SIZE) / 0x400])(address, value); }
C
#include <stdio.h> int main() { int counter = 0; int num = 1; int div = 1; printf(" Prime Number from 1 to 100 are: \n"); printf("1\n"); while(num <= 100) { div = 2; counter = 0; while (div <= num/2) { if (num % div == 0) { counter = 1; break; } div++; } if (counter == 0 && num != 1) { printf("%i\n", num); } num++; } return 0; }
C
int binarySearch (char aray[][Length], int size, char search_item[LENGTH]){ int first = 0, last = size -1; bool found = false; int position = -1, middle; while (!found && first <= last){ middle = (first + last ) / 2; if ((strcmp(array[middle],search_item))==0){ position = middle; found = true; }else if (array[middle] < search_item) first = middle + 1; else last = middle -1; } return position; }
C
/* ** aff_prompt.c for in /home/buffat_b/couver-shell ** ** Made by ** Login <buffat_b@epitech.net> ** ** Started on Wed May 25 14:05:49 2016 ** Last update Sun Jun 5 16:16:46 2016 Bertrand Buffat */ #include "shell.h" void erase_down_lines(t_prompt *prompt, int nb_lines) { write(1, prompt->start_line_str, strlen(prompt->start_line_str)); while (nb_lines >= 0) { write(1, "\033[K", 3); write(1, "\033[B", 3); --nb_lines; } write(1, prompt->start_line_str, strlen(prompt->start_line_str)); } void is_out_of_screen(t_prompt *prompt, int nb_lines_buffer) { if (prompt->start_line + nb_lines_buffer > prompt->nblines) { fill_tab_caps(prompt->start_line_str, --prompt->start_line, prompt->start_col); write(1, "\n", 1); } } void aff_line_prompt(t_prompt *prompt) { write(1, "\033[36;1m", strlen("\033[36;1m")); write(1, prompt->prompt, prompt->size_prompt); write(1, "\033[31;1m", strlen("\033[31;1m")); write(1, prompt->pwd, prompt->size_pwd); write(1, " ", 1); write(1, "\033[32;1m", strlen("\033[32;1m")); put_nbr(prompt->count_char); write(1, " ", 1); write(1, "\033[33;1m", strlen("\033[33;1m")); put_nbr(prompt->nbr); if (!prompt->ret) { write(1, "\033[0m", strlen("\033[0m")); write(1, " :)", 3); } else { write(1, "\033[31;5m", strlen("\033[31;5m")); write(1, " :(", 3); } write(1, "\033[0m", strlen("\033[0m")); write(1, "\033[1m", strlen("\033[1m")); write(1, " - ", 3); write(1, "\033[0m", strlen("\033[0m")); } void aff_total_line(t_prompt *prompt) { aff_line_prompt(prompt); write(1, prompt->line, prompt->count_char); if (!prompt->size_completion) return ; write(1, "\033[30;1m", strlen("\033[30;1m")); write(1, prompt->auto_completion + (prompt->count_char - prompt->offset), prompt->size_completion - (prompt->count_char - prompt->offset)); write(1, "\033[0m", strlen("\033[0m")); } void aff_prompt(t_prompt *prompt) { int nb_lines_buffer; int total_count; total_count = prompt->size_pwd + prompt->size_completion + prompt->size_prompt + prompt->count_char + (prompt->start_col - 1) + size_of_int(prompt->nbr) + size_of_int(prompt->count_char) + 8; nb_lines_buffer = total_count / prompt->nbcols; is_out_of_screen(prompt, nb_lines_buffer); erase_down_lines(prompt, nb_lines_buffer); aff_total_line(prompt); move_cursor_back(prompt); }
C
int arr[] = {0,0,0,0,0,0,0,0,0,0}; int *base = arr; void add(int val, int offset){ val = arr[offset] + val; arr[offset] = val; } void main(){ int var1 = 1; int var2 = 2; add(3,4); add(var1,var2); for (int x = 0; x < 10; x++) printf("%d\n", arr[x]); }
C
/** * Tree data structure header file */ #ifndef TREE_H #define TREE_H #include <stdio.h> #include <stdlib.h> typedef struct treeNode TreeNode; // Tree node struct struct treeNode { char *path; char *name; TreeNode *children; TreeNode *siblings; int level; }; typedef struct tree Tree; // Tree struct struct tree { TreeNode *root; }; /****** Tree Implementation ******/ // Create a tree with specified tree node as root Tree *CreateTree(TreeNode *root); // Destroy specified tree void DestroyTree(TreeNode *root); /****** Tree node Implementation ******/ // Create a tree node, using specified path and name TreeNode *CreateTreeNode(char *path, char *name); // Add a child to the specified tree node void AddChild(TreeNode *root, TreeNode *nodeToAdd); // Destroy specified tree node void DestroyTreeNode(TreeNode *node); // Print the specified tree void PrintTree(TreeNode *root); #endif
C
#include "cmod.h" #include "timer.h" #include "oi.h" #include "sensors.h" //drive straight until you hit something void findWall(void) { drive(100); for (;;) { delayMs(100); getBumps(); if (bumpLeft || bumpRight) { stop(); break; //escape for loop } } } //determines the wall sensor strength // value from 0-4095, // 4095 => as close to wall as possible uint16_t getWallDistance(void) { uint8_t hi, lo; byteTx(CmdSensors); byteTx(WallPID); hi = byteRx(); lo = byteRx(); return (hi << 8) | lo; } //determines whether bump sensors are active void getBumps(void) { uint8_t bumps; byteTx(CmdSensors); byteTx(BumpAndWheeldropPID); bumps = byteRx(); bumpLeft = bumps & (1 << 1); bumpRight = bumps & (1 << 0); } //print characters containing in char array //to serial - returns length of string // -useful for debugging int transmit(char* string) { int i; int length = strlen(string); //point to serial monitor setSerialDestination(SERIAL_USB); //send data to USB for (i=0; i<length; i++) { byteTx(string[i]); } //point back to create setSerialDestination(SERIAL_CREATE); return length; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* move_util.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: marvin <marvin@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/04/25 12:33:01 by marvin #+# #+# */ /* Updated: 2020/04/25 12:33:01 by marvin ### ########.fr */ /* */ /* ************************************************************************** */ #include "lem_in.h" void free_positions(t_pos **pos) { t_pos *tmp; if (pos) { while (*pos) { tmp = (*pos); (*pos) = (*pos)->next; free(tmp); } } } t_pos *new_position(int ant, t_room *room) { t_pos *pos; if (!(pos = (t_pos *)malloc(sizeof(t_pos)))) error(MOVE_ERROR); pos->ant = ant; pos->room = room; pos->next = NULL; return (pos); } void add_position(t_lemin *lemin, t_pos *pos) { t_pos *prev; t_pos *cur; prev = NULL; cur = lemin->pos; if (cur) { while (cur && pos->ant > cur->ant) { prev = cur; cur = cur->next; } if (!prev) lemin->pos = pos; else prev->next = pos; pos->next = cur; } else lemin->pos = pos; }
C
/* ** EPITECH PROJECT, 2019 ** BSQ ** File description: ** */ #include <stdlib.h> #include "my.h" void fs_understand_return_of_read(int fd, char *buffer, int size) { int buff_size = read(fd, buffer, size); if (buff_size == -1) my_putstr("read failed\n"); if (buff_size == 0) my_putstr("read has nothing more to read\n"); if (buff_size < size) my_putstr("read didn't complete the entire buffer_n"); if (buff_size == size) my_putstr("read completed the entire buffer\n"); return; } int fs_open_file(char const *filepath) { int fd = open(filepath, O_RDONLY); if (fd == -1) my_putstr("FAILURE\n"); else my_putstr("SUCCESS\n"); return fd; } void fs_cat_500_bytes(char const *filepath) { char *buffer = malloc(sizeof(char) * 500); int fd = fs_open_file(filepath); fs_understand_return_of_read(fd, buffer, 500); for (int i = 0; i < 500; i++) my_putchar(buffer[i]); close(fd); return; } void fs_cat_x_bytes(char const *filepath, int x) { char *buffer = malloc(sizeof(char) * x); int fd = fs_open_file(filepath); fs_understand_return_of_read(fd, buffer, x); for (int i = 0; i < x; i++) my_putchar(buffer[i]); close(fd); return; } void fs_print_first_line(char const *filepath) { char *buffer = malloc(sizeof(char) * 512); int fd = fs_open_file(filepath); fs_understand_return_of_read(fd, buffer, 512); for (int i = 0; buffer[i] != '\n', i++) my_putchar(buffer[i]); close(fd); return; } int main(int argc, char **argv) { }
C
#include "bggl3.h" #include <math.h> int bggl3_id_int, bggl3_id_float, bggl3_id_cons, bggl3_id_null; int bggl3_id_symbol, bggl3_id_string, bggl3_id_complex; int bggl3_id_fvector; elem bggl3_print(BGGL3_State *ctx, elem args) { elem a, c; int i; c=args; while(c) { a=BGGL3_CAR(c); i=BGGL3_GetTypeID(a); if(i==bggl3_id_int)printf("%d", BGGL3_TOINT(a)); if(i==bggl3_id_float)printf("%g", BGGL3_TOFLOAT(a)); if(i==bggl3_id_string)printf("%s", a); if(i==bggl3_id_symbol)printf("%s", a); if(i==bggl3_id_cons)BGGL3_Print(a); if(i==bggl3_id_complex)BGGL3_Print(a); if(i==bggl3_id_fvector)BGGL3_Print(a); c=BGGL3_CDR(c); if(c)printf(" "); } return(NULL); } elem bggl3_println(BGGL3_State *ctx, elem args) { bggl3_print(ctx, args); printf("\n"); return(NULL); } elem bggl3_sqrt(BGGL3_State *ctx, elem args) { float f; f=BGGL3_TOFLOAT(BGGL3_CAR(args)); if(f<0) { return(BGGL3_COMPLEX(0, sqrt(-f))); }else { return(BGGL3_FLOAT(sqrt(f))); } } elem bggl3_log2(BGGL3_State *ctx, elem args) { float f; f=BGGL3_TOFLOAT(BGGL3_CAR(args)); return(BGGL3_FLOAT(log2(f))); } elem bggl3_log10(BGGL3_State *ctx, elem args) { float f; f=BGGL3_TOFLOAT(BGGL3_CAR(args)); return(BGGL3_FLOAT(log10(f))); } elem bggl3_ln(BGGL3_State *ctx, elem args) { float f; f=BGGL3_TOFLOAT(BGGL3_CAR(args)); return(BGGL3_FLOAT(log(f))); } elem bggl3_log(BGGL3_State *ctx, elem args) { float f, g; f=BGGL3_TOFLOAT(BGGL3_CAR(args)); g=BGGL3_TOFLOAT(BGGL3_CADR(args)); return(BGGL3_FLOAT(log(g)/log(f))); } elem bggl3_floor(BGGL3_State *ctx, elem args) { float f; f=BGGL3_TOFLOAT(BGGL3_CAR(args)); return(BGGL3_FLOAT(floor(f))); } elem bggl3_ceil(BGGL3_State *ctx, elem args) { float f; f=BGGL3_TOFLOAT(BGGL3_CAR(args)); return(BGGL3_FLOAT(ceil(f))); } elem bggl3_round(BGGL3_State *ctx, elem args) { float f; f=BGGL3_TOFLOAT(BGGL3_CAR(args)); return(BGGL3_FLOAT(round(f))); } elem bggl3_sin(BGGL3_State *ctx, elem args) { float f; f=BGGL3_TOFLOAT(BGGL3_CAR(args)); return(BGGL3_FLOAT(sin(f))); } elem bggl3_cos(BGGL3_State *ctx, elem args) { float f; f=BGGL3_TOFLOAT(BGGL3_CAR(args)); return(BGGL3_FLOAT(cos(f))); } elem bggl3_tan(BGGL3_State *ctx, elem args) { float f; f=BGGL3_TOFLOAT(BGGL3_CAR(args)); return(BGGL3_FLOAT(tan(f))); } elem bggl3_asin(BGGL3_State *ctx, elem args) { float f; f=BGGL3_TOFLOAT(BGGL3_CAR(args)); return(BGGL3_FLOAT(asin(f))); } elem bggl3_acos(BGGL3_State *ctx, elem args) { float f; f=BGGL3_TOFLOAT(BGGL3_CAR(args)); return(BGGL3_FLOAT(acos(f))); } elem bggl3_atan(BGGL3_State *ctx, elem args) { float f; f=BGGL3_TOFLOAT(BGGL3_CAR(args)); return(BGGL3_FLOAT(atan(f))); } elem bggl3_atan2(BGGL3_State *ctx, elem args) { float f, g; f=BGGL3_TOFLOAT(BGGL3_CAR(args)); g=BGGL3_TOFLOAT(BGGL3_CADR(args)); return(BGGL3_FLOAT(atan2(f, g))); } elem bggl3_real(BGGL3_State *ctx, elem args) { return(BGGL3_FLOAT(BGGL3_GETREAL(BGGL3_CAR(args)))); } elem bggl3_imag(BGGL3_State *ctx, elem args) { return(BGGL3_FLOAT(BGGL3_GETIMAG(BGGL3_CAR(args)))); } elem bggl3_abs(BGGL3_State *ctx, elem args) { float f, g; f=BGGL3_GETREAL(BGGL3_CAR(args)); g=BGGL3_GETIMAG(BGGL3_CAR(args)); return(BGGL3_FLOAT(sqrt(f*f+g*g))); } elem bggl3_angle(BGGL3_State *ctx, elem args) { float f, g; if(BGGL3_COMPLEXP(BGGL3_CAR(args))) { f=BGGL3_GETREAL(BGGL3_CAR(args)); g=BGGL3_GETIMAG(BGGL3_CAR(args)); return(BGGL3_FLOAT(atan2(g, f))); } return(NULL); } elem bggl3_conj(BGGL3_State *ctx, elem args) { float f, g; f=BGGL3_GETREAL(BGGL3_CAR(args)); g=BGGL3_GETIMAG(BGGL3_CAR(args)); return(BGGL3_COMPLEX(f, -g)); } elem bggl3_fact(BGGL3_State *ctx, elem args) { float f, g; int i; i=BGGL3_TOINT(BGGL3_CAR(args)); f=1; while(i>1) { f*=i; i--; } return(BGGL3_FLOAT(f)); } elem bggl3_graph(BGGL3_State *ctx, elem args); elem bggl3_load(BGGL3_State *ctx, elem args) { elem a; a=BGGL3_LoadFile(ctx, BGGL3_CAR(args)); return(a); } elem bggl3_dumpmesh(BGGL3_State *ctx, elem args) { FILE *fd; elem a, c; float *fa, *fb, *fc; fd=fopen(BGGL3_CAR(args), "wt"); if(!fd)return(NULL); c=BGGL3_CADR(args); while(c) { a=BGGL3_CAR(c); fa=(float *)BGGL3_CAR(a); fb=(float *)BGGL3_CADR(a); fc=(float *)BGGL3_CADDR(a); fprintf(fd, "%f %f %f %f %f %f %f %f %f 0xFFFFFF\n", fa[0], fa[1], fa[2], fb[0], fb[1], fb[2], fc[0], fc[1], fc[2]); c=BGGL3_CDR(c); } fclose(fd); return(NULL); } void BGGL3_InitBuiltin() { BGGL3_BindValue("PI", "PI", BGGL3_FLOAT(M_PI)); BGGL3_BindValue("E", "E", BGGL3_FLOAT(M_E)); BGGL3_BindValue("I", "Complex i", BGGL3_COMPLEX(0, 1)); BGGL3_AddBuiltin("print", "print stuff", &bggl3_print, -1); BGGL3_AddBuiltin("println", "print line", &bggl3_println, -1); BGGL3_InitBuiltinOpr(); BGGL3_InitBuiltinVector(); BGGL3_AddBuiltin("sqrt", "square root", &bggl3_sqrt, 1); BGGL3_AddBuiltin("log2", "log 2", &bggl3_log2, 1); BGGL3_AddBuiltin("log10", "log 10", &bggl3_log10, 1); BGGL3_AddBuiltin("ln", "log e", &bggl3_ln, 1); BGGL3_AddBuiltin("log", "log x", &bggl3_log, 2); BGGL3_AddBuiltin("floor", "floor x", &bggl3_floor, 1); BGGL3_AddBuiltin("ceil", "ceil x", &bggl3_ceil, 1); BGGL3_AddBuiltin("round", "round x", &bggl3_round, 1); BGGL3_AddBuiltin("sin", "sine", &bggl3_sin, 1); BGGL3_AddBuiltin("cos", "cosine", &bggl3_cos, 1); BGGL3_AddBuiltin("tan", "tangent", &bggl3_tan, 1); BGGL3_AddBuiltin("asin", "arc sine", &bggl3_asin, 1); BGGL3_AddBuiltin("acos", "arc cosine", &bggl3_acos, 1); BGGL3_AddBuiltin("atan", "arc tangent", &bggl3_atan, 1); BGGL3_AddBuiltin("atan2", "arc tangent", &bggl3_atan2, 2); BGGL3_AddBuiltin("real", "real part", &bggl3_real, 1); BGGL3_AddBuiltin("imag", "imaginary part", &bggl3_imag, 1); BGGL3_AddBuiltin("abs", "abs value/complex arg", &bggl3_abs, 1); BGGL3_AddBuiltin("angle", "complex phase angle", &bggl3_angle, 1); BGGL3_AddBuiltin("conj", "complex conjugate", &bggl3_conj, 1); BGGL3_AddBuiltin("fact", "factorial", &bggl3_fact, 1); BGGL3_AddBuiltin("load", "load script", &bggl3_load, 1); BGGL3_AddBuiltin("graph", "graph function", &bggl3_graph, 6); BGGL3_AddBuiltin("dumpmesh", "dump tri mesh", &bggl3_dumpmesh, 2); }
C
#include <stdio.h> void main(){ int contador = 1; int numero; do{ printf("digite um numero: "); scanf("%d", &numero); if(numero % 3 == 0){ printf("o numero %d e divisivel por 3 \n", numero); } contador++; } while(contador <= 10); }
C
#include <stdio.h> typedef struct a { int i; int j; }a; *a f(a x) { a *r = x; return r; } int main(void) { a *x = { 56,89 }; a *y = f(x); printf("%d\n", y->j); return 0; }
C
/* * jpg-recover -- Extract JPEG/CR2 files from raw bytes (filesystem images etc.). * Copyright (c) 2011, Matus Tejiscak <functor.sk@ziman>. * Released under the BSD license: http://creativecommons.org/licenses/BSD/ */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include "globals.h" #include "jpeg.h" #include "tiff.h" /** * Recover image files from the given stream. * @param f The stream. * @param jpeg True to run JPEG recovery. * @param cr2 True to run CR2 recovery. * @param prefix The prefix used to generate the names of the recovered files. */ void recoverImages(FILE * f, bool_t jpeg, bool_t cr2, bool_t requireE0E1, const char * prefix) { /** Last two bytes read, big-endian. */ uint16_t state = 0; /** The index of the next recovered file. */ int index = 0; /* While not EOF... */ while (!feof(f)) { /* Update the state... */ state = (state << 8) | fgetc(f); /* Compare with known startcodes. */ switch (state) { case 0xFFD8: /* JPEG Start-Of-Image */ if (jpeg) index = recoverJpeg(f, index, requireE0E1, prefix); break; case 0x4949: /* TIFF endianity sign */ case 0x4D4D: if (cr2) { /* Try to recover the TIFF file. */ off_t beforeTiff = ftellx(f); int newIndex = recoverTiff(f, index, state == 0x4D4D, prefix); /* Check the success. */ if (newIndex == index) { /* Unsuccessful -> rewind to get at least the JPEG thumbnails. */ fseekx(f, beforeTiff); } else { index = newIndex; } } break; } } /* A report for the user to make them sure. */ printf("End of image reached, quitting.\n"); } /** Print usage, don't quit. */ void usage() { static const char * const content = "usage:\n" " ./recover [-j] [-e] [-r] [-p <prefix>] [-h/--help] /dev/memory_card\n" "\n" "Available options:\n" " -j -- Do not recover JPEG files.\n" " -e -- Recover JPEG files embedded in other files.\n" " Note: this lifts certain requirements put on the files being\n" " recovered; some of the resulting files may be unreadable\n" " (default: do not recover embedded JPEGs)\n" " -r -- Do not recover CR2 files.\n" " -p <prefix> -- Use this prefix for recovered files. May contain slashes.\n" " (default: \"recovered\")\n" " -h / --help -- Print this help and quit successfully.\n" "\n" "By default, the program will recover both JPEG files and CR2 files.\n" ; fprintf(stderr, "%s", content); } int main(int argc, char ** argv) { if (argc > 1) { /* Default options. */ bool_t jpeg = true; bool_t cr2 = true; bool_t requireE0E1 = true; const char * prefix = "recovered"; /* We have at least one argument, parse the commandline options. */ char ** argEnd = argv + argc; char ** curArg = argv + 1; while (curArg < argEnd) { if (!strcmp("-j", *curArg)) { jpeg = false; } else if (!strcmp("-r", *curArg)) { cr2 = false; } else if (!strcmp("-e", *curArg)) { requireE0E1 = false; } else if (!strcmp("-p", *curArg)) { if (++curArg >= argEnd) die("-p requires an argument: the prefix."); prefix = *curArg; } else if (!strcmp("--help", *curArg) || !strcmp("-h", *curArg)) { usage(); return 0; } else break; /* Move on... */ ++curArg; } /* Some sanity checks. */ if (!jpeg && !cr2) die("Both JPEG and CR2 recovery disabled, nothing to do."); if (curArg >= argEnd) die("Missing the last argument: /dev/memory_card or image file."); if (strlen(prefix) > MAX_PREFIX_LENGTH) die("Prefix too long."); /* Try to open the file. */ FILE * f = fopen(*curArg, "rb"); if (!f) { /* Bad luck opening the file. */ perror(*curArg); return 1; } /* Recover the images. */ printf("Recovering images from %s...\n", *curArg); recoverImages(f, jpeg, cr2, requireE0E1, prefix); /* Close the input file. */ fclose(f); } else { /* Print usage info. */ usage(); return 1; } return 0; }
C
#include <stdio.h> #include <string.h> #include "first.h" int main(int argc, char* argv[]) { unsigned short x; char* command; unsigned short arg1; unsigned short arg2; char* fileName = argv[1]; FILE* fp = fopen(fileName, "r"); fscanf(fp, "%hu", &x); while(fscanf(fp,"%s\t%hu\t%hu", command, &arg1, &arg2) != EOF){ if(strcmp(command, "set") == 0) { x = setNthBit(x, arg1, arg2); printf("%hu\n", x); } else if(strcmp(command, "comp") == 0) { x = setNthBitComplement(x, arg1); printf("%hu\n", x); }else if(strcmp(command, "get") == 0) { printf("%hu\n", getNthBit(x, arg1)); } } fclose(fp); return 0; } unsigned short setNthBit(unsigned short x, unsigned short n, unsigned short v) { if(v == 0 && getNthBit(x, n) == 1) { return x & ~(1<<n); } else if(v == 1 && getNthBit(x, n) == 0) { return x | (1<<n); } return x; } unsigned short setNthBitComplement(unsigned short x, unsigned short n) { return x ^ (1<<n); } unsigned short getNthBit(unsigned short x, unsigned short n) { return (x>>n) & 1; }
C
#include<stdio.h> int main() {int n,m,i,j, k, c, A=0, B=0; printf("Enter height n and width m\n"); scanf("%d %d",&n,&m); int a[n][m]; for(i=0;i<=n-1;i++){ for(j=0;j<=m-1;j++){ printf("Enter a[%d][%d]\n",i,j); scanf("%d",&a[i][j]); } } for(i=0;i<=n*m-1;i++){if((i-1)/m<i/m){ printf("\n"); }; printf("%d ", a[i/m][i%m]); } printf("\n\n"); for(i=0;i<m-1; i++) { for(j=0;j<m-1-i;j++){ for(k=0;k<=n-1;k++){ A+=a[k][j]; B+=a[k][j+1]; } if(A>B){ for(k=0;k<=n-1;k++){ c = a[k][j]; a[k][j] = a[k][j+1] ; a[k][j+1] = c; } } A=0;B=0;}} for(i=0;i<=n*m-1;i++){if((i-1)/m<i/m){ printf("\n"); }; printf("%d ", a[i/m][i%m]); } return 0; }
C
#include "../../common/common.h" #include "../../common/APP.h" /* *Find mac flag in table switch *@author SUN ZHOGNJIAN */ void getIpSwitch(){ int rc; char* sql = malloc(100); memset(sql, 0, 100); strcat(sql, "SELECT * FROM switch;"); char* zErrMsg = 0; rc = sqlite3_exec(db, sql, getSwitchCallback, IP_SA_Flag, &zErrMsg); //When sql format is incorrect if( rc != SQLITE_OK ){ printf("get switch error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } rc = sqlite3_exec(db, sql, getSwitchCallback, IP_DA_Flag, &zErrMsg); //When sql format is incorrect if( rc != SQLITE_OK ){ printf("get switch error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } free(sql); } /* *If set table switch successful *@parameter argc is the variable number *@parameter argv is the variable array(ID, MAC_DA, MAC_SA, IPv4, IP_PROTOCOL, IP_SA, IP_DA, Port_S, Port_D, UDP, TCP, ARP, ICMP, IP, Ip) *@parameter azColusername is the variable name array *@author SUN ZHOGNJIAN */ static int setIpSwitchCallback(void *NotUsed, int argc, char **argv, char **azColusername){ int i; char switchStr[13] = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; if(strcmp(argv[0], "1") == 0){ switchStr[2] = 0; }else if(strcmp(argv[0], "2") == 0){ switchStr[2] = 128; } for(i=1; i<9; i++){ switchStr[3] |= (atoi(argv[i]) << 8-i); } for(i=9; i<argc; i++){ switchStr[4] |= (atoi(argv[i]) << 14-i); } for(i=0; i<13; i++){ printf("%d ", switchStr[i]); } int fd; if((fd=open_port(fd,3))<0){ printf("open_port error"); return; } if((i=set_opt(fd,9600,8,'N',1))<0){ printf("set_opt error"); return; } write(fd,switchStr,13); close(fd); return 0; } /* *Set mac flag in table switch *@author SUN ZHOGNJIAN */ void setIpSwitch(char* field, char* state){ int rc; char* zErrMsg = 0; char* sql = (char*)malloc(100); memset(sql, 0, 100); //update switch according to row ID strcat(sql, "UPDATE switch SET "); if(strcmp(field, "inner") == 0){ strcat(sql, "IP_SA=\'"); }else if(strcmp(field, "outer") == 0){ strcat(sql, "IP_DA=\'"); } if(strcmp(state, "true") == 0){ strcat(sql, "1"); }else if(strcmp(state, "false")==0){ strcat(sql, "0"); } strcat(sql, "\' WHERE ID="); if(strcmp(field, "inner") == 0){ strcat(sql, "1;"); }else if(strcmp(field, "outer") == 0){ strcat(sql, "2;"); } strcat(sql, "SELECT * FROM switch;"); printf("sql = %s", sql); rc = sqlite3_exec(db, sql, setIpSwitchCallback, 0, &zErrMsg); //Access database error if( rc != SQLITE_OK ){ printf("updateSwitch error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } free(sql); } /* *Set mac flag in table switch *@author SUN ZHOGNJIAN */ cJSON* makeIpJSON(char* id, char* eth , char* addr, char* ipStr){ cJSON* pJSON = NULL; pJSON = cJSON_CreateObject(); if(pJSON == NULL){ //Error happend here return NULL; } cJSON_AddStringToObject(pJSON, "id", id); cJSON_AddStringToObject(pJSON, "eth", eth); cJSON_AddStringToObject(pJSON, "addr", addr); cJSON_AddStringToObject(pJSON, "ip", ipStr); return pJSON; } cJSON* objects[32]; int jSON_Index = 0; /* *If find flag in table switch *@parameter switchFlag is the flag index, check it in variable array *@parameter argc is the variable number *@parameter argv is the variable array(ID, MAC_DA, MAC_SA, IPv4, IP_PROTOCOL, IP_SA, IP_DA, Port_S, Port_D, UDP, TCP, ARP, ICMP, IP, Ip) *@parameter azColusername is the variable name array *@author SUN ZHOGNJIAN */ int getIpCallback(void *Notused, int argc, char **argv, char **azColName){ int i; char ipStr[16]; memset(ipStr, 0 ,18); for(i = 0; i < 7; i++){ switch(i){ case 0: break; case 1: break; case 2: break; case 3: strcat(ipStr, argv[i]); strcat(ipStr, "."); break; case 4: strcat(ipStr, argv[i]); strcat(ipStr, "."); break; case 5: strcat(ipStr, argv[i]); strcat(ipStr, "."); break; case 6: strcat(ipStr, argv[i]); break; } } objects[jSON_Index++] = makeIpJSON(argv[0], argv[1], argv[2], ipStr); if(jSON_Index == 32){ int i; cJSON *prev; cJSON *root = cJSON_CreateArray(); for (i = 0; i < 32; i++) { if (!i) { root -> child = objects[i]; } else { prev -> next = objects[i]; objects[i] -> prev = prev; } prev = objects[i]; } printf("%s \n", cJSON_Print(root)); } return 0; } void getIp(){ int rc; char* sql = malloc(100); memset(sql, 0, 100); strcat(sql, "SELECT * FROM ip;"); char* zErrMsg = 0; rc = sqlite3_exec(db, sql, getIpCallback, 0, &zErrMsg); //When sql format is incorrect if( rc != SQLITE_OK ){ printf("SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } free(sql); } void getIpJSON(char* input, char* id, char* eth, char* addr, char* IP_3, char* IP_2, char* IP_1, char* IP_0){ cJSON *json , *idJSON , *ethJSON , *addrJSON , *IP_3JSON , *IP_2JSON , *IP_1JSON , *IP_0JSON; json = cJSON_Parse(input); if (!json){ printf("Error before: [%s]\n",cJSON_GetErrorPtr()); } else{ idJSON = cJSON_GetObjectItem( json , "id"); strcpy(id,idJSON -> valuestring); printf("getJSON id = %s ", id); ethJSON = cJSON_GetObjectItem( json , "eth"); strcpy(eth,ethJSON -> valuestring); addrJSON = cJSON_GetObjectItem( json , "addr"); strcpy(addr,addrJSON -> valuestring); IP_3JSON = cJSON_GetObjectItem( json , "IP_3"); strcpy(IP_3,IP_3JSON -> valuestring); IP_2JSON = cJSON_GetObjectItem( json , "IP_2"); strcpy(IP_2,IP_2JSON -> valuestring); IP_1JSON = cJSON_GetObjectItem( json , "IP_1"); strcpy(IP_1,IP_1JSON -> valuestring); IP_0JSON = cJSON_GetObjectItem( json , "IP_0"); strcpy(IP_0,IP_0JSON -> valuestring); cJSON_Delete(json); } } int setIpRowCallback(void* NotUsed, int argc, char **argv, char **azColusername){ int i; char* stopstring; char IpRowStr[13] = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; for(i = 0; i < argc; i++){ switch(i){ case 0: break; case 1: IpRowStr[i] = 0; break; default: IpRowStr[i] = (int)strtol(argv[i], &stopstring, 10); break; } } int fd; if((fd=open_port(fd,3))<0){ printf("open_port error"); return; } if((i=set_opt(fd,9600,8,'N',1))<0){ printf("set_opt error"); return; } printf("fd=%d\n",fd); for(i = 0; i < 13; i++){ printf("%d ", IpRowStr[i]); } write(fd,IpRowStr,13); usleep(30000); int nread = 0; int ret; struct pollfd event; char readBuf[10]; memset(readBuf, 0, 10); memset(&event,0,sizeof(event)); event.fd = fd; event.events = POLLIN; ret=poll((struct pollfd *)&event,1,50); if(ret<0){ printf("poll error!\n"); exit(1); } if(ret==0){ printf("Time out!\n"); } if(event.revents&POLLERR){ //revents是由内核记录的实际发生的事件,events是进程等待的事件 printf("Device error!\n"); exit(1); } if(event.revents&POLLIN){ nread = read(fd,readBuf,10); printf("nread = %d,%s\n",nread,readBuf); } close(fd); return 0; } void setIpRow(char* id, char* eth, char* addr, char* IP_3, char* IP_2, char* IP_1, char* IP_0){ int rc; char* zErrMsg = 0; char* sql = (char*)malloc(200); memset(sql, 0, 200); //update switch according to row ID strcat(sql, "UPDATE ip SET IP_3=\'"); strcat(sql, IP_3); strcat(sql, "\' , IP_2=\'"); strcat(sql, IP_2); strcat(sql, "\' , IP_1=\'"); strcat(sql, IP_1); strcat(sql, "\' , IP_0=\'"); strcat(sql, IP_0); strcat(sql, "\' WHERE addr=\'"); strcat(sql, addr); strcat(sql, "\';"); strcat(sql, "SELECT * FROM ip WHERE addr = \'"); strcat(sql, addr); strcat(sql, "\';"); printf("%s ", sql); rc = sqlite3_exec(db, sql, setIpRowCallback, 0, &zErrMsg); //Access database error if( rc != SQLITE_OK ){ printf("update Ip error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } free(sql); }
C
#include <stdio.h> #include <stdlib.h> #include <pthread.h> int ar[1000]; int chunk_size=100; void * TestThread(void *arg) { int i=0,sum1=0; int start=(int)arg; int end=start+chunk_size; for ( i=start;i<end;i++) sum1=sum1+ar[i]; return ((void*)sum1); } int main () { int i=0; for ( i=0;i<1000;i++) ar[i]=i; int sum[10]; int sum1=0; pthread_t thread_t1[10]; for (i=0;i<10;i++) pthread_create(&thread_t1[i],NULL,TestThread,((void*)(i*100))); for (i=0;i<10;i++) pthread_join(thread_t1[i],(void**)&sum[i]); for (i=0;i<10;i++) sum1=sum1+sum[i]; printf("\nValue returned By Thread %d\n", sum1); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include "shet.h" #include "shet_json.h" #include "jsmn.h" #ifdef SHET_DEBUG #define DPRINTF(...) fprintf(stderr, __VA_ARGS__) #else #define DPRINTF(...) #endif //////////////////////////////////////////////////////////////////////////////// // Internal deferred utility functions/macros //////////////////////////////////////////////////////////////////////////////// // Given shet state, makes sure that the deferred is in the callback list, // adding it if it isn't already present. static void add_deferred(shet_state_t *state, shet_deferred_t *deferred) { shet_deferred_t **deferreds = &(state->callbacks); // Check to see if the deferred is already present shet_deferred_t *iter = (*deferreds); for (; iter != NULL; iter = iter->next) if (iter == deferred) break; // Add the deferred if it wasn't already added if (iter == NULL) { (deferred)->next = *(deferreds); *(deferreds) = (deferred); } } // Given a shet state make sure that the deferred is not in the callback list, // removing it if it is. void remove_deferred(shet_state_t *state, shet_deferred_t *deferred) { // Find and remove the deferred, if present. shet_deferred_t **iter = &(state->callbacks); for (; (*iter) != NULL; iter = &((*iter)->next)) { if ((*iter) == deferred) { *iter = (*iter)->next; break; } } } // Find a deferred callback for the return with the given ID. // Return NULL if not found. static shet_deferred_t *find_return_cb(shet_state_t *state, int id) { shet_deferred_t *callback = state->callbacks; for (; callback != NULL; callback = callback->next) if (callback->type == SHET_RETURN_CB && callback->data.return_cb.id == id) break; if (callback == NULL) { DPRINTF("No callback for id %d\n", id); return NULL; } return callback; } // Find a callnack for the named event/property/action. // Return NULL if not found. static shet_deferred_t *find_named_cb(shet_state_t *state, const char *name, shet_deferred_type_t type) { shet_deferred_t *callback = state->callbacks; for (; callback != NULL; callback = callback->next) if ( ( type == SHET_EVENT_CB && callback->type == SHET_EVENT_CB && strcmp(callback->data.event_cb.event_name, name) == 0) || ( type == SHET_PROP_CB && callback->type == SHET_PROP_CB && strcmp(callback->data.prop_cb.prop_name, name) == 0) || ( type == SHET_ACTION_CB && callback->type == SHET_ACTION_CB && strcmp(callback->data.action_cb.action_name, name) == 0)) break; if (callback == NULL) { DPRINTF("No callback under name %s with type %d\n", name, type); return NULL; } return callback; } //////////////////////////////////////////////////////////////////////////////// // Internal command processing functions //////////////////////////////////////////////////////////////////////////////// // Deal with a shet 'return' command, calling the appropriate callback. static shet_processing_error_t process_return(shet_state_t *state, shet_json_t json) { if (json.token[0].size != 4) { DPRINTF("Return messages should be of length 4\n"); return SHET_PROC_MALFORMED_RETURN; } // Requests sent by uSHET always use integer IDs. shet_json_t id_json; id_json.line = json.line; id_json.token = json.token + 1; if (!SHET_JSON_IS_TYPE(id_json, SHET_INT)) return SHET_PROC_MALFORMED_RETURN; int id = SHET_PARSE_JSON_VALUE(id_json, SHET_INT); // The success/fail value should be an int. Note this string is always a // substring surrounded by non-numbers so atoi is safe. shet_json_t success_json; success_json.line = json.line; success_json.token = json.token + 3; if (!SHET_JSON_IS_TYPE(success_json, SHET_INT)) return SHET_PROC_MALFORMED_RETURN; int success = SHET_PARSE_JSON_VALUE(success_json, SHET_INT); // The returned value can be any JSON object shet_json_t value_json; value_json.line = json.line; value_json.token = json.token+4; // Find the right callback. shet_deferred_t *callback = find_return_cb(state, id); // We want to leave everything in a consistent state, as the callback might // make another call to this lib, so get the info we need, "free" everything, // *then* callback. // Select either the success or fail callback (or fall-back on the shet_callback_t callback_fun = NULL; void *user_data = state->error_callback_data; if (callback != NULL) { if (success == 0) callback_fun = callback->data.return_cb.success_callback; else if (success != 0) callback_fun = callback->data.return_cb.error_callback; user_data = callback->data.return_cb.user_data; remove_deferred(state, callback); } // Fall back to default error callback. if (success != 0 && callback_fun == NULL) { callback_fun = state->error_callback; user_data = state->error_callback_data; } // Run the callback if it's not null. if (callback_fun != NULL) callback_fun(state, value_json, user_data); return SHET_PROC_OK; } // Process a command from the server static shet_processing_error_t process_command(shet_state_t *state, shet_json_t json, command_callback_type_t type) { bool accepts_var_args; switch (type) { case SHET_EVENT_DELETED_CCB: case SHET_EVENT_CREATED_CCB: case SHET_GET_PROP_CCB: accepts_var_args = false; if (json.token[0].size != 3) { DPRINTF("Command accepts no arguments.\n"); return SHET_PROC_MALFORMED_ARGUMENTS; } else { break; } case SHET_SET_PROP_CCB: accepts_var_args = false; if (json.token[0].size != 4) { DPRINTF("Command accepts exactly one argument.\n"); return SHET_PROC_MALFORMED_ARGUMENTS; } else { break; } case SHET_EVENT_CCB: case SHET_CALL_CCB: accepts_var_args = true; if (json.token[0].size < 3) { DPRINTF("Commands must have at least 3 components.\n"); return SHET_PROC_MALFORMED_ARGUMENTS; } else { break; } default: return SHET_PROC_MALFORMED_ARGUMENTS; } // Get the path name. shet_json_t name_json = shet_next_token(shet_next_token(state->recv_id)); if (!SHET_JSON_IS_TYPE(name_json, SHET_STRING)) return SHET_PROC_MALFORMED_COMMAND; const char *name = SHET_PARSE_JSON_VALUE(name_json, SHET_STRING); // Find the callback for this event. shet_deferred_t *callback; switch (type) { case SHET_EVENT_CCB: case SHET_EVENT_DELETED_CCB: case SHET_EVENT_CREATED_CCB: callback = find_named_cb(state, name, SHET_EVENT_CB); break; case SHET_GET_PROP_CCB: case SHET_SET_PROP_CCB: callback = find_named_cb(state, name, SHET_PROP_CB); break; case SHET_CALL_CCB: callback = find_named_cb(state, name, SHET_ACTION_CB); break; default: callback = NULL; break; } // Get the deferred callback and user data. shet_callback_t callback_fun = NULL; if (callback != NULL) { switch (type) { case SHET_EVENT_CCB: callback_fun = callback->data.event_cb.event_callback; break; case SHET_EVENT_DELETED_CCB: callback_fun = callback->data.event_cb.deleted_callback; break; case SHET_EVENT_CREATED_CCB: callback_fun = callback->data.event_cb.created_callback; break; case SHET_GET_PROP_CCB: callback_fun = callback->data.prop_cb.get_callback; break; case SHET_SET_PROP_CCB: callback_fun = callback->data.prop_cb.set_callback; break; case SHET_CALL_CCB: callback_fun = callback->data.action_cb.callback; break; default: callback_fun = NULL; break; } } if (callback_fun == NULL) { // No callback function specified, generate an appropriate switch (type) { case SHET_EVENT_CCB: case SHET_EVENT_DELETED_CCB: case SHET_EVENT_CREATED_CCB: shet_return(state, 0, NULL); break; case SHET_GET_PROP_CCB: case SHET_SET_PROP_CCB: case SHET_CALL_CCB: shet_return(state, 1, "\"No callback handler registered!\""); break; } return SHET_PROC_OK; } else { // Execute the user's callback function void *user_data; switch (type) { case SHET_EVENT_CCB: case SHET_EVENT_CREATED_CCB: case SHET_EVENT_DELETED_CCB: user_data = callback->data.event_cb.user_data; break; case SHET_GET_PROP_CCB: case SHET_SET_PROP_CCB: user_data = callback->data.prop_cb.user_data; break; case SHET_CALL_CCB: user_data = callback->data.action_cb.user_data; break; default: user_data = NULL; break; } // Find the first argument (if one is present) shet_json_t args_json = shet_next_token(name_json); // If varadic arguments are accepted, truncate the command array to just the // arguments and set this as the argument to the callback. if (accepts_var_args) { jsmntok_t *first_arg_token = args_json.token; // Truncate the array (remove the ID, command and path) args_json.token = first_arg_token - 1; *args_json.token = json.token[0]; args_json.token->size = json.token[0].size - 3; if (args_json.token->size > 0) { // If the array string now starts with a string, move the start to just // before the opening quotes, otherwise move to just before the indicated // start of the first element. if (first_arg_token->type == JSMN_STRING) args_json.token->start = first_arg_token->start - 2; else args_json.token->start = first_arg_token->start - 1; } else { // If the new array is empty, the array's first character is just before the // closing bracket. args_json.token->start = args_json.token->end - 2; } // Add the opening bracket. Note that this *may* corrupt the path argument but // since it won't be used again, this isn't a problem. args_json.line[args_json.token->start] = '['; } if (callback_fun != NULL) callback_fun(state, args_json, user_data); return SHET_PROC_OK; } } // Process a message from shet. static shet_processing_error_t process_message(shet_state_t *state, shet_json_t json) { if (!SHET_JSON_IS_TYPE(json, SHET_ARRAY)) return SHET_PROC_MALFORMED_COMMAND; if (json.token[0].size < 2) { DPRINTF("Command too short.\n"); return SHET_PROC_MALFORMED_COMMAND; } // Record the ID token state->recv_id.line = json.line; state->recv_id.token = json.token + 1; // Get the command shet_json_t command_json = shet_next_token(state->recv_id); if (!SHET_JSON_IS_TYPE(command_json, SHET_STRING)) return SHET_PROC_MALFORMED_COMMAND; const char *command = SHET_PARSE_JSON_VALUE(command_json, SHET_STRING); // Handle commands separately if (strcmp(command, "return") == 0) return process_return(state, json); else if (strcmp(command, "event") == 0) return process_command(state, json, SHET_EVENT_CCB); else if (strcmp(command, "eventdeleted") == 0) return process_command(state, json, SHET_EVENT_DELETED_CCB); else if (strcmp(command, "eventcreated") == 0) return process_command(state, json, SHET_EVENT_CREATED_CCB); else if (strcmp(command, "getprop") == 0) return process_command(state, json, SHET_GET_PROP_CCB); else if (strcmp(command, "setprop") == 0) return process_command(state, json, SHET_SET_PROP_CCB); else if (strcmp(command, "docall") == 0) return process_command(state, json, SHET_CALL_CCB); else { DPRINTF("Unknown command: \"%s\"\n", command); shet_return(state, 1, "\"Unknown command.\""); return SHET_PROC_UNKNOWN_COMMAND; } } //////////////////////////////////////////////////////////////////////////////// // Internal message generating functions //////////////////////////////////////////////////////////////////////////////// // Send a command, and register a callback for the 'return' (if the deferred is // not NULL). static void send_command(shet_state_t *state, const char *command_name, const char *path, const char *args, shet_deferred_t *deferred, shet_callback_t callback, shet_callback_t err_callback, void * callback_arg) { int id = state->next_id++; // Construct the command... snprintf( state->out_buf, SHET_BUF_SIZE-1 , "[%d,\"%s\"%s%s%s%s%s]\r\n" , id , command_name , path ? ",\"" : "" , path ? path : "" , path ? "\"": "" , args ? "," : "" , args ? args : "" ); state->out_buf[SHET_BUF_SIZE-1] = '\0'; // ...and send it state->transmit(state->out_buf, state->transmit_user_data); // Register the callback (if supplied). if (deferred != NULL) { deferred->type = SHET_RETURN_CB; deferred->data.return_cb.id = id; deferred->data.return_cb.success_callback = callback; deferred->data.return_cb.error_callback = err_callback; deferred->data.return_cb.user_data = callback_arg; // Push it onto the list. add_deferred(state, deferred); } } //////////////////////////////////////////////////////////////////////////////// // Internal callback for re-register //////////////////////////////////////////////////////////////////////////////// void reregister_complete_cb(shet_state_t *state, shet_json_t json, void *user_data) { // Callback when shet_reregister command completes: re-creates all nodes USE(json); USE(user_data); // Re-send all registration commands for watches, properties and actions shet_deferred_t *iter; for (iter = state->callbacks; iter != NULL; iter = iter->next) { switch(iter->type) { case SHET_EVENT_CB: { // Find the original watch callback deferred shet_deferred_t *watch_deferred = iter->data.event_cb.watch_deferred; if (watch_deferred != NULL && watch_deferred->type != SHET_RETURN_CB) watch_deferred = NULL; // Re-register the watch send_command(state, "watch", iter->data.event_cb.event_name, NULL, watch_deferred, watch_deferred ? watch_deferred->data.return_cb.success_callback : NULL, watch_deferred ? watch_deferred->data.return_cb.error_callback : NULL, watch_deferred ? watch_deferred->data.return_cb.user_data : NULL); break; } case SHET_ACTION_CB: { // Find the original make action callback deferred shet_deferred_t *mkaction_deferred = iter->data.action_cb.mkaction_deferred; if (mkaction_deferred != NULL && mkaction_deferred->type != SHET_RETURN_CB) mkaction_deferred = NULL; // Re-create the action send_command(state, "mkaction", iter->data.action_cb.action_name, NULL, mkaction_deferred, mkaction_deferred ? mkaction_deferred->data.return_cb.success_callback : NULL, mkaction_deferred ? mkaction_deferred->data.return_cb.error_callback : NULL, mkaction_deferred ? mkaction_deferred->data.return_cb.user_data : NULL); break; } case SHET_PROP_CB: { // Find the original make property callback deferred shet_deferred_t *mkprop_deferred = iter->data.prop_cb.mkprop_deferred; if (mkprop_deferred != NULL && mkprop_deferred->type != SHET_RETURN_CB) mkprop_deferred = NULL; // Re-create the property send_command(state, "mkprop", iter->data.prop_cb.prop_name, NULL, mkprop_deferred, mkprop_deferred ? mkprop_deferred->data.return_cb.success_callback : NULL, mkprop_deferred ? mkprop_deferred->data.return_cb.error_callback : NULL, mkprop_deferred ? mkprop_deferred->data.return_cb.user_data : NULL); break; } // Should not occur default: break; } } // Re-register any events shet_event_t *ev_iter; for (ev_iter = state->registered_events; ev_iter != NULL; ev_iter = ev_iter->next) { // Find the original make event callback deferred shet_deferred_t *mkevent_deferred = ev_iter->mkevent_deferred; if (mkevent_deferred != NULL && mkevent_deferred->type != SHET_RETURN_CB) mkevent_deferred = NULL; // Re-register the event send_command(state, "mkevent", ev_iter->event_name, NULL, mkevent_deferred, mkevent_deferred ? mkevent_deferred->data.return_cb.success_callback : NULL, mkevent_deferred ? mkevent_deferred->data.return_cb.error_callback : NULL, mkevent_deferred ? mkevent_deferred->data.return_cb.user_data : NULL); } } //////////////////////////////////////////////////////////////////////////////// // General Library Functions //////////////////////////////////////////////////////////////////////////////// void shet_state_init(shet_state_t *state, const char *connection_name, void (*transmit)(const char *data, void *user_data), void *transmit_user_data) { state->next_id = 0; state->callbacks = NULL; state->registered_events = NULL; state->connection_name = connection_name; state->transmit = transmit; state->transmit_user_data = transmit_user_data; state->error_callback = NULL; state->error_callback_data = NULL; // Send the initial register command to name this connection shet_reregister(state); } void shet_set_error_callback(shet_state_t *state, shet_callback_t callback, void *callback_arg) { state->error_callback = callback; state->error_callback_data = callback_arg; } shet_processing_error_t shet_process_line(shet_state_t *state, char *line, size_t line_length) { if (line_length <= 0) { DPRINTF("JSON string is too short!\n"); return SHET_PROC_INVALID_JSON; } shet_json_t json; json.line = line; json.token = state->tokens; jsmn_parser p; jsmn_init(&p); jsmnerr_t e = jsmn_parse( &p , json.line , line_length , json.token , SHET_NUM_TOKENS ); switch (e) { case JSMN_ERROR_NOMEM: DPRINTF("Out of JSON tokens in shet_process_line: %.*s\n", line_length, json.line); return SHET_PROC_ERR_OUT_OF_TOKENS; case JSMN_ERROR_INVAL: DPRINTF("Invalid char in JSON string in shet_process_line: %.*s\n", line_length, json.line); return SHET_PROC_INVALID_JSON; case JSMN_ERROR_PART: DPRINTF("Incomplete JSON string in shet_process_line: %.*s.\n", line_length, json.line); return SHET_PROC_INVALID_JSON; default: if ((int)e > 0) { return process_message(state, json); } else { return SHET_PROC_INVALID_JSON; } break; } } void shet_reregister(shet_state_t *state) { // Cause the server to drop all old objects from this device/application send_command(state, "register", NULL, state->connection_name, &(state->reregister_deferred), reregister_complete_cb, NULL, NULL); } void shet_cancel_deferred(shet_state_t *state, shet_deferred_t *deferred) { remove_deferred(state, deferred); } void shet_ping(shet_state_t *state, const char *args, shet_deferred_t *deferred, shet_callback_t callback, shet_callback_t err_callback, void *callback_arg) { send_command(state, "ping", NULL, args, deferred, callback, err_callback, callback_arg); } const char *shet_get_return_id(shet_state_t *state) { // Null terminate the ID. This is safe since the ID is part of an array and // thus there is at least one trailing character which can be clobbered (the // comma) with the null. Also, note that string start/ends must be extended to // include quotes. Other types start & end already include their surrounding // brackets etc. if (state->recv_id.token->type == JSMN_STRING) { state->recv_id.line[--(state->recv_id.token->start)] = '\"'; state->recv_id.line[state->recv_id.token->end++] = '\"'; state->recv_id.line[state->recv_id.token->end] = '\0'; return state->recv_id.line + state->recv_id.token->start; } else { state->recv_id.line[state->recv_id.token->end] = '\0'; return state->recv_id.line + state->recv_id.token->start; } } void shet_return_with_id(shet_state_t *state, const char *id, int success, const char *value) { // Construct the command... snprintf( state->out_buf, SHET_BUF_SIZE-1 , "[%s,\"return\",%d,%s]\r\n" , id , success , value ? value : "null" ); state->out_buf[SHET_BUF_SIZE-1] = '\0'; // ...and send it state->transmit(state->out_buf, state->transmit_user_data); } void shet_return(shet_state_t *state, int success, const char *value) { shet_return_with_id(state, shet_get_return_id(state), success, value); } //////////////////////////////////////////////////////////////////////////////// // Public Functions for actions //////////////////////////////////////////////////////////////////////////////// void shet_make_action(shet_state_t *state, const char *path, shet_deferred_t *action_deferred, shet_callback_t callback, void *action_arg, shet_deferred_t *mkaction_deferred, shet_callback_t mkaction_callback, shet_callback_t mkaction_error_callback, void *mkaction_callback_arg) { // Make a callback for the property. action_deferred->type = SHET_ACTION_CB; action_deferred->data.action_cb.mkaction_deferred = mkaction_deferred; action_deferred->data.action_cb.action_name = path; action_deferred->data.action_cb.callback = callback; action_deferred->data.action_cb.user_data = action_arg; // And push it onto the callback list. add_deferred(state, action_deferred); // Finally, send the command send_command(state, "mkaction", path, NULL, mkaction_deferred, mkaction_callback, mkaction_error_callback, mkaction_callback_arg); } void shet_remove_action(shet_state_t *state, const char *path, shet_deferred_t *deferred, shet_callback_t callback, shet_callback_t error_callback, void *callback_arg) { // Cancel the action deferred and associated mkaction deferred shet_deferred_t *action_deferred = find_named_cb(state, path, SHET_ACTION_CB); if (action_deferred != NULL) { remove_deferred(state, action_deferred); if (action_deferred->data.action_cb.mkaction_deferred != NULL) remove_deferred(state, action_deferred->data.action_cb.mkaction_deferred); } // Finally, send the command send_command(state, "rmaction", path, NULL, deferred, callback, error_callback, callback_arg); } void shet_call_action(shet_state_t *state, const char *path, const char *args, shet_deferred_t *deferred, shet_callback_t callback, shet_callback_t err_callback, void *callback_arg) { send_command(state, "call", path, args, deferred, callback, err_callback, callback_arg); } //////////////////////////////////////////////////////////////////////////////// // Public Functions for properties //////////////////////////////////////////////////////////////////////////////// void shet_make_prop(shet_state_t *state, const char *path, shet_deferred_t *prop_deferred, shet_callback_t get_callback, shet_callback_t set_callback, void *prop_arg, shet_deferred_t *mkprop_deferred, shet_callback_t mkprop_callback, shet_callback_t mkprop_error_callback, void *mkprop_callback_arg) { // Make a callback for the property. prop_deferred->type = SHET_PROP_CB; prop_deferred->data.prop_cb.mkprop_deferred = mkprop_deferred; prop_deferred->data.prop_cb.prop_name = path; prop_deferred->data.prop_cb.get_callback = get_callback; prop_deferred->data.prop_cb.set_callback = set_callback; prop_deferred->data.prop_cb.user_data = prop_arg; // And push it onto the callback list. add_deferred(state, prop_deferred); // Finally, send the command send_command(state, "mkprop", path, NULL, mkprop_deferred, mkprop_callback, mkprop_error_callback, mkprop_callback_arg); } void shet_remove_prop(shet_state_t *state, const char *path, shet_deferred_t *deferred, shet_callback_t callback, shet_callback_t error_callback, void *callback_arg) { // Cancel the property deferred (and that of the mkprop callback) shet_deferred_t *prop_deferred = find_named_cb(state, path, SHET_PROP_CB); if (prop_deferred != NULL) { remove_deferred(state, prop_deferred); if (prop_deferred->data.prop_cb.mkprop_deferred != NULL) remove_deferred(state, prop_deferred->data.prop_cb.mkprop_deferred); } // Finally, send the command send_command(state, "rmprop", path, NULL, deferred, callback, error_callback, callback_arg); } void shet_get_prop(shet_state_t *state, const char *path, shet_deferred_t *deferred, shet_callback_t callback, shet_callback_t err_callback, void *callback_arg) { send_command(state, "get", path, NULL, deferred, callback, err_callback, callback_arg); } void shet_set_prop(shet_state_t *state, const char *path, const char *value, shet_deferred_t *deferred, shet_callback_t callback, shet_callback_t err_callback, void *callback_arg) { send_command(state, "set", path, value, deferred, callback, err_callback, callback_arg); } //////////////////////////////////////////////////////////////////////////////// // Public Functions for events //////////////////////////////////////////////////////////////////////////////// void shet_make_event(shet_state_t *state, const char *path, shet_event_t *event, shet_deferred_t *mkevent_deferred, shet_callback_t mkevent_callback, shet_callback_t mkevent_error_callback, void *mkevent_callback_arg) { // Setup the event and push it into the callback list. event->event_name = path; event->mkevent_deferred = mkevent_deferred; event->next = state->registered_events; state->registered_events = event; // Finally, send the command send_command(state, "mkevent", path, NULL, mkevent_deferred, mkevent_callback, mkevent_error_callback, mkevent_callback_arg); } void shet_remove_event(shet_state_t *state, const char *path, shet_deferred_t *deferred, shet_callback_t callback, shet_callback_t error_callback, void *callback_arg) { // Remove the event from the list shet_event_t **iter = &(state->registered_events); for (;*iter != NULL; iter = &((*iter)->next)) { if (strcmp((*iter)->event_name, path) == 0) { // Also remove the mkevent deferred if ((*iter)->mkevent_deferred != NULL) remove_deferred(state, (*iter)->mkevent_deferred); *iter = (*iter)->next; break; } } // Finally, send the command send_command(state, "rmevent", path, NULL, deferred, callback, error_callback, callback_arg); } void shet_raise_event(shet_state_t *state, const char *path, const char *value, shet_deferred_t *deferred, shet_callback_t callback, shet_callback_t err_callback, void *callback_arg) { send_command(state, "raise", path, value, deferred, callback, err_callback, callback_arg); } void shet_watch_event(shet_state_t *state, const char *path, shet_deferred_t *event_deferred, shet_callback_t event_callback, shet_callback_t created_callback, shet_callback_t deleted_callback, void *event_arg, shet_deferred_t *watch_deferred, shet_callback_t watch_callback, shet_callback_t watch_error_callback, void *watch_callback_arg) { // Make a callback for the event. event_deferred->type = SHET_EVENT_CB; event_deferred->data.event_cb.watch_deferred = watch_deferred; event_deferred->data.event_cb.event_name = path; event_deferred->data.event_cb.event_callback = event_callback; event_deferred->data.event_cb.created_callback = created_callback; event_deferred->data.event_cb.deleted_callback = deleted_callback; event_deferred->data.event_cb.user_data = event_arg; // And push it onto the callback list. add_deferred(state, event_deferred); // Finally, send the command send_command(state, "watch", path, NULL, watch_deferred, watch_callback, watch_error_callback, watch_callback_arg); } void shet_ignore_event(shet_state_t *state, const char *path, shet_deferred_t *deferred, shet_callback_t callback, shet_callback_t error_callback, void *callback_arg) { // Cancel the watch deferred and associated event deferred shet_deferred_t *event_deferred = find_named_cb(state, path, SHET_EVENT_CB); if (event_deferred != NULL) { shet_deferred_t *watch_deferred = event_deferred->data.event_cb.watch_deferred; if (watch_deferred != NULL) { remove_deferred(state, event_deferred); } remove_deferred(state, event_deferred); } // Finally, send the command send_command(state, "ignore", path, NULL, deferred, callback, error_callback, callback_arg); }
C
#include <stdio.h> #include <string.h> struct person_name{ char first[10]; char middle_initial; char last[10]; }; struct student{ struct person_name name; int id, age; char sex; }; int main(){ struct student student1; strcpy(student1.name.first, "Artem"); printf("%s\n", student1.name.first); return 0; }
C
#include<stdio.h> int main() { char A[]="How are you"; int i,vcount=0,ccount=0; for(i=0;A[i]!='\0';i++) { if(A[i]=='a' || A[i]=='e' || A[i]=='i' || A[i]=='o' || A[i]=='u' || A[i]=='A' || A[i]=='E' || A[i]=='I' || A[i]=='O' || A[i]=='U') { vcount++; } else if((A[i]>=65 && A[i]<=90) || (A[i]>=97 && A[i]<=122)) { ccount++; } } printf("vowel count is %d ",vcount); printf("\n"); printf("consonent count is %d ",ccount); return 0; }
C
#include <stdio.h> #include <stdlib.h> int main () { int a[6]; int i; int Asc=0; int desc=0; printf ("Ingrese un listado de 5 numeros \n "); for (i=0;i<6;i++) { scanf ("%d",&a[i]); } //1 2 3 4 5 6 for (i=0;i<5;i++) { if (a[i]<=a[i+1]) { Asc++; } } // 6 5 4 3 2 1 for(i=0;i<5;i++){ if (a[i]>=a[i+1]) { desc++; } } if (Asc==5) { printf ("Estan ingresados de forma ascendente"); } else { if (desc==5) { printf ("Estan ingresados de forma descendente"); } else { printf ("Estan ingresados de forma desordenada"); } } printf ("\n La suma entre el primero y el ultimo es %d",a[0]+a[5]); system ("pause"); return 0; }
C
#include <stdio.h> int main(void){ int N; char name[256][256]; int i, j; scanf("%d", &N); for (i = 0; i < N; ++i){ scanf("%s", name[i]); } for (i = 0; i < N; ++i){ for (j = 0; name[i][j] != '\0'; ++j){ if (name[i][j] >= 65 && name[i][j] <=90){ name[i][j] += 32; } } } for (i = 0; i < N; ++i){ printf("%s\n", name[i]); } return 0; }
C
#include <stdio.h> void trocaVetor(int *v1, int v2[5]){ int i, aux; for(i=0; i < 5; i++){ aux = v1[i]; v1[i] = v2[i]; v2[i] = aux; } } void somaVetor(int v1[], int *v2, int v3[5]){ int i; for(i=0; i < 5; i++){ v3[i] = (v1[i] + v2[i]); } } int main(){ int i; int vetA[5], vetB[5], vetC[5]; for (i = 0; i < 5; i++){ scanf("%d",&vetA[i]); } for (i = 0; i < 5; i++){ scanf("%d",&vetB[i]); } trocaVetor(vetA, vetB); somaVetor(vetA, vetB, vetC); printf("vetA: "); for (i = 0; i < 5; i++){ printf("%d ", vetA[i]); } printf("\nvetB: "); for (i = 0; i < 5; i++){ printf("%d ", vetB[i]); } printf("\nvetC: "); for (i = 0; i < 5; i++){ printf("%d ", vetC[i]); } printf("\n"); return 0; }
C
#ifndef PRIM_C #define PRIM_C struct prim { char nome_arquivo[64]; int vertices; int arestas; int **grafo; // grafo com ate max_vertices quantidades de vertices int max_vertices; int infinito; int custo_minimo; // custo minimo do grafo char arquivo_saida[64]; // armazena arquivo de saida }; typedef struct prim Prim; /* Funcao qual ira inicializar a matriz de acordo com os parametros * de entrada dados pelo usuário. */ void inicializar_prim(Prim *prim, char *file, int qtd_max_vertices); /* Funcao qual ira alocar o grafo. */ void alocar_grafo(Prim *prim); /* Funcao qual ira liberar o grafo. */ void liberar_grafo(Prim *prim); /* Funcao qual ira fazer o calculo do custo minimo no grafo. */ void calcular_custo_minimo(Prim *prim); /* Funcao qual ira calcuar o custo minimo no grafo de acordo com o * algoritmo de Prim. */ void mostrar_custo_minimo(Prim *prim); /* Funcao qual ira mostrar a ordem dos vertices, em outras palavras, * ira montar a "arvore geradora de custo minimo" mostrando os * conjuntos de vertices. */ void mostrar_ordem_vertices(Prim *prim); /* Funcao qual ira salvar no arquivo de texto ".txt" os dados * armazenados na struct. */ void gerar_saida(Prim *prim); /* Funcao qual ira verificar se o arquivo ".txt" carregado esta vazio */ int verificar_arquivo_vazio(Prim *prim); #endif // PRIM_C
C
#define MAXROWS 10 #define MAXCOLS 10 #define TRUE 1 #define FALSE 0 #define TOP_MARGIN "\n" #define LEFT_MARGIN "\t" #define BOTTOM_MARGIN "\n" enum gameResults { IN_PROGRESS, DRAW, WIN1, WIN2, INVALID_MOVE1, INVALID_MOVE2, TIMEOUT1, TIMEOUT2, ERROR }; struct game { int rows; int columns; int piecesToWin; int timeLimitSeconds; int board[MAXROWS][MAXCOLS]; }; struct player { char* name; struct game g; int turn; int id; }; enum gameResults acceptMove(struct game* g, int playerId, int column); int getMove_Naive(struct player* p); int getMove_Random(struct player* p); int getNextMove(struct player* p); int isMoveValid(struct game* g, int column); struct game initializeGame(int rows, int columns, int piecesToWin, int timeLimitSeconds); void displayBoard(struct game* g); void noteOpponentsMove(struct player* p, struct player* opponent, int column);
C
#include<stdio.h> #include<stdlib.h> #include<time.h> void randomArray(int arr[], int n) { srand(time(0)); for(int i = 0; i<n; i++) { arr[i] = rand()%99; } } int left(int i) { return (2*i)+1; } int right(int i) { return (2*i)+2; } int parent(int i) { return (i/2)-1; } void swap(int *a,int *b) { int temp; temp=*a; *a=*b; *b=temp; } void max_heapify(int arr[], int n, int i) { int largest; int l=left(i); int r=right(i); if(l<n && arr[l]>arr[i]) { largest=l; } else { largest=i; } if(r<n && arr[r]>arr[largest]) { largest=r; } if(i!=largest) { swap(&arr[i],&arr[largest]); max_heapify(arr,n,largest); } } void build_max_heap(int arr[],int n) { for(int i=(n/2)-1;i>=0;i--) { max_heapify(arr,n,i); } } void heapSortAsc(int arr[],int n) { build_max_heap(arr,n); for(int i=n-1;i>=0;i--) { //printf("%d,",arr[0]); swap(&arr[0],&arr[i]); max_heapify(arr,i,0); } } void min_heapify(int arr[], int n, int i) { int smallest; int l=left(i); int r=right(i); if(l<n && arr[l]<arr[i]) { smallest=l; } else { smallest=i; } if(r<n && arr[r]<arr[smallest]) { smallest=r; } if(i!=smallest) { swap(&arr[i],&arr[smallest]); max_heapify(arr,n,smallest); } } void build_min_heap(int arr[],int n) { for(int i=(n/2)-1;i>=0;i--) { min_heapify(arr,n,i); } } void heapSortDesc(int arr[],int n) { build_min_heap(arr,n); for(int i=n-1;i>=0;i--) { swap(&arr[0],&arr[i]); min_heapify(arr,i,0); } } void display(int arr[],int n) { for(int i=0;i<n;i++) { printf("%d,",arr[i]); } } void tabularCase() { int n; printf("\nS.no.\tn\tRandom Data\tData in Ascending\tData inDescending\n"); for(int a=1;a<=10;a++) { printf("%d\t",a); scanf("%d",&n); printf("\t\t"); int arr[n]; randomArray(arr,n); clock_t t; t=clock(); heapSortAsc(arr,n); t=clock()-t; double time_taken=((double)t/CLOCKS_PER_SEC); printf("%lf",time_taken); printf("\t"); clock_t x=clock(); heapSortAsc(arr,n); x=clock()-x; time_taken=((double)x/CLOCKS_PER_SEC); printf("%lf\t",time_taken); clock_t y=clock(); heapSortDesc(arr,n); y=clock()-y; time_taken=((double)x/CLOCKS_PER_SEC); printf("%lf\n",time_taken); printf("\n"); } } int heap_extract_max(int arr[],int n) { if(n<1) { printf("Error\n"); } else { int max; max=arr[0]; arr[0]=arr[n-1]; n--; max_heapify(arr,n,0); return max; } } void heap_increase_key(int arr[],int n,int i,int key) { // if(key<=arr[i]) // { // printf("Error: new value is lesser than the old"); // } // else // { arr[i]=key; while(i>0 && arr[i]>arr[parent(i)] ) { swap(&arr[i],&arr[parent(i)]); i=parent(i); } // } } void heap_insert(int arr[],int n,int key) { if(n<1) { printf("Error"); } else { arr[n]=INT_MIN; heap_increase_key(arr,n+1,n-1,key); } } int main() { int n, choice; char ans = 'y'; int pos,key; int arr[n]; clock_t start, end; do { //menu printf("\n || Max heap & priority queue menu ||\n"); printf("\n 0. Quit \n1. generate random no array \n2. display \n3. sort ascending \n4. sort descending \n5. time complexity of sorting random data in ascending"); printf("\n 6. time complexity of sorting in ascending of data already sorted in ascending"); printf("\n 7. time complexity of sorting in ascending of data already sorted in descending"); printf("\n 8. time complexity of sorting in ascending of data in all cases"); printf("\n 9. extract largest element"); printf("\n10. replace value at a node with a new node"); printf("\n11. insert a new element"); // printf("\n12. delete an element"); printf("\n\nEnter choice :"); scanf("%d", &choice); switch(choice) { case 0: exit(1); case 1: printf("Enter the number of elements?"); scanf("%d",&n); randomArray(arr,n); break; case 2: display(arr,n); break; case 3: heapSortAsc(arr,n); break; case 4: heapSortDesc(arr,n); break; case 5: randomArray(arr,n); start = clock(); heapSortAsc(arr,n); end = clock(); printf("\ntime: %lf", ((double)(start-end))/CLOCKS_PER_SEC); break; case 6: randomArray(arr,n); heapSortAsc(arr,n); start=clock(); heapSortAsc(arr,n); end=clock(); printf("\ntime: %lf", ((double)(start-end))/CLOCKS_PER_SEC); break; case 7: randomArray(arr,n); heapSortDesc(arr,n); start=clock(); heapSortAsc(arr,n); end=clock(); printf("\ntime: %lf", ((double)(start-end))/CLOCKS_PER_SEC); break; case 8: tabularCase(); break; case 9: build_max_heap(arr,n); printf("Extract heap max:-%d\n",heap_extract_max(arr,n)); printf("Array after extracting max\n"); display(arr,n-1); break; case 10: build_max_heap(arr,n); printf("\nFor replace key:-\n"); printf("Enter position and new value?"); scanf("%d%d",&pos,&key); heap_increase_key(arr,n,pos,key); printf("New array\n"); display(arr,n-1); break; case 11: build_max_heap(arr,n); printf("\nFor inserting a new value\n"); printf("Enter value\n"); scanf("%d",&key); heap_insert(arr,n,key); display(arr,n); break; } printf("\nContinue?(y/n) "); scanf(" %c", &ans); } while(ans == 'y' || ans == 'Y'); // printf("\nDisplay before heapify\n"); // display(arr,n); // printf("\n\n\n"); // heapSort(arr,n); // //build_max_heap(arr,n); // printf("\nDisplay after heapSort\n"); // display(arr,n); return 0; }
C
#include "holberton.h" /** * reverse_array - This function reverses the content of an array of * integers * @a: The array of integers to reverse * @n: The number of elements in the array */ void reverse_array(int *a, int n) { int i, tmp; /* loop through array reversing elements */ for (i = 0; i < n; i++) { /* not including null byte */ n--; /* store first element in a temp variable */ tmp = a[i]; /* store last element in first variable */ a[i] = a[n]; /* store first element in last element's place */ a[n] = tmp; } }
C
#include<stdio.h> int main() { int start,end,i; scanf("%d %d",&start,&end); for(i=start+1;i<end;i++) { if(i%2==0) { printf("\t %d",i); } } return 0; }
C
#include <stdio.h> int rev(int); int fl(int); int main() { int i; int num; int tests; scanf("%d", &tests); for(i = 0; i < tests; i++) { scanf("%d", &num); printf("%d\n", fl(num)); } return 0; } int fl(int num) { int sum = 0; sum += num % 10; sum += rev(num) % 10; return sum; } int rev(int num) { int rev = 0; while(num != 0) { rev *= 10; rev += (num % 10); num /= 10; } return rev; }
C
#include<stdio.h> int main(void){ int n; int result=0,tmp; int i,flag=1; scanf("%d",&n); for(i=1;i<n;i++){ result=i; tmp=i; while(tmp){ result+=tmp%10; tmp/=10; } if(result==n){ printf("%d\n",i); flag=0; break; } } if(flag) printf("0\n"); return 0; }
C
//first 5 topics from the PDF #include <stdio.h> #include <math.h> // global variables in C char intro[100] = "Logic matters, language doesn't"; // functions in C int add(int a, int b){ int c; c = a + b; } int max(int a, int b){ if (a > b) return a; else return b; } void name(char name[100]){ printf("\nYour name is %s", name); } // function created to understrand the scope void localScope(){ int height = 123; printf("\nAccessing the variable defined inside a function by calling a function itself - %d", height); printf("\nGlobal variable inside a function - %s", intro); //accessing the global variable inside a function } int main() { // int num; // printf("enter the number"); // scanf("%d", &num); // printf("your number with the addition of 1 is %d", num+1); // to print the whole string(characters with spaces) // char ch[0]; // printf("Enter a string\n"); // gets(ch); // printf("The string: %s\n", ch); // float val; // printf("enter the float value"); // scanf("%f", &val); // printf("your float value is - %lf", val); // input and ouptput // int num; // float fl; // char word[100]; // printf("enter the number - "); // scanf("%d", &num); // printf("\nentered number is... %d", num); // printf("\nenter the character - "); // gets(word); // printf("\nentered character is... %s", word); // printf("\nenter the float number - "); // scanf("%f", &fl); // printf("\nentered float number is... %f", fl); // using the "add" function // int i = 10; // int j = 40; // int k = add(i, j); // printf("Addition of the numbers - %d",k); // using the "name" function // name("sam"); // scopes in C language // local scope { int local = 5; printf("%d", local); //we can't access this variable outside of this block printf("\nGlobal variable inside a block - %s", intro); //accessing the global variable inside block } localScope(); // printf("%d", height); //we can't acces the local variable defined inside the function over here printf("\nGlobal variable inside a main block - %s", intro); //accessing the global variable inside main block // use of math.h library to get the square root of a number // float root; // printf("\nEnter the number for sqrt"); // scanf("%f", &root); // printf("%f", sqrt(root)); int a = 11; a = 12; printf("\n%d", a); //taking the string input from the user and output it - this will display word before the space only - Axay Patoliya mathi khali Axay j print thase printf("\nEnter your name - "); char name[100]; //scanf("%s", name); fgets(name, 100, stdin); //this will get input as a whole line - this will print new line after printing the input printf("\nYour name is %s", name); char color[100]; char noun[100]; char celebFirstName[100]; char celebLastName[100]; printf("enter the color"); scanf("%s", color); printf("enter the noun"); scanf("%s", noun); printf("enter the celeb name"); scanf("%s%s", celebFirstName, celebLastName); printf("Roses are %s \n %s are %s \n I love %s %s", color, noun, color, celebFirstName, celebLastName); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "calculadora.h" int main(void) { setbuf(stdout,NULL); char opcionLetra; float numUno; float numDos; float resultadoSuma; float resultadoResta; float resultadoDivision; float resultadoMultplicacion; float resultadoFactorialUno; float resultadoFactorialDos; do { printf("\nMenu: a- Ingresar nmero 1 n\ b- Ingresar nmero 2 n\ c- Realizar todas las operaciones n\ d- Imprimir todas las operaciones n\ e- Salir "); scanf("%d", &opcion); switch(opcionLetra) { case a: printf("ingrese el primer numero: "); scanf(%d ,&numUno); break; case b: printf("ingrese el segundo numero: "); scanf(%d , &numDos); break; case c: if(numUno != NULL && numDos != NULL) { sumar(numUno, numDos, &resultadoSuma); restar(numUno, numDos, &resultadoResta); dividir(numUno, numDos, &resultadoDiv); multiplicar(numUno, numDos, &resultadoMultpl); factorial((int)numUno, &resultadoFactUno); factorial((int)numDos, &resultadoFactorialDos); printf("Operaciones hechas \n"); } else { printf("Ocurrio un error \n"); } break; case d: printf("El resultado de %d + %d es: %d \n", numUno, numDos, resultadoSuma); printf("El resultado de %d - %.d es: %d \n", numUno, numDos, resultadoResta); if(return == 0) { printf("El divisor no puede ser 0 \n"); } else { printf("El resultado de %d / %d es: %.2f \n", numUno, numDos, resultadoDivision); } printf("El resultado de %d * %d es: %d \n", numUno, numDos, resultadoMultplicacion); if(return == 0) { printf("Error en factorial \n"); } else { printf("El resultado de !%d es: %d\n", (int)numUno, (int)resultadoFactorialUno); } if(return == 0) { printf("Eror en el factorial de numero 2 \n"); } else { printf("El resultado de !%d es: %d \n", (int)numDos, (int)resultadoFactorialDos); } } break; default: printf("salir"); }while(opcion != 5); return EXIT_SUCCESS; }
C
#include<stdio.h> int main() { int i,res=0; int arr[11]; printf("enter array elements\n"); for(i=0;i<11;i++) scanf("%d",&arr[i]); for(i=0;i<11;i++) printf("array elements are %d\n",arr[i]); for(i=0;i<11;i++) res=res^arr[i]; printf("%d\n",res); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> char *read_line(); char *remove_equal_consecutive_chars(char *input); int main() { char *string = read_line(&string); string = remove_equal_consecutive_chars(string); printf("%s\n", string); return 0; } //removes equal consecutive chars ex. aaabb -> ab char *remove_equal_consecutive_chars(char *input) { size_t stringLength= strlen(input); char *cpy = malloc(stringLength); cpy[0] = input[0]; int i,index=0; for (i = 0; i < stringLength; i++) { if(input[i] != input[i-1]) { cpy[index] = input[i]; index++; } } cpy[index] = '\0'; strcpy(input,cpy); return input; } //reads the intire line char *read_line() { int initialSize = 4; char *readline = malloc(initialSize); int index = 0; char ch = getchar(); while (ch != '\n' && ch != EOF) { if (index == initialSize - 1) { char *newReadLine = realloc(readline, initialSize * 2); if (!newReadLine) { printf("Not enough memory!"); exit(1); } readline = newReadLine; initialSize *= 2; } *(readline + index) = ch; index++; ch = getchar(); } *(readline + index) = '\0'; return readline; }
C
/****************************************************************************** Welcome to GDB Online. GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog. Code, Compile, Run and Debug online from anywhere in world. *******************************************************************************/ #include <stdio.h> #define size 10 void dfs(int a[size][size],int n,int u,int vis[size]) { int v; for(v=1;v<=n;v++) { if(a[u][v]==1 && vis[v]==0) { vis[v]=1; dfs(a,n,v,vis); } } } int main() { int a[size][size],i,j,n,vis[size],flag,conn; printf("\n Welcome to the dfs algorithm:"); printf("\n how many nodes in the graph:---> "); scanf("%d",&n); printf("\n enter the adjacency matrix:\n"); for(i=1;i<=n;i++) for(j=1;j<=n;j++) scanf("%d",&a[i][j]); conn=1; for(j=1;j<=n;j++) { for(i=1;i<=n;i++) vis[i]=0; dfs(a,n,j,vis); flag=1; for(i=1;i<=n;i++) { if(vis[i]==0) flag=0; } if(flag==0) conn=0; } if(conn==1) printf("\n the graph is connected graph.\n"); else printf("\n the graph is not connected \n"); printf("\n bye ............"); return(0); }
C
#include "checkup.h" #define error_print(...) fprintf(stderr, __VA_ARGS__) int error(char *error) { error_print("%s\n", error); return UNSUCCESS; } bool check_count_of_parameters(parameters_count_t parameters_count) { if (parameters_count == PARAMS_COUNT) { return true; } return false; } bool check_existence_input_file(fname_t file_name) { FILE *input_file = fopen(file_name, "r"); if (input_file == NULL) { return false; } fclose(input_file); return true; } bool check_count_of_strings(fname_t file_name, count_of_strings_t count_of_strings) { FILE *input_file = fopen(file_name, "r"); array_size_t count_of_input_strings = 0; char *input_string = malloc(sizeof(char) * MAX_INPUT_STRING_SIZE); while (!feof(input_file)) { if (fgets(input_string, MAX_INPUT_STRING_SIZE, input_file) != NULL) { count_of_input_strings++; } } free(input_string); if (count_of_input_strings < count_of_strings) { fclose(input_file); return false; } fclose(input_file); return true; } bool is_integer(string_t string) { for (array_size_t i = 0; i < strlen(string); i++) if (string[i] < '0' || string[i] > '9') { return false; } return true; } int is_string_in_array(string_t string, const_string_array_t string_array, array_size_t array_size) { for (array_size_t i = 0; i < array_size; i++) { if (strcmp(string, string_array[i]) == 0) { return i; } } return UNSUCCESS; } int checks(parameters_count_t parameters_count, parameters_t parameters) { if (!check_count_of_parameters(parameters_count)) { return error("Incorrect parameters counts"); } if (!is_integer(parameters[COUNT_OF_STRINGS])) { return error("Incorrect type of strings"); } if (!check_existence_input_file(parameters[INPUT_FNAME])) { return error("Incorrect input file name"); } int count_of_strings = string_to_int(parameters[COUNT_OF_STRINGS]); if (!check_count_of_strings(parameters[INPUT_FNAME], count_of_strings)) { return error("Incorrect count of strings"); } if (is_string_in_array(parameters[SORT_NAME], SORTINGS, SORTINGS_COUNT) == UNSUCCESS) { return error("Incorrect incoming quick_sorting name"); } if (is_string_in_array(parameters[COMPARATOR_NAME], COMPARERS, COMPARERS_COUNT) == UNSUCCESS) { return error("Incorrect comparator name"); } return SUCCESS; }
C
/*QUESTO 08: Em uma empresa deseja-se fazer um levantamento sobre algumas informaes dos seus 250 funcionrios. Cada funcionrio dever responder um questionrio ao qual informar os seguintes dados: matrcula, sexo, idade, salrio e tempo (em anos) de trabalho na empresa. A execuo do programa deve exibir os seguintes itens: a) Quantidade de funcionrios que ingressaram na empresa com menos de 21 anos; b) Quantidade de funcionrios do sexo feminino; c) Mdia salarial dos homens; d) Matrcula dos funcionrios mais antigo e mais novo.*/ #include<stdio.h> #define QUANT 5 int main(){ int i, matric, idade, tempo, cont21=0, contF=0, contM=0, maior=-99999, menor=99999,matA,matN; char sexo; float sal, soma=0, media; for(i=1;i<=QUANT;i++) { printf("\nInforme a matricula: "); scanf("%d",&matric); printf("Informe o sexo(M/F): "); fflush(stdin); scanf("%c",&sexo); sexo=toupper(sexo); printf("Informe a idade: "); scanf("%d",&idade); printf("Informe o salario: "); scanf("%f",&sal); printf("Informe o tempo trabalhando na empresa: "); scanf("%d",&tempo); if((idade-tempo)<21) { cont21++; } if(sexo=='F') { contF++; } else { contM++; soma=soma+sal; } if(tempo>maior) { maior=tempo; matA=matric; } if(tempo<menor) { menor=tempo; matN=matric; } } media=soma/contM; printf("\nQuantidade de funcionrios que ingressaram na empresa com menos de 21 anos: %d\n",cont21); printf("Quantidade de funcionrios do sexo feminino: %d\n",contF); printf("Mdia salarial dos homens: %.2f",media); printf("A matricula do funcionario mais antigo e %d e do mais novo e %d",matA,matN); }
C
#define _CRT_SECURE_NO_DEPRECATE 1 #include <stdio.h> int main() { int arr[] = { 1, 2, 3, 4, 5, 1, 2, 3, 4 ,5,8,9}; int i = 0; int ret = 0; //int j = 0; int sz = sizeof(arr) / sizeof(arr[0]); for (i = 0; i < sz; i++) { ret = ret^arr[i]; /*int count = 0; for (j = 0; j < sz; j++) { if (arr[i] == arr[j]) { count++; } } if (count == 1) { printf("%d\n", arr[i]); }*/ } printf("ǣ%d\n", ret); printf("ǣ%d\n", 8^9); return 0; }
C
#include <conf.h> #include <kernel.h> #include <proc.h> #include <lock.h> #include <stdio.h> #define DEFAULT_LOCK_PRIO 20 void sem_fun (char *msg, int sem) { kprintf ("%s:to acquire sem\n", msg); wait(sem); kprintf ("%s:acquired sem\n", msg); sleep (2); kprintf ("%s:to release sem\n", msg); signal(sem); } void lock_fun (char *msg, int lck) { kprintf ("%s: to acquire lock\n", msg); lock (lck, WRITE, DEFAULT_LOCK_PRIO); kprintf ("%s: acquired lock\n", msg); sleep (2); kprintf ("%s: to release lock\n", msg); releaseall (1, lck); } void new_proc(char* msg) { kprintf(" Process %s running.\n", msg); sleep(2); kprintf(" Process %s finished running.\n", msg); } void sem_make(int sem) { int srd1,swr1,swr2; srd1 = create(sem_fun, 2000, 50, "ProcessA", 2,"ProcessA", sem); swr1 = create(new_proc, 2000, 70, "ProcessB", 1,"ProcessB"); swr2 = create(sem_fun, 2000, 90, "ProcessC", 2,"ProcessC",sem); resume(srd1); sleep(1); resume(swr1); sleep(1); resume(swr2); sleep(1); } void lock_make(int lck) { int rd1,wr1,wr2; rd1 = create(lock_fun, 2000, 50, "ProcessA", 2,"ProcessA",lck); wr1 = create(new_proc, 2000, 70, "ProcessB", 1,"ProcessB"); wr2 = create(lock_fun, 2000, 90, "ProcessC", 2, "ProcessC", lck); resume(rd1); sleep(1); resume(wr1); sleep(1); resume(wr2); sleep(1); } int main() { int sem; int lck; sem = screate(1); sem_make(sem); sleep(5); lck=lcreate(); lock_make(lck); return 0; }
C
extern char** environ; main() { char** env=environ; while(*env){ printf("%s\n",*env++); } return; }
C
#include <stdio.h> #include <signal.h> void handler(int signum) { signal(signum, handler); printf("caught: %d\n",signum); } int main(int argc, char* argv[]) { printf("test\n"); for (int i=1; i<=64; i++ ) { // signals 32 and 33 are not in kill -l if(i!=32 && i!=33) { // register handler signal(i, handler); printf("signal(%d) = %d\n",i,signal(i, handler)); // Raising these terminates the program, meaning they aren't handled. Uncomment to confirm. if(i!=9) raise(i); } } while(1); return 0; }
C
/* * This file is subject to the license agreement located in the file LICENSE * and cannot be distributed without it. This notice cannot be * removed or modified. */ #include "ocr.h" #include "extensions/ocr-affinity.h" /** * DESC: This program spawns a "latch" event, N task "A"'s and N "once" events. * Task A[i] satisfies event[i], which (eventually) allows the latch counter * to drop to zero, which runs done() and passes the test. * [references issue #197] */ // Uncomment usleep to help reproduce the issue // #include <unistd.h> #define N 1000 ocrGuid_t done(u32 paramc, u64 paramv[], u32 depc, ocrEdtDep_t depv[]) { PRINTF("Success!\n"); ocrShutdown(); return NULL_GUID; } ocrGuid_t A(u32 paramc, u64 paramv[], u32 depc, ocrEdtDep_t depv[]) { int i = paramv[0]; ocrGuid_t *event_array = (ocrGuid_t*)depv[0].ptr; if(!event_array || (((u64)event_array) == ((u64)-3))) PRINTF("[%"PRId32"] I AM GOING TO CRASH: depv[0].guid="GUIDF", depv[0].ptr=%p\n", i, GUIDA(depv[0].guid), depv[0].ptr); ocrEventSatisfy(event_array[i], NULL_GUID); // usleep(300); return NULL_GUID; } ocrGuid_t mainEdt(u32 paramc, u64 paramv[], u32 depc, ocrEdtDep_t depv[]) { u64 i; ocrGuid_t event_array_guid, *event_array, latch_guid, A_template, done_template, done_edt; ocrDbCreate(&event_array_guid, (void**)&event_array, N*sizeof(ocrGuid_t), DB_PROP_NONE, NULL_HINT, NO_ALLOC); ocrEdtTemplateCreate(&A_template, A, 1, 1); ocrEdtTemplateCreate(&done_template, done, 0, 1); ocrEventCreate(&latch_guid, OCR_EVENT_LATCH_T, FALSE); ocrAddDependence(NULL_GUID, latch_guid, OCR_EVENT_LATCH_INCR_SLOT, DB_MODE_CONST); ocrEdtCreate(&done_edt, done_template, 0, NULL, 1, &latch_guid, EDT_PROP_NONE, NULL_HINT, NULL); for(i = 0; i < N; i++) { ocrEventCreate(&event_array[i], OCR_EVENT_ONCE_T, FALSE); } for(i = 0; i < N; i++) { ocrGuid_t A_edt; ocrAddDependence(NULL_GUID , latch_guid, OCR_EVENT_LATCH_INCR_SLOT, DB_MODE_CONST); ocrAddDependence(event_array[i], latch_guid, OCR_EVENT_LATCH_DECR_SLOT, DB_MODE_CONST); ocrEdtCreate(&A_edt, A_template, 1, &i, 1, &event_array_guid, EDT_PROP_NONE, NULL_HINT, NULL); } ocrAddDependence(NULL_GUID, latch_guid, OCR_EVENT_LATCH_DECR_SLOT, DB_MODE_CONST); return NULL_GUID; }
C
#include<stdio.h> #include<stdlib.h> int stack[10]; int top=0; int push(int x) { stack[top++]=x; } int pop() { int d=stack[--top]; return d; } int expr(char ch) { int a,b; int c; b=pop(); a=pop(); if(ch == '+') { c=a+b; } else if(ch == '-') { c=a-b; } else if (ch == '*') { c=a*b; } push(c); } int main() { char arr[10]="23*54*+9-"; int i; for(i=0;i<10;i++) { if(arr[i] > 48 && arr[i]<58) { push(arr[i]-48); } else { expr(arr[i]); } } i=pop(); printf("Ans:%d\n",i); }
C
// divide_files.c for Yolo // Compile: gcc -o divide_files divide_files.c // Usage: // ./divide_files // ./divide_files [portion] // portion: the portion of test data. The default value is 0.2. #include <stdio.h> #include <stdlib.h> #include <err.h> #include <sys/types.h> #include <dirent.h> #include <string.h> #include <unistd.h> #define TEST_FILENAME "test.list" #define TRAIN_FILENAME "train.list" float g_portion = 0.2; int compar(const struct dirent **s1, const struct dirent **s2) { return strcmp( (*s1)->d_name, (*s2)->d_name); } int selects(struct dirent *dir) { if(dir->d_name[0] == '.') { return (0); } if (strstr(dir->d_name, ".jpg") != NULL) { return (1); } else { return 0; } } int main (int argc, char *argv[]) { FILE *fp_test, *fp_train; int i, test_no=0, train_no=0; float j=0,skip; const char *dirname = "."; struct dirent **namelist; char buf[1024]; if (argc == 2) { g_portion = atof(argv[1]); printf("Portion:%f",g_portion); } if (argc > 2) { printf("Usage: divide_files [portion] \n"); printf(" portion: the portion of test data\n"); exit(1); } int file_no = scandir(dirname, &namelist, (int (*)(const struct dirent *)) selects, compar); if ((fp_test = fopen(TEST_FILENAME, "w")) == NULL) { err(EXIT_FAILURE, "cannot open %s", TEST_FILENAME); } if ((fp_train = fopen(TRAIN_FILENAME, "w")) == NULL) { err(EXIT_FAILURE, "cannot open %s", TRAIN_FILENAME); } if(file_no == -1) { err(EXIT_FAILURE, "%s", dirname); } getcwd(buf, sizeof(buf)); skip = file_no / (file_no * g_portion); for (i = 0; i < file_no; i++) { if (j >= file_no) { break; } if (i < (int) j) { train_no++; printf("%d:train(%d):%s/%s\n", i+1,train_no, buf,namelist[i]->d_name); fprintf(fp_train, "%s/%s\n", buf,namelist[i]->d_name); } else if (i == (int) j) { j += skip; test_no++; printf("%d:test(%d):%s/%s\n", i+1,test_no,buf,namelist[i]->d_name); fprintf(fp_test, "%s/%s\n", buf,namelist[i]->d_name); } } for (i=0; i< file_no;i++) free(namelist[i]); free(namelist); printf("all =%d\n", file_no); printf("train=%d\n", train_no); printf("test =%d\n", test_no); printf("Set Portion=%f\n",g_portion); printf("Real Portion=%f\n", (float)test_no/file_no); exit(EXIT_SUCCESS); }
C
/* mtime.c, by Jehsom. * Shows the modification time of a file in epoch time. * This software is property of the public domain. */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <time.h> #include <strings.h> #define TIMELEN 300 int main( int argc, char *argv[] ){ char mtime[TIMELEN]; struct stat filestats; if( argc < 2 ){ fprintf( stderr, "Usage: %s file [file2 [file3 [...]]]\n", argv[0] ); return 1; } while( argv[1] != NULL ) { if( stat(argv[1], &filestats) == -1 ) { fprintf( stderr, "Could not open %s.\n", argv[1] ); } printf( "%d %s\n", filestats.st_mtime, argv[1] ); argv++; } return 0; }
C
#ifndef _STDIO_H #include <stdio.h> #include "Assignment2.h" #endif char *sappend (char *str1, char *str2) { while (*str1 != '\0') { str1 ++; } while (*str2 != '\0') { *str1 ++ = *str2 ++; } *str1 = '\0'; return str1; }
C
#include "lib.h" #include "types.h" int data = 0; void producer(int pid, sem_t mutex, sem_t empty, sem_t full) { int i = pid - 1; for(int k = 0; k < 8; k++) { sem_wait(&empty); printf("pid %d, producer %d, produce, product %d\n", pid, i, k + 1); sleep(128); printf("pid %d, producer %d, try lock, product %d\n", pid, i, k + 1); sem_wait(&mutex); printf("pid %d, producer %d, locked\n", pid, i); sem_post(&mutex); printf("pid %d, producer %d, unlock\n", pid, i); sem_post(&full); } } void consumer(int pid, sem_t mutex, sem_t empty, sem_t full) { int i = pid - 3; for(int k = 0; k < 4; k++) { printf("pid %d, consumer %d, try consume, product %d\n", pid, i, k + 1); sem_wait(&full); printf("pid %d, consumer %d, try lock, product %d\n", pid, i, k + 1); sem_wait(&mutex); printf("pid %d, consumer %d, locked\n", pid, i); sem_post(&mutex); printf("pid %d, consumer %d, unlock\n", pid, i); sem_post(&empty); sleep(128); printf("pid %d, consumer %d, consumed, product %d\n", pid, i, k + 1); } } int uEntry(void) { sem_t mutex, empty, full; sem_init(&mutex, 1); sem_init(&empty, 16); sem_init(&full, 0); pid_t pid; for(int i = 0; i < 6; i++) { pid = fork(); if(pid == 0 || pid == -1) break; } if(pid != -1) { pid = getpid(); if(pid > 3) { consumer(pid, mutex, empty, full); } else if(pid > 1) { producer(pid, mutex, empty, full); } exit(); } /*int i = 4; int ret = 0; sem_t sem; printf("Father Process: Semaphore Initializing.\n"); ret = sem_init(&sem, 2); if (ret == -1) { printf("Father Process: Semaphore Initializing Failed.\n"); exit(); } ret = fork(); if (ret == 0) { while( i != 0) { i --; printf("Child Process: Semaphore Waiting.\n"); sem_wait(&sem); printf("Child Process: In Critical Area.\n"); } printf("Child Process: Semaphore Destroying.\n"); sem_destroy(&sem); exit(); } else if (ret != -1) { while( i != 0) { i --; printf("Father Process: Sleeping.\n"); sleep(128); printf("Father Process: Semaphore Posting.\n"); sem_post(&sem); } printf("Father Process: Semaphore Destroying.\n"); sem_destroy(&sem); exit(); }*/ return 0; }
C
#include<stdio.h> #include<stdlib.h> int main() { int *ar[5],n[5],i,j,m; for(i=0;i<5;i++) { printf("Enter number of student for class %d\n",i+1); scanf("%d",&m); n[i]=m; ar[i]=(int *)malloc(sizeof(int)*m); if(ar[i]==NULL) { printf("Memory allocation failed\n"); return 1; } for(j=0;j<m;j++) { scanf("%d",&ar[i][j]); } } printf("Output\n"); for(i=0;i<5;i++) { printf("Results for class %d\n",i+1); for(j=0;j<n[i];j++) { printf("%d\n",ar[i][j]); } } free(ar[5]); }
C
#include "cq-header.h" int sec(pd0) /* 6.2 Float and double */ /* 6.3 Floating and integral */ /* 6.4 Pointers and integers */ /* 6.5 Unsigned */ /* 6.6 Arithmetic conversions */ struct defs *pd0; { setupTable(pd0); static char s626er[] = "s626,er%d\n"; static char qs626[8] = "s626 "; int rc; char *ps, *pt; float eps, f1, f2, f3, f4, f; long lint1, lint2, l, ls; char c, t[28], t0; short s; int is, i, j; unsigned u, us; double d, ds; ps = qs626; pt = pd0->rfs; rc = 0; while (*pt++ = *ps++); /* Conversions of integral values to floating type are well-behaved. */ f1 = 1.; lint1 = 1.; lint2 = 1.; for(j=0;j<pd0->lbits-2;j++){ f1 = f1*2; lint2 = (lint2<<1)|lint1; } f2 = lint2; f1 = (f1-f2)/f1; if(f1>2.*pd0->fprec){ rc = rc+2; if(pd0->flgd != 0) printf(s626er,2); } /* Pointer-integer combinations are discussed in s74, "Additive operators". The unsigned-int combination appears below. */ c = 125; s = 125; i = 125; is = 15625; u = 125; us = 15625; l = 125; ls = 15625; f = 125.; d = 125.; ds = 15625.; for(j=0;j<28;j++) t[j] = 0; if(c*c != is) t[ 0] = 1; if(s*c != is) t[ 1] = 1; if(s*s != is) t[ 2] = 1; if(i*c != is) t[ 3] = 1; if(i*s != is) t[ 4] = 1; if(i*i != is) t[ 5] = 1; if(u*c != us) t[ 6] = 1; if(u*s != us) t[ 7] = 1; if(u*i != us) t[ 8] = 1; if(u*u != us) t[ 9] = 1; if(l*c != ls) t[10] = 1; if(l*s != ls) t[11] = 1; if(l*i != ls) t[12] = 1; if(l*u != us) t[13] = 1; if(l*l != ls) t[14] = 1; if(f*c != ds) t[15] = 1; if(f*s != ds) t[16] = 1; if(f*i != ds) t[17] = 1; if(f*u != ds) t[18] = 1; if(f*l != ds) t[19] = 1; if(f*f != ds) t[20] = 1; if(d*c != ds) t[21] = 1; if(d*s != ds) t[22] = 1; if(d*i != ds) t[23] = 1; if(d*u != ds) t[24] = 1; if(d*l != ds) t[25] = 1; if(d*f != ds) t[26] = 1; if(d*d != ds) t[27] = 1; t0 = 0; for(j=0; j<28; j++) t0 = t0+t[j]; if(t0 != 0){ rc = rc+4; if(pd0->flgd != 0){ printf(s626er,4); printf(" key="); for(j=0;j<28;j++) printf("%d",t[j]); printf("\n"); } } /* When an unsigned integer is converted to long, the value of the result is the same numerically as that of the unsigned integer. */ l = (unsigned)0100000; if((long)l > (unsigned)0100000){ rc = rc+8; if(pd0->flgd != 0) printf(s626er,8); } return rc; } #include "cq-main.h"
C
#include "interface.h" void setEntradaGrafo(Grafo *grafo, char *entrada) { char **Buffer; int size; Buffer = leArquivo(entrada, &size); if(Buffer == NULL) { printf("\nErro ao ler arquivo, o programa sera fechado!!\n"); exit(EXIT_FAILURE); } int i, V1, V2, NVertices, NArestas; short inicializou = 0; i = 0; while(!inicializou) { while(strcmp(Buffer[i], "p") != 0 && i < size) { free(Buffer[i]); i++; } if(strcmp(Buffer[i], "p") == 0 && strcmp(Buffer[i+1], "edge") == 0) { NVertices = atoi(Buffer[i+2]); NArestas = atoi(Buffer[i+3]); inicializaGrafo(grafo, NArestas, NVertices); free(Buffer[i]); free(Buffer[i+1]); free(Buffer[i+2]); free(Buffer[i+3]); i += 4; inicializou = 1; } else { i++; } } while(i < size) { while(strcmp(Buffer[i], "e") != 0) { i++; } V1 = atoi(Buffer[i+1]); V2 = atoi(Buffer[i+2]); //todas as arestas terao uma unidade a menos (facilita busca em vetor) V1--; V2--; InsereAresta(grafo, V1, V2); free(Buffer[i]); free(Buffer[i+1]); free(Buffer[i+2]); i = i+3; } free(Buffer); } void SalvaSaida(int cor, long long int tentativas, double finalTime, char* saida, char *fileTeste) { printf("\n\nNumero de cores: %d", cor); printf("\nNumero de tentativas: %lld\n\n", tentativas); char *string = malloc(sizeof(char) * 50); sprintf(string, " %d %lld\n", cor, tentativas); saveFile(saida, string); free(string); string = malloc(sizeof(char) * 50); sprintf(string, " %f\n", finalTime); saveFile(fileTeste, string); free(string); } void readArgs(int argc, char** argv, char **entrada, char **saida, char **fileTeste, int *algoritmo) { int c; //variavel provisoria para a funcao get opt c = 0; if(argc < 7) { printf("Entrada invalida, erro! A entrada deve conter os seguintes parametros: \n" "-s <1|2|3> - indicando qual dos algoritmos deve ser utilizado\n" "-i <nome do arquivo de entrada>\n" "-o <nome do arquivo de saída>\n" "Para mais informaçoes cheque o arquivo leiame.txt \n" "O Programa sera fechado"); exit(EXIT_FAILURE); } int t = 0; while((c = getopt (argc, argv, ":s:i:o:t:")) != -1) { switch (c) { case 's': (*algoritmo) = atoi(optarg); break; case 'i': (*entrada) = optarg; break; case 'o': (*saida) = optarg; break; case 't': t = 1; (*fileTeste) = optarg; break; case '?': printf("Parametros de entrada incorretos, por favor cheque o arquivo leiame.txt para mais informacoes\n" "o programa sera fechado\n"); exit(EXIT_FAILURE); default: abort (); } } if(t == 0) { (*fileTeste) = malloc(sizeof(char) * 10); strcpy((*fileTeste),"saida.ods"); } } double getTime() { struct timeval tv; double curtime; gettimeofday(&tv, NULL); curtime = (double) tv.tv_sec + 1.e-6 * (double) tv.tv_usec; return(curtime); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <omp.h> #include <math.h> #define LINE_SIZE 26 //strict file format: assuming fixed length for each line and value #define POINT_SIZE 8 #define MAX_OUTPUT 3464 #define MAX_LINE_COUNT 1000000 //maximum of lines to be allocated at once void print_cells(short int ** arr, short int line_count) { for ( size_t ix = 0; ix < line_count; ++ix ) printf("%02d.%03d %02d.%03d %02d.%03d\n", arr[ix][0]/1000, abs(arr[ix][0]%1000), arr[ix][1]/1000, abs(arr[ix][1]%1000), arr[ix][2]/1000, abs(arr[ix][2]%1000)); } void print_output(int * arr_counts) { for ( size_t ix = 0; ix < MAX_OUTPUT; ++ix ) { if(arr_counts[ix] != 0) { float out = (float)ix/100; printf("%5.2f %d\n", out, arr_counts[ix]); } } } void process_cells(short int ** inputs, int * outputs, long int max_point) { size_t current_point = 0; #pragma omp parallel for private(current_point) for (current_point = 0; current_point < max_point - 1; current_point++) { float x1, y1, z1; int * outputs_local = (int*) malloc(sizeof(int) * MAX_OUTPUT); for ( size_t ix = 0; ix < MAX_OUTPUT; ++ix ) { outputs_local[ix] = 0; } x1 = inputs[current_point][0] / 1000.0; y1 = inputs[current_point][1] / 1000.0; z1 = inputs[current_point][2] / 1000.0; for (size_t i = 1; i < max_point - current_point; ++i) { //compare ix with current_point and store in outputs[current_point+ix-1] size_t ix = current_point + i; float x2, y2, z2; x2 = inputs[ix][0] / 1000.0; y2 = inputs[ix][1] / 1000.0; z2 = inputs[ix][2] / 1000.0; int index = (short) (100 * sqrtf((z2 - z1) * (z2 - z1) + (y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1))); outputs_local[index]++; } if(current_point % 10000 == 0) printf("silly\n"); #pragma omp critical { for ( size_t ix = 0; ix < MAX_OUTPUT; ++ix ) outputs[ix] += outputs_local[ix]; } free(outputs_local); } } /*void process_sequential(short int ** inputs, short int * outputs, int max_point) { size_t current_point = 0; #pragma omp parallel for private(current_point) for (current_point = 0; current_point < max_point - 1; current_point++) { float x1, y1, z1; short int * outputs_local = (short int*) malloc(sizeof(short int) * MAX_OUTPUT); for ( size_t ix = 0; ix < MAX_OUTPUT; ++ix ) { outputs_local[ix] = 0; } x1 = inputs[current_point][0] / 1000.0; y1 = inputs[current_point][1] / 1000.0; z1 = inputs[current_point][2] / 1000.0; for (size_t i = 1; i < max_point - current_point; ++i) { //compare ix with current_point and store in outputs[current_point+ix-1] size_t ix = current_point + i; float x2, y2, z2; x2 = inputs[ix][0] / 1000.0; y2 = inputs[ix][1] / 1000.0; z2 = inputs[ix][2] / 1000.0; int index = (short) (100 * sqrtf((z2 - z1) * (z2 - z1) + (y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1))); outputs_local[index]++; } printf("batch: %ld\n", current_point); #pragma omp critical { for ( size_t ix = 0; ix < MAX_OUTPUT; ++ix ) outputs[ix] += outputs_local[ix]; } free(outputs_local); } } */ void read_cells(FILE* pFile, short int ** cells_list, long int line_count) { char line[LINE_SIZE]; size_t i_point; for (i_point = 0; i_point < line_count; i_point++) { fgets(line, LINE_SIZE, pFile); int p = 0; int i = 0; int pos = 0; for (;i<3; ++i, ++p) { pos = i*POINT_SIZE; cells_list[i_point][i] = (line[pos+1]-'0')*10000+(line[pos+2]-'0')*1000+(line[pos+4]-'0')*100+(line[pos+5]-'0')*10+(line[pos+6]-'0'); if(line[pos] == '-') cells_list[i_point][i] *= -1; } } fclose(pFile); //print_cells(cells_list, i_point); } int main(int argc, char *argv[]) { int param_t; if(argc != 2) { printf("The number of arguments is invalid. Expected: -t#\n"); exit(1); } param_t = atoi(&argv[1][2]); omp_set_num_threads(param_t); char filename[] = "cells.txt"; FILE * pFile; pFile = fopen(filename, "r"); //determine number of lines long int line_count = 0; char line[LINE_SIZE]; while(fgets(line, LINE_SIZE, pFile)) { line_count++; } rewind(pFile); printf("line count: %ld\n", line_count); //getchar(); int * count_list = (int*) malloc(sizeof(int) * MAX_OUTPUT); //counting array for ( size_t ix = 0; ix < MAX_OUTPUT; ++ix ) { count_list[ix] = 0; } short int ** cells_list; if(line_count > MAX_LINE_COUNT) { int parts = line_count / MAX_LINE_COUNT + 1; cells_list = (short int**) malloc(sizeof(short int*) * MAX_LINE_COUNT); //maximum array for ( size_t ix = 0; ix < line_count; ++ix ) { cells_list[ix] = (short int*) malloc(sizeof(short int) * 3); } short int ** full_cells_list = (short int**) malloc(sizeof(short int*) * line_count); //maximum array for ( size_t ix = 0; ix < line_count; ++ix ) { cells_list[ix] = (short int*) malloc(sizeof(short int) * 3); } for(int i = 0; i < parts; i++) { read_cells(pFile, cells_list, line_count); process_cells(cells_list, count_list, MAX_LINE_COUNT); } } else { cells_list = (short int**) malloc(sizeof(short int*) * line_count); //array of points read for ( size_t ix = 0; ix < line_count; ++ix ) { cells_list[ix] = (short int*) malloc(sizeof(short int) * 3); } read_cells(pFile, cells_list, line_count); process_cells(cells_list, count_list, line_count); } print_output(count_list); free(cells_list); return 0; }
C
#include <stdio.h> #include <time.h> #include <stdlib.h> struct card{ int data; struct card *next; }; typedef struct card card; int check(int b, int* count){ if(count[b - 1] == 0){ count[b - 1] = 1; return b; }else{ b = rand() % 13 + 1; return check(b, count); } }; void putiInArray(int *b){ int count[13] = {0}; srand(time(NULL)); for(int i = 0; i < 13 ; i ++){ b[i] = rand() % 13 + 1; b[i] = check(b[i], count); } }; void printCard(card* head){ card *ptr1; ptr1 = head; while(ptr1 != NULL){ if(ptr1->data == 1){ printf("A "); }else if(ptr1->data == 11){ printf("J "); }else if(ptr1->data == 12){ printf("Q "); }else if(ptr1->data == 13){ printf("K "); }else{ printf("%d ", ptr1->data); } ptr1 = ptr1->next; } printf("\n"); }; int drawCard(int b, int rightcard){ if(b == rightcard){ return 1; }else{ return 0; } }; card* putToButtom(card *head){ card *ptr2; card *temp; ptr2 = head; while (ptr2->next != NULL) { ptr2 = ptr2->next; } temp = head; ptr2->next = temp; head = head->next; temp->next = NULL; return head; }; card* drawOut(card* head){ card* temp; temp = head; head = head->next; temp->next = NULL; free(temp); return head; }; int main(){ int b[13]; int i, j; int len = 13; card *head = NULL; card *ptr; card *now; card *prev; putiInArray(b); for(i = 0; i < 13; i++){ now = (card *)malloc(sizeof(card)); now->data = b[i]; now->next = NULL; if(head == NULL){ head = now; prev = now; }else{ prev->next = now; prev = now; } } while(ptr != NULL){ for(j = 13; j > 0;){ ptr = head; if(drawCard(ptr->data, j)){ j--; printCard(head); head = drawOut(head); }else{ printCard(head); head = putToButtom(head); } } } printCard(head); }
C
#include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <sys/ioctl.h> #include <ctype.h> #include <stdlib.h> #include "CtcDrvr.h" #define _DRVR_NM_ "CTC" #define matchEndian(bytes, size, depth) { } /** * @brief Open device driver node * * @param lun -- Logical Unit Number assigned to the module. Negative in case * of driver simulator * @param chanN -- Minor Device Number. There can be several entry points for * current Logical Unit Number (ChannelNumber). * * @return Open file decriptor (normally >= 3) - if success * @return -1 - if fails * Error message is printing out. */ int CtcEnableAccess(int lun, int chanN) { int fd; /* open file descriptor */ char fileName[0x100]; /* device file name */ char *tmp; if (!MODULE_NAME_OK(_DRVR_NM_)) { fprintf(stderr, "Spurious Module Name '%s'.\n" "Normally _should not_ contain any lowercase" " letters!\n", _DRVR_NM_); return -1; } tmp = _ncf(_DRVR_NM_); sprintf(fileName, "/dev/" NODE_NAME_FMT, tmp, (lun < 0)?_SIML_:_DRVR_, abs(lun), chanN); free(tmp); if ((fd = open(fileName, O_RDWR)) < 0) { /* error */ perror(NULL); fprintf(stderr, "Error [%s] in CtcEnableAccess()" " while opening '%s' file.\nCheck if '%s' module is" " installed.\n", strerror(errno), fileName, _DRVR_NM_); return -1; } return fd; } /** * @brief Close driver file descriptor. * * @param fd -- open file descriptor, retuned by CtcEnableAccess call * * @return void */ void CtcDisableAccess(int fd) { close(fd); } /** * @brief * * @param fd -- driver node descriptor * @param result -- buffer to put results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetSTATUS( int fd, unsigned long *result) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) result; /* where to put results */ arguments[1] = 1; /* number of elements to read */ arguments[2] = 0; /* element index */ /* driver call */ if (ioctl(fd, CTC_GET_STATUS, (char*)arguments)) return -1; /* handle endianity */ matchEndian((char*)result, sizeof(unsigned long), 0); return 0; } /** * @brief * * @param fd -- driver node descriptor * @param result -- buffer to put results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetCNTR_ENABLE( int fd, unsigned long *result) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) result; /* where to put results */ arguments[1] = 1; /* number of elements to read */ arguments[2] = 0; /* element index */ /* driver call */ if (ioctl(fd, CTC_GET_CNTR_ENABLE, (char*)arguments)) return -1; /* handle endianity */ matchEndian((char*)result, sizeof(unsigned long), 0); return 0; } /** * @brief * * @param fd -- driver node descriptor * @param arg -- new values * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcSetCNTR_ENABLE( int fd, unsigned long arg) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) &arg; /* where to take data from */ arguments[1] = 1; /* number of elements write */ arguments[2] = 0; /* element index */ /* handle endianity */ matchEndian((char*)&arg, sizeof(unsigned long), 0); return ioctl(fd, CTC_SET_CNTR_ENABLE, (char *)arguments); } /** * @brief * * @param fd -- driver node descriptor * @param result -- buffer to put results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetconfChan( int fd, unsigned long *result) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) result; /* where to put results */ arguments[1] = 1; /* number of elements to read */ arguments[2] = 0; /* element index */ /* driver call */ if (ioctl(fd, CTC_GET_CONFCHAN, (char*)arguments)) return -1; /* handle endianity */ matchEndian((char*)result, sizeof(unsigned long), 0); return 0; } /** * @brief * * @param fd -- driver node descriptor * @param arg -- new values * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcSetconfChan( int fd, unsigned long arg) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) &arg; /* where to take data from */ arguments[1] = 1; /* number of elements write */ arguments[2] = 0; /* element index */ /* handle endianity */ matchEndian((char*)&arg, sizeof(unsigned long), 0); return ioctl(fd, CTC_SET_CONFCHAN, (char *)arguments); } /** * @brief * * @param fd -- driver node descriptor * @param result -- buffer to put results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetclock1Delay( int fd, unsigned long *result) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) result; /* where to put results */ arguments[1] = 1; /* number of elements to read */ arguments[2] = 0; /* element index */ /* driver call */ if (ioctl(fd, CTC_GET_CLOCK1DELAY, (char*)arguments)) return -1; /* handle endianity */ matchEndian((char*)result, sizeof(unsigned long), 0); return 0; } /** * @brief * * @param fd -- driver node descriptor * @param arg -- new values * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcSetclock1Delay( int fd, unsigned long arg) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) &arg; /* where to take data from */ arguments[1] = 1; /* number of elements write */ arguments[2] = 0; /* element index */ /* handle endianity */ matchEndian((char*)&arg, sizeof(unsigned long), 0); return ioctl(fd, CTC_SET_CLOCK1DELAY, (char *)arguments); } /** * @brief * * @param fd -- driver node descriptor * @param result -- buffer to put results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetclock2Delay( int fd, unsigned long *result) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) result; /* where to put results */ arguments[1] = 1; /* number of elements to read */ arguments[2] = 0; /* element index */ /* driver call */ if (ioctl(fd, CTC_GET_CLOCK2DELAY, (char*)arguments)) return -1; /* handle endianity */ matchEndian((char*)result, sizeof(unsigned long), 0); return 0; } /** * @brief * * @param fd -- driver node descriptor * @param arg -- new values * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcSetclock2Delay( int fd, unsigned long arg) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) &arg; /* where to take data from */ arguments[1] = 1; /* number of elements write */ arguments[2] = 0; /* element index */ /* handle endianity */ matchEndian((char*)&arg, sizeof(unsigned long), 0); return ioctl(fd, CTC_SET_CLOCK2DELAY, (char *)arguments); } /** * @brief * * @param fd -- driver node descriptor * @param result -- buffer to put results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetoutputCntr( int fd, unsigned long *result) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) result; /* where to put results */ arguments[1] = 1; /* number of elements to read */ arguments[2] = 0; /* element index */ /* driver call */ if (ioctl(fd, CTC_GET_OUTPUTCNTR, (char*)arguments)) return -1; /* handle endianity */ matchEndian((char*)result, sizeof(unsigned long), 0); return 0; } /** * @brief * * @param fd -- driver node descriptor * @param result -- buffer to put results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetcntr1CurVal( int fd, unsigned long *result) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) result; /* where to put results */ arguments[1] = 1; /* number of elements to read */ arguments[2] = 0; /* element index */ /* driver call */ if (ioctl(fd, CTC_GET_CNTR1CURVAL, (char*)arguments)) return -1; /* handle endianity */ matchEndian((char*)result, sizeof(unsigned long), 0); return 0; } /** * @brief * * @param fd -- driver node descriptor * @param result -- buffer to put results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetcntr2CurVal( int fd, unsigned long *result) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) result; /* where to put results */ arguments[1] = 1; /* number of elements to read */ arguments[2] = 0; /* element index */ /* driver call */ if (ioctl(fd, CTC_GET_CNTR2CURVAL, (char*)arguments)) return -1; /* handle endianity */ matchEndian((char*)result, sizeof(unsigned long), 0); return 0; } /** * @brief * * @param fd -- driver node descriptor * @param elOffs -- element offset (expressed in elements) * @param depth -- number of elemets to get * @param result -- buffer for the results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetWindowchannel_1( int fd, unsigned int elOffs, unsigned int depth, unsigned long *result) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) result; arguments[1] = depth; arguments[2] = elOffs; /* driver call */ if (ioctl(fd, CTC_GET_CHANNEL_1, (char*)arguments)) return -1; /* handle endianity */ matchEndian((char*)result, sizeof(unsigned long), 6); return 0; } /** * @brief * * @param fd -- driver node descriptor * @param result -- buffer to put results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetchannel_1( int fd, unsigned long result[6]) { return CtcGetWindowchannel_1(fd, 0, 6, result); } /** * @brief * * @param fd -- driver node descriptor * @param elOffs -- element offset (expressed in elements) * @param depth -- number of elemets to set * @param arg -- buffer holds new values * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcSetWindowchannel_1( int fd, unsigned int elOffs, unsigned int depth, unsigned long *arg) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) arg; /* where to take data from */ arguments[1] = depth; /* number of elements write */ arguments[2] = elOffs; /* element index */ /* handle endianity */ matchEndian((char*)arg, sizeof(unsigned long), 6); /* driver call */ return ioctl(fd, CTC_SET_CHANNEL_1, (char *)arguments); } /** * @brief * * @param fd -- driver node descriptor * @param arg -- buffer holds new values * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcSetchannel_1( int fd, unsigned long arg[6]) { return CtcSetWindowchannel_1(fd, 0, 6, arg); } /** * @brief * * @param fd -- driver node descriptor * @param elOffs -- element offset (expressed in elements) * @param depth -- number of elemets to get * @param result -- buffer for the results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetWindowchannel_2( int fd, unsigned int elOffs, unsigned int depth, unsigned long *result) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) result; arguments[1] = depth; arguments[2] = elOffs; /* driver call */ if (ioctl(fd, CTC_GET_CHANNEL_2, (char*)arguments)) return -1; /* handle endianity */ matchEndian((char*)result, sizeof(unsigned long), 6); return 0; } /** * @brief * * @param fd -- driver node descriptor * @param result -- buffer to put results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetchannel_2( int fd, unsigned long result[6]) { return CtcGetWindowchannel_2(fd, 0, 6, result); } /** * @brief * * @param fd -- driver node descriptor * @param elOffs -- element offset (expressed in elements) * @param depth -- number of elemets to set * @param arg -- buffer holds new values * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcSetWindowchannel_2( int fd, unsigned int elOffs, unsigned int depth, unsigned long *arg) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) arg; /* where to take data from */ arguments[1] = depth; /* number of elements write */ arguments[2] = elOffs; /* element index */ /* handle endianity */ matchEndian((char*)arg, sizeof(unsigned long), 6); /* driver call */ return ioctl(fd, CTC_SET_CHANNEL_2, (char *)arguments); } /** * @brief * * @param fd -- driver node descriptor * @param arg -- buffer holds new values * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcSetchannel_2( int fd, unsigned long arg[6]) { return CtcSetWindowchannel_2(fd, 0, 6, arg); } /** * @brief * * @param fd -- driver node descriptor * @param elOffs -- element offset (expressed in elements) * @param depth -- number of elemets to get * @param result -- buffer for the results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetWindowchannel_3( int fd, unsigned int elOffs, unsigned int depth, unsigned long *result) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) result; arguments[1] = depth; arguments[2] = elOffs; /* driver call */ if (ioctl(fd, CTC_GET_CHANNEL_3, (char*)arguments)) return -1; /* handle endianity */ matchEndian((char*)result, sizeof(unsigned long), 6); return 0; } /** * @brief * * @param fd -- driver node descriptor * @param result -- buffer to put results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetchannel_3( int fd, unsigned long result[6]) { return CtcGetWindowchannel_3(fd, 0, 6, result); } /** * @brief * * @param fd -- driver node descriptor * @param elOffs -- element offset (expressed in elements) * @param depth -- number of elemets to set * @param arg -- buffer holds new values * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcSetWindowchannel_3( int fd, unsigned int elOffs, unsigned int depth, unsigned long *arg) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) arg; /* where to take data from */ arguments[1] = depth; /* number of elements write */ arguments[2] = elOffs; /* element index */ /* handle endianity */ matchEndian((char*)arg, sizeof(unsigned long), 6); /* driver call */ return ioctl(fd, CTC_SET_CHANNEL_3, (char *)arguments); } /** * @brief * * @param fd -- driver node descriptor * @param arg -- buffer holds new values * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcSetchannel_3( int fd, unsigned long arg[6]) { return CtcSetWindowchannel_3(fd, 0, 6, arg); } /** * @brief * * @param fd -- driver node descriptor * @param elOffs -- element offset (expressed in elements) * @param depth -- number of elemets to get * @param result -- buffer for the results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetWindowchannel_4( int fd, unsigned int elOffs, unsigned int depth, unsigned long *result) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) result; arguments[1] = depth; arguments[2] = elOffs; /* driver call */ if (ioctl(fd, CTC_GET_CHANNEL_4, (char*)arguments)) return -1; /* handle endianity */ matchEndian((char*)result, sizeof(unsigned long), 6); return 0; } /** * @brief * * @param fd -- driver node descriptor * @param result -- buffer to put results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetchannel_4( int fd, unsigned long result[6]) { return CtcGetWindowchannel_4(fd, 0, 6, result); } /** * @brief * * @param fd -- driver node descriptor * @param elOffs -- element offset (expressed in elements) * @param depth -- number of elemets to set * @param arg -- buffer holds new values * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcSetWindowchannel_4( int fd, unsigned int elOffs, unsigned int depth, unsigned long *arg) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) arg; /* where to take data from */ arguments[1] = depth; /* number of elements write */ arguments[2] = elOffs; /* element index */ /* handle endianity */ matchEndian((char*)arg, sizeof(unsigned long), 6); /* driver call */ return ioctl(fd, CTC_SET_CHANNEL_4, (char *)arguments); } /** * @brief * * @param fd -- driver node descriptor * @param arg -- buffer holds new values * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcSetchannel_4( int fd, unsigned long arg[6]) { return CtcSetWindowchannel_4(fd, 0, 6, arg); } /** * @brief * * @param fd -- driver node descriptor * @param elOffs -- element offset (expressed in elements) * @param depth -- number of elemets to get * @param result -- buffer for the results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetWindowchannel_5( int fd, unsigned int elOffs, unsigned int depth, unsigned long *result) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) result; arguments[1] = depth; arguments[2] = elOffs; /* driver call */ if (ioctl(fd, CTC_GET_CHANNEL_5, (char*)arguments)) return -1; /* handle endianity */ matchEndian((char*)result, sizeof(unsigned long), 6); return 0; } /** * @brief * * @param fd -- driver node descriptor * @param result -- buffer to put results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetchannel_5( int fd, unsigned long result[6]) { return CtcGetWindowchannel_5(fd, 0, 6, result); } /** * @brief * * @param fd -- driver node descriptor * @param elOffs -- element offset (expressed in elements) * @param depth -- number of elemets to set * @param arg -- buffer holds new values * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcSetWindowchannel_5( int fd, unsigned int elOffs, unsigned int depth, unsigned long *arg) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) arg; /* where to take data from */ arguments[1] = depth; /* number of elements write */ arguments[2] = elOffs; /* element index */ /* handle endianity */ matchEndian((char*)arg, sizeof(unsigned long), 6); /* driver call */ return ioctl(fd, CTC_SET_CHANNEL_5, (char *)arguments); } /** * @brief * * @param fd -- driver node descriptor * @param arg -- buffer holds new values * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcSetchannel_5( int fd, unsigned long arg[6]) { return CtcSetWindowchannel_5(fd, 0, 6, arg); } /** * @brief * * @param fd -- driver node descriptor * @param elOffs -- element offset (expressed in elements) * @param depth -- number of elemets to get * @param result -- buffer for the results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetWindowchannel_6( int fd, unsigned int elOffs, unsigned int depth, unsigned long *result) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) result; arguments[1] = depth; arguments[2] = elOffs; /* driver call */ if (ioctl(fd, CTC_GET_CHANNEL_6, (char*)arguments)) return -1; /* handle endianity */ matchEndian((char*)result, sizeof(unsigned long), 6); return 0; } /** * @brief * * @param fd -- driver node descriptor * @param result -- buffer to put results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetchannel_6( int fd, unsigned long result[6]) { return CtcGetWindowchannel_6(fd, 0, 6, result); } /** * @brief * * @param fd -- driver node descriptor * @param elOffs -- element offset (expressed in elements) * @param depth -- number of elemets to set * @param arg -- buffer holds new values * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcSetWindowchannel_6( int fd, unsigned int elOffs, unsigned int depth, unsigned long *arg) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) arg; /* where to take data from */ arguments[1] = depth; /* number of elements write */ arguments[2] = elOffs; /* element index */ /* handle endianity */ matchEndian((char*)arg, sizeof(unsigned long), 6); /* driver call */ return ioctl(fd, CTC_SET_CHANNEL_6, (char *)arguments); } /** * @brief * * @param fd -- driver node descriptor * @param arg -- buffer holds new values * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcSetchannel_6( int fd, unsigned long arg[6]) { return CtcSetWindowchannel_6(fd, 0, 6, arg); } /** * @brief * * @param fd -- driver node descriptor * @param elOffs -- element offset (expressed in elements) * @param depth -- number of elemets to get * @param result -- buffer for the results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetWindowchannel_7( int fd, unsigned int elOffs, unsigned int depth, unsigned long *result) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) result; arguments[1] = depth; arguments[2] = elOffs; /* driver call */ if (ioctl(fd, CTC_GET_CHANNEL_7, (char*)arguments)) return -1; /* handle endianity */ matchEndian((char*)result, sizeof(unsigned long), 6); return 0; } /** * @brief * * @param fd -- driver node descriptor * @param result -- buffer to put results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetchannel_7( int fd, unsigned long result[6]) { return CtcGetWindowchannel_7(fd, 0, 6, result); } /** * @brief * * @param fd -- driver node descriptor * @param elOffs -- element offset (expressed in elements) * @param depth -- number of elemets to set * @param arg -- buffer holds new values * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcSetWindowchannel_7( int fd, unsigned int elOffs, unsigned int depth, unsigned long *arg) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) arg; /* where to take data from */ arguments[1] = depth; /* number of elements write */ arguments[2] = elOffs; /* element index */ /* handle endianity */ matchEndian((char*)arg, sizeof(unsigned long), 6); /* driver call */ return ioctl(fd, CTC_SET_CHANNEL_7, (char *)arguments); } /** * @brief * * @param fd -- driver node descriptor * @param arg -- buffer holds new values * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcSetchannel_7( int fd, unsigned long arg[6]) { return CtcSetWindowchannel_7(fd, 0, 6, arg); } /** * @brief * * @param fd -- driver node descriptor * @param elOffs -- element offset (expressed in elements) * @param depth -- number of elemets to get * @param result -- buffer for the results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetWindowchannel_8( int fd, unsigned int elOffs, unsigned int depth, unsigned long *result) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) result; arguments[1] = depth; arguments[2] = elOffs; /* driver call */ if (ioctl(fd, CTC_GET_CHANNEL_8, (char*)arguments)) return -1; /* handle endianity */ matchEndian((char*)result, sizeof(unsigned long), 6); return 0; } /** * @brief * * @param fd -- driver node descriptor * @param result -- buffer to put results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetchannel_8( int fd, unsigned long result[6]) { return CtcGetWindowchannel_8(fd, 0, 6, result); } /** * @brief * * @param fd -- driver node descriptor * @param elOffs -- element offset (expressed in elements) * @param depth -- number of elemets to set * @param arg -- buffer holds new values * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcSetWindowchannel_8( int fd, unsigned int elOffs, unsigned int depth, unsigned long *arg) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) arg; /* where to take data from */ arguments[1] = depth; /* number of elements write */ arguments[2] = elOffs; /* element index */ /* handle endianity */ matchEndian((char*)arg, sizeof(unsigned long), 6); /* driver call */ return ioctl(fd, CTC_SET_CHANNEL_8, (char *)arguments); } /** * @brief * * @param fd -- driver node descriptor * @param arg -- buffer holds new values * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcSetchannel_8( int fd, unsigned long arg[6]) { return CtcSetWindowchannel_8(fd, 0, 6, arg); } /** * @brief * * @param fd -- driver node descriptor * @param elOffs -- element offset (expressed in elements) * @param depth -- number of elemets to get * @param result -- buffer for the results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetWindowALL_CHANNELS( int fd, unsigned int elOffs, unsigned int depth, unsigned long *result) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) result; arguments[1] = depth; arguments[2] = elOffs; /* driver call */ if (ioctl(fd, CTC_GET_ALL_CHANNELS, (char*)arguments)) return -1; /* handle endianity */ matchEndian((char*)result, sizeof(unsigned long), 48); return 0; } /** * @brief * * @param fd -- driver node descriptor * @param result -- buffer to put results * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcGetALL_CHANNELS( int fd, unsigned long result[48]) { return CtcGetWindowALL_CHANNELS(fd, 0, 48, result); } /** * @brief * * @param fd -- driver node descriptor * @param elOffs -- element offset (expressed in elements) * @param depth -- number of elemets to set * @param arg -- buffer holds new values * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcSetWindowALL_CHANNELS( int fd, unsigned int elOffs, unsigned int depth, unsigned long *arg) { unsigned long arguments[3]; /* pack ioctl args */ arguments[0] = (unsigned long) arg; /* where to take data from */ arguments[1] = depth; /* number of elements write */ arguments[2] = elOffs; /* element index */ /* handle endianity */ matchEndian((char*)arg, sizeof(unsigned long), 48); /* driver call */ return ioctl(fd, CTC_SET_ALL_CHANNELS, (char *)arguments); } /** * @brief * * @param fd -- driver node descriptor * @param arg -- buffer holds new values * * @return 0 - on success. * @return -1 - if error occurs. errno is set appropriately. */ int CtcSetALL_CHANNELS( int fd, unsigned long arg[48]) { return CtcSetWindowALL_CHANNELS(fd, 0, 48, arg); }
C
#include "binary_trees.h" /** * binary_tree_preorder - a function that pre-order traverses a binary tree * @tree: a pointer to the root node of the tree to traverse * @func: a pointer to a function to call for each node, value passed as param * * Return: No data type returned. If tree or func is NULL do nothing. */ void binary_tree_preorder(const binary_tree_t *tree, void (*func)(int)) { if (tree && func) { /* value in node passed as a parameter to function */ func(tree->n); binary_tree_preorder(tree->left, func); binary_tree_preorder(tree->right, func); } }
C
#include<stdio.h> int cnt=0; void move(int,char,char,char); int main(){ int disk; printf("Input num of disks : "); scanf("%d",&disk); move(disk,'A','B','C'); return 0; } void move(int n, char a, char b, char c) { if (n == 1) { ++cnt; printf("\n%5d: Move disk 1 from %c to %c", cnt, a, c); return; } else { move(n-1, a, c, b); ++cnt; printf("\n%5d: Move disk %d from %c to %c", cnt, n, a, c); move(n-1, b, a, c); return; } }
C
#include<sys/ipc.h> #include<sys/shm.h> #include<stdio.h> #include<stdlib.h> #include<unistd.h> int main (){ // ftok to generate unique key key_t key = ftok("shmfile",65); // shmget returns an identifier in shmid int shmid = shmget(key,5*sizeof(int),0666|IPC_CREAT); // shmat to attach to shared memory int *arr = shmat(shmid, 0, 0); arr[0] = 0; arr[1] = 1; arr[2] = 2; arr[3] = 3; arr[4] = 4; pid_t pid = fork(); if(pid == 0){ arr[0] = 10; arr[1] = 11; arr[2] = 12; arr[3] = 13; arr[4] = 14; } else{ for(int i=0; i<5; i++){ printf("%d ", arr[i]); } sleep(2); for(int i=0; i<5; i++){ printf("%d ", arr[i]); } shmdt(arr); shmctl(shmid,IPC_RMID,NULL); } return 0; }
C
#include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "utility.h" unsigned char debug; int GetClockSecond(void) {int ret,time; struct timespec res; ret=clock_gettime(CLOCK_MONOTONIC,&res); if(ret==0){ time=res.tv_sec+(res.tv_nsec/1000000000); } else { return -1; } return time; } int GetClockMsec(void) {int ret,time; struct timespec res; ret=clock_gettime(CLOCK_MONOTONIC,&res); if(ret==0){ time=(res.tv_sec*1000)+(res.tv_nsec/1000000); } else { return -1; } return time; } char *ReadParamFile (char *parametro, char *file) { FILE *fpconf; char *line = NULL; char *position = NULL; char *param; int i; fpconf = fopen(file,"r"); if(fpconf == NULL){ WriteLog("Unable to open param file %s",file); return 0; } i=100; while(getline (&line, &i, fpconf)!= -1){// read config file line per line position = strstr(line,parametro); if(position!=NULL){ position+=strlen(parametro); param=strchr(position,' ')+1; if(strchr(param,'\n')){ position = strchr(param,'\n'); *position = 0; } if(strchr(param,'\r')){ position = strchr(param,'\r'); *position = 0; } //WriteDebug("ReadParamFile 3 (%s)",param); fclose(fpconf); return param; } } fclose(fpconf); //WriteLog("ReadParamFile error searching parameter <%s> ",parametro); return 0; } WriteDebug(char *str,...) { FILE *fp; char tmp[30]; time_t mytime; struct tm *mytm; if(debug!=1){ return 0; } fp = fopen(FILE_DEBUG,"a+"); if (fp==NULL) return -1; mytime=time(NULL); mytm=localtime(&mytime); strftime(tmp,sizeof (tmp),"(%d%b%Y)%H:%M:%S",mytm); fprintf(fp,"%s: ",tmp); va_list arglist; va_start(arglist,str); vfprintf(fp,str,arglist); va_end(arglist); fprintf(fp,"\n"); fclose(fp); return 1; } int WriteLog(char *str,...) { FILE *fp; char tmp[30]; time_t mytime; struct tm *mytm; fp = fopen(FILE_LOG,"a+"); if (fp==NULL) return -1; mytime=time(NULL); mytm=localtime(&mytime); strftime(tmp,sizeof (tmp),"(%d%b%Y)%H:%M:%S",mytm); fprintf(fp,"%s: ",tmp); va_list arglist; va_start(arglist,str); vfprintf(fp,str,arglist); va_end(arglist); fprintf(fp,"\n"); fclose(fp); return 1; }
C
#include "holberton.h" /** * print_rev - function that prints a string * in reverse, followed by a new line. * @s: input is a parameter * Return: void */ void print_rev(char *s) { int i, j; i = 0; while (s[i] != 0) { i++; } for (j = (i - 1); j >= 0; j--) { _putchar(*(s + j)); } _putchar('\n'); }
C
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <pthread.h> double factor(double num) { if (num == 0) { return 1; } double answ = 1; for(int i = 1;i<=num;i++) { answ*=i; } return answ; } int* erat(int n) { int* begining = (int*)malloc((n+1)*sizeof(int)); int counter = 0; int* current = (int*)malloc(sizeof(int)); for (int i = 0; i < n+1; ++i) { begining[i] = i; } for (int i = 2; i < n+1; ++i) { if (begining[i] != 0) { counter++; int* tmp = (int*)realloc(current,counter); if (tmp != NULL) { current = tmp; } else { printf(stderr,"%s\n", "Out of memory"); } current[counter-1] = begining[i]; for (int o = i*i; o < n+1; o+=i) { begining[o] = 0; } } } counter++; int* tmp = (int*)realloc(current,counter); if (tmp != NULL) { current = tmp; } else { printf(stderr,"%s\n", "Out of memory"); } current[counter-1] = NULL; free(tmp); free(begining); return current; } int* catalan(int n) { int* current = (int*)malloc((n+1)*sizeof(int)); for (int i = 0; i <= n; ++i) { current[i] = factor(2*i)/(factor(i+1)*factor(i)); } current[n] = NULL; return current; } int main(void) { int* child1; int* child2; pthread_t tid1; pthread_t tid2; if (pthread_create(&tid1,NULL,erat,10)) { printf(stderr, "%s\n", "Error!"); } if (pthread_create(&tid2,NULL,catalan,15)) { printf(stderr, "%s\n", "Error!"); } pthread_join(tid1,&child1); pthread_join(tid2,&child2); printf("%s\n", "Simples :"); for (int i = 0;child1[i] != NULL; ++i) { if (i%10 == 0 && i != 0) { printf("\n"); } printf("%d ", child1[i]); } printf("\n"); printf("%s\n", "Catalan's :"); for (int i = 0;child2[i] != NULL; ++i) { if (i%10 == 0 && i != 0) { printf("\n"); } printf("%d ", child2[i]); } printf("\n"); return 0; }
C
/* $Id: msh.c,v 1.48 2017/06/02 03:38:15 tranb7 Exp $ */ /* CS 352 -- Mini Shell! * * Sept 21, 2000, Phil Nelson * Modified April 8, 2001 * Modified January 6, 2003 * */ /* Brandon Tran * March 29, 2017 * CS 352 * Assignment 2 */ #include <stdio.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include "proto.h" #include "globals.h" /* Constants */ #define LINELEN 200000 /* Globals */ extern int argcount; extern char** args; extern int shift; extern int exitstatus; extern int sig; extern int WAIT; extern int DONTWAIT; extern int EXPAND; extern int DONTEXPAND; FILE* input; /* Prototypes */ void sig_handler (int signo, siginfo_t *siginfo, void *context); int findunquote (char *buf, char c); int pipeline (char* line, int cinfd, int coutfd, int cerrfd); /* Shell main */ int main (int argc, char **argv) { char buffer [LINELEN]; int len; argcount = argc; args = argv; struct sigaction act; WAIT = 1; DONTWAIT = 0; EXPAND = 4; DONTEXPAND = 0; act.sa_sigaction = &sig_handler; act.sa_flags = SA_SIGINFO + SA_RESTART; if (sigaction(SIGINT, &act, NULL) < 0) { dprintf(2, "sigaction: %s\n", strerror(errno)); return 1; } if (argc > 1) { input = fopen(argv[1], "r"); if(input == NULL) { dprintf(2, "Could not open file.\n"); exit(127); } } else { input = stdin; } while (1) { char* p1 = getenv("P1"); memset (&act, '\0', sizeof(act)); /* prompt and get line */ if(argc == 1) { if (p1 != NULL) { fprintf (stderr, "%s ", p1); } else { fprintf (stderr, "%% "); } } if (fgets (buffer, LINELEN, input) != buffer) break; /* Get rid of \n at end of buffer. */ len = strlen(buffer); if (buffer[len-1] == '\n') buffer[len-1] = 0; /* Run it ... */ sig = 0; processline (buffer, 0, 1, WAIT | EXPAND); } if (!feof(stdin) && argc == 1) dprintf(2, "read: %s\n", strerror(errno)); return 0; /* Also known as exit (0); */ } int processline (char *line, int infd, int outfd, int flags) { char newarray[LINELEN]; pid_t cpid; int status; int argcp = 0; int cinfd = infd; int coutfd = outfd; int cerrfd = 2; while (waitpid(-1, &status, WNOHANG) > 0); if(flags & EXPAND) { if (expand(line, newarray, LINELEN) == -1) { return -1; } } else { strcpy(newarray, line); } if (flags & EXPAND) { if (pipeline(newarray, cinfd, coutfd, cerrfd) == 1) { return 0; } } if(redirection(newarray, &cinfd, &coutfd, &cerrfd) == 1) { return -1; } char **line_parsed = arg_parse(newarray, &argcp); if (argcp == 0) { return -1; } //checks for builtin commands int checkbuiltin = builtin(line_parsed, &argcp); /* Start a new process to do the job. */ if (checkbuiltin == -1) { cpid = fork(); if (cpid < 0) { if (line_parsed) { free (line_parsed); } dprintf(cerrfd, "fork: %s\n", strerror(errno)); return -1; } /* Check for who we are! */ if (cpid == 0) { /* We are the child! */ if (sig == 1) { raise(SIGINT); } if (cinfd != 0) { dup2(cinfd, 0); } if (coutfd != 1) { dup2(coutfd, 1); } if (cerrfd != 2) { dup2(cerrfd, 2); } execvp (line_parsed[0], line_parsed); dprintf(cerrfd, "exec: %s\n", strerror(errno)); fclose(input); exit (127); } //frees malloced space if (line_parsed) { free (line_parsed); } /* Have the parent wait for child to complete */ if (flags & WAIT) { if (waitpid(cpid, &status, 0) < 0) { dprintf(cerrfd, "wait: %s\n", strerror(errno)); } else { if (WIFEXITED(status)) { exitstatus = WEXITSTATUS(status); } else if(WIFSIGNALED(status)) { exitstatus = 127; } } } } else { exitstatus = runbuiltin(line_parsed, &argcp, checkbuiltin, coutfd, cinfd, cerrfd); if (line_parsed) { free (line_parsed); } } if (cinfd != infd) { close(cinfd); } if (coutfd != outfd) { close(coutfd); } if (cerrfd != 2) { close(cerrfd); } return cpid; } //handles sigint void sig_handler (int signo, siginfo_t *siginfo, void *context) { sig = 1; } int pipeline (char* line, int cinfd, int coutfd, int cerrfd) { int inquotes = 0; int pipeCount = 0; int fd[2]; char* lineStart = line; int pipePresent = 0; while (*line != '\0') { if (*line == '\"') { inquotes = !inquotes; line++; } if (*line == '|' && !inquotes) { pipeCount++; *line = '\0'; pipePresent = 1; } line++; } if (pipePresent == 1) { char *pipeStarts[pipeCount+1]; line = lineStart; pipeStarts[0] = lineStart; int i = 0; while (*line != '\0' || pipeCount != i) { if (*line == '\0') { line++; i++; pipeStarts[i] = line; } line++; } int infd = cinfd; for (int i = 0; i < pipeCount; i++) { if (pipe(fd) < 0) { dprintf(cerrfd, "pipe: %s\n", strerror(errno)); return -1; } processline (pipeStarts[i], infd, fd[1], DONTWAIT | DONTEXPAND); close(fd[1]); if (infd != cinfd) { close(infd); } infd = fd[0]; } processline (pipeStarts[i], infd, coutfd, WAIT | DONTEXPAND); close(infd); } return pipePresent; }
C
/** * Copyright (c) 2017 willydlw * * This library is free software; you can redistribute it and/or modify it * under the terms of the MIT license. See `main.c` for details. */ /** @file communication_state.h * * @brief Finite state machine definitions for communication * with another program. * * * @author willydlw * @date 15 Jan 2018 * * @bugs No known bugs * */ #ifndef COMMUNICATION_STATE_H #define COMMUNICATION_STATE_H #include <stdbool.h> #include <stdint.h> #include <sys/select.h> // fd_set #include <debuglog.h> /* ========== Preprocessor Directives ==========*/ #define NUM_MESSAGE_STATES 7 // number of message states definec in enum MessageState #define MESSAGE_LENGTH_BYTES 5 // every message received will be this length /* ========== External Global Variables ========== */ // external globals must be initialized in the c file // and declared extern in the h file // string arrays used for debugging // states are numeric, when writing an error message // displaying a string provides more meaningful information extern const char* debug_comm_read_state_string[]; extern const char* debug_comm_write_state_string[]; extern const char* debug_message_state_string[]; extern const char* debug_error_condition_string[]; // command messages transmitted to other program extern const char* readyCommand; extern const char* resetCommand; extern const char* stopCommand; // response messages received from other program extern const char* ackResponse; // acknowledge message received, command implemented extern const char* nackResponse; // nack - not acknowledge extern const char* helloMessage; // confirms connection extern const char* helloMessageHEX; // hexadecimal string of helloMessage character values // communication states typedef enum comm_read_state_t { NO_READ = 0, WAIT_FOR_CONNECTION = 1, READ_ACK = 2, READ_SENSOR = 3 }CommReadState; typedef enum comm_write_state_t { NO_WRITE = 0, SEND_READY_SIGNAL = 1, SEND_RESET = 2, SEND_STOP = 3 }CommWriteState; /* messages are received byte by byte. As each byte is recevied, the message state is changed to reflect which bytes have been received, and which byte is expected next. */ typedef enum message_state_t { AWAITING_START_MARKER, AWAITING_SENSOR_ID, AWAITING_DATA_BYTE_ONE, AWAITING_DATA_BYTE_TWO, AWAITING_DATA_BYTE_THREE, AWAITING_END_MARKER, MESSAGE_COMPLETE } MessageState; /* error conditions help indicate exact sources of failure */ typedef enum error_conditions_t { SUCCESS, SELECT_FAILURE, SELECT_ZERO_COUNT, SERIAL_WRITE_ERROR, FD_ISSET_ERROR } ErrorCondition; /* ========== Function Prototypes ========= */ ErrorCondition check_select_return_value(int selectfds, int errnum, int *zeroCount); ssize_t read_message(int fd, fd_set readfds, uint8_t *buf); ssize_t process_received_message_bytes(MessageState *msgState, const uint8_t *buf, ssize_t bytes_read, uint8_t *responseData); ErrorCondition write_message(int fd, fd_set writefds, CommWriteState commWriteState); bool valid_sensor_id(uint8_t id); void process_sensor_data_received(uint16_t theData); void convert_array_to_hex_string(char* destination, ssize_t dlength, const uint8_t* source, ssize_t slength); void process_read_state_error_message(CommReadState commReadState, const uint8_t *responseData, ssize_t rlength); #endif
C
#include<stdio.h> typedef struct TreeNode { char c; struct TreeNode *leftchild; struct TreeNode *rightchild; }TreeNode; int CompTree(TreeNode* tree1,TreeNode* tree2); struct TreeNode* createTree( TreeNode * ); void showTree( TreeNode * ); int main(void) { TreeNode *tree1, *tree2; tree1 = createTree( tree1 ); tree2 = createTree( tree2 ); _Bool equal; equal = CompTree( tree1, tree2 ); printf("equal = %d\n", equal ); showTree( tree1 ); showTree( tree2 ); return 0; } int CompTree( TreeNode* tree1,TreeNode* tree2 ) { if( tree1==NULL && tree2==NULL ) return 1; if( tree1!=NULL && tree2!=NULL ) { if( tree1->c==tree2->c ) return ( CompTree( tree1->leftchild, tree2->leftchild ) && CompTree( tree1->rightchild, tree2->rightchild ) ) || ( CompTree( tree1->leftchild, tree2->rightchild ) && CompTree( tree1->rightchild, tree2->leftchild ) ) ; return 0; } } struct TreeNode* createTree( TreeNode * root ) { return root; } void showTree( TreeNode * tree ) { return ; }
C
/* $Copyright: $ * Copyright (c) 1994 by Steve Baker (ice@mama.indstate.edu) * All Rights reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * suck: Clear your screen with suckage. Takes "quad" as an argument to clear * the screen in quadrants. * Usage: suck [quad] * * Make: gcc -O -o suck suck.c -s */ #include <stdio.h> #include <sys/ioctl.h> #include <termios.h> #include <sys/time.h> #include <strings.h> #include <time.h> typedef enum bool {TRUE=1, FALSE=0} bool; int main(int argc, char **argv) { struct winsize win; int i, j; bool quad = FALSE; if (argc > 1 && !strcasecmp("quad", argv[1])) { quad = TRUE; } /* get the size of the window */ ioctl(0,TIOCGWINSZ,&win); if (win.ws_row < 4) { fprintf(stderr,"suck: window too small.\n"); return 1; } /* assumes you are using all the lines in the window */ for(i = 0; i < win.ws_row/2; i++) { if (!quad) { struct timespec pause = {0, 20000000}; nanosleep(&pause, NULL); /* slow it down so we can watch it */ } /* crazy ANSI escape code magic for controlling the terminal */ printf("\033[1;%dr\033[0H\033M", win.ws_row/2); printf("\033[%d;%dr\033[%dH\n", win.ws_row/2 + 1, win.ws_row, win.ws_row); /* crappy quarter-screen sucking action */ if (quad) { for(j = i; j < win.ws_row - i; j++) { printf("\033[%dH\033[2@", j + 1); printf("\033[%dG\033[4P", (win.ws_col/2) - 2); } } } printf("\033[1;%dr\033[H", win.ws_row); return 0; }
C
// If SW1 is pressed, the green LED will be toggled every half second (the red LED will be off). // If SW1 is not pressed, the red LED will be toggled every half second (the green LED will be off). // Whenever SW2 is pressed (no matter SW1 is pressed or not), all LEDs will be off. // Considering the Tiva’s clock frequency is 16 MHz +/- 1%, one cycle duration is 1 / (16 * 10^6) = 62.5 ns. // Using SysCtlDelay, each iteration takes 3 CPU cycles, therefore the // total delay (in seconds) per toggle would be (3 cycle/loop) * (number of loops) * (1 / clock freq.). // To get 0.5 second delays, we would need 0.5s / [3 * 62.5 ns] = 2,666,667 loops. //***************************************************************************** #include <stdint.h> #include <stdbool.h> #include "rg_toggle.h" #include "inc/hw_types.h" #include "inc/hw_memmap.h" #include "inc/hw_gpio.h" #include "driverlib/sysctl.h" #include "driverlib/pin_map.h" #include "driverlib/gpio.h" #include "inc/tm4c123gh6pm.h" #define SW1 GPIO_PIN_4 // PF4 #define SW2 GPIO_PIN_0 // PF0 #define red_LED GPIO_PIN_1 // 0x02 #define green_LED GPIO_PIN_3 // 0x08 //***************************************************************************** void PortFunctionInit(void) { // // Enable Peripheral Clocks // SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF); // //First open the lock and select the bits we want to modify in the GPIO commit register. // HWREG(GPIO_PORTF_BASE + GPIO_O_LOCK) = GPIO_LOCK_KEY; HWREG(GPIO_PORTF_BASE + GPIO_O_CR) = 0x1; // //Now modify the configuration of the pins that we unlocked. // // // Enable pin PF0 for GPIOInput // GPIOPinTypeGPIOInput(GPIO_PORTF_BASE, GPIO_PIN_0); // // Enable pin PF4 for GPIOInput // GPIOPinTypeGPIOInput(GPIO_PORTF_BASE, GPIO_PIN_4); // // Enable pin PF1 for GPIOOutput // GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_1); // // Enable pin PF3 for GPIOOutput // GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_3); // ************** Initialized by PinMux Utility *************** // enable pullup resistors using bitwise OR of PF4(0x10), PF0(0x01) GPIO_PORTF_PUR_R |= 0x11; } int clock = SysCtlClockGet(); // returns 16000000 void DelayInSec(double delay_in_s) { // SysCtlClockGet() returns the PIOSC clock frequency of the Tiva (16 MHz +/- 1%) // 1 clock cycle (in seconds) = 1 / SysCtlClockGet() second // 1 loop of SysCtlDelay = 3 clock cycles = 3 / SysCtlClockGet() // 1 second = SysCtlClockGet() / 3 SysCtlDelay(delay_in_s * (SysCtlClockGet() / 3)); } int main(void) { uint8_t LED_data; // initializes the GPIO ports PortFunctionInit(); while(1) { if(GPIOPinRead(GPIO_PORTF_BASE, SW2)==0x00) //SW2 is pressed, all off { GPIOPinWrite(GPIO_PORTF_BASE, red_LED, 0x00); // red LED off GPIOPinWrite(GPIO_PORTF_BASE, green_LED, 0x00); // green LED off } else { if(GPIOPinRead(GPIO_PORTF_BASE, SW1)==0x00) //SW1 is pressed { GPIOPinWrite(GPIO_PORTF_BASE, red_LED, 0x00); // red LED off SysCtlDelay(2666667); // about 0.5 second delay LED_data^=green_LED; // toggles green LED (PF3) GPIOPinWrite(GPIO_PORTF_BASE, green_LED, LED_data); // green LED on } else //SW1 is not pressed, toggle red LED (PF3) { GPIOPinWrite(GPIO_PORTF_BASE, green_LED, 0x00); // green LED off DelayInSec(0.5); // about 0.5 second delay LED_data^=red_LED; // bitwise XOR red LED (PF1) GPIOPinWrite(GPIO_PORTF_BASE, red_LED, LED_data); // red LED on } } } }
C
#include<stdio.h> void main() { // sp=selling price,cp=cost price,p=profit,l=loss int sp,cp,p,l; printf("\n enter the selling price and cost price"); scanf("\n %d%d",&sp,&cp); if(sp>cp) printf("\n profit %d",sp-cp); else printf("\n loss %d",cp-sp); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "Node.h" #include <stdbool.h> int countNodes(node *root, int *count) { if(root==NULL) return 0; countNodes(root->left, count); (*count)++; countNodes(root->right, count); return *count; } bool checkBinary(node *root, int i, int count) { if(root==NULL) return true; if(i>=count) return false; return (checkBinary(root->left, 2*i+1, count) && checkBinary(root->right, 2*i+2, count)); } int main() { node* root = NULL; root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(6); int count=0; count = countNodes(root, &count); printf("\n no. of nodes = %d\n", count); printf("\n %d\n", checkBinary(root, 0, count)); return 0; }
C
#include <stdio.h> int main(){ int a,b,c; printf("informe o valor dos tres lados do triangulo:\n"); scanf("%d %d %d", &a, &b, &c); if ((a == b)&&(b==c)){ printf("O triangulo e equilatero."); }else if ((a == b)||(b==c)) { printf("O triangulo e isosceles."); }else{ printf("O triangulo e escaleno.");}}
C
#pragma once #include <stdio.h> #include "DetermineBarcodeInfo.h" #include "menu.h" #include "printReceipts.h" //void barcodeDataToProduct(productNow productList[],int i); int isProductInTheList(); void salesProcess(); void printProductInTheList(productNow productList[], int b[7]); void resetList(productNow productList[]); void printReceipt(int b[7]); void Display(productNow productList[], int b[7]); void salesProcess() { productNow productList[7]; // Ǹ߸Ʈ int i=0,j = 0; int k = i + j; int a[7] = { -1,-1,-1,-1,-1,-1,-1};//Ǹ߸Ʈ ǰ Ʈġ int b[7] = { 0,0,0,0,0,0,0 }; // ǰ resetList(productList); //reset currentList //Լκи for (i = 0; i < 8; i++) { int k = i + j; int payment = 0; int selection = 0; int type = 10; printSaleMenu(); //barcodeDataToProduct(productList,i); char barcodeData[5]; strcpy(barcodeData, barcodeScannerData()); if (strcmp(barcodeData, "001") == 0) { if (a[0] == -1) //Ǹ߸Ʈ ٸ Ʈ ߰ { strcpy(productList[k].name, "chip"); productList[k].price = 1000; productList[k].quantity = 1; a[0] = k; //߰ Ǿ ʹ ߺ̰ Ʈġ.. b[0] ++; //ǰ Ʈ bŭ ̳ʽȴ.. } else //Ǹ߸Ʈ ִٸ ߰ { productList[a[0]].quantity += 1; j -= 1; b[0] ++; } } else if (strcmp(barcodeData, "010") == 0) { if (a[1] == -1) { strcpy(productList[k].name, "icecream"); productList[k].price = 1500; productList[k].quantity = 1; a[1] = k; b[1] ++; } else { productList[a[1]].quantity += 1; j -= 1; b[1] ++; } } else if (strcmp(barcodeData, "011") == 0) { if (a[2] == -1) { strcpy(productList[k].name, "fruit"); productList[k].price = 3000; productList[k].quantity = 1; a[2] = k; b[2] ++; } else { productList[a[2]].quantity += 1; j -= 1; b[2] ++; } } else if (strcmp(barcodeData, "100") == 0) { if (a[3] == -1) { strcpy(productList[k].name, "water"); productList[k].price = 500; productList[k].quantity = 1; a[3] = k; b[3] ++; } else { productList[a[3]].quantity += 1; j -= 1; b[3] ++; } } else if (strcmp(barcodeData, "101") == 0) { if (a[4] == -1) { strcpy(productList[k].name, "ramen"); productList[k].price = 800; productList[k].quantity = 1; a[4] = k; b[4] ++; } else { productList[a[4]].quantity += 1; j -= 1; b[4] ++; } } else if (strcmp(barcodeData, "110") == 0) { if (a[5] == -1) { strcpy(productList[k].name, "drink"); productList[k].price = 1200; productList[k].quantity = 1; a[5] = k; b[5] ++; } else { productList[a[5]].quantity += 1; j -= 1; b[5] ++; } } else if (strcmp(barcodeData, "111") == 0) { if (a[6] == -1) { strcpy(productList[k].name, "coffee"); productList[k].price = 2000; productList[k].quantity = 1; a[6] = k; b[6] ++; } else { productList[a[6]].quantity += 1; j -= 1; b[6] ++; } } else printf("wrong barcode \n"); printf("*********PRODUCT LIST*********\n"); printProductInTheList(productList, b); printf("enter 1 to proceed Payment. enter 2 to continue scanning enter 3 to add/delete \n"); scanf("%d", &payment); if (payment == 1) { break; //for Ż } else if (payment == 3) { printf("select 1.add 2.reduce 3.delete \n"); scanf("%d", &selection); if (selection == 1) { printf("select product 0 1 2 3 4 5 6 \n"); scanf("%d", &type); if (b[type] != 0) b[type]++; else printf("invalid value \n"); printProductInTheList(productList, b); } else if (selection == 2) { printf("select product 0 1 2 3 4 5 6 \n"); scanf("%d", &type); if (b[type] != 0) b[type]--; else printf("invalid value \n"); printProductInTheList(productList, b); } else if (selection == 3) { printf("select product 0 1 2 3 4 5 6 \n"); scanf("%d", &type); if (b[type] != 0) b[type] = 0; else printf("invalid value \n"); printProductInTheList(productList, b); } else printf("invalid value \n"); } else if(payment !=2) printf("invalid value \n"); } //for printf("*********PRODUCT LIST*********\n"); printProductInTheList(productList,b); printf("**************************\n"); printf("\n"); printf("\n"); printf("payment processing..\n"); printf("\n"); printf("\n"); Display(productList,b); updateStockAfterSell(b); //update stock printf("Stock Update Complete \n"); printReceipt(b); updateSaleManage(b); printf("Sale mangement Update Complete \n"); printf(" \n"); printf(" \n"); printf(" \n"); } /* void barcodeDataToProduct(productNow productList[],int i) { int j = 0; int k = i+j; int a=-1, b=-1, c=-1, d=-1, e=-1, f=-1, g = -1; char barcodeData[5]; strcpy(barcodeData, barcodeScannerData()); if (strcmp(barcodeData, "100") == 0) { printf("%d", a); if (a == -1) { strcpy(productList[k].name, ""); productList[k].price = 1000; productList[k].quantity = 1; a = k; printf("%d", a); } else { productList[a].quantity += 1; j -= 1; } } else if (strcmp(barcodeData, "010") == 0) { strcpy(productList[k].name, "̽ũ"); productList[k].price = 1500; productList[k].quantity = 1; } else if (strcmp(barcodeData, "011") == 0) { strcpy(productList[i].name, "̽ũ"); productList[i].price = 1500; productList[i].quantity = 1; } else if (strcmp(barcodeData, "100") == 0) { strcpy(productList[i].name, ""); productList[i].price = 1000; productList[i].quantity = 1; } else if (strcmp(barcodeData, "101") == 0) { strcpy(productList[i].name, ""); productList[i].price = 1000; productList[i].quantity = 1; } else if (strcmp(barcodeData, "110") == 0) { strcpy(productList[i].name, ""); productList[i].price = 1000; productList[i].quantity = 1; } else if (strcmp(barcodeData, "111") == 0) { strcpy(productList[i].name, ""); productList[i].price = 1000; productList[i].quantity = 1; } } */ int isProductInTheList() { return 0; } void printProductInTheList(productNow productList[], int b[7]) //Ǹ߸Ʈ { for (int i = 0; i < 7; i++) { printf("%s %d %d \n", getStockFromDB()[i].name, getStockFromDB()[i].price, b[i]); } } void resetList(productNow productList[]) //Ǹ߸Ʈ ʱȭ { for (int i = 0; i < 7; i++) { strcpy(productList[i].name, "0"); productList[i].price=0; productList[i].quantity=0; } } void Display(productNow productList[],int b[7]) { int total=0; int cash; int leftCash; printf("*******CASHER DISPLAY******* : \n"); //cashier Display for (int i = 0; i < 7; i++) //ǸѾװ { total = total + (getStockFromDB()[i].price *b[i]); } printf(" total : %d ", total); while (1) { printf("PayWith cash. Insert Cash : not enough money \n"); scanf("%d", &cash); if (cash >= total) break; } leftCash = cash - total; printf("Total amount: %d \n", total); printf("Cash input : %d \n", cash); printf("Leftmoney: %d \n", leftCash); for (int i = 0; i < 7; i++) { printf("%s %d %d \n", getStockFromDB()[i].name, getStockFromDB()[i].price, b[i]); } printf("*******CASHER DISPLAY END******* : \n"); //cashier Display End printf("\n"); printf("\n"); printf("*******CUSTOMER DISPLAY******* : \n"); //cu Display printf("Total amount: %d \n", total); printf("Cash input : %d \n", cash); printf("Leftmoney: %d \n", leftCash); printf("*******CUSTOMER DISPLAY END******* : \n"); //cu display end printf("\n"); printf("\n"); }
C
/* * mm_alloc.h * * Exports a clone of the interface documented in "man 3 malloc". */ #pragma once #include <stdlib.h> void *mm_malloc(size_t size); void *mm_realloc(void *ptr, size_t size); void mm_free(void *ptr); /*struct of block*/ struct block { struct block *prev; struct block *next; int free; void *ptr; size_t size; char data [0]; };
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* kostyliivelosipedy.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mjohnsie <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/12/07 15:14:01 by mjohnsie #+# #+# */ /* Updated: 2019/12/10 18:51:17 by sassassi ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" void ft_kostyl(int verif, t_struct *list) { if (list->length < verif) list->length = verif; } int ft_kostyl2(const char *format, t_struct *list) { int verif; if (format[list->i] == 'h' && format[list->i + 1] == 'h') verif = 2; else if (format[list->i] == 'h') verif = 1; else if (format[list->i] == 'l' && format[list->i + 1] == 'l') verif = 4; else if (format[list->i] == 'l') verif = 3; else if (format[list->i] == 'L') verif = 5; else if (format[list->i] == 'j') verif = 6; else verif = 0; return (verif); } void ft_kostyl3(int verif, t_struct *list) { if (list->length < verif) list->length = verif; list->i++; } void ft_printdat(const char *format, t_struct *list) { list->len += write(list->fd, &format[list->i], 1); list->i++; } void ft_printform(const char *format, t_struct *list) { ft_print(format, list); ft_reset_struct(list); }