language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include "ctrl.h" #include "list.h" #include <linux/kernel.h> #include <linux/types.h> #include <linux/fs.h> #include <linux/device.h> #include <linux/slab.h> #include <asm/errno.h> struct ctrl* ctrl_get(struct list* list, struct class* cls, struct pci_dev* pdev, int number) { struct ctrl* ctrl = NULL; ctrl = kmalloc(sizeof(struct ctrl), GFP_KERNEL | GFP_NOWAIT); if (ctrl == NULL) { printk(KERN_CRIT "Failed to allocate controller reference\n"); return ERR_PTR(-ENOMEM); } list_node_init(&ctrl->list); ctrl->pdev = pdev; ctrl->number = number; ctrl->rdev = 0; ctrl->cls = cls; ctrl->chrdev = NULL; snprintf(ctrl->name, sizeof(ctrl->name), "%s%d", KBUILD_MODNAME, ctrl->number); ctrl->name[sizeof(ctrl->name) - 1] = '\0'; list_insert(list, &ctrl->list); return ctrl; } void ctrl_put(struct ctrl* ctrl) { if (ctrl != NULL) { list_remove(&ctrl->list); ctrl_chrdev_remove(ctrl); kfree(ctrl); } } struct ctrl* ctrl_find_by_pci_dev(const struct list* list, const struct pci_dev* pdev) { const struct list_node* element = list_next(&list->head); struct ctrl* ctrl; while (element != NULL) { ctrl = container_of(element, struct ctrl, list); if (ctrl->pdev == pdev) { return ctrl; } element = list_next(element); } return NULL; } struct ctrl* ctrl_find_by_inode(const struct list* list, const struct inode* inode) { const struct list_node* element = list_next(&list->head); struct ctrl* ctrl; while (element != NULL) { ctrl = container_of(element, struct ctrl, list); if (&ctrl->cdev == inode->i_cdev) { return ctrl; } element = list_next(element); } return NULL; } int ctrl_chrdev_create(struct ctrl* ctrl, dev_t first, const struct file_operations* fops) { int err; struct device* chrdev = NULL; if (ctrl->chrdev != NULL) { printk(KERN_WARNING "Character device is already created\n"); return 0; } ctrl->rdev = MKDEV(MAJOR(first), MINOR(first) + ctrl->number); cdev_init(&ctrl->cdev, fops); err = cdev_add(&ctrl->cdev, ctrl->rdev, 1); if (err != 0) { printk(KERN_ERR "Failed to add cdev\n"); return err; } chrdev = device_create(ctrl->cls, NULL, ctrl->rdev, NULL, ctrl->name); if (IS_ERR(chrdev)) { cdev_del(&ctrl->cdev); printk(KERN_ERR "Failed to create character device\n"); return PTR_ERR(chrdev); } ctrl->chrdev = chrdev; printk(KERN_INFO "Character device /dev/%s created (%d.%d)\n", ctrl->name, MAJOR(ctrl->rdev), MINOR(ctrl->rdev)); return 0; } void ctrl_chrdev_remove(struct ctrl* ctrl) { if (ctrl->chrdev != NULL) { device_destroy(ctrl->cls, ctrl->rdev); cdev_del(&ctrl->cdev); ctrl->chrdev = NULL; printk(KERN_DEBUG "Character device /dev/%s removed (%d.%d)\n", ctrl->name, MAJOR(ctrl->rdev), MINOR(ctrl->rdev)); } }
C
#include <string.h> int strncmp (const char *s1, const char *s2, size_t n) { while (n > 0 && *s1 && *s2 && *s1 == *s2) n--, s1++, s2++; return n == 0 ? 0 : (int)*s1 - (int)*s2; }
C
/*! ---------------------------------------------------------------------------- * @file main.c * @brief RX using double buffering example code * * This example keeps listening for any incoming frames, storing in a local buffer any frame received before going back to listening. This * examples activates interrupt handling and the double buffering feature of the DW1000 (but automatic RX re-enabling is not supported). * Frame processing and manual RX re-enabling are performed in the RX good frame callback. * * @attention * * Copyright 2015 (c) Decawave Ltd, Dublin, Ireland. * Copyright 2019 (c) Frederic Mes, RTLOC. * * All rights reserved. * * @author Decawave */ #ifdef EX_02E_DEF #include "deca_device_api.h" #include "deca_regs.h" #include "deca_spi.h" #include "port.h" /* Example application name and version to display on console. */ #define APP_NAME "RX DBL BUFF v1.1" /* Default communication configuration. */ static dwt_config_t config = { 5, /* Channel number. */ DWT_PRF_64M, /* Pulse repetition frequency. */ DWT_PLEN_128, /* Preamble length. Used in TX only. */ DWT_PAC8, /* Preamble acquisition chunk size. Used in RX only. */ 9, /* TX preamble code. Used in TX only. */ 9, /* RX preamble code. Used in RX only. */ 1, /* 0 to use standard SFD, 1 to use non-standard SFD. */ DWT_BR_6M8, /* Data rate. */ DWT_PHRMODE_EXT, /* PHY header mode. */ (129) /* SFD timeout (preamble length + 1 + SFD length - PAC size). Used in RX only. */ }; /* Buffer to store received frame. See NOTE 1 below. */ #define FRAME_LEN_MAX 127 static uint8 rx_buffer[FRAME_LEN_MAX]; /* Declaration of static functions. */ static void rx_ok_cb(const dwt_cb_data_t *cb_data); static void rx_err_cb(const dwt_cb_data_t *cb_data); /** * Application entry point. */ int dw_main(void) { /* Display application name on console. */ printk(APP_NAME); /* Configure DW1000 SPI */ openspi(); /* Install DW1000 IRQ handler. */ port_set_deca_isr(dwt_isr); /* Reset and initialise DW1000. See NOTE 2 below. * For initialisation, DW1000 clocks must be temporarily set to crystal speed. After initialisation SPI rate can be increased for optimum * performance. */ reset_DW1000(); /* Target specific drive of RSTn line into DW1000 low for a period. */ port_set_dw1000_slowrate(); if (dwt_initialise(DWT_LOADNONE) == DWT_ERROR) { printk("INIT FAILED"); while (1) { }; } port_set_dw1000_fastrate(); /* Configure DW1000. */ dwt_configure(&config); /* Configure DW1000 LEDs */ dwt_setleds(1); /* Activate double buffering. */ dwt_setdblrxbuffmode(1); /* Register RX call-back. */ dwt_setcallbacks(NULL, &rx_ok_cb, NULL, &rx_err_cb); /* Enable wanted interrupts (RX good frames and RX errors). */ dwt_setinterrupt(DWT_INT_RFCG | DWT_INT_RPHE | DWT_INT_RFCE | DWT_INT_RFSL | DWT_INT_SFDT, 1); /* Activate reception immediately. See NOTE 3 below. */ dwt_rxenable(DWT_START_RX_IMMEDIATE); /* Loop forever receiving frames. See NOTE 4 below. */ while (1) { }; } /*! ------------------------------------------------------------------------------------------------------------------ * @fn rx_ok_cb() * * @brief Callback to process RX good frame events * * @param cb_data callback data * * @return none */ static void rx_ok_cb(const dwt_cb_data_t *cb_data) { /* Perform manual RX re-enabling. See NOTE 5 below. */ dwt_rxenable(DWT_START_RX_IMMEDIATE | DWT_NO_SYNC_PTRS); /* TESTING BREAKPOINT LOCATION #1 */ /* A frame has been received, copy it to our local buffer. See NOTE 6 below. */ if (cb_data->datalength <= FRAME_LEN_MAX) { dwt_readrxdata(rx_buffer, cb_data->datalength, 0); } /* TESTING BREAKPOINT LOCATION #2 */ } /*! ------------------------------------------------------------------------------------------------------------------ * @fn rx_err_cb() * * @brief Callback to process RX error events * * @param cb_data callback data * * @return none */ static void rx_err_cb(const dwt_cb_data_t *cb_data) { /* Re-activate reception immediately. */ dwt_rxenable(DWT_START_RX_IMMEDIATE); /* TESTING BREAKPOINT LOCATION #3 */ } #endif /***************************************************************************************************************************************************** * NOTES: * * 1. In this example, maximum frame length is set to 127 bytes which is 802.15.4 UWB standard maximum frame length. DW1000 supports an extended * frame length (up to 1023 bytes long) mode which is not used in this example. * 2. In this example, LDE microcode is not loaded upon calling dwt_initialise(). This will prevent the IC from generating an RX timestamp. If * time-stamping is required, DWT_LOADUCODE parameter should be used. See two-way ranging examples (e.g. examples 5a/5b). * 3. Manual reception activation is performed here but DW1000 offers several features that can be used to handle more complex scenarios or to * optimise system's overall performance (e.g. timeout after a given time, automatic re-enabling of reception in case of errors, etc.). * 4. There is nothing to do in the loop here as frame reception and RX re-enabling is handled by the callbacks. In a less trivial real-world * application the RX data callback would generally signal the reception event to some background protocol layer to further process each RX frame. * 5. When using double buffering, RX can be re-enabled before reading all the frame data as this is precisely the purpose of having two buffers. All * the registers needed to process the received frame are also double buffered with the exception of the Accumulator CIR memory and the LDE * threshold (accessed when calling dwt_readdiagnostics). In an actual application where these values might be needed for any processing or * diagnostics purpose, they would have to be read before RX re-enabling is performed so that they are not corrupted by a frame being received * while they are being read. Typically, in this example, any such diagnostic data access would be done at the very beginning of the rx_ok_cb * function. * 6. A real application might get an operating system (OS) buffer for this data reading and then pass the buffer onto a queue into the next layer of processing task via an appropriate OS call. * 7. The user is referred to DecaRanging ARM application (distributed with EVK1000 product) for additional practical example of usage, and to the * DW1000 API Guide for more details on the DW1000 driver functions. ****************************************************************************************************************************************************/
C
#include "AVL.h" #include <malloc.h> #include <math.h> #include <stdio.h> #include <stdlib.h> int max(int a, int b) { if (a > b) { return a; } return b; } int getHeight(Node *node) { int x, y; if (node == NULL) { return -1; } x = getHeight(node->left); y = getHeight(node->right); return x >= y ? x + 1 : y + 1; } int getBalance(Node *node) { return getHeight(node->left) - getHeight(node->right); } Node *findNode(Node *root, int x) { if (root == NULL) { return NULL; } if (root->key == x) { return root; } return x < root->key ? findNode(root->left, x) : findNode(root->right, x); } Node *rightRotate(Node *node) { Node *left = node->left; Node *right = left->right; left->right = node; node->left = right; node->height = max(getHeight(node->left), getHeight(node->right)) + 1; left->height = max(getHeight(left->left), getHeight(left->right)) + 1; return left; } Node *leftRotate(Node *node) { Node *right = node->right; Node *left = right->left; right->left = node; node->right = left; node->height = max(getHeight(node->left), getHeight(node->right)) + 1; right->height = max(getHeight(right->left), getHeight(right->right)) + 1; return right; } Node *minNode(Node *node) { while (node->left) { node = node->left; } return node; } Node *insertNode(Node **root, int x) { Node *ret; /* insert the data */ if (*root == NULL) { *root = (Node *)malloc(sizeof(Node)); if (*root == NULL) { printf("Can't allocate memory"); exit(1); } (*root)->key = x; (*root)->height = 0; (*root)->left = NULL; (*root)->right = NULL; return *root; } else if ((*root)->key > x) { ret = insertNode(&(*root)->left, x); } else if ((*root)->key < x) { ret = insertNode(&(*root)->right, x); } /* handle the unbalance problem */ (*root)->height = 1 + max(getHeight((*root)->left), getHeight((*root)->right)); int balance = getBalance(*root); /* case 1 left left unbalance */ if (balance > 1 && getBalance((*root)->left) >= 0) { *root = rightRotate(*root); } /* case 2 left right unbalance */ if (balance > 1 && getBalance((*root)->left) < 0) { (*root)->left = leftRotate((*root)->left); *root = rightRotate(*root); } /* case 3 right left unbalance */ if (balance < -1 && getBalance((*root)->right) > 0) { (*root)->right = rightRotate((*root)->right); *root = leftRotate(*root); } /* case 4 right right unbalance */ if (balance < -1 && getBalance((*root)->right) <= 0) { *root = leftRotate(*root); } return ret; } Node *deleteNode(Node **root, int x) { Node *tmp = *root; if (*root == NULL) return NULL; if (x < (*root)->key) { tmp = deleteNode(&(*root)->left, x); } else if (x > (*root)->key) { tmp = deleteNode(&(*root)->right, x); } else { if ((*root)->left == NULL || (*root)->right == NULL) { Node *child = (*root)->left != NULL ? (*root)->left : (*root)->right; /* no child case */ if (child == NULL) { *root = NULL; return tmp; } else { (*root)->key = child->key; if ((*root)->left && /* left child case */ (*root)->left->key == child->key) { tmp = deleteNode(&(*root)->left, child->key); } else if ((*root)->right && /* right child case */ (*root)->right->key == child->key) { tmp = deleteNode(&(*root)->right, child->key); } } /* two child case */ } else { Node *child = minNode((*root)->right); (*root)->key = child->key; tmp = deleteNode(&(*root)->right, child->key); } } if ((*root) == NULL) { return *root; } int balance = getBalance(*root); (*root)->height = 1 + max(getHeight((*root)->left), getHeight((*root)->right)); /* case 1 left left unbalance */ if (balance > 1 && getBalance((*root)->left) >= 0) { *root = rightRotate(*root); } /* case 2 left right unbalance */ if (balance > 1 && getBalance((*root)->left) < 0) { (*root)->left = leftRotate((*root)->left); *root = rightRotate(*root); } /* case 3 right left unbalance */ if (balance < -1 && getBalance((*root)->right) > 0) { (*root)->right = rightRotate((*root)->right); *root = leftRotate(*root); } /* case 4 right right unbalance */ if (balance < -1 && getBalance((*root)->right) <= 0) { *root = leftRotate(*root); } return tmp; } void destroyTree(Node *root) { if (root == NULL) { return; } destroyTree(root->left); destroyTree(root->right); free(root); }
C
#include <stdio.h> void InsertionSort(int *start,int *end) { for(int *i = start + 1; i!= end;i++) { for (int *j = start; j < i ; j++) // the code is not optimized; After the short is found, you should not go to the j-1 entry level { if( *i < *j) { int key = *j; *j = *i; *i = key; } } } } int main () { int num[] = {5,2,4,6,13,201,2,7,10,7,2,8,0}; //numbers to be shorted int size = sizeof(num)/sizeof(num[0]); InsertionSort(num, size+num); //Half open range for(int loop = 0; loop < size; loop++) { printf("%d\n", num[loop]); } }
C
#include "analex.h" #include "anasin.h" #include "gerenciador.h" int indice=0; int variavelDeclaraAtrib(){ int aux,troca; aux = topo; troca = 0; if (tk.cat == ID){ if (escopo == 1){ while (aux > 0){ if (troca == 1){ if ( (strcmp(gT[aux].lexema,tk.tipo.lexema)) == 0 ){ if ( gT[aux].escopo == 0){ return gT[aux].tipo; } } } else{ if ( (gT[aux].classe == FUNC) ){ if ( (strcmp(gT[aux].lexema,tk.tipo.lexema)) == 0 ){ return gT[aux].tipo; } troca = 1; } if ( (strcmp(gT[aux].lexema,tk.tipo.lexema)) == 0 ){ if ( gT[aux].escopo == escopo){ if ((gT[aux].classe == LOCAL)|| (gT[aux].classe == PARAM)){ return gT[aux].tipo; } } } } aux -= 1; } } else{ while (aux > 0){ if ( (gT[aux].escopo == escopo) ){ if ( (strcmp(gT[aux].lexema,tk.tipo.lexema)) == 0 ){ return gT[aux].tipo; } } aux -= 1; } } printf("Variavel nao declarada na linha %d\n",linha); system("PAUSE"); exit(1); } return tk.cat; } /* void verificaProcedimento(){ int aux; aux = topo; while (aux > 0){ if ( (strcmp(gT[aux].lexema,tk.tipo.lexema)) == 0 ){ if ( gT[aux].classe == PROC){ indice = aux; return; } else{ printf("Apenas procedimentos podem ser chamados por CALL na linha %d\n",linha); system("PAUSE"); exit(1); } } aux--; } } */ void verificaTipoExp(){ int aux; if (tk.cat == SN){ return; } if (tk.cat == ID){ aux = variavelDeclaraAtrib(); } if ( (aux == INT) || (tk.cat == CTI) || (aux == BOOL) ); else{ printf("Inconsistencia de tipos na linha %d\n",linha); system("PAUSE"); exit(1); } } int retornaClasse(){ int aux; aux = topo; while (aux>0){ if (escopo == 0){ if ( ((strcmp(gT[aux].lexema,tk.tipo.lexema)) == 0) && (gT[aux].escopo == 0) ){ if ( (gT[aux].classe == FUNC)){ indice = aux; } return gT[aux].classe; } } else{ if ( (strcmp(gT[aux].lexema,tk.tipo.lexema)) == 0 ){ if ( (gT[aux].classe == FUNC)){ indice = aux; } return gT[aux].classe; } } aux -=1; } return 0; } int checaReturn(){ int aux; aux = topo; while (aux>0){ if ( (gT[aux].classe == FUNC) ){ break; } aux -=1; } return gT[aux].classe; } void checaChamada(int aux){ indice +=1; if (gT[indice].classe == PARAM){ if (gT[indice].tipo == aux); else{ printf("Inconsistencia na chamada de funcao na linha %d\n",linha); system("PAUSE"); exit(1); } } else{ if (indice != 0){ printf("Parametros a mais na funcao da linha %d\n",linha); system("PAUSE"); exit(1); } } } void paramMenos(){ if (gT[indice+1].classe == PARAM){ printf("Faltam parametros na chamada da funcao linha %d\n",linha); system("PAUSE"); exit(1); } } void verificaTipo(int tipo){ int aux,classe; classe = retornaClasse(); if (tk.cat == ID){ aux = variavelDeclaraAtrib(); if (indice != 0){ if ( (classe == GLOBAL) || (classe == LOCAL) ){ checaChamada(aux); } } } /* if (classe == PROC){ printf("Procedimento so pode ser chamado por CALL, na linha %d\n",linha); system("PAUSE"); exit(1); } */ if (tipo == FLOAT){ if ( (aux == FLOAT) || (tk.cat == CTR) ); else{ printf("Inconsistencia de tipos na linha %d\n",linha); system("PAUSE"); exit(1); } } if (tipo == INT){ if ( (aux == INT) || (tk.cat == CTI) || (aux == CHAR) || (tk.cat == CTC) || (aux == BOOL) ); else{ printf("Inconsistencia de tipos na linha %d\n",linha); system("PAUSE"); exit(1); } } if (tipo == CHAR){ if ( (aux == CHAR) || (aux == INT) || (tk.cat == CTC) || (tk.cat == CTI) ); else{ printf("Inconsistencia de tipos na linha %d\n",linha); system("PAUSE"); exit(1); } } } void variavelDeclara(){ int aux,troca; aux = topo; troca = 0; if (tk.cat == ID){ if (escopo == 1){ while (aux > 0){ if (troca == 1){ if ( (strcmp(gT[aux].lexema,tk.tipo.lexema)) == 0 ){ if ( gT[aux].escopo == 0){ return; } } } else{ if ( (gT[aux].classe == FUNC) ){ troca = 1; } if ( (strcmp(gT[aux].lexema,tk.tipo.lexema)) == 0 ){ if ( gT[aux].escopo == escopo){ if ((gT[aux].classe == LOCAL)|| (gT[aux].classe == PARAM)){ return; } } } } aux -= 1; } } else{ while (aux > 0){ if ( (gT[aux].escopo == escopo) ){ if ( (strcmp(gT[aux].lexema,tk.tipo.lexema)) == 0 ){ return; } } aux -= 1; } } printf("Variavel nao declarada na linha %d\n",linha); system("PAUSE"); exit(1); } } void adicionaTipoParam(int cod,int aux){ int cont; cont = topo; while (1){ if ( (gT[cont].classe == FUNC) ){ //printf("Aqui %s\n",gT[cont].lexema); gT[cont].param.quantidade = aux; gT[cont].param.tipo[aux-1] = cod; break; } cont -=1; } } void checaTipoParam(int cod,int aux,int pos){ if (cod == VOID){ if ( gT[pos].param.tipo[0] == VOID ){ adicionaTipoParam(cod,aux); return; } else{ printf("Tipos de parametros inconsistentes na linha %d\n",linha); system("PAUSE"); exit(1); } } if ( gT[pos].param.quantidade < aux ){ printf("Tipos de parametros inconsistentes na linha %d\n",linha); system("PAUSE"); exit(1); } else{ if ( gT[pos].param.tipo[aux-1] == cod ); else{ printf("Tipos de parametros inconsistentes na linha %d\n",linha); system("PAUSE"); exit(1); } } adicionaTipoParam(cod,aux); } void checaTipoRetorno(int cod){ int aux; aux = topo; while ( aux > 0 ){ if ( (strcmp(gT[aux].lexema,tk.tipo.lexema)) == 0 ){ if (gT[aux].tipo == cod){ break; } else{ printf("Funcao com valor de retorno incompativel com a assinatura na linha %d\n",linha); system("PAUSE"); exit(1); } } aux -= 1; } } void redeclaracaoFWD(int classe,int aux){ while ( aux > 0 ){ if ( (strcmp(gT[aux].lexema,tk.tipo.lexema)) == 0 ){ if (gT[aux].classe == FWD){ printf("Assinatura redeclarada na linha %d\n",linha); system("PAUSE"); exit(1); } if ( (gT[aux].classe == FUNC) ){ printf("Assinatura deve vir acima da funcao na linha %d\n",linha); system("PAUSE"); exit(1); } } aux -= 1; } } int verificaFWD(){ int topoAux; char lexemaAux[TAM]; topoAux = topo-1; strcpy(lexemaAux,gT[topo].lexema); while ( topoAux > 0 ){ if ( (strcmp(gT[topoAux].lexema,lexemaAux)) == 0 ){ return topoAux; } topoAux -= 1; } return 0; } void adicionaTipoParamFWD(int cod,int aux){ if (cod == VOID){ gT[topo].param.quantidade = 0; gT[topo].param.tipo[0] = VOID; return; } if (aux == 0){ gT[topo].param.quantidade = 0; } gT[topo].param.quantidade = aux+1; gT[topo].param.tipo[aux] = cod; }
C
//#define _CRT_SECURE_NO_WARNINGS 1 // //#include <stdio.h> //#include <math.h> // //int main() //{ // int n = 0; // int f1 = 0; // int f2 = 1; // int f3 = 0; // while (1) // { // if (n == f2) // { // printf("0\n"); // break; // } // else if (n < f2) // { // if (abs(f1 - n) < abs(f2 - n)) // { // printf("%d\n", abs(f1 - n)); // break; // } // else // { // printf("%d\n", abs(f2 - n)); // break; // } // } // else // { // f3 = f1 + f2; // f1 = f2; // f2 = f3; // } // } // return 0; //}
C
#include "holberton.h" #include <stdio.h> /** * print_number - prints an integer * @n: integer to be printed * Return: Nothing */ void print_number(int n) { char last_digit; int rev; if (n < 0) { _putchar('-'); last_digit = ('0' - (n % 10)); n /= -10; } else { last_digit = ((n % 10) + '0'); n /= 10; } rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } while (rev > 0) { _putchar((rev % 10) + '0'); rev /= 10; } _putchar(last_digit); }
C
#include <stdlib.h> #include <string.h> #include <assert.h> #include <stdio.h> #include <zlib.h> #include "rle.h" #include "rope.h" /******************* *** Memory Pool *** *******************/ #define MP_CHUNK_SIZE 0x100000 // 1MB per chunk typedef struct { // memory pool for fast and compact memory allocation (no free) int size, i, n_elems; int64_t top, max; uint8_t **mem; } mempool_t; static mempool_t *mp_init(int size) { mempool_t *mp; mp = calloc(1, sizeof(mempool_t)); mp->size = size; mp->i = mp->n_elems = MP_CHUNK_SIZE / size; mp->top = -1; return mp; } static void mp_destroy(mempool_t *mp) { int64_t i; for (i = 0; i <= mp->top; ++i) free(mp->mem[i]); free(mp->mem); free(mp); } static inline void *mp_alloc(mempool_t *mp) { if (mp->i == mp->n_elems) { if (++mp->top == mp->max) { mp->max = mp->max? mp->max<<1 : 1; mp->mem = realloc(mp->mem, sizeof(void*) * mp->max); } mp->mem[mp->top] = calloc(mp->n_elems, mp->size); mp->i = 0; } return mp->mem[mp->top] + (mp->i++) * mp->size; } /*************** *** B+ rope *** ***************/ rope_t *rope_init(int max_nodes, int block_len) { rope_t *rope; rope = calloc(1, sizeof(rope_t)); if (block_len < 32) block_len = 32; rope->max_nodes = (max_nodes+ 1)>>1<<1; rope->block_len = (block_len + 7) >> 3 << 3; rope->node = mp_init(sizeof(rpnode_t) * rope->max_nodes); rope->leaf = mp_init(rope->block_len); rope->root = mp_alloc(rope->node); rope->root->n = 1; rope->root->is_bottom = 1; rope->root->p = mp_alloc(rope->leaf); return rope; } void rope_destroy(rope_t *rope) { mp_destroy(rope->node); mp_destroy(rope->leaf); free(rope); } static inline rpnode_t *split_node(rope_t *rope, rpnode_t *u, rpnode_t *v) { // split $v's child. $u is the first node in the bucket. $v and $u are in the same bucket. IMPORTANT: there is always enough room in $u int j, i = v - u; rpnode_t *w; // $w is the sibling of $v if (u == 0) { // only happens at the root; add a new root u = v = mp_alloc(rope->node); v->n = 1; v->p = rope->root; // the new root has the old root as the only child memcpy(v->c, rope->c, 48); for (j = 0; j < 6; ++j) v->l += v->c[j]; rope->root = v; } if (i != u->n - 1) // then make room for a new node memmove(v + 2, v + 1, sizeof(rpnode_t) * (u->n - i - 1)); ++u->n; w = v + 1; memset(w, 0, sizeof(rpnode_t)); w->p = mp_alloc(u->is_bottom? rope->leaf : rope->node); if (u->is_bottom) { // we are at the bottom level; $v->p is a string instead of a node uint8_t *p = (uint8_t*)v->p, *q = (uint8_t*)w->p; rle_split(p, q); rle_count(q, w->c); } else { // $v->p is a node, not a string rpnode_t *p = v->p, *q = w->p; // $v and $w are siblings and thus $p and $q are cousins p->n -= rope->max_nodes>>1; memcpy(q, p + p->n, sizeof(rpnode_t) * (rope->max_nodes>>1)); q->n = rope->max_nodes>>1; // NB: this line must below memcpy() as $q->n and $q->is_bottom are modified by memcpy() q->is_bottom = p->is_bottom; for (i = 0; i < q->n; ++i) for (j = 0; j < 6; ++j) w->c[j] += q[i].c[j]; } for (j = 0; j < 6; ++j) // compute $w->l and update $v->c w->l += w->c[j], v->c[j] -= w->c[j]; v->l -= w->l; // update $v->c return v; } int64_t rope_insert_run(rope_t *rope, int64_t x, int a, int64_t rl, rpcache_t *cache) { // insert $a after $x symbols in $rope and the returns rank(a, x) rpnode_t *u = 0, *v = 0, *p = rope->root; // $v is the parent of $p; $u and $v are at the same level and $u is the first node in the bucket int64_t y = 0, z = 0, cnt[6]; int n_runs; do { // top-down update. Searching and node splitting are done together in one pass. if (p->n == rope->max_nodes) { // node is full; split v = split_node(rope, u, v); // $v points to the parent of $p; when a new root is added, $v points to the root if (y + v->l < x) // if $v is not long enough after the split, we need to move both $p and its parent $v y += v->l, z += v->c[a], ++v, p = v->p; } u = p; if (v && x - y > v->l>>1) { // then search backwardly for the right node to descend p += p->n - 1; y += v->l; z += v->c[a]; for (; y >= x; --p) y -= p->l, z -= p->c[a]; ++p; } else for (; y + p->l < x; ++p) y += p->l, z += p->c[a]; // then search forwardly assert(p - u < u->n); if (v) v->c[a] += rl, v->l += rl; // we should not change p->c[a] because this may cause troubles when p's child is split v = p; p = p->p; // descend } while (!u->is_bottom); rope->c[a] += rl; // $rope->c should be updated after the loop as adding a new root needs the old $rope->c counts if (cache) { if (cache->p != (uint8_t*)p) memset(cache, 0, sizeof(rpcache_t)); n_runs = rle_insert_cached((uint8_t*)p, x - y, a, rl, cnt, v->c, &cache->beg, cache->bc); cache->p = (uint8_t*)p; } else n_runs = rle_insert((uint8_t*)p, x - y, a, rl, cnt, v->c); z += cnt[a]; v->c[a] += rl; v->l += rl; // this should be after rle_insert(); otherwise rle_insert() won't work if (n_runs + RLE_MIN_SPACE > rope->block_len) { split_node(rope, u, v); if (cache) memset(cache, 0, sizeof(rpcache_t)); } return z; } static rpnode_t *rope_count_to_leaf(const rope_t *rope, int64_t x, int64_t cx[6], int64_t *rest) { rpnode_t *u, *v = 0, *p = rope->root; int64_t y = 0; int a; memset(cx, 0, 48); do { u = p; if (v && x - y > v->l>>1) { p += p->n - 1; y += v->l; for (a = 0; a != 6; ++a) cx[a] += v->c[a]; for (; y >= x; --p) { y -= p->l; for (a = 0; a != 6; ++a) cx[a] -= p->c[a]; } ++p; } else { for (; y + p->l < x; ++p) { y += p->l; for (a = 0; a != 6; ++a) cx[a] += p->c[a]; } } v = p; p = p->p; } while (!u->is_bottom); *rest = x - y; return v; } void rope_rank2a(const rope_t *rope, int64_t x, int64_t y, int64_t *cx, int64_t *cy) { rpnode_t *v; int64_t rest; v = rope_count_to_leaf(rope, x, cx, &rest); if (y < x || cy == 0) { rle_rank1a((const uint8_t*)v->p, rest, cx, v->c); } else if (rest + (y - x) <= v->l) { memcpy(cy, cx, 48); rle_rank2a((const uint8_t*)v->p, rest, rest + (y - x), cx, cy, v->c); } else { rle_rank1a((const uint8_t*)v->p, rest, cx, v->c); v = rope_count_to_leaf(rope, y, cy, &rest); rle_rank1a((const uint8_t*)v->p, rest, cy, v->c); } } /********************* *** Rope iterator *** *********************/ void rope_itr_first(const rope_t *rope, rpitr_t *i) { memset(i, 0, sizeof(rpitr_t)); i->rope = rope; for (i->pa[i->d] = rope->root; !i->pa[i->d]->is_bottom;) // descend to the leftmost leaf ++i->d, i->pa[i->d] = i->pa[i->d - 1]->p; } const uint8_t *rope_itr_next_block(rpitr_t *i) { const uint8_t *ret; assert(i->d < ROPE_MAX_DEPTH); // a B+ tree should not be that tall if (i->d < 0) return 0; ret = (uint8_t*)i->pa[i->d][i->ia[i->d]].p; while (i->d >= 0 && ++i->ia[i->d] == i->pa[i->d]->n) i->ia[i->d--] = 0; // backtracking if (i->d >= 0) while (!i->pa[i->d]->is_bottom) // descend to the leftmost leaf ++i->d, i->pa[i->d] = i->pa[i->d - 1][i->ia[i->d - 1]].p; return ret; }
C
/* ============================================================================ Name : clock.c Author : mpelcat Version : 1.0 Copyright : CECILL-C Description : Timing primitive for Preesm Codegen. ============================================================================ */ #include "clock.h" #include <stdio.h> #include <sys/time.h> // for gettimeofday() struct timeval startTimes[MAX_STAMPS]; double elapsedTimes[MAX_STAMPS]; // Starting to record time for a given stamp void startTiming(int stamp){ gettimeofday(&startTimes[stamp], NULL); } // Stoping to record time for a given stamp. Returns the time in us unsigned int stopTiming(int stamp){ unsigned int elapsedus = 0; struct timeval t2; gettimeofday(&t2, NULL); // compute and print the elapsed time in millisec elapsedTimes[stamp] = (t2.tv_sec - startTimes[stamp].tv_sec) * 1000.0; // sec to ms elapsedTimes[stamp] += (t2.tv_usec - startTimes[stamp].tv_usec) / 1000.0; // us to ms elapsedus = (int)(elapsedTimes[stamp]*1000); return elapsedus; }
C
#include <stdlib.h> #include <stdio.h> #include <math.h> #include "knn.h" #define max(a,b) \ ({ __typeof__ (a) _a = (a); \ __typeof__ (b) _b = (b); \ _a > _b ? _a : _b; }) ////////////////////////////////////// Main Algorithm Functions ////////////////////////////////// // External function called to run algorithm int classify_knn(RPoint r, RPoint * training_data, int numTrainingPoints, int numFeatures, int numClasses){ int k = 7; return classify_knn_internal(r,training_data, numTrainingPoints, numFeatures, numClasses, k); } // Steps for classification // 1. Using input point, create Points from each RPoint of the training set // 2. Sort Points // 3. Take first k Points from the sorted list // 4. Analyze first k Points int classify_knn_internal(RPoint r, RPoint * training, int numTrainingPoints, int numFeatures, int numClasses, int k){ Point points[numTrainingPoints]; int classes[numClasses + 1], gesture = -1; size_t size_struct_points = sizeof(Point); for(int i = 0; i < numClasses + 1; i++) classes[i] = 0; for(int i = 0; i < numTrainingPoints; i++) points[i] = euclidean_distance(training[i], r, numFeatures); qsort(points, (size_t)numTrainingPoints, size_struct_points, compare); calculate_frequencies(points, classes, k); for(int i = 0; i < 5; i++) // printf("%f %f %f\n", r.data_x[i], r.data_y[i], r.data_z[i]); // printf("%d, %f\n", points[i].class, points[i].distance); gesture = determine_class(classes, numClasses); // printf("Gesture: %d\n", gesture); return gesture; } void calculate_frequencies(Point * sorted_points, int * classes, int k){ for(int i = 0; i < k; i++) classes[sorted_points[i].class]++; } int determine_class(int * classes, int num){ int count = 0; int answer = 0; for(int i = 0; i < num + 1; i++){ if(classes[i] > count){ count = classes[i]; answer = i; } } return answer; } //////////////////////////////////// Helper Functions ///////////////////////////// // Compare function for Point structs, used for qsort int compare(const void *v1, const void *v2){ const Point *p1 = v1; const Point *p2 = v2; if(p1->distance > p2->distance) return 1; else if(p1->distance < p2->distance) return -1; else return 0; } // Dynamic Time Warping implementation. Better way to compare time-series data. // Takes N^2 time wrt #features. Point dtw(RPoint r1, RPoint r2, int size){ double dtwCalc1[size+1][size+1]; double dtwCalc2[size+1][size+1]; double dtwCalc3[size+1][size+1]; double infinity = 10000000; double cost1, cost2, cost3; double distance; Point p; for(int i = 0; i < size+1; i++){ dtwCalc1[i][0] = infinity; dtwCalc1[0][i] = infinity; dtwCalc2[i][0] = infinity; dtwCalc2[0][i] = infinity; dtwCalc3[i][0] = infinity; dtwCalc3[0][i] = infinity; } dtwCalc1[0][0] = 0.0; dtwCalc2[0][0] = 0.0; dtwCalc3[0][0] = 0.0; for(int i = 0; i < size; i++){ for(int j = 0; j < size; j++){ cost1 = fabs(r1.data_x[i] - r2.data_x[j]); dtwCalc1[i+1][j+1] = cost1 + minimum(dtwCalc1[i][j+1], dtwCalc1[i+1][j], dtwCalc1[i][j]); cost2 = fabs(r1.data_y[i] - r2.data_y[j]); dtwCalc2[i+1][j+1] = cost2 + minimum(dtwCalc2[i][j+1], dtwCalc2[i+1][j], dtwCalc2[i][j]); cost3 = fabs(r1.data_z[i] - r2.data_z[j]); dtwCalc3[i+1][j+1] = cost3 + minimum(dtwCalc3[i][j+1], dtwCalc3[i+1][j], dtwCalc3[i][j]); } } distance = dtwCalc1[size][size] + dtwCalc2[size][size] + dtwCalc3[size][size]; p.distance = distance; p.class = r1.class; return p; } // Calculate minimum of three doubles double minimum(double a, double b, double c){ if(a < b && a < c) return a; else if(b < a && b < c) return b; else return c; } Point euclidean_distance(RPoint r1, RPoint r2, int size){ Point p; double squared_distance1 = 0.0; double squared_distance2 = 0.0; double squared_distance3 = 0.0; double distance1; double distance2; double distance3; for(int i = 1; i < size; i++){ squared_distance1 = squared_distance1 + pow((r1.data_x[i] - r2.data_x[i]), 2); squared_distance2 = squared_distance2 + pow((r1.data_y[i] - r2.data_y[i]), 2); squared_distance3 = squared_distance3 + pow((r1.data_z[i] - r2.data_z[i]), 2); } distance1 = sqrt(squared_distance1); distance2 = sqrt(squared_distance2); distance3 = sqrt(squared_distance3); p.distance = distance1 + distance2 + distance3; p.class = r1.class; return p; } int normalize(RPoint * r, int numFeatures){ double max_x = 0.0, max_y = 0.0, max_z = 0.0 ; for(int i = 0; i < numFeatures; i++){ if(fabs(r[0].data_x[i]) > max_x) max_x = r[0].data_x[i]; if(fabs(r[0].data_y[i]) > max_y) max_y = r[0].data_y[i]; if(fabs(r[0].data_z[i]) > max_z) max_z = r[0].data_z[i]; } for(int i = 0; i < numFeatures; i++){ r[0].data_x[i] = r[0].data_x[i]/max_x; r[0].data_y[i] = r[0].data_y[i]/max_y; r[0].data_y[i] = r[0].data_y[i]/max_z; } return 0; }
C
#include<stdio.h> int main (void) { printf ("1. In C, lowercase letters are significant \n"); printf ("2. main is where program execution begins \n"); printf ("3. Opening and closing braces enclose program statements in a routine \n"); printf ("4. All Program Statements must be terminated by a semi-colon \n"); return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <stddef.h> #include <stack.h> #include <general_tree.h> #include <baselib.h> struct general_tree *tree_create(void) { struct general_tree *p_tree = NULL; p_tree = malloc(sizeof(struct general_tree)); if (!p_tree) { fprintf(stderr, "fail to create general tree.\n"); return NULL; } p_tree->root = NULL; p_tree->count = 0; return p_tree; } void tree_init(struct general_tree *tree) { tree->root = NULL; tree->count = 0; } int tree_add_node(struct general_tree *tree, struct tree_node *parent, struct tree_node *src_node) { int i = 0; unsigned int tmp = 0; if (!parent) { if (!tree->root) { tree->root = src_node; tree->count = 1; src_node->tree = tree; return 0; } goto fail; } src_node->tree = tree; if (parent->nodes_num == parent->chld_num) { parent->nodes = realloc(parent->nodes, (parent->nodes_num + DEFAULT_TREE_NODE_SIZE) * sizeof(struct tree_node *)); if (!parent->nodes) { fprintf(stderr, " fail to realloc struct tree_node *\n"); return -1; } tmp = parent->nodes_num; parent->nodes[tmp] = src_node; parent->nodes_num += DEFAULT_TREE_NODE_SIZE; parent->chld_num ++; src_node->index = tmp; src_node->parent = parent; tree->count ++; return 0; } if (parent->nodes_num > parent->chld_num) { for (i = 0; i < parent->nodes_num; i ++) { if (!parent->nodes[i]) { parent->nodes[i] = src_node; src_node->parent = parent; src_node->index = i; break; } } parent->chld_num ++; tree->count ++; return 0; } fail: fprintf(stderr, "add tree node fail.\n"); return -1; } size_t tree_size(struct general_tree *tree) { return tree->count; } size_t tree_chld_tree_size(struct tree_node *pnode) { size_t size = 0; int i = 0; if (!pnode) return 0; for (i = 0; i < pnode->nodes_num; i ++) { if (pnode->nodes[i]) size += tree_chld_tree_size(pnode->nodes[i]); } size ++; return size; } struct tree_node *tree_node_alloc_nc(char *key, unsigned int num) { struct tree_node *tmp_node = NULL; struct tree_node **p_nodes = NULL; char *tmp_key = NULL; int i = 0; tmp_node = malloc(sizeof(struct tree_node)); if (!tmp_node) { fprintf(stderr, "fail to malloc tree node\n"); return NULL; } p_nodes = malloc(num * sizeof(struct tree_node *)); if (!p_nodes) { fprintf(stderr, "fail to struct tree_node *.\n"); goto fail; } tmp_key = malloc(B_ROUND(strlen(key), 4)); if (!tmp_key) { fprintf(stderr, "fail to malloc key space\n"); goto fail; } strcpy(tmp_key, key); tmp_node->nodes = p_nodes; tmp_node->key = tmp_key; tmp_node->index = 0; tmp_node->chld_num = 0; tmp_node->nodes_num = num; tmp_node->parent = NULL; tmp_node->tree = NULL; for (i = 0; i < num; i ++) { tmp_node->nodes[i] = NULL; } return tmp_node; fail: if (tmp_node) free(tmp_node); if (tmp_key) free(tmp_key); if (p_nodes) free(p_nodes); return NULL; } struct tree_node *tree_node_alloc_binary(char *key) { return tree_node_alloc_nc(key, 2); } void release_tree(struct tree_node *root) { int i = 0; if (!root) return; for (i = 0; i < root->nodes_num; i ++) { if (root->nodes[i]) release_tree(root->nodes[i]); } free(root->nodes); free(root->key); free(root); } void tree_remove_chld_tree(struct tree_node *pnode) { size_t chld_size = 0; int i = 0; if (!pnode) return; chld_size = tree_chld_tree_size(pnode) - 1; pnode->tree->count -= chld_size; for (i = 0; i < pnode->nodes_num; i ++) { if (pnode->nodes[i]){ release_tree(pnode->nodes[i]); pnode->nodes[i] = NULL; } } pnode->chld_num = 0; } static int traverse_tree(struct tree_node * root, struct stack *p_stack) { struct tree_node *cur_node = NULL; struct tree_node *next_node = NULL; int level = 0, ret = 0; int flag = 0; struct stack_n *tmp = NULL; int i = 0, j = 0; unsigned int slash_flag = 0; cur_node = root; if (cur_node) { list_for_each_entry(tmp, &p_stack->entry, head) { if (*(unsigned int *)tmp->ptr) { printf(" |"); flag = 1; } else { printf(" "); flag = 0; } } if (flag) printf("\n"); else printf("\b|\n"); list_for_each_entry(tmp, &p_stack->entry, head) { if (*(unsigned int *)tmp->ptr) { printf(" |"); flag = 1; } else { printf(" "); flag = 0; } } if (!cur_node->chld_num) { if (flag) printf("----%s\n", cur_node->key); else printf("\b|----%s\n", cur_node->key); } else { if (flag) printf("----%s\n", cur_node->key); else printf("\b|----%s\n", cur_node->key); } if (cur_node->chld_num) { for (i = 0; i < cur_node->nodes_num; i ++) { /*there are some chld node after this node*/ for (j = i + 1; j < cur_node->nodes_num; j ++) { slash_flag = slash_flag || cur_node->nodes[j]; } if (cur_node->nodes[i]) { stack_push(p_stack, (void *)&slash_flag); traverse_tree(cur_node->nodes[i], p_stack); stack_pop(p_stack); } } } } return 0; } static void release_node(struct stack_n *p_stn) { return; } int tree_traverse_key(struct general_tree *tree) { struct stack *p_stack = NULL; struct tree_node *pnode = tree->root; if (!tree->root) return -1; p_stack = stack_create(); traverse_tree(pnode, p_stack); stack_release(p_stack, release_node); return 0; } static struct tree_node *last_node(struct tree_node *pnode) { int i = 0, j= 0; while (i < pnode->nodes_num && j < pnode->chld_num) { if (pnode->nodes[i]) j ++; i++; } if (i) return pnode->nodes[i - 1]; else return NULL; } struct tree_node *tree_last_node(struct general_tree *tree) { struct tree_node *pnode = tree->root; struct tree_node *tmpnode = NULL; if (!pnode) return NULL; while(pnode) { tmpnode = pnode; pnode = last_node(pnode); } return tmpnode; }
C
// 문제 링크 : https://www.acmicpc.net/problem/2580 // 제출 공유 링크 : http://boj.kr/092ef8097e7a4554a801668b62da0d9d // 백준 스도쿠 // c 언어를 공부하기 위해서 풀고 있는 문제 (백트래킹) /* 중간에 정수론 및 조합론이 있었지만, 그것은 정말.. 수학 수식을 공부하고 그대로 코딩하는 방식이라서 코테와는 거리가 멀어 생략하였다. 전역변수로 옮길지 말지 고민하다가 몇몇만 전역변수가 되어버렸다; 예전에는 못 풀었는데.. 어쩌다보니 풀었다; 이전에 너무 어렵게 생각했었나..? 오늘은 운이 좋은 것 같다. */ #include <stdio.h> // 스도쿠에 숫자가 없는 칸의 수 int empty_cnt = 0; // 가로, 세로, 3x3 정사각형 안에 존재하는 숫자 사용 여부 // 예를 들어 used[0][1][2]는 2번째 가로에 숫자 3의 사용여부 // 인덱스는 0부터 모두 사용하므로 적절하게 +1 혹은 -1을 계산하여 처리한다. char used[3][9][9]; int solve(int sudoku[9][9], int empty[81][2], int num); int main(){ // used 배열 0으로 초기화 for (int i = 0; i < 3; i++) { for (int j = 0; j < 9; j++) { for (int k = 0; k < 9; k++) { used[i][j][k] = 0; } } } // 스도쿠 초기화 및 빈칸의 위치와 개수 초기화 int sudoku[9][9], empty[81][2]; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { int num; scanf("%d", &num); sudoku[i][j] = num; if (num == 0) { empty[empty_cnt][0] = j; empty[empty_cnt++][1] = i; }else{ used[0][i][num-1] = 1; used[1][j][num-1] = 1; used[2][(i / 3) * 3 + j / 3][num - 1] = 1; } } } // 칸 채워넣기 solve(sudoku, empty, 0); // 완성한 스도쿠 출력 for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { printf("%d ", sudoku[i][j]); } printf("\n"); } return 0; } // 스도쿠 풀기 // 스도쿠 배열, 스도쿠의 빈 곳 배열, 스도쿠의 빈 곳 순서 int solve(int sudoku[9][9], int empty[81][2], int num){ // 빈 곳의 가로, 세로 위치 int w = empty[num][0], h = empty[num][1]; // 빈 곳의 정사각형 순서 계산 int squre_order = (h / 3) * 3 + w / 3; // 빈 곳에 어떤 숫자를 넣을지 탐색한다. for (int i = 0; i < 9; i++) { // 가로, 세로, 해당 정사각형에서 사용하지 않은 숫자라면 if (!used[0][h][i] && !used[1][w][i] && !used[2][squre_order][i]) { // 스도쿠에 숫자를 기록하고 sudoku[h][w] = i + 1; // 만약 모든 빈곳을 채웠다면 return 1 if (num + 1 == empty_cnt) { return 1; } // 해당 위치에 숫자를 사용하고 있음을 기록한 후 used[0][h][i] = 1; used[1][w][i] = 1; used[2][squre_order][i] = 1; // 다음 빈 칸을 채워 넣는다. if (solve(sudoku, empty, num + 1) == 1){ // 모든 빈 칸을 채운 경우 return 1 return 1; } // 해당 빈 칸의 숫자가 맞지 않았을 경우 숫자를 지우고 // 사용 기록도 지운 후 스도쿠 풀기를 계속 진행한다. sudoku[h][w] = 0; used[0][h][i] = 0; used[1][w][i] = 0; used[2][squre_order][i] = 0; } } return 0; }
C
#include <stdio.h> int *fun() { int a; return &a; } int main() { int *p = NULL; p = fun(); *p = 100; printf("*p=%p\n", *p); return 0; }
C
/* *********************************************************************** */ /* *********************************************************************** */ /* MFILE Memory-mapped I/O Library Source Code Module */ /* *********************************************************************** */ /* File Name : %M% File Version : %I% Last Extracted : %D% %T% Last Updated : %E% %U% File Description : Handles formatted output to a memory-mapped file using a variable argument list. Revision History : 1992-08-25 --- Creation. Michael L. Brock Copyright Michael L. Brock 1992 - 2018. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ /* *********************************************************************** */ /* *********************************************************************** */ /* *********************************************************************** */ /* Include necessary header files . . . */ /* *********************************************************************** */ #include <string.h> #include "mfilei.h" /* *********************************************************************** */ /* *********************************************************************** */ /* *********************************************************************** */ /* BOH NAME : vmprintf SYNOPSIS : bytes_output = vmprintf(MFILE *mfile_ptr, const char *in_format, arg_list); int bytes_output; MFILE *mfile_ptr; const char *in_format; va_list arg_list; DESCRIPTION : Writes data to a memory-mapped file as specified by the ``in_format`` parameter and the subsequent parameters encapsulated within the ``arg_list`` parameter. PARAMETERS : Parameters to this function are as follow: (.) ``mfile_ptr``, which is the pointer to a structure of type ''MFILE''. (.) ``in_format`` is a ``printf()`` format specified. (.) ``arg_list`` contains subsequent arguments to this function. They will be output in accordance with the specifications embedded in the ``in_format`` parameter. RETURNS : Returns from this function are as follow: (.) The number of bytes output by this function if successful. (.) The value of the manifest constant ''EOF'' if an error occurs. NOTES : This function is the memory-mapped file library analogue of the ANSI C level two I/O function ``vfprintf()``. CAVEATS : This function uses the function ``vsprintf()`` to perform the actual work of formatting the output. Therefore, the exact nature of the formatted output may vary according to the compatibility with the ANSI C standard of the local C library implementation of that function. SEE ALSO : mprintf EXAMPLES : AUTHOR : Michael L. Brock COPYRIGHT : Copyright 1992 - 2018 Michael L. Brock OUTPUT INDEX: vmprintf Memory-mapped File Functions:printf Functions:vmprintf MFILE Functions:vmprintf PUBLISH XREF: vmprintf PUBLISH NAME: vmprintf ENTRY CLASS : Memory-mapped File Functions:printf Functions EOH */ /* *********************************************************************** */ #ifndef NARGS int vmprintf(MFILE *mfile_ptr, const char *in_format, va_list arg_list) #else int vmprintf(mfile_ptr, in_format, arg_list) MFILE *mfile_ptr; const char *in_format; va_list arg_list; #endif /* #ifndef NARGS */ { int char_count = 0; if (mprintf_ensure_space(mfile_ptr) != MFILE_FALSE) { #ifndef MFILE_MMAP_NON_NATIVE vsprintf(((char *) mfile_ptr->mmap_ptr) + mfile_ptr->current_offset, in_format, arg_list); /* ******************************************************** */ /* ******************************************************** */ /* We take the length of the formatted output string */ /* below because we can't depend upon the return value from */ /* 'vsprintf()' --- pre-ANSI compilers returned a pointer */ /* the buffer rather than the number of characters minus */ /* the terminating ASCII zero. */ /* ******************************************************** */ char_count = strlen(((char *) mfile_ptr->mmap_ptr) + mfile_ptr->current_offset); /* ******************************************************** */ #else char_count = vfprintf(mfile_ptr->file_ptr, in_format, arg_list); #endif /* #ifndef MFILE_MMAP_NON_NATIVE */ if (char_count > 0) { mfile_ptr->mfile_flags |= MFILE_FLAG_WRITTEN; mfile_ptr->current_offset += char_count; mfile_ptr->file_size = (mfile_ptr->current_offset > mfile_ptr->file_size) ? mfile_ptr->current_offset : mfile_ptr->file_size; } } return(char_count); } /* *********************************************************************** */ #ifdef TEST_MAIN COMPAT_FN_DECL(int main, (void)); int main() { int return_code = 0; MFILE *m_file_ptr = NULL; unsigned int in_count = 0; unsigned int line_count = 0; int out_count; char *fgets_return; char buffer[512]; fprintf(stderr, "Test routine for 'vmprintf()'\n"); fprintf(stderr, "---- ------- --- ------------\n\n"); if ((m_file_ptr = mopen("ERASE.ME", "w")) == NULL) { fprintf(stderr, "ERROR: Unable to open output file 'ERASE.ME'.\n\n"); return_code = -1; } else { while ((!feof(stdin)) && (!ferror(stdin))) { *buffer = '\0'; fgets_return = buffer; while (fgets_return && (!(*buffer))) { fgets_return = fgets(buffer, sizeof(buffer) - 1, stdin); in_count++; } if ((!fgets_return) || (!strnicmp(buffer, "END", 3))) { fprintf(stderr, "ENDING PROCESS: %s\n", (!fgets_return) ? "END-FILE-ENCOUNTERED" : "END IN INPUT ENCOUNTERED"); break; } out_count = mprintf(m_file_ptr, "%s", buffer); line_count++; } mclose(m_file_ptr); } return(return_code); } #endif /* #ifdef TEST_MAIN */
C
#include <stdio.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <stdlib.h> #define MAX_LINE 80 /* 80 chars per line, per command, should be enough. */ /* The setup function below will not return any value, but it will just: read in the next command line; separate it into distinct arguments (using blanks as delimiters), and set the args array entries to point to the beginning of what will become null-terminated, C-style strings. */ void setup(char inputBuffer[], char *args[],int *background) { int length, /* # of characters in the command line */ i, /* loop index for accessing inputBuffer array */ start, /* index where beginning of next command parameter is */ ct; /* index of where to place the next parameter into args[] */ ct = 0; /* read what the user enters on the command line */ length = read(STDIN_FILENO,inputBuffer,MAX_LINE); /* 0 is the system predefined file descriptor for stdin (standard input), which is the user's screen in this case. inputBuffer by itself is the same as &inputBuffer[0], i.e. the starting address of where to store the command that is read, and length holds the number of characters read in. inputBuffer is not a null terminated C-string. */ start = -1; if (length == 0) exit(0); /* ^d was entered, end of user command stream */ /* the signal interrupted the read system call */ /* if the process is in the read() system call, read returns -1 However, if this occurs, errno is set to EINTR. We can check this value and disregard the -1 value */ if ( (length < 0) && (errno != EINTR) ) { perror("error reading the command"); exit(-1); /* terminate with error code of -1 */ } fprintf(">>%s<<",inputBuffer); for (i=0;i<length;i++){ /* examine every character in the inputBuffer */ switch (inputBuffer[i]){ case ' ': case '\t' : /* argument separators */ if(start != -1){ args[ct] = &inputBuffer[start]; /* set up pointer */ ct++; } inputBuffer[i] = '\0'; /* add a null char; make a C string */ start = -1; break; case '\n': /* should be the final char examined */ if (start != -1){ args[ct] = &inputBuffer[start]; ct++; } inputBuffer[i] = '\0'; args[ct] = NULL; /* no more arguments to this command */ break; default : /* some other character */ if (start == -1) start = i; if (inputBuffer[i] == '&'){ *background = 1; inputBuffer[i-1] = '\0'; } } /* end of switch */ } /* end of for */ args[ct] = NULL; /* just in case the input line was > 80 */ for (i = 0; i <= ct; i++) fprintf("args %d = %s\n",i,args[i]); } /* end of setup routine */ int main(void) { char inputBuffer[MAX_LINE]; /*buffer to hold command entered */ int background; /* equals 1 if a command is followed by '&' */ char *args[MAX_LINE/2 + 1]; /*command line arguments */ int childpid; int ret; /*keeps the return value of chdir*/ int callFromHistory = 0; /* if its 0 then it means that the command is not executed through '! string' */ int lengthOfHist=0; /*number of commands which is recorded in the history*/ int isPipe=0; /*checks if a pipe exists*/ int sizeOfHist=10; /* size of history buffer */ int fd[2]; /* array for the pipe */ int isBackground=0; /* checks if there are any background processes currently running */ char *pipeCmd[MAX_LINE/2 + 1]; /* keeps the command data for the parent and child in pipe */ /* struct for the linked list used for history buffer */ typedef struct hist{ char *command[MAX_LINE/2 + 1]; /* keeps the command data */ struct hist *next; } hist; /* keeps the head of the linked list */ struct hist *head=NULL; while (1){ background = 0; /*setup() calls exit() when Control-D is entered */ /* checks the status of all child processes, and if the result is 1 it means they are still active, so it sets isBackground to 1, otherwise it'll be set to 0 */ int status; pid_t result = waitpid (-1, &status, WNOHANG); if(result==0) isBackground=1; else isBackground=0; /* if a '! string' type command is executed, then callFromHistory becomes 1, and it's not needed to get the user command input */ if(callFromHistory == 0) { fprintf(stderr,"CSE333sh: "); setup(inputBuffer, args, &background); } /* sets callFromHistory to 0*/ callFromHistory=0; /* if the command is not one of the " cd, dir, clr, wait, hist, !, exit " commands, then enters here */ if(strcmp(args[0],"cd")!=0 && strcmp(args[0],"dir")!=0 && strcmp(args[0],"clr")!=0 && strcmp(args[0],"wait")!=0 && strcmp(args[0],"hist")!=0 && strcmp(args[0],"!")!=0 && strcmp(args[0],"exit")!=0) { /* creates a child */ childpid=fork(); /* this part is exected only by the child */ if(childpid==0){ /* checks if a path entered for the command, and if this is the case then it'll use execl */ if(*args[0]=='/'){ /* commands with path supports maximum 10 arguments */ execl(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9],NULL); /* if a path is not entered, it uses execvp */ } else { /* goes through the arguments to check if there is a pipe operation */ for(int i=0;args[i]!='\0';i++){ if(args[i][0]=='|'){ /* sets isPipe to 1 in order to indicate that there is a pipe operation */ isPipe=1; break; } } /* if there no pipe operation then it only executes execvp with the given command and arguments */ if(isPipe==0){ int i=0; char *temp[MAX_LINE/2 + 1]; /* copies all the arguments except '&' to temp to prevent any errors that is caused by passing & as an argument to the command */ for(;args[i]!='\0';i++){ if(args[i][0]!='&'){ temp[i] = strdup(args[i]); } else { temp[i]='\0'; break; } } execvp(temp[0],&temp[0]); /* if there is a pipe operation, enters here */ } else { /* isPipe is set to 0 */ isPipe=0; /* Pipe operation */ /* child is the left part of the pipe operator */ if ((pipe(fd) == -1) || ((childpid = fork()) == -1)) { perror("Failed to setup pipeline"); return 1; } /* copies the command which is on the left side of the operator, and all of its arguments to pipeCmd array */ int i=0; for(;args[i][0]!='|';i++){ pipeCmd[i] = strdup(args[i]); } pipeCmd[i]=NULL; /* sets the last element of the pipeCmd to NULL to prevent any errors */ if (childpid == 0) { if (dup2(fd[1], STDOUT_FILENO) == -1) perror("Failed to redirect stdout of command"); else if ((close(fd[0]) == -1) || (close(fd[1]) == -1)) perror("Failed to close extra pipe descriptors on ls"); else { /* execvp is used for the child operator */ execvp(pipeCmd[0], &pipeCmd[0]); perror("Failed to exec command"); } return 1; } /* copies the command which is on the right side of the pipe operation, and all of its arguments to pipeCmd */ int counter=0; for(i+=1;args[i]!='\0';i++){ pipeCmd[counter] = strdup(args[i]); counter++; } /* last element of pipeCmd is set to NULL */ pipeCmd[counter]=NULL; if (dup2(fd[0], STDIN_FILENO) == -1) perror("Failed to redirect stdin of sort"); else if ((close(fd[0]) == -1) || (close(fd[1]) == -1)) perror("Failed to close extra pipe file descriptors on sort"); else { /* execvp is executed for the parent */ execvp(pipeCmd[0],&pipeCmd[0]); perror("Failed to exec sort"); } return 1; } } } /* if the command is one of "cd, dir, clr, wait, hist, !, exit", then it enters here, and it executes the command without creating a new process */ } else { /* cd command */ if(strcmp(args[0],"cd") == 0){ /* if a path is given for cd then enters here */ if(args[1] != NULL){ /* change the directory, and sets the return value of chdir to ret */ ret=chdir(args[1]); /* if ret is 0, then directory is changed carefully */ if(ret==0){ /* sets the pdw value with the new directory path */ setenv("PDW",args[1],1); /* if directory is changed successfully, then ret is -1, and prints an error message */ } else if(ret == -1) { fprintf(stderr,"couldn't change directory\n"); } /* if a path is not given, then enters here */ } else { /* since a path is not given, it changes directory to home, if ret is 0,then directory is changed successfully */ ret=chdir(getenv("HOME")); if(ret == 0){ /* updates pwd value */ setenv("PWD","HOME",1); /* if directory isn't changed successfully, then it enters here, and prints a message */ } else if(ret == -1) { fprintf(stderr,"couldn't change directory\n"); } } /* if command is dir, then enters here */ } else if(strcmp(args[0],"dir") == 0){ /* get current directory value and puts it into path, then prints it */ char *path[1024]; getcwd( path, 1024 ); fprintf(stderr,path); fprintf(stderr,"\n"); /* if the entered command is clr enters here */ } else if(strcmp(args[0],"clr") == 0){ /* uses system function to clear the screen*/ char c[50]; strcpy( c, "clear" ); system(c); /* if the entered command is wait, then it waits until the child process is terminated */ } else if(strcmp(args[0],"wait") == 0){ while(wait(NULL)>0); /* if the entered command is hist, and there isn't any arguments, then enters here */ } else if(strcmp(args[0],"hist") == 0 && args[1]=='\0'){ /* assigns the head of the linked list to temp */ struct hist *temp=head; int i=0; /* if temp value is not null, and i is smaller than the size of the buffer, loop continues */ for(;temp!=NULL && i<sizeOfHist;temp=temp->next,i++){ /* prints the command and its arguments */ fprintf(stderr,"%d -)",i); for(int j=0;temp->command[j]!='\0';j++){ fprintf(stderr,temp->command[j]); fprintf(stderr," "); } fprintf(stderr,"\n"); } /* if hist command is entered with '-set' argument, then it enters here */ } else if(strcmp(args[0],"hist") == 0 && strcmp(args[1],"-set")== 0){ /* takes the number that is entered after -set, and converts it into integer */ sizeOfHist = atoi(args[2]); /* prints the previously entered commands which is within the newly set buffer size */ struct hist *temp=head; int i=0; for(;temp!=NULL && i<sizeOfHist;temp=temp->next,i++){ fprintf(stderr,"%d -)",i); for(int j=0;temp->command[j]!='\0';j++){ fprintf(stderr,temp->command[j]); fprintf(stderr," "); } fprintf(stderr,"\n"); } /* if '!' command is entered, enters here */ } else if(strcmp(args[0],"!") == 0) { /* if the entered argument is a number, then enters here */ if(*args[1] == '0' || *args[1] == '1'|| *args[1] == '2'|| *args[1] == '3'|| *args[1] == '4' || *args[1] == '5'|| *args[1] == '6'|| *args[1] == '7'|| *args[1] == '8'|| *args[1] == '9'){ /* converts the argument into integer */ int t = atoi(args[1]); /* if there is a corresponding command for the entered number, then enters here */ if(t < lengthOfHist && t < sizeOfHist){ /* head of the list is assigned to temp, and then it moves to the corresponding element of the list */ struct hist *temp=head; for(int i=0;i!=t;i++){ temp=temp->next; } temp = temp->next; /* sets callFromHistory to 1 to indicate that the next command will be given from the history */ callFromHistory=1; int i=0; /* copies the corresponding command and its arguments to args */ for(;temp->command[i]!='\0';i++){ args[i] = strdup(temp->command[i]); } /* sets the last element */ args[i]='\0'; /* if there isn't a corresponding command, then prints a message */ } else { fprintf(stderr,"there isn't a command which corresponds to number %d.\n",t); } /* if the argument that is entered isn't an integer, then enters here */ } else { struct hist *temp=head; int i=0; int found=0; /* checks if the command is found or not */ /* keeps moving through the history buffer until it finds a command whose first two letters correspond to any command in the history buffer */ for(;temp!=NULL && i<sizeOfHist;temp=temp->next,i++){ if(temp->command[0][0] == args[1][0]){ if(temp->command[0][1]==args[1][1]){ callFromHistory=1; int j=0; /* if the command is found, then copies it to args */ for(;temp->command[j]!='\0';j++){ args[j] = temp->command[j]; } /* found is set to 1 to indicate that a match is found, and breaks the loop */ found = 1; args[j]='\0'; break; } } } /* if it doesn't find a match, then enters here, and prints a message */ if(found==0){ fprintf(stderr,"Command you entered doesn't have a match \n"); } } /* if the entered command is exit, then enters here */ } else if(strcmp(args[0],"exit") == 0){ /* prints a message, and waits for the child process to be terminated, and exits */ if(isBackground==1) fprintf(stderr,"Please terminate any working background process in order to exit\n"); while(wait(NULL)>0); exit(0); } } /* if the command is entered without an & argument, then shell waits until the child is terminated. */ if(background==0) { while(wait(NULL)>0); } /* if the command isn't called from history, it enters here */ if(callFromHistory==0){ /* allocates some space for temp */ struct hist *temp = (struct hist*) malloc(sizeof(struct hist)); /* copies the command and its arguments, to the newly created element of the list */ for(int i=0;args[i]!='\0';i++){ temp->command[i] = strdup(args[i]); } /* if it is the first element to be added into the list, then it becomes the head */ if(head==NULL){ head = temp; /* if the new element won't be first element in the list, then it is added to the beginning of the list */ } else { temp->next = head; head=temp; } /* keeps the number of commands that is added to the list */ lengthOfHist++; } } }
C
#include <errno.h> #include <math.h> /* C99's isnan() is a macro */ #include <stdlib.h> #include <string.h> #include "private.h" __PUBLIC const char json_true[] = "true"; __PUBLIC const char json_false[] = "false"; __PUBLIC int json_as_bool(const char *json) { if (!json) { errno = EINVAL; return 0; } skip_white(&json); if (word_strcmp(json, json_false) == 0) return 0; if (word_strcmp(json, json_true) == 0) return 1; /* Everything after here is EINVAL, * but we can make a best-effort conversion. */ errno = EINVAL; /* Objects and arrays are truthy */ if (json[0] == '[') return 1; if (json[0] == '{') return 1; /* Empty strings are falsey */ if (json[0] == '"') return json[1] != '"'; if (json[0] == '\'') return json[1] != '\''; /* Empty JSON expressions are falsey */ if (is_delimiter(*json)) return 0; /* empty */ if (strchr("+-0.N", *json)) { double fp; char *end = NULL; /* NaN and 0 are falsey */ fp = strtod(json, &end); errno = EINVAL; /* strtod() may have set it to ERANGE */ if (end && is_delimiter(*end)) return !(fp == 0 || isnan(fp)); } /* null and undefined are falsey */ if (word_strcmp(json, json_null) == 0) return 0; if (word_strcmp(json, "undefined") == 0) return 0; return 1; }
C
#include "io.h" char rom[ROM_SIZE + 1]; unsigned int p = 0; char io_readChar(){ return rom[p++]; } int io_isEoF(){ return p >= ROM_SIZE; } void io_readRom(){ FILE *romFile = fopen("roms\\DMG_ROM.bin", "rb"); if(romFile != NULL){ fread(rom, 1, ROM_SIZE, romFile); }else{ printf("file not found\n"); exit(1); } /*for(int i = 0; i < ROM_SIZE; i++){ printf("%d ", rom[i]); } printf("\n");*/ } void io_applyRom(char *mem){ memcpy(mem, rom, ROM_SIZE); }
C
#include<iostream> #include<algorithm> #include<string.h> using namespace std; int C,B; int visit[650][200000]; int solve(int t, int b) { int& ret = visit[t][b]; if(ret!=0){ return ret; } int c = C+(t*(t+1))/2; if(c>200000){ ret=1; return -1; } if(b<0||b>200000){ ret=1; //d[t][b]=-1; return -1; } if(c==b){ //d[t][b]=t; ret=t; return ret; } int r1,r2,r3; r1=solve(t+1,b-1); r2=solve(t+1,b+1); r3=solve(t+1,2*b); ret = min(r1,min(r2,r3)); //d[t][b] = min(r1,min(r2,r3)); return ret; } int main() { cin>>C>>B; if(C==B){ cout<<0; return 0; } int a,b,c; memset(visit,0,sizeof(visit)); a=solve(1,B-1); // cout<<a<<endl; printf("%d\n", a); b=solve(1,B+1); // cout<<b<<endl; printf("%d\n", b); c=solve(1,2*B); // cout<<c<<endl; printf("%d\n", c); int ans = min(a,min(b,c)); cout<<ans; return 0; }
C
/* stringdist - a C library of string distance algorithms with an interface to R. * Copyright (C) 2013 Mark van der Loo * * 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 3 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, see <http://www.gnu.org/licenses/>. * * You can contact the author at: mark _dot_ vanderloo _at_ gmail _dot_ com */ #include "utils.h" #include <string.h> #ifdef _OPENMP #include <omp.h> #endif /* First match of a in b[] * Returns -1 if no match is found * Parameter 'guard; indicates which elements of b have been matched before to avoid * matching two instances of the same character to the same position in b (which we treat read-only). */ static int match_int(unsigned int a, unsigned int *b, double *guard, int width, int m){ int i = 0; while ( ( i < width ) && ( b[i] != a || (b[i] == a && guard[i] > 0)) ){ ++i; } // ugly edge case workaround if ( !(m && i==width) && b[i] == a ){ guard[i] = 1.0; return i; } return -1; } // Winkler's l-factor (nr of matching characters at beginning of the string). static double get_l(unsigned int *a, unsigned int *b, int n){ int i=0; double l; while ( a[i] == b[i] && i < n ){ i++; } l = (double) i; return l; } /* jaro distance (see http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance). * * a : string (in int rep) * b : string (in int rep) * x : length of a (in uints) * y : length of b (in uints) * p : Winkler's p-factor in (0,0.25) * work : workspace, minimally of length max(x,y) * */ double jaro_winkler_dist( unsigned int *a, int x, unsigned int *b, int y, double p, double *w, double *work ){ // edge case if ( x == 0 && y == 0 ) return 0; // swap arguments if necessary, so we always loop over the shortest string if ( x > y ){ unsigned int *c = b; unsigned int z = y; b = a; a = c; y = x; x = z; } for (int k=0; k<MAX(x,y); k++) work[k] = 0.0; // max transposition distance int M = MAX(MAX(x,y)/2 - 1,0); // transposition counter double t = 0.0; // number of matches double m = 0.0; int max_reached; int left, right, J, jmax=0; for ( int i=0; i < x; ++i ){ left = MAX(0, i-M); if ( left >= y ){ J = -1; } else { right = MIN(y, i+M); // ugly workaround: I should rewrite match_int. max_reached = (right == y) ? 1 : 0; J = match_int(a[i], b + left, work + left, right - left, max_reached); } if ( J >= 0 ){ ++m; t += (J + left < jmax ) ? 1 : 0; jmax = MAX(jmax, J + left); } } double d; if ( m < 1 ){ d = 1.0; } else { d = 1.0 - (1.0/3.0)*(w[0]*m/((double) x) + w[1]*m/((double) y) + w[2]*(m-t)/m); } // Winkler's penalty factor if ( p > 0 && d > 0 ){ int n = MIN(MIN(x,y),4); d = d - get_l(a,b,n)*p*d; } return d; }
C
#ifndef ROFI_MODE_H #define ROFI_MODE_H /** * @defgroup MODE Mode * * The 'object' that makes a mode in rofi. * @{ */ /** * Type of a mode. * Access should be done via mode_* functions. */ typedef struct rofi_mode Mode; /** * Enum used to sum the possible states of ROFI. */ typedef enum { /** Exit. */ MODE_EXIT = 1000, /** Skip to the next cycle-able dialog. */ NEXT_DIALOG = 1001, /** Reload current DIALOG */ RELOAD_DIALOG = 1002, /** Previous dialog */ PREVIOUS_DIALOG = 1003, /** Reloads the dialog and unset user input */ RESET_DIALOG = 1004, } ModeMode; /** * State returned by the rofi window. */ typedef enum { /** Entry is selected. */ MENU_OK = 0x00010000, /** User canceled the operation. (e.g. pressed escape) */ MENU_CANCEL = 0x00020000, /** User requested a mode switch */ MENU_NEXT = 0x00040000, /** Custom (non-matched) input was entered. */ MENU_CUSTOM_INPUT = 0x00080000, /** User wanted to delete entry from history. */ MENU_ENTRY_DELETE = 0x00100000, /** User wants to jump to another switcher. */ MENU_QUICK_SWITCH = 0x00200000, /** Go to the previous menu. */ MENU_PREVIOUS = 0x00400000, /** Bindings specifics */ MENU_CUSTOM_ACTION = 0x10000000, /** Mask */ MENU_LOWER_MASK = 0x0000FFFF } MenuReturn; /** * @param mode The mode to initialize * * Initialize mode * * @returns FALSE if there was a failure, TRUE if successful */ int mode_init ( Mode *mode ); /** * @param mode The mode to destroy * * Destroy the mode */ void mode_destroy ( Mode *mode ); /** * @param sw The mode to query * * Get the number of entries in the mode. * * @returns an unsigned in with the number of entries. */ unsigned int mode_get_num_entries ( const Mode *sw ); /** * @param mode The mode to query * @param selected_line The entry to query * @param state The state of the entry [out] * @param attribute_list List of extra (pango) attribute to apply when displaying. [out][null] * @param get_entry If the should be returned. * * Returns the string as it should be displayed for the entry and the state of how it should be displayed. * * @returns allocated new string and state when get_entry is TRUE otherwise just the state. */ char * mode_get_display_value ( const Mode *mode, unsigned int selected_line, int *state, GList **attribute_list, int get_entry ); /** * @param mode The mode to query * @param selected_line The entry to query * * Return a string that can be used for completion. It has should have no markup. * * @returns allocated string. */ char * mode_get_completion ( const Mode *mode, unsigned int selected_line ); /** * @param mode The mode to query * @param menu_retv The menu return value. * @param input Pointer to the user input string. [in][out] * @param selected_line the line selected by the user. * * Acts on the user interaction. * * @returns the next #ModeMode. */ ModeMode mode_result ( Mode *mode, int menu_retv, char **input, unsigned int selected_line ); /** * @param mode The mode to query * @param tokens The set of tokens to match against * @param selected_line The index of the entry to match * * Match entry against the set of tokens. * * @returns TRUE if matches */ int mode_token_match ( const Mode *mode, GRegex **tokens, unsigned int selected_line ); /** * @param mode The mode to query * * Get the name of the mode. * * @returns the name of the mode. */ const char * mode_get_name ( const Mode *mode ); /** * @param mode The mode to query * * Free the resources allocated for this mode. */ void mode_free ( Mode **mode ); /** * @param mode The mode to query * * Helper functions for mode. * Get the private data object. */ void *mode_get_private_data ( const Mode *mode ); /** * @param mode The mode to query * @param pd Pointer to private data to attach to the mode. * * Helper functions for mode. * Set the private data object. */ void mode_set_private_data ( Mode *mode, void *pd ); /** * @param mode The mode to query * * Get the name of the mode as it should be presented to the user. * * @return the user visible name of the mode */ const char *mode_get_display_name ( const Mode *mode ); /** * @param mode The mode to query * * Should be called once for each mode. This adds the display-name configuration option for the mode. */ void mode_set_config ( Mode *mode ); /** * @param mode The mode to query * @param input The input to process * * This processes the input so it can be used for matching and sorting. * This includes removing pango markup. * * @returns a newly allocated string */ char * mode_preprocess_input ( Mode *mode, const char *input ); /** * @param mode The mode to query * * Query the mode for a user display. * * @return a new allocated (valid pango markup) message to display (user should free). */ char *mode_get_message ( const Mode *mode ); /*@}*/ #endif
C
#include<stdio.h> #include<stdlib.h> #include<glob.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <string.h> #include<errno.h> #include<pwd.h> #if 0 // debug #define DBG(...) printf(__VA_ARGS__) #else #define DBG(...) #endif #if 0 struct passwd { char *pw_name; /* username */ char *pw_passwd; /* user password */ uid_t pw_uid; /* user ID */ gid_t pw_gid; /* group ID */ char *pw_gecos; /* user information */ char *pw_dir; /* home directory */ char *pw_shell; /* shell program */ }; #endif int main(int argc, char *argv[]) { struct passwd *pwdline; if(argc < 2){ fprintf(stderr, "Usage...\n"); exit(1); } pwdline = getpwuid(atoi(argv[1])); if(NULL == pwdline){ perror("getpwuid error:"); exit(1); } puts(pwdline->pw_name); }
C
#include "iostream" #include "fstream" #include "math.h" using namespace std; float a = 1/(2*pow(2,0.5)); float dt = 0.006; float t = 3000.0; int n = 10000; float q1[n], q2[n], p1[n], p2[n]; float q1rk[4], q2rk[4], p1rk[4], p2rk[4]; float q1[0] = a, q2[0] = -a, p1[0] = 0.0, p2[0] = 0.0; float e = 1.0/1000; float sol(float a1, float a2, float b1, float b2, int i); void rungekutta(); void actualizar(); int main() { //Se leen los datos ofstream d("datos_caos.txt"); rungekutta(); actualizar(); for (int i = 0; i < n-1; ++ i) { d << q1[i] << " " << q2[i] << " " << p1[i] << " " << p2[i]; d << endl; } return 0; } //Soluciones a las ecuaciones float sol(float a1, float a2, float b1, float b2, int i) { //Soluciones float s1; float s2; float s3; float s4; //Dependiendo del int se devuelve la solucion correspondiente if (i==0) { return s1 = b1; } else if (i==1) { return s2 = b2; } else if (i==2) { return s3 = -(2*a1)/(pow(4.0*pow(a1,2)+ pow(e,2),1.5)); } else { return s4 = (a1-a2)/(pow( pow((a1-a2),2)+pow(e,2)/4.0 ,1.5) - (a1+a2)/(pow( pow((a1+a2),2)+pow(e,2)/4.0 ,1.5); } } //Metodo de Runge Kutta de cuarto orden void rungekutta() { //Paso 1 for (int i = 0; i < n; i++) { q1rk[0] = sol(0, q1[i], q2[i], p1[i], p2[i]); q2rk[0] = sol(1, q1[i], q2[i], p1[i], p2[i]); p1rk[0] = sol(2, q1[i], q2[i], p1[i], p2[i]); p2rk[0] = sol(3, q1[i], q2[i], p1[i], p2[i]); } //Paso 2 for (int i = 0; i < n; i++) { float a = q1[i]+0.5*dt*q1rk[0]; float b = q2[i]+0.5*dt*q2rk[0]; float c = p1[i]+0.5*dt*p1rk[0]; float d = p2[i]+0.5*dt*p2rk[0]; q1rk[1] = sol(0, a, b, c, d); q2rk[1] = sol(1, a, b, c, d); p1rk[1] = sol(2, a, b, c, d); p2rk[1] = sol(3, a, b, c, d); } //Paso 3 for (int i = 0; i < n; i++) { float a = q1[i]+0.5*dt*q1rk[1]; float b = q2[i]+0.5*dt*q2rk[1]; float c = p1[i]+0.5*dt*p1rk[1]; float d = p2[i]+0.5*dt*p2rk[1]; q1rk[2] = sol(0, a, b, c, d); q2rk[2] = sol(1, a, b, c, d); p1rk[2] = sol(2, a, b, c, d); p2rk[2] = sol(3, a, b, c, d); } //Paso 4 for (int i = 0; i < n; i++) { float a = q1[i]+1.0*dt*q1rk[2]; float b = q2[i]+1.0*dt*q2rk[2]; float c = p1[i]+1.0*dt*p1rk[2]; float d = p2[i]+1.0*dt*p2rk[2]; q1rk[3] = sol(0, a, b, c, d); q2rk[3] = sol(1, a, b, c, d); p1rk[3] = sol(2, a, b, c, d); p2rk[3] = sol(3, a, b, c, d); } } //Actualizar void actualizar() { for (int i = 0; i < n; i++) { q1[i+1] = q1[i] + dt/6.0*( q1rk[0] + 2*q1rk[1] + 2*q1rk[2] +q1rk[3] ); q2[i+1] = q2[i] + dt/6.0*( q2rk[0] + 2*q2rk[1] + 2*q2rk[2] +q2rk[3] ); p1[i+1] = p1[i] + dt/6.0*( p1rk[0] + 2*p1rk[1] + 2*p1rk[2] +p1rk[3] ); p2[i+1] = p2[i] + dt/6.0*( p2rk[0] + 2*p2rk[1] + 2*p2rk[2] +p2rk[3] ); } }
C
Assignment name : print_hex Expected files : print_hex.c Allowed functions: write -------------------------------------------------------------------------------- Write a program that takes a positive (or zero) number expressed in base 10, and displays it in base 16 (lowercase letters) followed by a newline. If the number of parameters is not 1, the program displays a newline. Écrivez un programme qui prend un nombre positif (ou zéro) exprimé en base 10, et laffiche en base 16 (lettres minuscules) suivi dune nouvelle ligne. Si le nombre de paramètres nest pas 1, le programme affiche une nouvelle ligne. Esemples : $> ./print_hex "10" | cat -e a$ $> ./print_hex "255" | cat -e ff$ $> ./print_hex "5156454" | cat -e 4eae66$ $> ./print_hex | cat -e $
C
void print_char(char); void print_last_digit(int n) { n=n%10; /*obtain last digit*/ if (n<0){ n=n*(-1); /*make pos if neg*/ } print_char(n+48); }
C
/* * Copyright (C) 2012 Sistemas Operativos - UTN FRBA. 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 3 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, see <http://www.gnu.org/licenses/>. */ #include "bitarray.h" #include "Malloc.h" #include <stddef.h> /* array index for character containing bit */ static inline uint8_t _bit_in_char(size_t bit, bit_numbering_t mode) { switch (mode) { case MSB_FIRST: // 0x80: 1000 0000 binario return (((uint8_t) 0x80) >> (bit % BYTE_BITS)); case LSB_FIRST: default: // 0x01: 0000 0001 binario return (((uint8_t) 0x01) << (bit % BYTE_BITS)); } } t_bitarray* bitarray_create(uint8_t* bitarray, size_t size) { return bitarray_create_with_mode(bitarray, size, LSB_FIRST); } t_bitarray* bitarray_create_with_mode(uint8_t* bitarray, size_t size, bit_numbering_t mode) { t_bitarray* self = Malloc(sizeof(t_bitarray)); self->bitarray = bitarray; self->size = size; self->mode = mode; return self; } bool bitarray_test_bit(t_bitarray* self, size_t bit_index) { return ((self->bitarray[BIT_CHAR(bit_index)] & _bit_in_char(bit_index, self->mode)) != 0); } void bitarray_set_bit(t_bitarray* self, size_t bit_index) { self->bitarray[BIT_CHAR(bit_index)] |= _bit_in_char(bit_index, self->mode); } void bitarray_clean_bit(t_bitarray* self, size_t bit_index) { /* create a mask to zero out desired bit */ uint8_t const mask = ~_bit_in_char(bit_index, self->mode); self->bitarray[BIT_CHAR(bit_index)] &= mask; } size_t bitarray_get_max_bit(t_bitarray* self) { return self->size * BYTE_BITS; } void bitarray_destroy(t_bitarray* self) { Free(self); }
C
/* * Copyright (c) 2008 Rainer Clasen * * This program is free software; you can redistribute it and/or modify * it under the terms described in the file LICENSE included in this * distribution. * */ #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <stdio.h> #include <errno.h> #include "proto_helper.h" #define BUFLENLINE 4096 static char *proto_fmtline( int last, const char *code, const char *fmt, va_list ap ) { char buffer[BUFLENLINE]; int r; sprintf( buffer, "%3.3s%c", code, last ? ' ' : '-' ); r = vsnprintf( buffer + 4, BUFLENLINE - 5, fmt, ap ); if( r < 0 || r > BUFLENLINE - 5 ) return NULL; r+=4; buffer[r++] = '\n'; buffer[r++] = 0; return strdup(buffer); } static int proto_vline( t_client *client, int last, const char *code, const char *fmt, va_list ap ) { char *line; int ret; if( NULL == ( line = proto_fmtline( last, code, fmt, ap ))) return -1; ret = client_send( client, line ); free(line); return ret; } /* * send non-last line */ int proto_rline( t_client *client, const char *code, const char *fmt, ... ) { va_list ap; int r; va_start( ap, fmt ); r = proto_vline( client, 0, code, fmt, ap ); va_end( ap ); return r; } /* * send single line reply or last line of a multi-line reply */ int proto_rlast( t_client *client, const char *code, const char *fmt, ... ) { va_list ap; int r; va_start( ap, fmt ); r = proto_vline( client, 1, code, fmt, ap ); va_end( ap ); return r; } /* * broadcast a reply to all clients with at least "right" rights. */ void proto_bcast( t_rights right, const char *code, const char *fmt, ... ) { char *line; va_list ap; va_start(ap, fmt); if( NULL != (line = proto_fmtline(1, code, fmt, ap))){ client_bcast_perm(line, right); free(line); } va_end(ap); } void proto_player_reply( t_client *client, t_playstatus r, char *code, char *reply ) { switch(r){ case PE_OK: proto_rlast(client, code, "%s", reply ); break; case PE_NOTHING: proto_rlast(client,"541", "nothing to do" ); return; case PE_BUSY: proto_rlast(client,"541", "already doing this" ); return; case PE_NOSUP: proto_rlast(client,"541", "not supported" ); return; case PE_SYS: proto_rlast(client,"540", "player error: %s", strerror(errno)); return; default: proto_rlast(client, "541", "player error" ); return; } }
C
#include<stdio.h> #include<string.h> int main() { char s[70]; int i, j, temp; printf("Enter a string\n"); scanf("%s", s); i = 0; j = strlen(s) - 1; while(i < j) { temp = s[i]; s[i] = s[j]; s[j] = temp; i++; j--; } printf("%s", s); return 0; }
C
#include "csapp.h" #define MAXARGS 128 void eval(char *cmdline); int parseline(char *buf, char **argv); int builtin_command(char **argv); /* Still runs in main process! */ int builtin_command(char **argv) { if (!strcmp(argv[0], "quit")) exit(0); // Terminate shell's main process! if (!strcmp(argv[0], "&")) return 1; return 0; // Return 0 if argv contains '&' only } /* Still in main process! */ int parseline(char *buf, char *argv[]) { char *delim; int argc, bg; buf[strlen(buf)-1] = ' '; while (*buf && (*buf == ' ')) // Ignore leading spaces buf++; /* Build the argv list */ argc = 0; while (delim = strchr(buf, ' ')) { // Point to the next ' ' argv[argc++] = buf; // Allocate argv[argc]'s pointer *delim = '\0'; buf = delim + 1; // Move buf forward while (*buf && (*buf == ' ')) // Ignore leading spaces buf++; } argv[argc] = NULL; if (argc == 0) return 1; // Ignore blank line if ((bg = (*argv[argc-1] == '&')) != 0) argv[--argc] = NULL; // We do not consider '&' an argument return bg; } void eval(char *cmdline) { // Main process! Execute one time for each program char *argv[MAXARGS] = { NULL }, buf[MAXLINE]; pid_t pid; strcpy(buf, cmdline); int bg = parseline(buf, argv); // Set argv[] if(argv[0] == NULL) return; // Ignore empty lines if(!builtin_command(argv)) { if((pid = Fork()) == 0) { // Only runs in child process if(execve(argv[0], argv, environ) < 0) { printf("%s: Command not found. \n", argv[0]); exit(0); } } if(!bg) { // Parent wait for fg process to terminate. Never runs in child process int status; if(waitpid(pid, &status, 0) < 0) unix_error("waitfg: waitpid error"); } else printf("%d %s", pid, cmdline); } return; } int main() { /* Main process */ char cmdline[MAXLINE]; while(1) { printf("getpgrp: %d\n", getpgrp()); printf("> "); Fgets(cmdline, MAXLINE, stdin); if(feof(stdin)) exit(0); eval(cmdline); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <pthread.h> #include <sys/socket.h> #include <arpa/inet.h> struct Client { struct sockaddr_in clientAddr; int index; int sockID; int len; } clients[1024]; struct Ristoranti { int index; int menu; // indica il cliente che ha chiesto di vedere il menu char name[1024]; } ristoranti[1024]; pthread_t thread[1024]; int clientsCount = 0; int ind = 0; char rist[1024]; // stringa della lista dei ristoranti che verrà inviata ai clienti void *doNetworking(void *ClientDetail) { struct Client *clientDetail = (struct Client *)ClientDetail; char type[2]; char data[1024]; recv(clientDetail->sockID, type, sizeof(char), 0); // aspetto di sapere se si tratta di un rist o di un cliente if (strcmp(type, "r") == 0) // se è un ristorante { int currRist = ind++; char temp[1024]; recv(clientDetail->sockID, data, sizeof(data), 0); // ricevi il nome strcpy(ristoranti[currRist].name, data); // salvo il nome ristoranti[currRist].index = clientDetail->index; //salva l'index nel tuo array ordinato di ristoranti ristoranti[currRist].menu = -1; printf("Il ristorante '%s' si e' connesso.\n", ristoranti[currRist].name); snprintf(temp, sizeof(temp), "[%d]%s\n", currRist + 1, ristoranti[currRist].name); strcat(rist, temp); // aggiorno la lista dei ristoranti while (1) // resto in ascolto del ristorante corrente, la ricezione dai ristoranti è centralizzata qui { memset(data, 0, sizeof(data)); recv(clientDetail->sockID, data, sizeof(data), 0); // ricevo qualcosa dal ristorante if (data[0] == '[') // se ho ricevuto il suo menu, invialo al cliente che lo ha chiesto { send(clients[ristoranti[currRist].menu].sockID, data, sizeof(data), 0); ristoranti[currRist].menu = -1; // permetti ad altri clienti di chiedere il menu di questo ristorante } else if (data[0] == 'r') // invece ho ricevuto l'id di un rider { char rID[1024]; strcpy(rID, data + 1); // salvo questo id memset(data, 0, sizeof(data)); recv(clientDetail->sockID, data, sizeof(data), 0); // prima di dedicarti a un altro ordine, aspetta l'id del cliente interessato send(clients[atoi(data)].sockID, rID, sizeof(rID), 0); // invia l'id del rider al cliente } else // altrimenti se il rider ha effettuato la consegna, ricevo l'id del cliente servito conferma la consegna al cliente che la stava aspettando { send(clients[atoi(data)].sockID, "y", sizeof(char), 0); printf("L'ordine del cliente numero %d e' stato consegnato.\n", atoi(data)); close(clients[atoi(data)].sockID); } } } else if (strcmp(type, "c") == 0) // se sei un cliente { printf("Il cliente numero '%d' si e' connesso.\n", clientDetail->index); int scelta; char clientID[1024]; char ordine[2][1024]; snprintf(data, sizeof(data), "%d", clientDetail->index); strcpy(clientID, data); while (1) // finche il cliente non effettua l'ordine { send(clientDetail->sockID, rist, sizeof(rist), 0); // invio la lista dei ristoranti disponibili al cliente memset(data, 0, sizeof(data)); recv(clientDetail->sockID, data, sizeof(data), 0); // ricevo la scelta del ristorante scelta = atoi(data) - 1; printf("Il cliente numero %d vuole vedere il menu del ristorante '%s'.\n", clientDetail->index, ristoranti[scelta].name); while (ristoranti[scelta].menu != -1) // scelto il ristorante, aspetto di poter inviare il menu ; ristoranti[scelta].menu = clientDetail->index; // nessun altro cliente può chiedere il menu del ristorante se il cliente corrente non l'ha ancora ricevuto send(clients[ristoranti[scelta].index].sockID, "menu", 4 * sizeof(char), 0); // chiedo al rist selezionato il menu memset(data, 0, sizeof(data)); recv(clientDetail->sockID, data, sizeof(data), 0); // ricevo l'ordine if (strcmp("-1", data) != 0) // se ricevo -1 significa che il cliente vuole tornare tornare alla lista dei rist, altrimenti esco break; } printf("Il cliente numero %d ha effettuato un ordine presso il ristorante '%s'.\n(Ordine: %s)\n\n", clientDetail->index, ristoranti[scelta].name, data); strcpy(ordine[0], clientID); strcpy(ordine[1], data); send(clients[ristoranti[scelta].index].sockID, ordine, sizeof(ordine), 0); // invio ordine pthread_exit(0); } } int main() { struct sockaddr_in serverAddr; int listenFD = socket(AF_INET, SOCK_STREAM, 0); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(8080); serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(listenFD, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) == -1) exit(-1); if (listen(listenFD, 1024) == -1) exit(-1); printf("Il server e' stato avviato sulla porta 8080 ...........\n\n"); while (1) { clients[clientsCount].sockID = accept(listenFD, (struct sockaddr *)&clients[clientsCount].clientAddr, &clients[clientsCount].len); clients[clientsCount].index = clientsCount; pthread_create(&thread[clientsCount], NULL, doNetworking, (void *)&clients[clientsCount]); // ogni cliente o rist che si connette avvio un thread e torno ad ascoltare clientsCount++; } }
C
/* Prime numbers can also be generated by an algorithm known as the Sieve of Erastosthenes. Write a program that implements this algorithm. have the program find all prime numbers up to n = 150. What can you say about this algorithm as compared to the ones used in the text for calculating prime numbers? */ /* TODO Come back to this exercise. This exercise is incomplete. I am struggling to comprehend the algorithm as the text explains it. */ #include <stdio.h> int main (void) { int n = 150; int p[n]; // Step 1: initialize entire array to 0 (for false) for ( int index = 0; index < 150; ++index) { p[index] = 0; } // Step 2: set i to 2 int i = 2; // Step 3: if i > n, the algorithm terminates while (i < n) { if (p[i] == 0) { // Step 4: if p[i] is 0, then i is prime p[i] = 1; // Step 5: For all positive integer values of j, // set p to 1 for ( int j = i * 2; j <= n; j+=i ) { //printf ("here"); p[i * j] = 1; } } ++i; } for ( int index = 0; index < 150; ++index) { printf ("%i ", p[index]); } printf ("\n"); return 0; }
C
#include <stdlib.h> #include <ctype.h> #include "zw_usbpipe_util.h" static const char* g_arrMsgType[2] = { "Msg-Request", "Msg-Response" }; const char* getMsgTypeName(E_MSG_TYPE e) { return g_arrMsgType[e]; } static const char g_module_name[] = "usbpipe"; static unsigned verbosity = 7; static char* getFileName(char *p) { char ch = '/'; char *q = strrchr(p, ch) + 1; return q; } void _msg(unsigned level, const char* file, const char* fun, int line, const char *fmt, ...) { if (level < 2) level = 2; else if (level > 7) level = 7; if (level <= verbosity) { static const char levels[8][6] = { [2] = "crit", [3] = "err", [4] = "warn", [5] = "note", [6] = "info", [7] = "dbg" }; static const char color[8][6] = { [2] = "32", [3] = "31", [4] = "35", [5] = "34", [6] = "37", [7] = "32" }; int _errno = errno; va_list ap; fprintf(stderr, "\033[40;%sm[%s: %s]-[%s-%s:%d] ", color[level], g_module_name, levels[level], getFileName(file), fun, line); va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); if (fmt[strlen(fmt) - 1] != '\n') { char buffer[128]; strerror_r(_errno, buffer, sizeof buffer); fprintf(stderr, ": (-%d) %s\n", _errno, buffer); } fprintf(stderr, "\033[0m"); fflush(stderr); } } void HexOutput(void *buf, size_t len) { char *b = (char*)buf; int numRow = 0; int numCol = 0; printf("Hen[%p]Len[%d]:\n", buf, len); size_t i = 0; for(i=0; i<len; i=i+16) { printf("%p|", b+i); numCol = (len-i>=16) ? 16 : (len-i); int j = 0; for (j = 0; j < numCol; j++) { unsigned char c = b[i+j]; // must use unsigned char to print >128 value if( c < 16) { printf(" 0%x", c); } else { printf(" %x", c); } } printf("\n"); } printf("\n"); } // 链表擝作 int zw_uptp_list_echo(struct zw_uptp_list* list) { if ((NULL == list)) { return -1; } char buf[1024]; struct elNode *np; LIST_FOREACH(np, list, elements) { memcpy(buf, np->data, np->dataLen); buf[np->dataLen] = '\0'; info("Seq[%d] Data[%s]\n", np->seq, buf); } return 0; } int zw_uptp_list_length(struct zw_uptp_list* list) { if ((NULL == list)) { return 0; } int lens = 0; struct elNode *np; pthread_mutex_lock(&list->mtxLock); LIST_FOREACH(np, list, elements) { lens++; } pthread_mutex_unlock(&list->mtxLock); return lens; } int zw_uptp_list_destroy(struct zw_uptp_list* list) { if (NULL == list) { return 0; } struct elNode *np = NULL; struct elNode *next = NULL; for ((np=list->lh_first); np; (np = next)) { next = (np)->elements.le_next; LIST_REMOVE(np, elements); if (np->data) { free(np->data); } free(np); np = NULL; } return 0; } void zw_uptp_list_push(struct zw_uptp_list *list, struct elNode* np) { if (NULL == list || NULL == np) { err("PramErr list[%p] np[%p]\n", list, np); return; } LIST_INSERT_HEAD(list, np, elements); return; } struct elNode* zw_uptp_list_pop_by_seq(struct zw_uptp_list *list, int seq) { if (NULL == list) { err("PramErr list[%p]\n", list); return NULL; } struct elNode *np; struct elNode *next = NULL; struct elNode *elRes = NULL; for ((np=list->lh_first); np; (np = next)) { next = (np)->elements.le_next; if (seq == np->seq) { LIST_REMOVE(np, elements); elRes = np; break; } } return elRes; }
C
/*9.3.Se sabe que como máximo en una comisión de Elementos de Programación hay 80 alumnos. De cada alumno se conoce: •Número de DNI (entero). •Apellido y Nombre(80 caracteres). •Nota1, Nota2 (entero). •Nota Promedio (real, calculado según Nota1 y Nota2). Se solicita: a.Declarar un tipo de dato que contenga la información del alumno. b.Declarar un vector de estructuras del tipo de dato creado en el punto a. c.Cargar en un vector de estructuras, los datos referentes a los alumnos de la comisión, esta información termina con DNI igual al 0.Función INGRESO. d.Indicar cuántos alumnos aprobaron (ambos parciales con nota >= 4 y cuántos reprobaron la materia. Función RESULTADO. e.Informar los datos de los alumnos de (DNI–Apellido y Nombre –Nota Promedio) de los alumnos. PROMOCIONADOS (ambas notas>= 7).Función INFORME_PROM */ #include <stdio.h> #include <string.h> #include <ctype.h> #define MAX_ALUMNOS 80 void clean_stdin(void) { int c; do { c = getchar(); } while (c != '\n' && c != EOF); } typedef struct { int DNI; char Apenom[81]; int notas[2]; float Promedio; }Alumno; int ingreso(Alumno[], int); void resultado(Alumno[], int); void informePromo(Alumno[], int); int buscar(Alumno[], int, int); int leerDNI(Alumno[], int); void leerApenom(char[], int); void leerTexto (char[], int); int leerNota(); int main() { int cantidadDeAlumnos = 0; Alumno alumnos[80]; cantidadDeAlumnos = ingreso(alumnos, MAX_ALUMNOS); if(cantidadDeAlumnos > 0) { resultado(alumnos, cantidadDeAlumnos); informePromo(alumnos, cantidadDeAlumnos); } return 0; } int ingreso(Alumno alumnos[], int tamanio) { int i = 0; int j; alumnos[i].DNI = leerDNI(alumnos, i); while(alumnos[i].DNI !=0 && i < tamanio) { leerApenom(alumnos[i].Apenom, 81); for(j=0; j<2; j++) { printf("Ingrese nota %d: ",j+1); alumnos[i].notas[j] = leerNota(); } alumnos[i].Promedio = (float)(alumnos[i].notas[0] + alumnos[i].notas[1])/2; i++; if(i < tamanio) alumnos[i].DNI = leerDNI(alumnos, i); else printf("Se alcanzó el valor maximo de carga\n"); } return i; } void resultado(Alumno alumnos[], int cantidadDeAlumnos) { int cantidadDeAprobados = 0; int i; for(i=0; i<cantidadDeAlumnos; i++) { if( alumnos[i].notas[0] >=4 && alumnos[i].notas[1] >= 4) cantidadDeAprobados ++; } printf("\nCantidad de alumnos APROBADOS: %d\n", cantidadDeAprobados); printf("Cantidad de alumnos REPROBADOS: %d\n", cantidadDeAlumnos - cantidadDeAprobados); } void informePromo(Alumno alumnos[], int cantidadDeAlumnos) { printf("\n%-10s\t%-42s\t%-9s\n","DNI", "Apellido y Nombres", "Promedios"); for(int i=0; i<cantidadDeAlumnos; i++) { if(alumnos[i].notas[0] >=7 && alumnos[i].notas[1] >=7) { printf("%-10d\t%-42s\t%-4.1f\n", alumnos[i].DNI, alumnos[i].Apenom, alumnos[i].Promedio); } } } int leerDNI(Alumno alumnos[], int cant) { int dni; int pos = -1; do { printf ("Ingrese DNI(0 para terminar): "); scanf("%d", &dni); pos = buscar(alumnos, dni, cant); if (pos!=-1) printf("Ya se ha registrado ese Alumno\n"); }while (((dni < 10000 || dni > 99999999) && dni!=0 ) || pos!=-1); return dni; } int buscar(Alumno alumnos[], int dni, int cant) { int i = 0; int pos = -1; while(pos == -1 && i < cant) { if(alumnos[i].DNI == dni) pos = i; else i++; } return pos; } void leerApenom(char texto[], int largo) { clean_stdin(); do { printf("Ingrese Apellido, Nombre: "); leerTexto(texto,largo); }while(strcmp(texto,"")==0); } void leerTexto (char texto[], int largo) { int i; fgets(texto, largo, stdin); i=0; while (texto[i]!='\0') { if (texto[i]=='\n') texto[i]='\0'; else i++; } } int leerNota() { int nota = 0; int error = 0; do { if (error) printf("Nota invalida, ingrese nuevamente: "); scanf("%d", &nota); error = 1; }while(nota < 1 || nota > 10); return nota; }
C
#include <stdio.h> #include <stdlib.h> int main(void) { int character; while((character = getc(stdin)) != EOF) // get typed(stdin) charcter until the end of line(ctrl D) if(putc(character, stdout) == EOF){ // print the character to terminal fprintf(stderr, "standard output error\n"); // error or end of the file exit(1); } if(ferror(stdin)){ // to check whether error or end of the file fprintf(stderr, "standard input error\n"); exit(1); } exit(0); }
C
#include <stdio.h> #include <stdlib.h> int test[100]; int num = 0, len = 0; void Quick_Core(int arr[], int start, int end) { int left, right, temp, mid; if (start > end) { return; } mid = arr[start]; left = start; right = end; while (left != right) { while (arr[right] >= mid && left < right) { right--; } while (arr[left] <= mid && left < right) { left++; } if (arr[left] >= arr[right]) { temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } } // left==right arr[start] = arr[left]; arr[left] = mid; Quick_Core(arr, start, left - 1); Quick_Core(arr, left + 1, end); } void Quick_Sort(int arr[], int length) { Quick_Core(arr, 0, length - 1); } int main() { printf("please input number:\n"); scanf("%d", &num); for (int i = 0; i < num; i++) { printf("please input the %d:\n", i + 1); scanf("%d", &test[i]); } Quick_Sort(test, num); for (int i = 0; i < num; i++) { printf("%d ", test[i]); } printf("\n"); system("pause"); }
C
//program listing of data-str\array2.c //Programs on arrays => To demonstrate the fill up logic of an array. /* col -> 1 2 3 4 ------------- row 1| 1 5 9 13 2| 2 6 10 14 => (col-1)*4 + row ^ 3| 3 7 11 15 | 4| 4 8 12 16 */ #include <stdio.h> #include <conio.h> void main(void) { int row,col,m[10][10]; clrscr(); for(row=1;row<=4;row++) for(col=1;col<=4;col++) m[row][col]=(col-1)*4+row; for(row=1;row<=4;row++) { for(col=1;col<=4;col++) printf(" %3d ",m[row][col]); printf("\n"); } getch(); }
C
#include "mylist.h" #include <stdio.h> #include <stdlib.h> int main(){ MYLIST_HEADER *root=createmyList(); int data = 1; int* ptr = NULL; FILE* fp = fopen("list.dat", "w"); ptr = (int*) (insertFirst(root,&data))->Data; printf("%i\n",*ptr); data = data+1; ptr = (int*) (insertLast(root,&data))->Data; printf("%i\n",*ptr); ptr = (int*)(get_entryMYLIST(root, 1))->Data; printf("%i\n", *ptr); pr_MYLIST(root, fp); getchar(); return EXIT_SUCCESS; }
C
#include <stdarg.h> #include <stdio.h> /** * print_strings - print strings * @separator: separator * @n: number of element **/ void print_strings(const char *separator, const unsigned int n, ...) { unsigned int i = 0; va_list args; char *c; va_start(args, n); while (i < n) { c = va_arg(args, char *); if (c) printf("%s", c); else printf("(nil)"); if (separator && i + 1 != n) printf("%s", separator); i++; } printf("\n"); va_end(args); }
C
#include "hospital.h" #include "comm.h" #include "reparto.h" #ifdef PRINT_COLOR #define REPARTO_NAME ANSI_COLOR_CYAN "Reparto" ANSI_COLOR_RESET #else #define REPARTO_NAME "Reparto" #endif void reparto(char* fifoPathTriage, int IDReparto, int semIDPazienti){ //printf("REPARTO %d AVVIATO\n", IDReparto); printf("["REPARTO_NAME" %d] AVVIATO\n", IDReparto); int fifoIDTriage = open(fifoPathTriage, O_RDONLY | O_NONBLOCK); // apro il file fifo in lettura (connessione triage --> reparto) int msgqIDPrestazione = createMsgQ(getpid(), false); // creo la coda verso la prestazione // creo la prestazione int pid = fork(); if (!pid) { prestazione(msgqIDPrestazione, IDReparto, semIDPazienti); exit(EXIT_SUCCESS); } // contenitore per info in arrivo dal FIFO del triage struct paziente pazienteDaServire; // ROUTINE PRINCIPALE REPARTI while (OSPEDALE_APERTO) { // prelevo un paziente dal FIFO del triage if(read(fifoIDTriage, &pazienteDaServire, sizeof(struct paziente)) > 0){ pazienteDaServire.turno = (long) 11-pazienteDaServire.gravita; // assegno turno (ribalto la gravita per inserire correttamente la priorita dei pazienti nella coda) // PRINT INFO printf("["REPARTO_NAME" %d] Paziente: %ld, Sintomo: %s, Gravita: %d\n", IDReparto, pazienteDaServire.ID, pazienteDaServire.sintomo, pazienteDaServire.gravita); sendMessage(msgqIDPrestazione, &pazienteDaServire, sizeof(pazienteDaServire));// invio alla prestazione il cliente da operare sleep(1); // processo intervalli regolari } else { if (OSPEDALE_IN_CHIUSURA) // ricevuta SIGALRM, se non ho piu nessun paziente da servire termino OSPEDALE_APERTO = false; } } printf("["REPARTO_NAME" %d] ** ATTENDO FIGLI **\n", IDReparto); waitAllChild(); // aspetto che muoiano tutti i figli prima di liberare le risorse printf("["REPARTO_NAME" %d] ** CHIUDO **\n", IDReparto); destroyMsgQ(msgqIDPrestazione); // distruggo la coda verso la prestazione close(fifoIDTriage); // chiudo FIFO in lettura }
C
/* code for linked lists */ #include "definitions.h" #include "functions.h" #define SYMBOL_ROW ((symbolTableRow*)newLine->data) #define DATA_ROW ((dataTableRow*)newLine->data) #define CODE_ROW ((codeTableRow*)newLine->data) #define ERROR {numOfErrors++; fprintf(stderr, "ERROR: can not allocate memmory.\n"); exit(0);} /*-----------------functions for linked lists---------------*/ /*This functions adds data from a generic pointer to a linked list, by list type*/ void add2Table(ptr* head, void* lineData, int type) { ptr newLine; int rowSize; /*allocate memory according to table type*/ if (type == CODET) rowSize = sizeof(codeTableRow); else if (type == DATAT) rowSize = sizeof(dataTableRow); else rowSize = sizeof(symbolTableRow); newLine = (ptr)malloc(sizeof(list)); if (!newLine) ERROR newLine->data = malloc(rowSize + sizeof(list)); if (!(newLine->data)) ERROR if (!*head) (newLine)->next = NULL; else newLine->next = *head; /*Add data by table type*/ switch (type) { case CODET: { CODE_ROW->IC = ((codeTableRow*)lineData)->IC; CODE_ROW->codeRow = ((codeTableRow*)lineData)->codeRow; break; } case DATAT: { DATA_ROW->DC = ((dataTableRow*)lineData)->DC; DATA_ROW->dataRow = ((dataTableRow*)lineData)->dataRow; break; } case SYMBOLT: { strcpy(SYMBOL_ROW->name, ((symbolTableRow*)lineData)->name); SYMBOL_ROW->addressOrValue = ((symbolTableRow*)lineData)->addressOrValue; SYMBOL_ROW->type = ((symbolTableRow*)lineData)->type; SYMBOL_ROW->external = ((symbolTableRow*)lineData)->external; break; } } *head = newLine; } /*This function searches symbol list by value "name". If the item was not found the function returns false*/ boolean searchTable(ptr head, char* name) { while (head) { if (strcmp(((symbolTableRow*)head->data)->name, name) == 0) return TRUE; head = head->next; } return FALSE; } /*This function returns the value from symbol list by name, will be used after confirming value existd with searchTable*/ int macroValue(ptr head, char* name) { while (head) { if (strcmp(((symbolTableRow*)head->data)->name, name) == 0) return ((symbolTableRow*)head->data)->addressOrValue; head = head->next; } return NONE; } /*This function returns true if the variable "name" is marked as external in the symbol table*/ boolean isExternal(ptr head, char* name) { while (head) { if (strcmp(((symbolTableRow*)head->data)->name, name) == 0) return ((symbolTableRow*)head->data)->external; head = head->next; } return FALSE; } /*This function returns a pointer to the node with the given address in code table*/ ptr* findNode(ptr* head, int address) { while (*head) { if (((codeTableRow*)(*head)->data)->IC == address) return head; *head = (*head)->next; } return NULL; } /*This function delets a linked list and frees memory*/ void deleteTable(ptr* head) { ptr temp; while (*head) { temp = *head; *head = (*head)->next; free(temp); } } /*This function reverses the direction of a one-way linked list*/ void reverseList(ptr* head) { ptr prev = NULL, current = *head, nextNode = NULL; while (current != NULL) { nextNode = current->next; current->next = prev; prev = current; current = nextNode; } *head = prev; } /*---------------------Functions for Queue-------------------*/ /*This function adds info to a new node*/ qNode* newNode(int line, int CTadress, char* str1, char* str2) { qNode* temp = (qNode*)malloc(sizeof(qNode)); if (!temp) ERROR; temp->line = line; temp->CTadress = CTadress; if (str1 != NULL) strcpy(temp->str1, str1); else strcpy(temp->str2, "-1"); if (str2 != NULL) strcpy(temp->str2, str2); else strcpy(temp->str2, "-1"); temp->next = NULL; return temp; } /*This function creats a new empty queue*/ queue* createQueue() { queue* q = (queue*)malloc(sizeof(queue)); if (!q) ERROR; q->front = NULL; q->rear = NULL; return q; } /*This functions adds a new node to end of a queue*/ void enQueue(queue* q, int line, int CTadress, char* str1, char* str2) { qNode* temp = newNode(line, CTadress, str1, str2); /* If queue is empty, then new node is both front and rear*/ if (q->rear == NULL) { q->front = q->rear = temp; return; } /*Add the new node at the end of queue and change rear*/ q->rear->next = temp; q->rear = temp; } /*remove first node from queue and return a pointer to it*/ qNode* deQueue(queue* q) { qNode* temp; /*If queue is empty, return NULL*/ if (q->front == NULL) return NULL; /*Store previous front and move front one node ahead*/ temp = q->front; q->front = q->front->next; /* If front becomes NULL, then change rear also as NULL*/ if (q->front == NULL) q->rear = NULL; return temp; } /*This function deletes a queue and frees memory*/ void deleteQueue(queue* q) { while (q->front) free(deQueue(q)); }
C
/* UDP echo server program -- echo-server-udp.c */ #include <stdio.h> /* standard C i/o facilities */ #include <stdlib.h> /* needed for atoi() */ #include <unistd.h> /* defines STDIN_FILENO, system calls,etc */ #include <sys/types.h> /* system data type definitions */ #include <sys/socket.h> /* socket specific definitions */ #include <netinet/in.h> /* INET constants and stuff */ #include <arpa/inet.h> /* IP address conversion stuff */ #include <netdb.h> /* gethostbyname */ #include <arpa/inet.h> /* IP address conversion stuff */ #include <ctype.h> #include <errno.h> #include <netdb.h> /* gethostbyname */ #include <netinet/in.h> /* INET constants and stuff */ #include <string.h> #include <sys/socket.h> /* socket specific definitions */ #include <sys/types.h> #include <unistd.h> void die (const char *s) { perror (s); exit (1); } int get_socket_fd (struct addrinfo** return_res, char *hostname, int port) { char portname[10]; snprintf (portname, sizeof (portname), "%d", port); // printf ("About to send to: %s:%s (%d)\n", hostname, portname, port); struct addrinfo hints; memset (&hints, 0, sizeof (hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = 0; hints.ai_flags = AI_ADDRCONFIG; struct addrinfo* res = 0; int err = getaddrinfo (hostname, portname, &hints, &res); if (err != 0) die("getaddrinfo"); int fd = socket (res->ai_family, res->ai_socktype, res->ai_protocol); if (fd == -1) die("socket"); // Return the res by setting in place *return_res = res; return fd; } /* this routine echos any messages (UDP datagrams) received */ #define MAXBUF 1024*1024 void echo( int sd ) { uint len; int n; char bufin[MAXBUF]; struct sockaddr_in remote; /* need to know how big address struct is, len must be set before the call to recvfrom!!! */ len = sizeof(remote); while (1) { /* read a datagram from the socket (put result in bufin) */ n=recvfrom(sd,bufin,MAXBUF,0,(struct sockaddr *)&remote,&len); /* print out the address of the sender */ printf("Got a datagram from %s port %d\n", inet_ntoa(remote.sin_addr), ntohs(remote.sin_port)); if (n<0) { perror("Error receiving data"); } else { printf("GOT %d BYTES (%s / %x)\n", n, bufin, bufin[0]); /* Got something, just send it back */ sendto(sd,bufin,n,0,(struct sockaddr *)&remote,len); } } } /* server main routine */ int main() { int ld; struct sockaddr_in skaddr; uint length; /* create a socket IP protocol family (PF_INET) UDP protocol (SOCK_DGRAM) */ if ((ld = socket( PF_INET, SOCK_DGRAM, 0 )) < 0) { printf("Problem creating socket\n"); exit(1); } /* establish our address address family is AF_INET our IP address is INADDR_ANY (any of our IP addresses) the port number is assigned by the kernel */ skaddr.sin_family = AF_INET; skaddr.sin_addr.s_addr = htonl(INADDR_ANY); skaddr.sin_port = htons(12346); // 0 for the kernel to choose random if (bind(ld, (struct sockaddr *) &skaddr, sizeof(skaddr))<0) { printf("Problem binding\n"); exit(0); } /* find out what port we were assigned and print it out */ length = sizeof( skaddr ); if (getsockname(ld, (struct sockaddr *) &skaddr, &length)<0) { printf("Error getsockname\n"); exit(1); } /* port number's are network byte order, we have to convert to host byte order before printing ! */ printf("The server UDP port number is %d\n",ntohs(skaddr.sin_port)); /* Go echo every datagram we get */ echo(ld); return(0); }
C
#include <stdio.h> #include <string.h> #include <netdb.h> #include <sys/socket.h> #include <unistd.h> #include<stdlib.h> #define buflen 512 unsigned int portno = 5055; char hostname[] = "192.168.30.6"; char *buf[buflen]; /* declare global to avoid stack */ void dia(char *sz) { printf("Dia %s\n", sz); } int printFromSocket(int sd, char *buf) { int len = buflen+1; int continueflag=1; while((len >= buflen)&&(continueflag)) /* quit b4 U read an empty socket */ { len = read(sd, buf, buflen); write(1,buf,len); buf[buflen-1]='\0'; /* Note bug if "Finished" ends the buffer */ continueflag=(strstr(buf, "Finished")==NULL); /* terminate if server says "Finished" */ } return(continueflag); } main() { int sd = socket(AF_INET, SOCK_STREAM, 0); /* init socket descriptor */ struct sockaddr_in sin; struct hostent *host = gethostbyname(hostname); char buf[buflen]; int len; /*** PLACE DATA IN sockaddr_in struct ***/ memcpy(&sin.sin_addr.s_addr, host->h_addr, host->h_length); sin.sin_family = AF_INET; sin.sin_port = htons(portno); /*** CONNECT SOCKET TO THE SERVICE DESCRIBED BY sockaddr_in struct ***/ if (connect(sd, (struct sockaddr *)&sin, sizeof(sin)) < 0) { perror("connecting"); exit(1); } sleep(1); /* give server time to reply */ while(1) { printf("\n\n"); if(!printFromSocket(sd, buf)) break; fgets(buf, buflen, stdin); /* remember, fgets appends the newline */ write(sd, buf, strlen(buf)); sleep(1); /* give server time to reply */ } close(sd); }
C
#ifndef CMM_H #define CMM_H // [[Rcpp::depends(RcppArmadillo)]] #include <RcppArmadillo.h> // [[Rcpp::export]] arma::mat r_cmm_internal(unsigned int n, unsigned int m, const arma::vec& p, double nu, unsigned int burn, unsigned int thin, const arma::vec& x_init, unsigned int report_period); //' @name cmm //' @export // [[Rcpp::export]] double d_cmm(const arma::vec& x, const arma::vec& p, double nu, bool take_log = false, bool normalize = true); //' @name cmm //' @export // [[Rcpp::export]] double normconst_cmm(unsigned int m, const arma::vec& p, double nu, bool take_log = false); //' Density for CMM random sample //' //' Compute individual density contributions for //' \deqn{ //' \bm{X}_i \sim \textrm{CMM}_k(m_i, \bm{p}_i, \nu_i), //' \quad i = 1, \ldots, n. //' } //' //' @param X An \eqn{n \times k} matrix of outcomes, where the \eqn{i}th row //' \eqn{\bm{x}_i^\top} represents the \eqn{i}th observation. //' @param P An \eqn{n \times k} matrix, where the \eqn{i}th row //' \eqn{\bm{p}_i^\top} represents the probability parameter for the //' \eqn{i}th observation. //' @param nu An \eqn{n}-dimensional vector of dispersion parameters //' \eqn{\nu_1, \ldots, \nu_n} //' @param take_log \code{TRUE} or \code{FALSE}; if \code{TRUE}, return the //' value on the log-scale. //' @param normalize \code{TRUE} or \code{FALSE}; if \code{FALSE}, do not //' compute or apply the normalizing constant to each density value. //' //' @return //' A vector of density values //' \eqn{ //' f(\bm{x}_1^\top \mid m_1, \bm{p}_1^\top, \nu_1), //' \ldots, //' f(\bm{x}_n^\top \mid m_n, \bm{p}_n^\top, \nu_n), //' } //' which may be on the log-scale and/or unnormalized //' according to input arguments. The value of each //' \eqn{m_i} is assumed to be \eqn{\sum_{j=1}^k x_{ij}}. //' //' @details //' The entire computation for this function is done in C++, and therefore //' may be more efficient than calling \code{d_cmm} in a loop from R. //' //' @examples //' set.seed(1234) //' //' n = 20 //' m = rep(10, n) //' k = 3 //' //' x = rnorm(n) //' X = model.matrix(~ x) //' beta = matrix(NA, 2, k-1) //' beta[1,] = -1 //' beta[2,] = 1 //' P = t(apply(X %*% beta, 1, inv_mlogit)) //' //' w = rnorm(n) //' W = model.matrix(~ x) //' gamma = c(1, -0.1) //' nu = X %*% gamma //' //' y = matrix(NA, n, k) //' for (i in 1:n) { //' y[i,] = r_cmm(1, m[i], P[i,], nu[i], burn = 200) //' } //' //' d_cmm_sample(y, P, nu, take_log = TRUE) //' //' @export // [[Rcpp::export]] arma::vec d_cmm_sample(const arma::mat& X, const arma::mat& P, const arma::vec& nu, bool take_log = false, bool normalize = true); #endif
C
#include <stdio.h> int main(void){ int numero, i; printf("Neste exercício vamos buscar o maior e o menor número em uma lista\nPara isso você escolherá quantos números digitará e depois pressionará ENTER: "); scanf("%d", &numero); int lista[numero+2]; for (i=1; i<=numero; i++){ printf("\nDigite o %dº número da lista: ",i); scanf("%d", &lista[i]); } lista[0]=0; for (i=1; i<=numero; ++i){ if (lista[0]<lista[i]){ lista[0]=lista[i]; } } lista[numero+1]=lista[0]; for (i=numero; i>=1; i--){ if (lista[numero+1]>lista[i]){ lista[numero+1]=lista[i]; } } printf("\nO maior número da lista é %d e o menor é %d", lista[0], lista[numero+1]); return 0; }
C
#include<stdio.h> #define WIDTH 200 #define HEIGHT 150 int main() { printf("%s = %d\n", "ANCHO", WIDTH); return 0; }
C
#include "hash_tables.h" /** * key_index - gives the index of a key * @key: they key * @size: size of the array of the hash table * Return: index at the key/value pair **/ unsigned long int key_index(const unsigned char *key, unsigned long int size) { unsigned long int kv_index; kv_index = hash_djb2(key); kv_index = kv_index % size; return (kv_index); }
C
//program to find and print permutation of any string //swap, permutate , swap (easy but logical program) // C program to print all permutations with duplicates allowed #include <stdio.h> #include <string.h> /* Function to swap values at two pointers */ void swap(char *x, char *y) { char temp; temp = *x; *x = *y; *y = temp; } /* Function to print permutations of string This function takes three parameters: 1. String 2. Starting index of the string denoted as l 3. Ending index of the string. denoted as r*/ void permute(char *a, int l, int r) { int i,c=0; if (l == r) printf("%s\n", a); else { for (i = l; i <= r; i++) { swap((a+l), (a+i)); permute(a, l+1, r); swap((a+l), (a+i)); //backtrack c++; printf("\nvalue is %d \n",c); //counting string ch } } } /* Driver program to test above functions */ int main() { char str[] = "Rashmi"; int n = strlen(str); permute(str, 0, n-1); return 0; }
C
//---------------------------------------------------------------------------| SEL von Dietmar SCHRAUSSER 2009 // #include <stdio.h> #include <stdlib.h> #include <string.h> #include <conio.h> #include <time.h> void _profil(); void _kopf(); void main(int argc, char *argv[]) { FILE *inStream, *outStream, *logStream; int n_=0, iLauf, jLauf; char data[20]; if (argc != 5 ){ printf("\n> check arguments\n"); _profil();} logStream = fopen( "SEL_log.txt", "a" ); fprintf(logStream, "%s @ %s\n", __DATE__, __TIME__); fclose( logStream ); _kopf(); inStream = fopen( argv[1], "r" ); do { if(fgetc(inStream)=='\n') n_++;} while (feof (inStream) == 0); fclose( inStream ); inStream = fopen( argv[1], "r" ); outStream = fopen( argv[2],"w" ); for (iLauf=1; iLauf<=n_; iLauf++) { for (jLauf=1; jLauf<= atoi(argv[3]);jLauf++) fscanf( inStream, "%s", data); fprintf( outStream, "%s\n", data); for (jLauf=atoi(argv[3]);jLauf< atoi(argv[4]);jLauf++) fscanf( inStream, "%s", data); } fclose( inStream ); fclose( outStream ); //getch(); } void _profil() { printf("--------------------------------------\n"); printf("Usage: SEL [input] [output] [a] [k]\n"); printf(" [input] ............... Eingabe Datei\n"); printf(" [output] .............. Ausgabe Datei\n"); printf(" [a] .................... Vektornummer\n"); printf(" [k] .................... Vektoranzahl\n"); printf("--------------------------------------\n"); printf("SEL by Dietmar Schrausser\n"); printf("compiled on %s @ %s\n", __DATE__, __TIME__); //getch(); exit(0); } void _kopf() { printf("\nSEL by Dietmar Schrausser\n"); printf("compiled on %s @ %s\n", __DATE__, __TIME__); printf("computing SEL:\n"); }
C
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "bitstring.h" #include "huffman.h" void compress(const char *src_filename, const char *dest_filename) { FILE *f_src = fopen(src_filename, "rb"); if (f_src == NULL) { fprintf(stderr, "failed to open %s\n", src_filename); exit(1); } long *symbol_frequencies = calloc(num_symbols, sizeof(long)); int capacity = 1 << 15; // TODO: find a good size unsigned char *buf = malloc(sizeof(unsigned char) * capacity); int nread; while ((nread = fread(buf, sizeof(unsigned char), capacity, f_src)) > 0) { for (int i = 0; i < nread; i++) { symbol_frequencies[buf[i]]++; } } tree_node *tree = build_huffman_tree(symbol_frequencies); free(symbol_frequencies); bitstring **codes = get_codes_from_tree(tree); tree_delete(tree); // TODO: don't overwrite an existing file -- (avoid race condition when fix) FILE *f_dest = fopen(dest_filename, "wb"); if (f_dest == NULL) { fprintf(stderr, "failed to open %s for writing\n", dest_filename); fclose(f_src); delete_codes(codes); exit(1); } // write the symbols' codes bitstring *empty_bitstring = bitstring_new_empty(); for (int i = 0; i < num_symbols; i++) { const bitstring *code = (codes[i] == NULL) ? empty_bitstring : codes[i]; bool success = bitstring_write(code, f_dest); if (!success) { fprintf(stderr, "error saving codes\n"); fclose(f_src); delete_codes(codes); fclose(f_dest); bitstring_delete(empty_bitstring); exit(1); } } bitstring_delete(empty_bitstring); rewind(f_src); while ((nread = fread(buf, sizeof(unsigned char), capacity, f_src)) > 0) { bitstring *encoded = encode(buf, nread, (const bitstring **)codes); bool success = bitstring_write(encoded, f_dest); bitstring_delete(encoded); if (!success) { fprintf(stderr, "error saving content\n"); fclose(f_src); delete_codes(codes); fclose(f_dest); free(buf); exit(1); } } fclose(f_src); delete_codes(codes); fclose(f_dest); free(buf); } void decompress(const char *src_filename, const char *dest_filename) { FILE *f_src = fopen(src_filename, "rb"); if (f_src == NULL) { fprintf(stderr, "failed to open %s\n", src_filename); exit(1); } bitstring **codes = malloc(sizeof(bitstring *) * num_symbols); for (int i = 0; i < num_symbols; i++) { bitstring *code = bitstring_read(f_src); if (code == NULL) { fprintf(stderr, "error reading codes from %s\n", src_filename); fclose(f_src); delete_codes(codes); exit(1); }else if (bitstring_bitlength(code) == 0) { // a zero bitstring is saved to indicate this symbol has no code codes[i] = NULL; bitstring_delete(code); }else { codes[i] = code; } } tree_node *tree = get_tree_from_codes((const bitstring **)codes); delete_codes(codes); FILE *f_dest = fopen(dest_filename, "wb"); bitstring *encoded; while ((encoded = bitstring_read(f_src)) != NULL) { int decoded_length; unsigned char *decoded = decode(encoded, tree, &decoded_length); bitstring_delete(encoded); if (fwrite(decoded, sizeof(unsigned char), decoded_length, f_dest) != decoded_length) { fprintf(stderr, "error writing to file\n"); fclose(f_src); fclose(f_dest); tree_delete(tree); free(decoded); exit(1); } free(decoded); } fclose(f_src); fclose(f_dest); tree_delete(tree); } int main(int argc, char const *argv[]) { bool mode_compress = true; int i = 1; if (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--compress") == 0) { mode_compress = true; i++; }else if (strcmp(argv[i], "-d") == 0 || strcmp(argv[i], "--decompress") == 0) { mode_compress = false; i++; } const char *src_filename = argv[i++]; const char *dest_filename = argv[i++]; if (mode_compress) { compress(src_filename, dest_filename); }else { decompress(src_filename, dest_filename); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* libui_pixel_draw.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tfernand <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/08/22 16:30:15 by tfernand #+# #+# */ /* Updated: 2019/08/22 16:30:16 by tfernand ### ########.fr */ /* */ /* ************************************************************************** */ #include <libui_pixel.h> /* ** expect a 32bit surface created by this library, will use the alpha part of ** the color to do a blendig with the current surface color */ int libui_pixel_draw(SDL_Surface *surface, int x, int y, Uint32 color) { t_libui_pixel_color c1; t_libui_pixel_color c2; Uint32 *ptr; double m; c1.u32 = color; if (c1.c.a == 0) return (0); ptr = &((Uint32*)surface->pixels)[x + y * surface->w]; if (c1.c.a != 255) { m = 255. / (double)c1.c.a; c2.u32 = *ptr; c1.c.a = 255; c1.c.r = (Uint8)(c1.c.r * m + c2.c.r * (1. - m)); c1.c.g = (Uint8)(c1.c.g * m + c2.c.g * (1. - m)); c1.c.b = (Uint8)(c1.c.b * m + c2.c.b * (1. - m)); } *ptr = c1.u32; return (0); } int libui_pixel_draw_atomic(SDL_Surface *surface, int x, int y, Uint32 color) { t_libui_pixel_color c1; t_libui_pixel_color c2; Uint32 *ptr; double m; c1.u32 = color; if (c1.c.a == 0) return (0); SDL_LockSurface(surface); ptr = &((Uint32*)surface->pixels)[x + y * surface->w]; if (c1.c.a != 255) { m = 255. / (double)c1.c.a; c2.u32 = *ptr; c1.c.a = 255; c1.c.r = (Uint8)(c1.c.r * m + c2.c.r * (1. - m)); c1.c.g = (Uint8)(c1.c.g * m + c2.c.g * (1. - m)); c1.c.b = (Uint8)(c1.c.b * m + c2.c.b * (1. - m)); } *ptr = c1.u32; SDL_UnlockSurface(surface); return (0); }
C
/* Program 2 : Write a Program to print cube of first n numbers . */ extern int printf (const char *, ...); extern int scanf (const char *, ...); void main (void) { int x; printf ("\nEnter a Number :"); scanf ("%d", &x); printf ("\nCube of First %d numbers are : \n", x); for (int i = 1; i < x + 1; i++) { printf("\nCube of %2d : %4d", i, i * i * i); } }
C
#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int dias, segundos; printf("digite os dias:"); scanf("%d",&dias); segundos= dias*24*60*60; printf("dias em segundos e %d", segundos ); return 0; }
C
#include <stdio.h> int main() { int a, b, q, k = 1; scanf("%d %d", &a, &b); int bear[a][b]; for (int i = 0; i < a; i++) { q = k; for (int j = 0; j < b; j++) { bear[i][j] = q; printf("%3d ", bear[i][j]); q = q + a; } k++; printf("\n"); } } }
C
/* * Struct to define a single layer in a NN */ #ifndef LAYER_H #define LAYER_H #include <stdlib.h> #include <stdio.h> #include <math.h> typedef struct Layer { double bias; // bias of the current layer double** weights; // 2D array of random weights int n_neurons; // number of output neurons } Layer; /* Definition of the functions * More details of each function can be found in the layer.c */ Layer new_layer(int r, int size_out); //creates a new layer double** generate_rnd_weights(int r, int size_out); //creates random weights for the layer double activation(double x); // sigmoid as activation function void free_layer(Layer layer); // deallocate a layer's memory #endif
C
#ifndef COPY_H #define COPY_H #include <unistd.h> #include <string.h> #include <sys/mman.h> #include <fcntl.h> #include <syslog.h> #include "conf.h" /** \brief odpowiada za kopiowanie plików z katalogu źródłowego do docelowego \details otwierany jest katalog źródłowy, następnie za pomocą struktury 'dirent' czytany jest każdy plik z katalogu oprócz . i .., tworzona jest pełna ścieżka docelowa i źródłowa. Jeśli plik istnieje w folderze docelowym i posiada on inne czasy modyfikacji niż plik źródłowy to flaga 'copy' jest ustawiana na 1. Jeżeli pliku nie ma w folderze docelowym to ustawiania jest na 1 flaga 'copy' oraz 'create'. Następnie w zależności od tego czy plik jest katalogiem czy zwykłym plikiem i na podstawie flag jest on najpierw tworzony i kopiowany lub tylko kopiowany. */ void work(char*, char*, off_t, int); /** \brief decyduje, którą opcję kopiowania wybrać \details jeśli rozmiar pliku źródłowego jest większy niż max_size to wywływane jest kopiowanie za pomocą mapowania */ void make_copy(char*, char*, off_t); /** \brief kopiowanie zwyczajne za pomocą open() i read() */ void copy_normal(char*, char*); /** \brief kopiowanie za pomocą mapowaniaw w pamięci \details oba ppliki otwierane są za pomocą deskryptorów, a następnie za pomocą funkcji mmap zwracane jest rzeczywiste zamapowanie obiektów, funkcja trunacte plik docelowy skraca to długości pliku, źródłowego a funkcja memcpy kopiuje oba miejsca, a konkretniej size bajtów. Następnie munmap usuwa mapowanie pliów z pamięci oraz zamykamy deskryptory. */ void copy_mmap(char*, char*); #endif
C
#include <stdio.h> #include <string.h> #include <unistd.h> char *my_revstr( char * str ) { char *dest=str; char* p = str + strlen(str)-1; char temp; while(str<p) { temp=*p; *p--=*str; *str++=temp; } str=dest; return str; } void my_putchar(char *s) { write(1, s, strlen(s)); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_fraction.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbecker <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/23 21:14:38 by sbecker #+# #+# */ /* Updated: 2019/04/09 16:18:41 by sschmele ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" /* **We get the long double float (after the point) part in binary */ char *bit_fraction_l(long *exponent_l, t_int128 bl, int *len) { register int i; register int j; t_int128 one; char *b_fraction; one = 1; *len = (*exponent_l == -16383) ? 64 + 16382 : 64 - *exponent_l; b_fraction = ft_strnewsetchar(*len, '0'); if (*exponent_l < 0) { if (!(bl << 16 != 0 && *exponent_l == -16383)) b_fraction[*len - 65] = '1'; i = 64; while (--i >= 0) b_fraction[*len - 1 - i] = ((one << i) & bl) ? '1' : '0'; } else { j = -1; i = *len - 1; while (--i >= 0) b_fraction[++j] = ((one << i) & bl) ? '1' : '0'; } *exponent_l = (*exponent_l == -16383) ? -16382 : *exponent_l; return (b_fraction); } /* **We get the float or double float (after the point) part in binary */ char *bit_fraction(long *exponent, long b, int *len) { register int i; register int j; char *b_fraction; *len = (*exponent == -1023) ? 53 + 1022 : 53 - *exponent; b_fraction = ft_memalloc(*len); if (*exponent < 0) { ft_memset((void*)b_fraction, '0', *len - 1); if (!(b << 12 != 0 && *exponent == -1023)) b_fraction[*len - 54] = '1'; i = 52; while (--i >= 0) b_fraction[*len - 2 - i] = ((1l << i) & b) ? '1' : '0'; } else { j = -1; i = *len - 1; while (--i >= 0) b_fraction[++j] = ((1l << i) & b) ? '1' : '0'; } *exponent = (*exponent == -1023) ? -1022 : *exponent; return (b_fraction); } void countup_fraction(t_fcomp *fcomp, int *num, char bit, int *count) { *count = -1; if (bit == '1') while (++*count < fcomp->len_fraction) { fcomp->fraction[*count] += num[*count]; fcomp->fraction[*count + 1] += fcomp->fraction[*count] / 10; fcomp->fraction[*count] %= 10; } *count = -1; } /* **In order to get a number using long ariphmetics we multipy each 1 in binary **by 1/(2 raised to some power) = 1/2, 1/4, 1/8 etc. Here we get it. */ void get_negative_power(t_fcomp *fcomp, int *num, int i) { int count; count = fcomp->len_fraction - i - 3; while (++count < fcomp->len_fraction - 1) num[count] = num[count + 1]; num[fcomp->len_fraction - 1] = 0; count = fcomp->len_fraction - i - 3; while (++count < fcomp->len_fraction) num[count] *= 5; count = fcomp->len_fraction - i - 3; while (++count < fcomp->len_fraction) { num[count + 1] += num[count] / 10; num[count] %= 10; } } /* **Here we get decimal float from the binary float with the help of long **ariphmetics. All the numbers are saved in reverse order - **from right to left. */ void get_fraction(char *b_fraction, t_fcomp *fcomp) { register int i; int count; int *num; fcomp->fraction = (int*)ft_memalloc((fcomp->len_fraction + 1) * 4); num = (int*)ft_memalloc((fcomp->len_fraction + 1) * 4); num[fcomp->len_fraction - 1] = 5; i = -1; while (b_fraction[++i]) { countup_fraction(fcomp, num, b_fraction[i], &count); get_negative_power(fcomp, num, i); } free(num); }
C
#include <stdlib.h> #include <unistd.h> #include <string.h> #include <stdio.h> char * convert(char * s, int numRows){ char **stock = malloc(sizeof(char*)*numRows); char *ret = malloc(sizeof(char)*strlen(s)); for(int i= 0; i < numRows; i++) { char* tmp = malloc(sizeof(char)*strlen(s)); memset(tmp, 0, strlen(s)); stock[i] = (char*)tmp; } int row = 0; int direction = 1; for(int i = 0; i < strlen(s); i++) { int pos = strlen(stock[row]); stock[row][pos] = s[i]; if(row == 0) direction = 1; else if(row == (numRows - 1)) direction = -1; row += direction; } int pos = 0; for(int i = 0; i < numRows; i++) { for(int j = 0; j < strlen(stock[i]); j++) { ret[pos] = stock[i][j]; pos++; } free(stock[i]); } free(stock); return ret; } int main() { char* ret = convert("PAYPALISHIRING", 3); printf("%s\r\n", ret); free(ret); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> typedef struct StructTree{ int Key; struct StructTree *Left; struct StructTree *Right; struct StructTree *Back; } TypeTree; int StringCmp(int *TempInt1,int *TempInt2,char filename[]); void FreeTree(TypeTree *Tree); TypeTree *AddTree(TypeTree *Tree,int Elem); TypeTree* TreeSearch(TypeTree* Tree,int SearchNum,int TypeSearch,int flag); void PrintTree(TypeTree *Tree,int level); void SaveFile(TypeTree *Tree,FILE **openFile); void LoadFile(TypeTree **Tree,FILE **openFile); void Analysis(TypeTree *Tree,int flag); int CommandCheck(int TempNum1,int TempNum2,int TempNum3,int TempNum4,int *TempInt1,int *TempInt2); void BackPtr(TypeTree *Tree,TypeTree *ptr); int StringCmp(int *TempInt1,int *TempInt2,char filename[]){ char Command[255]; scanf("%s",Command); if (strcmp(Command,"show")==0) return 10; if (strcmp(Command,"exit")==0) return 14; if (strcmp(Command,"save")==0){ scanf("%s",filename); return 11; } if (strcmp(Command,"load")==0){ scanf("%s",filename); return 12; } if (strcmp(Command,"add")==0) return CommandCheck(1,2,3,4,TempInt1,TempInt2); if (strcmp(Command,"renew")==0) return CommandCheck(5,6,7,8,TempInt1,TempInt2); if (strcmp(Command,"del")==0){ scanf("%s",Command); if (strcmp(Command,"tree")==0) return 9; } return -1; } int CommandCheck(int TempNum1,int TempNum2,int TempNum3,int TempNum4,int *TempInt1,int *TempInt2){ char Command[255]; scanf("%s",Command); if (strcmp(Command,"root")==0){ scanf("%d",TempInt1); return TempNum1; } if (strcmp(Command,"node")==0){ scanf("%d",TempInt1); scanf("%s",Command); if (strcmp(Command,"left")==0){ scanf("%s",Command); if (strcmp(Command,"parent")==0){ scanf("%d",TempInt2); return TempNum2; } } if (strcmp(Command,"right")==0){ scanf("%s",Command); if (strcmp(Command,"parent")==0){ scanf("%d",TempInt2); return TempNum3; } } if (strcmp(Command,"sibling")==0){ scanf("%d",TempInt2); return TempNum4; } } return -1; } TypeTree *AddTree(TypeTree *Tree,int Elem){ if (Tree==NULL){ Tree=(TypeTree*)malloc(sizeof(TypeTree)); Tree->Key=Elem; Tree->Left=NULL; Tree->Right=NULL; } return Tree; } void FreeTree(TypeTree *Tree){ if (Tree!=NULL){ FreeTree(Tree->Left); FreeTree(Tree->Right); free(Tree); } } TypeTree* TreeSearch(TypeTree* Tree,int SearchNum,int TypeSearch,int flag){ static TypeTree *SearchTree; TypeTree *TempTree; if (flag==1) SearchTree=NULL; if (Tree!=NULL){ if (Tree->Key==SearchNum){ if ((TypeSearch==1)&&(Tree->Left==NULL)) SearchTree=Tree; if ((TypeSearch==2)&&(Tree->Right==NULL)) SearchTree=Tree; if ((TypeSearch==3)&&((Tree->Back!=NULL))) if ((Tree->Back->Left==NULL)||(Tree->Back->Right==NULL)) SearchTree=Tree; if ((TypeSearch==4)&&(Tree->Left!=NULL)) SearchTree=Tree; if ((TypeSearch==5)&&(Tree->Right!=NULL)) SearchTree=Tree; if ((TypeSearch==6)&&(Tree->Back!=NULL)){ if ((Tree->Back->Left==Tree)&&(Tree->Back->Right!=NULL)) SearchTree=Tree->Back->Right; if ((Tree->Back->Right==Tree)&&(Tree->Back->Left!=NULL)) SearchTree=Tree->Back->Left; } } TempTree=TreeSearch(Tree->Left,SearchNum,TypeSearch,0); TempTree=TreeSearch(Tree->Right,SearchNum,TypeSearch,0); } if (flag==1) return SearchTree; return Tree; } void PrintTree(TypeTree *Tree,int level){ int i; if(Tree!=NULL){ PrintTree(Tree->Right,level+1); for (i=0;i<level;i++) printf(" "); printf("%d\n",Tree->Key); PrintTree(Tree->Left,level+1); } } void SaveFile(TypeTree *Tree,FILE **openFile){ if (Tree!=NULL){ fwrite(Tree,sizeof(TypeTree),1,*openFile); if (Tree->Left!=NULL) SaveFile(Tree->Left,openFile); if (Tree->Right!=NULL) SaveFile(Tree->Right,openFile); } } void LoadFile(TypeTree **Tree,FILE **openFile){ if (!feof(*openFile)){ (*Tree)=(TypeTree*)malloc(sizeof(TypeTree)); fread(*Tree,sizeof(TypeTree),1,*openFile); if ((*Tree)->Left!=NULL) LoadFile(&((*Tree)->Left),openFile); if ((*Tree)->Right!=NULL) LoadFile(&((*Tree)->Right),openFile); } } void BackPtr(TypeTree *Tree,TypeTree *ptr){ if (Tree!=NULL){ Tree->Back=ptr; BackPtr(Tree->Left,Tree); BackPtr(Tree->Right,Tree); } } int main(void){ TypeTree *Tree=0,*TempTree; FILE *openFile; int True=1,SwitchNum,TempNum1=0,TempNum2=0; char filename[255]; while(True){ system("CLS"); printf("Enter com: "); SwitchNum=StringCmp(&TempNum1,&TempNum2,filename); fflush(stdin); switch (SwitchNum){ case 1: if (Tree==NULL){ Tree=AddTree(Tree,TempNum1); Tree->Back=NULL; } else printf("Root is creat\n"); break; case 2: TempTree=TreeSearch(Tree,TempNum2,1,1); if (TempTree==NULL){ printf("Full house\n"); break; } TempTree->Left=AddTree(TempTree->Left,TempNum1); TempTree->Left->Back=TempTree; break; case 3: TempTree=TreeSearch(Tree,TempNum2,2,1); if (TempTree==NULL){ printf("Full house\n"); break; } TempTree->Right=AddTree(TempTree->Right,TempNum1); TempTree->Right->Back=TempTree; break; case 4: TempTree=TreeSearch(Tree,TempNum2,3,1); if (TempTree==NULL){ printf("Free sibling is not found\n"); break; } if (TempTree->Back->Left==NULL){ TempTree->Back->Left=AddTree(TempTree->Back->Left,TempNum1); TempTree->Back->Left->Back=TempTree->Back; } if (TempTree->Back->Right==NULL){ TempTree->Back->Right=AddTree(TempTree->Back->Right,TempNum1); TempTree->Back->Right->Back=TempTree->Back; } break; case 5: if (Tree==NULL){ printf("Root is not made\n"); break; } Tree->Key=TempNum1; break; case 6: TempTree=TreeSearch(Tree,TempNum2,4,1); if (TempTree==NULL){ printf("Not found\n"); break; } TempTree->Left->Key=TempNum1; break; case 7: TempTree=TreeSearch(Tree,TempNum2,5,1); if (TempTree==NULL){ printf("Not found\n"); break; } TempTree->Right->Key=TempNum1; break; case 8: TempTree=TreeSearch(Tree,TempNum2,6,1); if (TempTree==NULL){ printf("Not found\n"); break; } TempTree->Key=TempNum1; break; case 9: if (Tree==NULL){ printf("Tree is empty\n"); break; } FreeTree(Tree); Tree=NULL; break; case 10: PrintTree(Tree,0); break; case 11: openFile=fopen(filename,"w"); SaveFile(Tree,&openFile); fclose(openFile); break; break; case 12: FreeTree(Tree); openFile=fopen(filename,"r"); if (openFile!=NULL){ LoadFile(&Tree,&openFile); fclose(openFile); BackPtr(Tree,NULL); }else printf("Error\n"); break; case 14: FreeTree(Tree); return 0; break; default: printf("Error\n"); } } }
C
#include<stdlib.h> #include<stdio.h> #include<math.h> #include "Point.h" #define POW(a) (a)*(a) static void Point_Init(Point*); static float get_abscisse(Point *This); static int set_abscisse(Point *This,float abscisse); static float get_ordonne(Point *This); static int set_ordonne(Point *This,float ordonne); static float norme(Point *This); /******************************************************************************/ Point* New_Point(float abscisse,float ordonne) { Point *This = malloc(sizeof(Point)); if(!This) return NULL; Point_Init(This); This->set_abscisse(This,abscisse); This->set_ordonne(This,ordonne); return This; } /******************************************************************************/ static void Point_Init(Point *This) { This->get_abscisse = get_abscisse; This->set_abscisse = set_abscisse; This->get_ordonne = get_ordonne; This->set_ordonne = set_ordonne; This->norme = norme; This->abscisse = 0; This->ordonne = 0; } /******************************************************************************/ static float get_abscisse(Point *This) { return This->abscisse; } /******************************************************************************/ static int set_abscisse(Point *This,float abscisse) { This->abscisse = abscisse; return 1; } /******************************************************************************/ static float get_ordonne(Point *This) { return This->ordonne; } /******************************************************************************/ static int set_ordonne(Point *This,float ordonne) { This->ordonne = ordonne; return 1; } /******************************************************************************/ static float norme(Point *This) { return sqrt( POW((double)This->get_abscisse(This)) + POW((double)This->get_ordonne(This)) ); }
C
#include <sys/types.h> /* some systems still require this */ #include <sys/stat.h> #include <stdio.h> /* for convenience */ #include <stdlib.h> /* for convenience */ #include <stddef.h> /* for offsetof */ #include <string.h> /* for convenience */ #include <unistd.h> #include <error.h> /* for convenience */ #include <signal.h> /* for SIG_ERR */ #include <netdb.h> #include <errno.h> #include <syslog.h> #include <sys/socket.h> #include <fcntl.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/resource.h> #include <sys/types.h> #include <sys/wait.h> #include "logdb.h" int connect_retry( int domain, int type, int protocol, const struct sockaddr *addr, socklen_t alen){ int numsec, fd; for (numsec = 1; numsec <= 64; numsec <<= 1) { if (( fd = socket( domain, type, protocol)) < 0){ return(-1); }if (connect( fd, addr, alen) == 0) { printf("conexion aceptada\n"); return(fd); } close(fd); if (numsec <= 64/2) sleep( numsec); } return(-1); } conexionlogdb *conectar_db(char *ip, int puerto){ int sockfd=0; struct sockaddr_in direccion_cliente; memset(&direccion_cliente, 0, sizeof(direccion_cliente)); conexionlogdb *conexion; conexion=(conexionlogdb *)malloc(sizeof(conexion)); direccion_cliente.sin_family = AF_INET; direccion_cliente.sin_port = htons(puerto); direccion_cliente.sin_addr.s_addr = inet_addr(ip) ; if (( sockfd = connect_retry( direccion_cliente.sin_family, SOCK_STREAM, 0, (struct sockaddr *)&direccion_cliente, sizeof(direccion_cliente))) < 0) { printf("falló conexión\n"); exit(-1); } conexion->ip=ip; conexion->puerto=puerto; conexion->sockdf=sockfd; conexion->id_sesion=rand()%1000; return conexion; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* read_cor.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ysibous <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/05/20 16:54:54 by ysibous #+# #+# */ /* Updated: 2018/05/20 16:59:53 by ysibous ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/vm.h" /* ** Safely open the file. */ int open_file(char *file_name) { int fd; if ((fd = open(file_name, O_RDONLY)) == -1) { ft_putstr_fd("File Error!", 2); exit(0); } return (fd); } /* ** Open the file and check whether the extension is a .cor */ int handle_file(char *file_name, t_vm *vm) { int fd; fd = open_file(file_name); if (get_next_player(vm)) return (1); if (handle_cor_file(file_name)) return (1); if (read_file_header(fd, &(vm->champs[vm->curr_champ].header))) return (1); if (read_file_program(fd, &(vm->champs[vm->curr_champ]))) return (1); return (-1); } /* ** Check if extension is .cor */ int handle_cor_file(char *file_name) { int len; len = ft_strlen(file_name); while (*file_name && *(file_name + len) != '.') len--; return (!ft_strequ((file_name + len), ".cor")); } /* ** Read the file header. ** 1) 4 bytes for the .cor magic number ** 2) PROG_NAME_LENGTH bytes for the program name ** 3) 4 bytes for 0 buffer ** 4) 4 bytes for program size ** 5) COMMENT_LENGTH bytes for the comment ** 6) 4 bytes for 0 buffer */ int read_file_header(int fd, t_header *header) { unsigned char buff[4]; if (!(read(fd, buff, 4) == 4 && ft_memcmp(buff, COREWAR_EXEC_MAGIC, 4) == 0)) return (ft_puterror(-1, "Invalid Magic Number.")); read(fd, header->prog_name, PROG_NAME_LENGTH); header->prog_name[PROG_NAME_LENGTH] = '\0'; if (!(read(fd, buff, 4) == 4 && ft_memcmp(buff, "\0\0\0\0", 4) == 0)) return (ft_puterror(-1, "Incorrect buffer")); if (!(read(fd, buff, 4) == 4)) return (ft_puterror(-1, "Incorrect program size.")); header->prog_size = (unsigned int)buff; if (!(read(fd, header->comment, COMMENT_LENGTH))) return (ft_puterror(-1, "Invalid comment.")); header->comment[COMMENT_LENGTH] = '\0'; if (!(read(fd, buff, 4) == 4 && ft_memcmp(buff, "\0\0\0\0", 4) == 0)) return (ft_puterror(-1, "Invalid buffer between comment and program.")); return (1); } /* ** Read the next prog_size bytes */ int read_file_program(int fd, t_champ *champ) { champ->prog = ft_memalloc(sizeof(unsigned char *) * champ->header.prog_size); if (read(fd, champ->prog, champ->header.prog_size) != champ->header.prog_size) return (ft_puterror(-1, "Invalid program.")); return (1); }
C
//DATAPOINTS //Calcula quadrado e raz quadrada de nmeros introduzidos pelo utilizador em estruturas de dados //BIBLIOTECAS #include <stdio.h> #include <math.h> #include <windows.h> //ESTRUTURAS DE DADOS typedef struct DPs { int num; int quadrado; float raiz; }DP; //PROTTIPOS int menu(void); int inserir(DP *r); void listar(DP *r,int count); void remover(DP *r,int *count,int flag); void ordenar(DP *r,int count); void main() //manipula opes do menu { DP vet[20]; int count=0,i,x,op=0,resp=0,flag=0; do { op=menu(); switch(op) { case 1: { resp=inserir(&vet[count]); count++; break; } case 2: { listar(vet,count); break; } case 3: { remover(vet,&count,flag); break; } case 4: { ordenar(vet,count); break; } } }while(op!=0); } int menu() //l opo do menu e retorna-a { system("cls"); int op; printf("\n\t** DataPoints\n\n"); printf("1. Inserir\n"); printf("2. Listar\n"); printf("3. Remover\n"); printf("4. Ordenar\n"); printf("0. Sair\n\n"); printf("Selecione uma opcao: "); scanf("%d",&op); return op; } int inserir(DP *r) //l valores e calcula os respetivos quadrados e razes { system("cls"); printf("\n\nIntroduza um numero: "); scanf("%d",&(*r).num); (*r).quadrado = (*r).num * (*r).num; (*r).raiz = sqrt((*r).num); } void listar(DP *r,int count) //recebe um vetor de DPs e mostra-o { system("cls"); int i; printf("\nIndice\tNum\tQuadrado\tRaiz\n"); for(i=0;i<count;i++) printf("%d\t%d\t%d\t\t%.2f\n",i,r[i].num,r[i].quadrado,r[i].raiz); getch(); } void remover(DP *r,int *count,int flag) //recebe o vetor de DPs, l nmero a remover do vetor e remove-o { int num; int i,j; listar(r,(*count)); printf("\nNumero a remover: "); scanf("%d",&num); for(i=0;i<count;i++) { if(r[i].num == num) { printf("\nEncontrado na %da posicao.",i+1); flag=1; for(j=i;j<count-1;j++) { r[i].num = r[i+1].num; r[i].quadrado = r[i+1].quadrado; r[i].raiz = r[i+1].raiz; } (*count)--; } else printf("\nNao foi encontrado."); if(flag==1) break; } listar(r,(*count)); getch(); } void ordenar(DP *r,int count) //recebe o vetor de DPs e ordena-o crescentemente pelo nmero { int i,j; int tempNum,tempQuad; float tempRaiz; for(i=0;i<count-1;i++) { for(j=0;j<count-i-1;j++) { if(r[j].num > r[j+1].num) { tempNum = r[j].num; r[j].num = r[j+1].num; r[j+1].num = tempNum; tempQuad = r[j].quadrado; r[j].quadrado = r[j+1].quadrado; r[j+1].quadrado = tempQuad; tempRaiz = r[j].raiz; r[j].raiz = r[j+1].raiz; r[j+1].raiz = tempRaiz; } } } listar(r,count); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* check_error_utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: vveyrat- <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/03/10 11:42:26 by vveyrat- #+# #+# */ /* Updated: 2020/03/10 11:42:28 by vveyrat- ### ########lyon.fr */ /* */ /* ************************************************************************** */ #include "lemin.h" #include "check_error.h" #include "misc.h" int free_temp_line(char *temp, char *line, int ret) { ft_memdel((void**)&temp); ft_memdel((void**)&line); return (ret); } /* ** count_space: ** ** Return count of space in a string */ int count_space(char *line) { int index; int count; index = 0; count = 0; while (line[index]) { if (line[index] == ' ') count++; index++; } return (count); } /* ** check_room: ** ** Check if a room definition is valid */ int check_room(char *line, int tube_pars) { int count; char **split; count = 0; if (count_space(line) != 2 && ft_count_words(line, ' ') != 3 && tube_pars == 0) return (-1); if (!(split = ft_strsplit(line, ' '))) return (-1); while (split[count]) count++; if (count != 3) return (-1); if (ft_is_strdigit(split[1]) != 1 || ft_is_strdigit(split[2]) != 1) return (-1); ft_free(split); return (1); } /* ** check_definition: ** ** run check_room and check_tubes */ int check_definition(t_read_room *pars, t_check_bad_order *order, int index) { if (nmatch(pars->room[index], "* * *") == 1) { if (check_room(pars->room[index], order->tube_pars) == -1) return (-1); pars->nb_room++; } else if (nmatch(pars->room[index], "*-*") == 1 && check_tubes(pars->room[index]) == -1) return (-1); return (0); } /* ** check_tubes: ** ** Check if a tube definition is valid */ int check_tubes(char *line) { int index; index = 0; while (line[index] && line[index] != '-') { if (ft_isspace(line[index])) return (-1); index++; } if (line[index] != '-') return (-1); index++; while (line[index]) { if (ft_isspace(line[index])) return (-1); index++; } return (1); }
C
/** \brief This is a standalone test program for testing the hybrid ARQ concept \author Thomas Watteyne <[email protected]>, September 2010 */ //board #include "gina.h" //drivers #include "leds.h" #include "button.h" //openwsn #include "opendefs.h" #include "scheduler.h" #include "packetfunctions.h" #include "openqueue.h" #include "radio.h" OpenQueueEntry_t* testRadioPacketToSend; int main(void) { //configuring P1OUT |= 0x04; // set P1.2 for debug gina_init(); scheduler_init(); button_init(); openwsn_init(); openqueue_init(); P1OUT &= ~0x04; // clear P1.2 for debug radio_init(); radio_rxOn(DEFAULTCHANNEL); scheduler_start(); } void isr_button(void) { //prepare packet testRadioPacketToSend = openqueue_getFreePacketBuffer(); //l1 testRadioPacketToSend->l1_channel = DEFAULTCHANNEL; //payload packetfunctions_reserveHeaderSize(testRadioPacketToSend,5); testRadioPacketToSend->payload[0] = 0x01; testRadioPacketToSend->payload[1] = 0x02; testRadioPacketToSend->payload[2] = 0x03; testRadioPacketToSend->payload[3] = 0x04; testRadioPacketToSend->payload[4] = 0x05; packetfunctions_reserveFooterSize(testRadioPacketToSend,2); //space for radio to fill in CRC //send packet radio_send(testRadioPacketToSend); //debug P1OUT ^= 0x02; // toggle P1.1 (for debug) leds_circular_shift(); // circular-shift LEDs (for debug) } void stupidmac_sendDone(OpenQueueEntry_t* pkt, error_t error) { openqueue_freePacketBuffer(pkt); } void radio_packet_received(OpenQueueEntry_t* packetReceived) { openqueue_freePacketBuffer(packetReceived); P1OUT ^= 0x02; // toggle P1.1 for debug leds_increment(); // increment LEDs for debug }
C
/* * Header file for a generic fixed capacity queue implemented with an array * */ #ifndef _ARRAY_QUEUE_H_ #define _ARRAY_QUEUE_H_ typedef void (*FreeFunction)(void*); /** * ptr_array: circular array of pointers to the struct's contents * elem_size: the size of the elements in the queue * length: the current number of elements in the queue * capacity: the maximum number of elements the queue holds * head: pointer to the next element to be dequeued * tail: pointer to next element to be enqueued * head==tail indicates an empty queue * free_func function to free complex data in the queue * NULL indicates no free_function is supplied */ typedef struct { void* ptr_array; size_t elem_size; int capacity; int length; void* head; void* tail; FreeFunction free_func; } ArrayQueue; /** * Initializes an empty queue. */ void aqueue_init(ArrayQueue* queue, int capacity, size_t elem_size, FreeFunction free_func); /** * Deallocates the queue and all currently enqueued elements, along with their data, using * the caller supplied free function if one exists. Data stored on the heap which was previosly * enqueued is up to the caller to free. */ void aqueue_destroy(ArrayQueue* queue); /** * Enqueues an element on the end of the queue. * Return: * 0: enqueued * 1: Not enough space on the queue * 2: general error */ void aqueue_enqueue(ArrayQueue* queue, void* data); /** * Dequeues first element from the queue * Return: * NULL: No elements left to dequeue * void*: pointer to the element to be dequeued */ void* aqueue_dequeue(ArrayQueue* queue); /** * Shows the element of the queue which will be dequeued next without removing it * Return: * NULL: No elements left to dequeue * void*: pointer to the element to be dequeued */ void* aqueue_peek(ArrayQueue* queue); #endif /* _ARRAY_QUEUE_H_ */
C
// ------------------------------------------------------------------ // exemple-serie.c // Fichier d'exemple du livre "Developpement Systeme sous Linux" // (C) 2000-2019 - Christophe BLAESS <[email protected]> // https://www.blaess.fr/christophe/ // ------------------------------------------------------------------ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main (int argc, char * argv[]) { int fd; char string[2]; if (argc != 2) { fprintf (stderr, "%s <fichier special>\n", argv[0]); exit(EXIT_FAILURE); } fprintf(stdout, "Nous allons verifier la tension entre les broches :\n" " 7 (-) et 20 (+) pour un connecteur DB-25 \n" " 5 (-) et 4 (+) pour un connecteur DB-9 \n \n "); fprintf(stdout, "La tension doit etre inferieure a -3 V \n"); fprintf(stdout, "Pressez Entree pour continuer\n"); fgets(string, 2, stdin); fd = open(argv[1], O_RDONLY | O_NONBLOCK); if (fd < 0) { perror("open"); exit(EXIT_FAILURE); } fprintf(stdout, "La tension doit etre superieure a +3 V\n"); fprintf(stdout, "Pressez Entree pour continuer\n"); fgets(string, 2, stdin); fprintf(stdout, "La tension doit etre a nouveau < -3 V\n"); if (close(fd) < 0) { perror ("close"); exit(EXIT_FAILURE); } return EXIT_SUCCESS; }
C
/* ______ _________ _ _ _ | ____ \|___ ___| | | | | | | | \ \ | | | |____| | | | | | | | | | | ____ | | | | |____/ /___| |___| | | |_____| | |_______/|_________|_| |_________| M A H I R L A B I B D I H A N */ int main() { // for(;condition;) // { // } // for(;;) // If the condition is not provided it is assumed to be true . // And its a infinity loop // { // } int i,j; for(i=0;i<10;i++) { } // Upper loop can also be written as i=0; for(;;) { if(i<10) break; i++; } for(i=0,j=5;i<j;i++,j--) // use of comma operator { } }
C
#include "holberton.h" /** * rot13 - encodes a string using rot13 * @s: string being encoded * * Return: returns a string encoded in rot13 */ char *rot13(char *s) { int x, y; char *reg = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; char *rot = "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM"; for (x = 0; *(s + x) != '\0'; x++) { for (y = 0; *(reg + y) != '\0'; y++) { if (*(s + x) == *(reg + y)) { *(s + x) = *(rot + y); break; } } } return (s); }
C
#include "ft_ls.h" char *ft_get_right(size_t n) { char *s; if(!(s = ft_strnew(10))) exit (0); s[0] = (S_IRUSR & n) ? 'r' : '-'; s[1] = (S_IWUSR & n) ? 'w' : '-'; s[2] = (S_IXUSR & n) ? 'x' : '-'; s[3] = (S_IRGRP & n) ? 'r' : '-'; s[4] = (S_IWGRP & n) ? 'w' : '-'; s[5] = (S_IXGRP & n) ? 'x' : '-'; s[6] = (S_IROTH & n) ? 'r' : '-'; s[7] = (S_IWOTH & n) ? 'w' : '-'; s[8] = (S_IXOTH & n) ? 'x' : '-'; return (s); } char ft_get_type(t_stat info) { if ((info.st_mode & S_IFMT) == S_IFREG) return ('-'); if ((info.st_mode & S_IFMT) == S_IFDIR) return ('d'); if ((info.st_mode & S_IFMT) == S_IFIFO) return ('p'); if ((info.st_mode & S_IFMT) == S_IFLNK) return ('l'); if (S_ISCHR(info.st_mode)) return ('c'); if (S_ISBLK(info.st_mode)) return ('b'); if ((info.st_mode & S_IFMT) == S_IFSOCK) return ('s'); return ('?'); } char *ft_get_link(size_t size, char *path) { char *buf; buf = ft_strnew(size); readlink(path, buf, size); return (buf); } t_file *ft_get_info(t_file *file, t_stat info, int ops) { t_pwd *pswd; t_grp *gid; file->type = ft_get_type(info); if(CHECK_OPS(ops, L) || CHECK_OPS(ops, G)) { if(!(pswd = getpwuid(info.st_uid))) file->owner = "204"; else file->owner = pswd->pw_name; gid = getgrgid(info.st_gid); file->nlinks = info.st_nlink; file->size = info.st_size; file->group = gid->gr_name; file->right = ft_get_right(info.st_mode); file->stime = info.st_mtime; file->block = info.st_blocks; file->time = ctime(&info.st_mtime); file->time = ft_mod_time(file->time); } if(CHECK_OPS(ops, T)) file->stime = info.st_mtime; return (file); } t_file *ft_get_file(t_file *file, int ops) { t_file *tmp; t_stat info; char *path_nm; tmp = file; while(tmp) { path_nm = ft_strjoin(tmp->path, tmp->name); if(tmp->type == 'l') { if(lstat(path_nm, &info) >= 0) { tmp->link = ft_get_link(info.st_size, path_nm); tmp = ft_get_info(tmp, info, ops); } } else { if(stat(path_nm, &info) >= 0) tmp = ft_get_info(tmp, info, ops); } tmp = tmp->next; } ft_strdel(&path_nm); free(tmp); return (file); } t_dirent *ft_get_dirent(DIR *rep) { t_dirent *dirent; if(!(dirent = readdir(rep))) return(NULL); return (dirent); } DIR *ft_get_dir(char *name) { DIR *rep; char *error; if(!(rep = opendir(name))) { name[ft_strlen_p(name) - 1] = '\0'; error = ft_strjoin("ft_ls: ", name); perror(error); ft_strdel(&error); return (NULL); } return (rep); } char *ft_mod_time(char *time) { char **tab; char *ret; int i; i = -1; tab = ft_strsplit(time, ' '); tab[3][5] = '\0'; ret = ft_strjoinf(tab[2], " ", 0); ret = ft_strjoinf(ret, tab[1], 1); ret = ft_strjoinf(ret, " ", 1); ret = ft_strjoinf(ret, tab[3], 1); while(tab[++i]) ft_strdel(&tab[i]); free(tab); return(ret); }
C
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <assert.h> //#include <iostream> //using namespace std; int BinarySearch(int* a, int n, int x) { assert(a); int begin = 0; int end = n - 1; while (begin <= end) { int mid = begin + ((end - begin) >> 1); if (a[mid] < x) begin = mid + 1; else if (a[mid] > x) end = mid; else return mid; } return -1; } // ַ(жٴ2ĴηܳN) -> O(log2N) int main() { int a[10]; BinarySearch(a, 5, 10); system("pause"); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<GL/glut.h> #include<math.h> GLint screenSize[2] = {800, 500}; // width, height struct polygonPoints { GLint x1, y1, x2, y2, x3, y3, x4, y4; }; struct polygonPoints *skyPolygon, * outerskyPolygon, *oceanPolygon, *ozonePolygon, *landPolygon, *greenPolygon; // background struct polygonPoints* factoryPolygon, * buildingPolygon, *windowPolygon; // elements struct polygonVertices { GLint a[2]; GLint b[2]; GLint c[2]; GLint d[2]; }; struct polygonVertices * skyVertices, * outerskyVertices, * oceanVertices, * ozoneVertices, * landVertices, * greenVertices; // background struct polygonVertices* factoryVertices, * buildingVertices, *windowVertices; //elements int CFC_array[13][13], xmin, xmax=100, ymin, ymax=100, xlen, ylen, ozonelen=10; float ozoneVertices2[] = { 10, 10, 10, 10, 10, 10, 10, 10 }; float skyVertices2[] = { 10, 10, 10, 10, 10, 10, 10, 10 }; int translate = 0, tr_x, tr_y; float color_sky[] = { 1, 0.768, 0.658 }; float color_green[] = { 0.290, 0.690, 0.011 }; void allocateMemory() { outerskyVertices = (struct polygonVertices*)malloc(sizeof(struct polygonVertices)); outerskyPolygon = (struct polygonPoints*)malloc(sizeof(struct polygonPoints)); ozoneVertices = (struct polygonVertices*)malloc(sizeof(struct polygonVertices)); ozonePolygon = (struct polygonPoints*)malloc(sizeof(struct polygonPoints)); skyVertices = (struct polygonVertices *)malloc(sizeof(struct polygonVertices)); skyPolygon = (struct polygonPoints*)malloc(sizeof(struct polygonPoints)); landVertices = (struct polygonVertices*)malloc(sizeof(struct polygonVertices)); landPolygon = (struct polygonPoints*)malloc(sizeof(struct polygonPoints)); greenVertices = (struct polygonVertices*)malloc(sizeof(struct polygonVertices)); greenPolygon = (struct polygonPoints*)malloc(sizeof(struct polygonPoints)); oceanVertices = (struct polygonVertices*)malloc(sizeof(struct polygonVertices)); oceanPolygon = (struct polygonPoints*)malloc(sizeof(struct polygonPoints)); factoryVertices = (struct polygonVertices*)malloc(sizeof(struct polygonVertices)); factoryPolygon = (struct polygonPoints*)malloc(sizeof(struct polygonPoints)); windowVertices = (struct polygonVertices*)malloc(sizeof(struct polygonVertices)); windowPolygon = (struct polygonPoints*)malloc(sizeof(struct polygonPoints)); buildingVertices = (struct polygonVertices*)malloc(sizeof(struct polygonVertices)); buildingPolygon = (struct polygonPoints*)malloc(sizeof(struct polygonPoints)); } void polygonPointSetup(struct polygonPoints* ptr, GLint x1, GLint y1, GLint x2, GLint y2, GLint x3, GLint y3, GLint x4, GLint y4) { ptr->x1 = x1; ptr->y1 = y1; ptr->x2 = x2; ptr->y2 = y2; ptr->x3 = x3; ptr->y3 = y3; ptr->x4 = x4; ptr->y4 = y4; } void polygonVertexSetup(struct polygonVertices *ptr, struct polygonPoints *pnt) { ptr->a[0] = pnt->x1; ptr->a[1] = pnt->y1; ptr->b[0] = pnt->x2; ptr->b[1] = pnt->y2; ptr->c[0] = pnt->x3; ptr->c[1] = pnt->y3; ptr->d[0] = pnt->x4; ptr->d[1] = pnt->y4; } void polygonSetup() { allocateMemory(); GLint width = screenSize[0], len = screenSize[1]; // points polygonPointSetup(factoryPolygon, 0, 0, 0, 0, 0, 0, 0, 0); polygonPointSetup(windowPolygon, 0, 0, 10, 0, 10, 10, 0, 10 ); polygonPointSetup(buildingPolygon, 0, 0, 0.1*width, 0, 0.1*width, 0.2*len, 0, 0.2*len); polygonPointSetup(outerskyPolygon, 0, 0.8*len, width, 0.8*len, width, len, 0, len); polygonPointSetup(ozonePolygon, 0, 0.7 * len, width, 0.7 * len, width, .8*len, 0, .8*len); ozonelen = ozoneVertices2[7] - ozoneVertices2[1]; polygonPointSetup(skyPolygon, 0, 0.3 * len, width, 0.3 * len, width, .8 * len, 0, .8 * len); polygonPointSetup(landPolygon, 0, 0, 0.3*width, 0, 0.3*width, 0.3 * len, 0, 0.3 * len); polygonPointSetup(greenPolygon, 0.3 * width, 0, 0.6 * width, 0, 0.6 * width, 0.3 * len, 0.3*width, 0.3 * len); polygonPointSetup(oceanPolygon, 0.6 * width, 0, width, 0, width, 0.3 * len, 0.6*width, 0.3 * len); xmin = 0.015 * screenSize[0]; ymin = 0.025 * screenSize[1] + buildingPolygon->y4; // from draw_building xmax = 0.175 * screenSize[0] + buildingPolygon->x2; ymax = ozonePolygon->y4; xlen = xmax - xmin; ylen = ymax - ymin; // verices polygonVertexSetup(factoryVertices, factoryPolygon); polygonVertexSetup(windowVertices, windowPolygon); polygonVertexSetup(buildingVertices, buildingPolygon); polygonVertexSetup(outerskyVertices, outerskyPolygon); polygonVertexSetup(ozoneVertices, ozonePolygon); polygonVertexSetup(skyVertices, skyPolygon); polygonVertexSetup(landVertices, landPolygon); polygonVertexSetup(greenVertices, greenPolygon); polygonVertexSetup(oceanVertices, oceanPolygon); } void draw_polygon(struct polygonVertices* ptr, GLint i, GLint j) { glBegin(GL_POLYGON); glVertex2i(ptr->a[0]+i, ptr->a[1]+j); glVertex2i(ptr->b[0]+i, ptr->b[1]+j); glVertex2i(ptr->c[0]+i, ptr->c[1]+j); glVertex2i(ptr->d[0]+i, ptr->d[1]+j); glEnd(); } void draw_outersky() { glColor3f(1, 0.549, 0.341); draw_polygon(outerskyVertices, 0, 0); } void draw_ozone() { //draw_polygon(ozoneVertices, 0 , 0); glColor3f(0.815, 0.705, 0.662); glBegin(GL_POLYGON); glVertex2f(ozoneVertices2[0], ozoneVertices2[1]); glVertex2f(ozoneVertices2[2], ozoneVertices2[3]); glVertex2f(ozoneVertices2[4], ozoneVertices2[5]); glVertex2f(ozoneVertices2[6], ozoneVertices2[7]); glEnd(); } void draw_sky2() { glColor3fv(color_sky); glBegin(GL_POLYGON); glVertex2f(skyVertices2[0], skyVertices2[1]); glVertex2f(skyVertices2[2], skyVertices2[3]); glVertex2f(skyVertices2[4], skyVertices2[5]); glVertex2f(skyVertices2[6], skyVertices2[7]); glEnd(); } void generateOzone() { float temp[] = { 0, 0.7 * screenSize[1], screenSize[0], 0.7 * screenSize[1], screenSize[0], .8 * screenSize[1], 0, .8 * screenSize[1] }; for (int i = 0; i < 8; i++) ozoneVertices2[i] = temp[i]; } void generateSky() { int temp[] = { 0, 0.3 * screenSize[1], screenSize[0], 0.3 * screenSize[1], screenSize[0], .8 * screenSize[1], 0, .8 * screenSize[1] }; for (int i = 0; i < 8; i++) skyVertices2[i] = temp[i]; draw_sky2(); } void draw_land() { glColor3f(0.992, 0.709, 0.266); draw_polygon(landVertices, 0, 0); } void draw_green() { glColor3fv(color_green); draw_polygon(greenVertices, 0, 0); } void draw_ocean() { glColor3f(0.109, 0.811, 0.890); draw_polygon(oceanVertices, 0, 0); } void draw_factory() { glColor3f(0, 0, 0); draw_polygon(factoryVertices, 0, 0); glColor3f(1, 1, 1); for (int i = 10 + factoryPolygon->y1; i < 10 - factoryPolygon->y3; i += 10) for (int j = 10 + factoryPolygon->x1; j < 10 - factoryPolygon->x3; j += 10) draw_polygon(windowVertices, j, i); } void draw_building(GLint buildPosx, GLint buildPosy) { //glColor3f(0.964, 0.968, 0.470); glColor3f(0, 0, 0); draw_polygon(buildingVertices, buildPosx, buildPosy); glColor3f(1, 1, 1); GLint startx = buildingPolygon->x1 + 10+buildPosx, starty = buildingPolygon->y1 + 10+ buildPosy; GLint endx = buildingPolygon->x3 - 10+ buildPosx, endy = buildingPolygon->y3 - 10+ buildPosy; for (GLint i = startx; i < endx; i += 20) for (GLint j = starty; j < endy; j += 20) draw_polygon(windowVertices, i, j); } void draw_point(int p, int q) { // glColor3f(0.839, 0.658, 0.478); float theta = 0; glColor3f(1, 1, 1); glBegin(GL_POLYGON); for (int i = 0; i < 360; i++) { theta = i * 3.142 / 180; glVertex2f(p + 5 * cos(theta), q + 5 * sin(theta)); } glEnd(); } void generate_CFC() { if (translate == 1) { for (int i = 0; i < 13; i++) { CFC_array[i][0] = (rand() / (double)RAND_MAX) * xlen + xmin; CFC_array[i][1] = (rand() / (double)RAND_MAX) * ylen + ymin; draw_point(CFC_array[i][0], CFC_array[i][1]); } } if (translate == 3) { for (int i = 0; i < 4; i++) { CFC_array[i][0] = (rand() / (double)RAND_MAX) * xlen + xmin; CFC_array[i][1] = (rand() / (double)RAND_MAX) * ylen + ymin; draw_point(CFC_array[i][0], CFC_array[i][1]); } } } void translatepoint() { if (translate==1 || translate==3) { long j = 0; // delay(500); while (j++ < 100000000); } } void fish(int x, int y, int fcx, int fcy, int fcz) { glColor3f(fcx, fcy, fcz); glBegin(GL_TRIANGLES); glVertex2i(350 + x , 30 + y ); glVertex2i(360 + x , 40 + y ); glVertex2i(360 + x , 30 + y ); glEnd(); glBegin(GL_TRIANGLES); glVertex2i(350 + x , 30 + y ); glVertex2i(360 + x , 40 + y ); glVertex2i(340 + x , 60 + y ); glEnd(); glBegin(GL_TRIANGLES); glVertex2i(345 + x , 80 + y ); glVertex2i(340 + x , 60 + y ); glVertex2i(325 + x , 70 + y ); glEnd(); } void translate_ozone() { glPushMatrix(); glTranslatef(1, tr_y, 1); draw_ozone(); glTranslatef(1, -tr_y, 1); glPopMatrix(); draw_outersky(); glutPostRedisplay(); } void set_color(float *array, float r, float g, float b) { array[0] = r; array[1] = g; array[2] = b; } void initializeScreen() { glClear(GL_COLOR_BUFFER_BIT); gluOrtho2D(0, screenSize[0], 0, screenSize[1]); // make sure that it is sufficient } void draw_background() { polygonSetup(); draw_outersky(); generateSky(); if (translate==1) { // start translate_ozone(); tr_y++; set_color(color_green, 0.65, 0.99, 0.41); set_color(color_sky, 1, 0.71, 0.47); if (tr_y >= ozonelen) { set_color(color_sky, 1, 0.549, 0.341); set_color(color_green, 0.8, 1, 0.2); } } else if (translate == 3) { translate_ozone(); tr_y--; set_color(color_green, 0.65, 0.99, 0.41); set_color(color_sky, 1, 0.71, 0.47); if (tr_y == 0) { translate = 0; } } else if (translate == 2) { // stop translate_ozone(); } else { // reset draw_ozone(); tr_y = 0; set_color(color_sky, 1, 0.768, 0.658); set_color(color_green, 0.290, 0.690, 0.011); } draw_land(); draw_green(); draw_ocean(); fish(170, 60, 1, 1, 1); fish(270, 50, 1, 1, 1); if (translate == 0) { fish(280, 30, 1, 1, 1); fish(190, 50, 1, 1, 1); } if (tr_y < ozonelen) { fish(170, 10, 1, 1, 1); fish(220, 50, 1, 1, 1); } draw_building(0.15 * screenSize[0], 0.15 * screenSize[1]); draw_building(0.05 * screenSize[0], 0.05 * screenSize[1]); draw_building(0.015 * screenSize[0], 0.025 * screenSize[1]); draw_building(0.175 * screenSize[0], 0.075 * screenSize[1]); } void mouseactions(int key) { if (key == 1) { translate = 1; } if (key == 2 && translate==1) { translate = 2; } if (key == 3 && (translate == 1 || translate == 2)) { translate = 3; } if (key == 4) { translate = 0; } } void display() { draw_background(); generateOzone(); if(translate == 1 || translate == 3) generate_CFC(); glutPostRedisplay(); glutSwapBuffers(); glFlush(); } void main(int argc, char** argv) { glutInit(&argc, argv); glutInitWindowSize(screenSize[0], screenSize[1]); glutInitWindowPosition(0, 0); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutCreateWindow("Trial"); initializeScreen(); glutDisplayFunc(display); glutCreateMenu(mouseactions); glutAddMenuEntry("Start", 1); glutAddMenuEntry("Stop", 2); glutAddMenuEntry("Reduce", 3); glutAddMenuEntry("Reset", 4); glutAttachMenu(GLUT_RIGHT_BUTTON); glutIdleFunc(translatepoint); glutMainLoop(); }
C
/* Labs week 4 Erik Grunnr Problem 4 */ #include <stdio.h> int main () { int input1=0; int input2=0; int calc1=0; int calc2=0; printf("pls input two integers\n"); scanf("%d",&input1); scanf("%d",&input2); flushall(); calc1 = input1%input2; switch (calc1)//switch statement { case 0: { printf("\n%d is evenly divisable by %d",input1,input2); break; } default: { printf("\n%d is not evenly divisable by %d",input1,input2); break; } } getchar(); return 0; }
C
/** * \file reader_t1_block.c * \copyright This file is part of the Open-ISO7816-Stack project and is distributed under the MIT license. See LICENSE file in the root directory. * This file contains the functions to operate safely on the READER_T1_Block data stuctures representing the T=1 Block objects. */ #include "reader_t1_block.h" #include "reader_hal.h" /** * \fn READER_T1_SetBlockSAD(READER_T1_Block *pBlock, uint8_t blockSAD) * \return READER_Status execution code. READER_OK indicates successful execution. Any other value is an error. * \param *pBlock is a pointer on a READER_T1_Block data structure we want to operate on. * \param blockSAD is the "Source Node Address" as defined in ISO/IEC7816-3 section 11.3.2.1. It identifies the source of the block. It may be used to distinguish between multiple logical connections when they coexist. Most of the time it is set to 0x00. * This function sets the SAD (source address of a T=1 block structure). SAD is a part of the NAD byte. See ISO/IEC7816-3 section 11.3.2.1. */ READER_Status READER_T1_SetBlockSAD(READER_T1_Block *pBlock, uint8_t blockSAD){ READER_Status retVal; uint8_t *pCurrentNAD; uint8_t *blockFrame; if(blockSAD > 0x07){ return READER_ERR; } blockFrame = READER_T1_GetBlockFrame(pBlock); pCurrentNAD = blockFrame + READER_T1_BLOCKFRAME_NAD_POSITION; *pCurrentNAD = (*pCurrentNAD & 0xF8) | (blockSAD & 0x07); /* See ISO7816-3 section 11.3.2.1 */ /* Updating block's checksum ... */ retVal = READER_T1_UpdateBlockChecksum(pBlock); if(retVal != READER_OK) return retVal; return READER_OK; } /** * \fn READER_T1_SetBlockDAD(READER_T1_Block *pBlock, uint8_t blockDAD) * \return READER_Status execution code. READER_OK indicates successful execution. Any other value is an error. * \param *pBlock is a pointer on a READER_T1_Block data structure we want to operate on. * \param blockDAD is the "Destination Node Address" as defined in ISO/IEC7816-3 section 11.3.2.1. It identifies the intended destination of the block. It may be used to distinguish between multiple logical connections when they coexist. Most of the time it is set to 0x00. * This function sets the DAD (destination address of a T=1 block structure). DAD is a part of the NAD byte. See ISO/IEC7816-3 section 11.3.2.1. */ READER_Status READER_T1_SetBlockDAD(READER_T1_Block *pBlock, uint8_t blockDAD){ READER_Status retVal; uint8_t *pCurrentNAD; uint8_t *blockFrame; if(blockDAD > 0x07){ return READER_ERR; } blockFrame = READER_T1_GetBlockFrame(pBlock); pCurrentNAD = blockFrame + READER_T1_BLOCKFRAME_NAD_POSITION; *pCurrentNAD = (*pCurrentNAD & 0x8F) | (4<<(blockDAD & 0x07)); /* See ISO7816-3 section 11.3.2.1 */ /* Updating block's checksum ... */ retVal = READER_T1_UpdateBlockChecksum(pBlock); if(retVal != READER_OK) return retVal; return READER_OK; } /** * \fn READER_T1_SetBlockNAD(READER_T1_Block *pBlock, uint8_t blockNAD) * \return READER_Status execution code. READER_OK indicates successful execution. Any other value is an error. * \param *pBlock is a pointer on a READER_T1_Block data structure we want to operate on. * \param blockNAD is the value of the Node Address Byte (NAD) to be set. See ISO/IEC7816-3 section 11.3.2.1. * This function sets the NAD byte of the T=1 block structure. See ISO/IEC7816-3 section 11.3.2.1. */ READER_Status READER_T1_SetBlockNAD(READER_T1_Block *pBlock, uint8_t blockNAD){ READER_Status retVal; uint8_t *pCurrentNAD; uint8_t *blockFrame; blockFrame = READER_T1_GetBlockFrame(pBlock); pCurrentNAD = blockFrame + READER_T1_BLOCKFRAME_NAD_POSITION; *pCurrentNAD = blockNAD; /* See ISO7816-3 section 11.3.2.1 */ /* Updating block's checksum ... */ retVal = READER_T1_UpdateBlockChecksum(pBlock); if(retVal != READER_OK) return retVal; return READER_OK; } /** * \fn READER_T1_SetBlockPCB(READER_T1_Block *pBlock, uint8_t blockPCB) * \return READER_Status execution code. READER_OK indicates successful execution. Any other value is an error. * \param *pBlock is a pointer on a READER_T1_Block data structure we want to operate on. * \param blockPCB is the value of the PCB byte to be set for the T=1 block. * This function the PCB byte of the T=1 block. It codes for the type of block (I-Block, R-Block, S-Block). See ISO/IEC7816-3 section 11.3.2.2. */ READER_Status READER_T1_SetBlockPCB(READER_T1_Block *pBlock, uint8_t blockPCB){ READER_Status retVal; uint8_t *pCurrentPCB; uint8_t *blockFrame; blockFrame = READER_T1_GetBlockFrame(pBlock); pCurrentPCB = blockFrame + READER_T1_BLOCKFRAME_PCB_POSITION; *pCurrentPCB = blockPCB; /* See ISO7816-3 section 11.3.2.1 */ /* Updates block's checksum ... */ retVal = READER_T1_UpdateBlockChecksum(pBlock); if(retVal != READER_OK) return retVal; return READER_OK; } /** * \fn READER_T1_SetBlockType(READER_T1_Block *pBlock, READER_T1_BlockType type) * \return READER_Status execution code. READER_OK indicates successful execution. Any other value is an error. * \param *pBlock is a pointer on a READER_T1_Block data structure we want to operate on. * \param type is a READER_T1_BlockType value coding for the type of block (I-Block, R-Block, S-Block). * This function configures the type of the block (I-Block, R-Block, S-Block). */ READER_Status READER_T1_SetBlockType(READER_T1_Block *pBlock, READER_T1_BlockType type){ /* Voir ISO7816-3 section 11.3.2.2 */ READER_Status retVal; uint8_t currentPCB, newPCB; currentPCB = READER_T1_GetBlockPCB(pBlock); if(type == READER_T1_IBLOCK){ newPCB = (currentPCB) & (0x7F); /* On force bit 8 a 0 */ } else if(type == READER_T1_RBLOCK){ newPCB = (currentPCB | 0x80) & 0xBF; /* On force bits 8 et 7 a 10 */ } else if(type == READER_T1_SBLOCK){ newPCB = (currentPCB | 0x80) | 0x40; /* On force bits 8 et 7 a 11 */ } else{ return READER_ERR; } retVal = READER_T1_SetBlockPCB(pBlock, newPCB); if(retVal != READER_OK) return retVal; /* Updating block's checksum ... */ retVal = READER_T1_UpdateBlockChecksum(pBlock); if(retVal != READER_OK) return retVal; return READER_OK; } /** * \fn READER_T1_SetBlockLEN(READER_T1_Block *pBlock, uint8_t blockLEN) * \return READER_Status execution code. READER_OK indicates successful execution. Any other value is an error. * \param *pBlock is a pointer on a READER_T1_Block data structure we want to operate on. * \param blockLEN is coding for the length of the data contained in an I-Block. See ISO/IEC7816-3 section 11.3.2.3. It shoud not be higher than 0xFE. * This function sets the length of the data field contained in an I-Block. See ISO/IEC7816-3 section 11.3.2.3. */ READER_Status READER_T1_SetBlockLEN(READER_T1_Block *pBlock, uint8_t blockLEN){ READER_Status retVal; uint8_t *pCurrentLEN; uint8_t *blockFrame; /* We check that the value is not higher than the max one. See ISO/IEC7816-3 section 11.3.2.3. */ if(blockLEN > READER_T1_BLOCK_MAX_DATA_SIZE){ return READER_ERR; } blockFrame = READER_T1_GetBlockFrame(pBlock); pCurrentLEN = blockFrame + READER_T1_BLOCKFRAME_LEN_POSITION; *pCurrentLEN = blockLEN; /* Updating block's checksum ... */ retVal = READER_T1_UpdateBlockChecksum(pBlock); if(retVal != READER_OK) return retVal; return READER_OK; } /** * \fn READER_T1_SetBlockRedundancyType(READER_T1_Block *pBlock, READER_T1_RedundancyType type) * \return READER_Status execution code. READER_OK indicates successful execution. Any other value is an error. * \param *pBlock is a pointer on a READER_T1_Block data structure we want to operate on. * \param type is a READER_T1_RedundancyType value encoding the type of corrector code to be used (LRC or CRC). */ READER_Status READER_T1_SetBlockRedundancyType(READER_T1_Block *pBlock, READER_T1_RedundancyType type){ if((type != READER_T1_CRC) && (type != READER_T1_LRC)){ return READER_ERR; } pBlock->RedundancyType = type; return READER_OK; } READER_Status READER_T1_SetBlockLRC(READER_T1_Block *pBlock, uint8_t blockLRC){ READER_Status retVal; uint8_t currentLEN; uint8_t *pCurrentLRC; uint8_t *blockFrame; /* On recupere un pointeur sur le block brut */ blockFrame = READER_T1_GetBlockFrame(pBlock); /* On place le LRC au bon endroit */ currentLEN = READER_T1_GetBlockLEN(pBlock); pCurrentLRC = blockFrame + READER_T1_BLOCK_PROLOGUE_SIZE + currentLEN ; *pCurrentLRC = blockLRC; /* On mets a jour le RedundancyType a LRC */ retVal = READER_T1_SetBlockRedundancyType(pBlock, READER_T1_LRC); if(retVal != READER_OK) return retVal; return READER_OK; } /* TODO: Implementing CRC (only LRC implemented yet) for the T=1 blocks. */ READER_Status READER_T1_SetBlockCRC(READER_T1_Block *pBlock, uint16_t blockCRC){ READER_Status retVal; uint8_t currentLEN; uint16_t *pCurrentCRC; uint8_t *blockFrame; /* On recupere un pointeur sur le block brut */ blockFrame = READER_T1_GetBlockFrame(pBlock); /* On place le CRC au bon endroit */ currentLEN = READER_T1_GetBlockLEN(pBlock); pCurrentCRC = (uint16_t*)(blockFrame + READER_T1_BLOCK_PROLOGUE_SIZE + currentLEN); *pCurrentCRC = blockCRC; /* On mets a jour le RedundancyType a LRC */ retVal = READER_T1_SetBlockRedundancyType(pBlock, READER_T1_CRC); if(retVal != READER_OK) return retVal; return READER_OK; } READER_Status READER_T1_SetBlockData(READER_T1_Block *pBlock, uint8_t *data, uint8_t dataSize){ READER_Status retVal; //READER_T1_BlockType bType; READER_T1_RedundancyType rType; uint32_t i; uint8_t *pBlockData; uint8_t tmpLRC; uint16_t tmpCRC; /* Attention, ici, l'ordre des actions effectuees sur le Block est important ! */ /* On recupere un pointeur sur la zone de donnees du Block ... */ pBlockData = READER_T1_GetBlockData(pBlock); /* On fait les verifications elementaires sur le Block ... */ if(dataSize > READER_T1_BLOCK_MAX_DATA_SIZE){ return READER_ERR; } /* On sauvegarde temporairement le champ LRC/CRC (il va etre ecrase quand on va ecrire les donnees) */ rType = READER_T1_GetBlockRedundancyType(pBlock); if(rType == READER_T1_LRC){ tmpLRC = READER_T1_GetBlockLRC(pBlock); } else if(rType == READER_T1_CRC){ tmpCRC = READER_T1_GetBlockCRC(pBlock); } else{ return READER_ERR; } /* On ecrit le champ de donnees dans le Block ... */ for(i=0; i<dataSize; i++){ pBlockData[i] = data[i]; } /* Mise a jour du LEN du Block */ retVal = READER_T1_SetBlockLEN(pBlock, dataSize); if(retVal != READER_OK) return retVal; /* On met a jour le checksum du Block */ retVal = READER_T1_UpdateBlockChecksum(pBlock); if(retVal != READER_OK) return retVal; return READER_OK; } uint8_t READER_T1_GetBlockSAD(READER_T1_Block *pBlock){ uint8_t *pCurrentNAD; uint8_t *blockFrame; blockFrame = READER_T1_GetBlockFrame(pBlock); pCurrentNAD = blockFrame + READER_T1_BLOCKFRAME_NAD_POSITION; return (*pCurrentNAD) & 0x07; } uint8_t READER_T1_GetBlockDAD(READER_T1_Block *pBlock){ uint8_t *pCurrentNAD; uint8_t *blockFrame; blockFrame = READER_T1_GetBlockFrame(pBlock); pCurrentNAD = blockFrame + READER_T1_BLOCKFRAME_NAD_POSITION; return (*pCurrentNAD & 0xE0) >> 4; } uint8_t READER_T1_GetBlockNAD(READER_T1_Block *pBlock){ uint8_t *pCurrentNAD; uint8_t *blockFrame; blockFrame = READER_T1_GetBlockFrame(pBlock); pCurrentNAD = blockFrame + READER_T1_BLOCKFRAME_NAD_POSITION; return *pCurrentNAD; } uint8_t READER_T1_GetBlockPCB(READER_T1_Block *pBlock){ uint8_t *pCurrentPCB; uint8_t *blockFrame; blockFrame = READER_T1_GetBlockFrame(pBlock); pCurrentPCB = blockFrame + READER_T1_BLOCKFRAME_PCB_POSITION; return *pCurrentPCB; } /** * \fn READER_T1_BlockType READER_T1_GetBlockType(READER_T1_Block *pBlock) * \param *pBlock est un pointeur sur une structure de type READER_T1_BLOCK. * \return La fonction retourne une valeur de type READER_T1_BlockType selon le type de Block. Attention, cette valeur est erronée si la stucture Block n'a jamais été initailisée. (En principe un init est fait au moment de la construction du Block avec READER_T1_ForgeBlock()) * Cette fonction permet de connaitre le type d'un Block tel (tel que décrit dans ISO7816-3 section 11.3.2.2). I-Block, R-Block ou S-Block. */ READER_T1_BlockType READER_T1_GetBlockType(READER_T1_Block *pBlock){ /* Voir ISO7816-3 section 11.3.2.2 */ uint8_t currentPCB; currentPCB = READER_T1_GetBlockPCB(pBlock); if((currentPCB & 0x80) == 0x00){ return READER_T1_IBLOCK; } else if((currentPCB & 0xC0) == 0x80){ return READER_T1_RBLOCK; } else if((currentPCB & 0xC0) == 0xC0){ return READER_T1_SBLOCK; } else{ return READER_T1_SBLOCK; } } /** * \fn uint8_t READER_T1_GetBlockLEN(READER_T1_Block *pBlock) * \param *pBlock est un pointeur sur une stucture de type READER_T1_BLOCK. * \return La fonction retourne un entier uint8_t. La valeur de cet entier est le champ LEN tel que décrit ISO7816-3 section 11.3.2.3. * Attention, si la strucure Block n'a jamais été initialisée, cette valeur est erronée. (En principe un init est fait au moment de la construction du Block avec READER_T1_ForgeBlock()) * * Cette fonction permet de récupérer le champ LEN d'un Block. Le champs LEN est décrit dans ISO7816-3 section 11.3.1. * Ici, on ne calcule pas cette valeur, il s'agit d'un accesseur sur cette valeur dans la stucture Block. */ uint8_t READER_T1_GetBlockLEN(READER_T1_Block *pBlock){ uint8_t *pCurrentLEN; uint8_t *blockFrame; /* Ici on ne calcule pas une taille. On va lire dans la sructure du Block le champ LEN */ blockFrame = READER_T1_GetBlockFrame(pBlock); pCurrentLEN = blockFrame + READER_T1_BLOCKFRAME_LEN_POSITION; return *pCurrentLEN; } READER_T1_RedundancyType READER_T1_GetBlockRedundancyType(READER_T1_Block *pBlock){ return pBlock->RedundancyType; } uint8_t READER_T1_GetBlockLRC(READER_T1_Block *pBlock){ uint8_t currentLEN; uint8_t *pCurrentLRC; uint8_t *blockFrame; blockFrame = READER_T1_GetBlockFrame(pBlock); currentLEN = READER_T1_GetBlockLEN(pBlock); pCurrentLRC = blockFrame + READER_T1_BLOCK_PROLOGUE_SIZE + currentLEN; return *pCurrentLRC; } uint16_t READER_T1_GetBlockCRC(READER_T1_Block *pBlock){ uint8_t currentLEN; uint16_t *pCurrentCRC; uint8_t *blockFrame; blockFrame = READER_T1_GetBlockFrame(pBlock); currentLEN = READER_T1_GetBlockLEN(pBlock); pCurrentCRC = (uint16_t*)(blockFrame + READER_T1_BLOCK_PROLOGUE_SIZE + currentLEN); return *pCurrentCRC; } /* retourne un pointeur sur les donnes du Block */ uint8_t* READER_T1_GetBlockData(READER_T1_Block *pBlock){ uint8_t *blockFrame; blockFrame = READER_T1_GetBlockFrame(pBlock); return blockFrame + READER_T1_BLOCKFRAME_INF_POSITION; } uint8_t READER_T1_ComputeBlockLRC(READER_T1_Block *pBlock){ uint8_t xorSum; uint8_t *pBlockFrame; uint8_t dataSize; uint32_t blockFrameSize; uint32_t i; dataSize = READER_T1_GetBlockLEN(pBlock); blockFrameSize = (uint32_t)dataSize + (uint32_t)READER_T1_BLOCK_PROLOGUE_SIZE; /* > 3 */ pBlockFrame = READER_T1_GetBlockFrame(pBlock); xorSum = pBlockFrame[0]; for(i=1; i<blockFrameSize; i++){ xorSum = xorSum ^ (pBlockFrame[i]); } return xorSum; } uint16_t READER_T1_ComputeBlockCRC(READER_T1_Block *pBlock){ uint8_t *blockFrame; uint16_t crc = 0x0000; uint32_t len; uint8_t currentByte; uint32_t i, j; blockFrame = READER_T1_GetBlockFrame(pBlock); len = READER_T1_GetBlockSizeWithoutCheck(pBlock); for(i=0; i<len; i++){ currentByte = blockFrame[i]; crc ^= currentByte; for(j=0; j<8; j++){ crc ^= READER_T1_CRC_POLY; crc >>= 1; } } return crc; } /** * \fn uint32_t READER_T1_GetBlockTotalSize(READER_T1_Block *pBlock) * \param *pBlock est un pointeur sur une stucture Block : READER_T1_BLOCK. * \return La fonction retourne un entier uint32_t. La valeur de cet entier est le nombre d'octets necessaires pour représenter le Block. * Cette fonction calcule le nombre d'octets necessaires pour représeter le block tel que décrit dans ISO7816-3 section 11.3.1. * Il s'agt ici de la taille totale, c'est a dire : len(Prologue field) + len(Information field) + len(Epilogue field) */ uint32_t READER_T1_GetBlockTotalSize(READER_T1_Block *pBlock){ READER_T1_RedundancyType checkType; uint32_t checkLen; uint32_t tmpLen; tmpLen = READER_T1_GetBlockSizeWithoutCheck(pBlock); checkType = READER_T1_GetBlockRedundancyType(pBlock); if(checkType == READER_T1_CRC){ checkLen = 2; } else{ checkLen = 1; } return tmpLen + checkLen; } /** * \fn READER_T1_GetBlockSizeWithoutCheck(READER_T1_Block *pBlock) * \param *pBlock est un pointeur sur une stucture Block : READER_T1_BLOCK. * \return La fonction retourne un entier uint32_t. La valeur de cet entier est le nombre d'octets necessaires pour représenter le Block (sans compte le Epilogue field). * Cette fonction calcule le nombre d'octets necessaires pour représeter le block privé de son Epilogue field, tel que décrit dans ISO7816-3 section 11.3.1. * la fonction calcule : len(Prologue field) + len(Information field). */ uint32_t READER_T1_GetBlockSizeWithoutCheck(READER_T1_Block *pBlock){ uint8_t dataLEN; dataLEN = READER_T1_GetBlockLEN(pBlock); return READER_T1_BLOCK_PROLOGUE_SIZE + (uint32_t)dataLEN; } uint8_t* READER_T1_GetBlockFrame(READER_T1_Block *pBlock){ return pBlock->blockFrame; } uint32_t READER_T1_GetBlockRedundancyLen(READER_T1_Block *pBlock){ READER_T1_RedundancyType rType; rType = READER_T1_GetBlockRedundancyType(pBlock); if(rType == READER_T1_LRC){ return 1; } else{ return 2; } } READER_Status READER_T1_UpdateBlockChecksum(READER_T1_Block *pBlock){ READER_Status retVal; READER_T1_RedundancyType rType; uint16_t blockCRC; uint8_t blockLRC; rType = READER_T1_GetBlockRedundancyType(pBlock); if(rType == READER_T1_LRC){ blockLRC = READER_T1_ComputeBlockLRC(pBlock); retVal = READER_T1_SetBlockLRC(pBlock, blockLRC); if(retVal != READER_OK) return retVal; } else if(rType == READER_T1_CRC){ blockCRC = READER_T1_ComputeBlockCRC(pBlock); retVal = READER_T1_SetBlockCRC(pBlock, blockCRC); if(retVal != READER_OK) return retVal; } else{ return READER_ERR; } return READER_OK; } /** * \fn READER_Status READER_T1_ForgeBlock(READER_T1_Block *pBlock, READER_T1_RedundancyType rType) * Cette fonction permet de construire un Block vierge. La fonction prends un pointeur sur un structure Block qui n'est pas initialisée, la fonction initialise ce Block de sorte à ce qu'il puisse être utilisé par les autres fonctions. * \param *pBlock est un pointeur sur une structure de type READER_T1_Block. Il s'agit d'un pointeur sur un espace mémoire déjà alloué et capable de contenir un Block. Ce Block n'est pas initialisé. * \param rType est uen valeur de type READER_T1_RedundancyType. Elle indique le type de code correcteur qui va etre utilisé pour ce Block. * \return La fonction retourne une valeur de type READER_Status. READER_OK indiue le bon déroulement de la fonction. */ READER_Status READER_T1_ForgeBlock(READER_T1_Block *pBlock, READER_T1_RedundancyType rType){ READER_Status retVal; retVal = READER_T1_SetBlockRedundancyType(pBlock, rType); if(retVal != READER_OK) return retVal; /* On initialise la taille des data a zero */ retVal = READER_T1_SetBlockLEN(pBlock, READER_T1_BLOCK_INITIAL_LEN); if(retVal != READER_OK) return retVal; /* On initialise le PCB à zero ... */ retVal = READER_T1_SetBlockPCB(pBlock, READER_T1_BLOCK_INITIAL_PCB); if(retVal != READER_OK) return retVal; /* A priori on utilise pas l'adresse, donc NAD et SAD sont a 000. Voir ISO7815-3 section 11.3.2.1 */ retVal = READER_T1_SetBlockNAD(pBlock, READER_T1_BLOCK_INITIAL_NAD); if(retVal != READER_OK) return retVal; return READER_OK; } /** * \fn READER_T1_SendBlock(READER_T1_Block *pBlock, uint32_t currentCWT, uint32_t extraStartDelay, uint32_t *pTickstart, READER_HAL_CommSettings *pSettings) * Cette fonction permet de placer une structure de type READER_T1_Block sur le support support de transmission. * Cette fonction permet l'envoi des octets et assure le respect des délais (WT, GT, BWT, BGT ...). Elle n'a pas conscience du contexte de communication. * Elle traduit le niveau logique Block en uen chaine de caractères à envoyer. * Elle permet également de remonter de l'information sur l'envoi du Block. * \param *pBlock est un pointeur sur une structure de type READER_T1_Block. Il s'agit du Block à envoyer. * \param currentCWT est un uint32_t qui indique la valeur de CWT (voir ISO7816-3 section 11.4.3) à appliquer pour l'envoi de ce Block. C'est une valeur en milisecondes. * \param extraStartDelay est un uint32_t permet d'indiquer un délai supplémentaire à appliquer avant de déclencher l'envoi du premier caractère du Block. C'est une valeur en milisecondes. Permet d'assurer le respect du BGT par exemple (voir ISO7816-3 section 11.4.3). * \param *pTickStart est un pointeur sur un uint32_t. Il permet la fonction de retourner la date (en milisecondes) du début de l'envoi du dernier caractère du Block. (leading edge du dernier caractère du block, voir ISO7816-3 section 11.4.3). * \param *pSettings is a pointer on a READER_HAL_CommSettings data structure that should already be containing the low level communications settings for the hardware abstraction layer. * \return La fonction retourne un code d'erreur de type READER_Status. READER_OK indique le bon déroulement. */ READER_Status READER_T1_SendBlock(READER_T1_Block *pBlock, uint32_t currentCWT, uint32_t extraStartDelay, uint32_t *pTickstart, READER_HAL_CommSettings *pSettings){ READER_Status retVal; uint8_t *blockFrame; uint32_t blockFrameSize; uint32_t tickstart; /* On recupere les donnees a envoyer sous format brut ... */ blockFrame = READER_T1_GetBlockFrame(pBlock); blockFrameSize = READER_T1_GetBlockTotalSize(pBlock); /* On patiente extraDelay milisecondes (arrondi a la milisec inf, pour eviter de depasser) ... */ tickstart = READER_HAL_GetTick(); while((READER_HAL_GetTick() - tickstart) < extraStartDelay){ } /* On envoie toutes les donnees brutes. Le temps maximal dont ont dispose pour envoyer un caractere est currentCWT ... */ retVal = READER_HAL_SendCharFrameTickstart(pSettings, READER_HAL_PROTOCOL_T1, blockFrame, blockFrameSize, currentCWT, &tickstart); if(retVal != READER_OK) return retVal; *pTickstart = tickstart; return READER_OK; } /** * \fn READER_T1_RcvBlock(READER_T1_Block *pBlock, READER_T1_RedundancyType rType, uint32_t currentCWT, uint32_t extraTimeout, uint32_t *pTickstart, READER_HAL_CommSettings *pSettings * Cette fonction permet de recevoir un Block. La fonction recoit d'abord le prologue du Block, puis à partir des informations qui y sont contenues, elle recoit le reste du Block. Attention cette fonction ne vérifie pas l'intégrité du Block, pas de vérification du checksum. * \return La fonction revoie un code de type READER_Status. Le retour est READER_OK si le Block esr reçu en entier et si le formatage du Block reçu est correct. * \param *pBlock Pointeur sur une structure de type READER_T1_Block. Le contenu du Block reçu sera placé à l'intérieur. * \param timeout Il s'agit de la valeur du timeout pour chaque caractère en milisecondes. * \param *pSettings is a pointer on a READER_HAL_CommSettings data structure that should already be containing the low level communications settings for the hardware abstraction layer. */ READER_Status READER_T1_RcvBlock(READER_T1_Block *pBlock, READER_T1_RedundancyType rType, uint32_t currentCWT, uint32_t extraTimeout, uint32_t *pTickstart, READER_HAL_CommSettings *pSettings){ READER_Status retVal; uint8_t buffPrologue[READER_T1_BLOCK_PROLOGUE_SIZE]; uint8_t buff[READER_T1_BLOCK_MAX_DATA_SIZE + 2]; /* MAXDATA + MAX CRC */ uint32_t buffSize; uint8_t blockLRC; uint16_t blockCRC; uint32_t count; uint32_t tickstart; /* Quoi qu'il arrive on veut recuperer les trois premiers caracteres du Block (Prologue). */ /* Ensuite, en fonction des valeurs recues, on decide ... */ /* On recoit le premier caractere separepment (on prend en compte le WT entre deux Blocks) */ /* En l'occurence on ajoute le WT du Block au WT du premier caractere */ /* Il s'agit du premier caractere du Prologue */ /* Le extraTimeout est calcule a plus haut niveau ... */ retVal = READER_HAL_RcvCharFrameCount(pSettings, READER_HAL_PROTOCOL_T1, buffPrologue, 1, &count, currentCWT + extraTimeout); if((retVal != READER_OK) && (retVal != READER_TIMEOUT)){ return retVal; } if(retVal == READER_TIMEOUT){ return READER_TIMEOUT; } if(count != 1){ return READER_TIMEOUT; } /* Ensuite on recupere les deux suivants du prologue ... */ retVal = READER_HAL_RcvCharFrameCount(pSettings, READER_HAL_PROTOCOL_T1, buffPrologue +1, READER_T1_BLOCK_PROLOGUE_SIZE-1, &count, currentCWT); if((retVal != READER_OK) && (retVal != READER_TIMEOUT)){ return retVal; } if(retVal == READER_TIMEOUT){ return READER_TIMEOUT; } if(count != READER_T1_BLOCK_PROLOGUE_SIZE -1){ return READER_TIMEOUT; } /* Selon le prologue recu ... */ //rType = READER_T1_GetBlockRedundancyType(pBlock); buffSize = buffPrologue[READER_T1_BLOCKFRAME_LEN_POSITION]; if(buffSize > READER_T1_BLOCK_MAX_DATA_SIZE) return READER_ERR; /* On regarde combien de place il faut prevoir pour recevoir le code correcteur ... */ if(rType == READER_T1_LRC){ buffSize += 1; } else if(rType == READER_T1_CRC){ buffSize += 2; } else{ return READER_ERR; } /* On recoit les data et CRC/LRC d'un seul coups */ retVal = READER_HAL_RcvCharFrameCountTickstart(pSettings, READER_HAL_PROTOCOL_T1, buff, buffSize, &count, currentCWT, &tickstart); if((retVal != READER_OK) && (retVal != READER_TIMEOUT)){ return retVal; } if(retVal == READER_TIMEOUT){ return READER_TIMEOUT; } if(count != buffSize){ return READER_ERR; } /* On mets a jour la date du leading edge du dernier caractere du Block ... */ *pTickstart = tickstart; /* On forge un block vide */ retVal = READER_T1_ForgeBlock(pBlock, rType); if(retVal != READER_OK) return retVal; /* On commence a fabriquer le block a partir des donnees recues ... */ retVal = READER_T1_SetBlockNAD(pBlock, buffPrologue[READER_T1_BLOCKFRAME_NAD_POSITION]); if(retVal != READER_OK) return retVal; retVal = READER_T1_SetBlockPCB(pBlock, buffPrologue[READER_T1_BLOCKFRAME_PCB_POSITION]); if(retVal != READER_OK) return retVal; retVal = READER_T1_SetBlockLEN(pBlock, buffPrologue[READER_T1_BLOCKFRAME_LEN_POSITION]); if(retVal != READER_OK) return retVal; /* Recuperation du code correcteur d'erreur */ if(rType == READER_T1_LRC){ retVal = READER_T1_SetBlockData(pBlock, buff, buffSize -1); if(retVal != READER_OK) return retVal; blockLRC = buff[buffSize-1]; retVal = READER_T1_SetBlockLRC(pBlock, blockLRC); if(retVal != READER_OK) return retVal; } else if(rType == READER_T1_CRC){ retVal = READER_T1_SetBlockData(pBlock, buff, buffSize -2); if(retVal != READER_OK) return retVal; blockCRC = *(uint16_t*)(buff + buffSize - 2); retVal = READER_T1_SetBlockCRC(pBlock, blockCRC); if(retVal != READER_OK) return retVal; } else{ return READER_ERR; } return READER_OK; } READER_Status READER_T1_CheckBlockIntegrity(READER_T1_Block *pBlock, READER_T1_RedundancyType rType){ uint8_t blockLRC, expectedBlockLRC; uint16_t blockCRC, expectedBlockCRC; if(rType == READER_T1_LRC){ expectedBlockLRC = READER_T1_GetBlockLRC(pBlock); blockLRC = READER_T1_ComputeBlockLRC(pBlock); if(expectedBlockLRC != blockLRC) return READER_INTEGRITY; } else if(rType == READER_T1_CRC){ expectedBlockCRC = READER_T1_GetBlockCRC(pBlock); blockCRC = READER_T1_ComputeBlockCRC(pBlock); if(expectedBlockCRC != blockCRC) return READER_INTEGRITY; } else{ return READER_ERR; } return READER_OK; } READER_Status READER_T1_CopyBlock(READER_T1_Block *pBlockDest, READER_T1_Block *pBlockSource){ uint32_t i; uint8_t len; /* Ici, on peut encore optimiser la fonction en ne copiant que les LEN donnees */ for(i=0; i<READER_T1_BLOCK_MAX_TOTAL_LENGTH; i++){ pBlockDest->blockFrame[i] = pBlockSource->blockFrame[i]; } len = READER_T1_GetBlockLEN(pBlockSource); if(len > READER_T1_BLOCK_MAX_DATA_SIZE){ return READER_ERR; } pBlockDest->RedundancyType = pBlockSource->RedundancyType; return READER_OK; } READER_Status READER_T1_CopyBlockData(READER_T1_Block *pBlock, uint8_t *destBuffer, uint32_t destBufferSize){ uint8_t *pBlockData; uint8_t blockLEN; uint32_t i; pBlockData = READER_T1_GetBlockData(pBlock); blockLEN = READER_T1_GetBlockLEN(pBlock); if(blockLEN > destBufferSize){ return READER_OVERFLOW; } for(i=0; i<blockLEN; i++){ destBuffer[i] = pBlockData[i]; } return READER_OK; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include "types.h" #include <sys/queue.h> #include "queue.c" TicketCaller* pc; pthread_mutex_t mutex_cliente; pthread_mutex_t mutex_retrieved_ticket; pthread_mutex_t mutex_queue; sem_t sem_espera_cliente; sem_t* sem_client; sem_t* sem_clerk; sem_t sem_cooker; void client_inform_order(order_t* od, int clerk_id) { pc->clerks_order_spot[clerk_id] = od; sem_post(&sem_clerk[clerk_id]); } void client_think_order() { sleep(rand() % (clientMaxThinkSec + CLIENT_MIN_THINK_SEC) + CLIENT_MIN_THINK_SEC); } void client_wait_order(order_t* od) { sem_wait(&sem_client[od->client_id]); } void clerk_create_order(order_t* od) { pthread_mutex_lock(&mutex_queue); enqueue(od); pthread_mutex_unlock(&mutex_queue); sem_post(&sem_cooker); } void clerk_annotate_order() { sleep(rand() % (clerkMaxWaitSec + CLERK_MIN_WAIT_SEC) + CLERK_MIN_WAIT_SEC); } void cooker_wait_cook_time() { sleep(rand() % (cookMaxWaitSec + COOK_MIN_WAIT_SEC) + COOK_MIN_WAIT_SEC); } void* client(void *args) { client_t client = *(client_t *) args; // Pega o ticket único pthread_mutex_lock(&mutex_cliente); int senha_cliente = get_unique_ticket(pc); pthread_mutex_unlock(&mutex_cliente); // Avisa que chegou um client sem_post(&sem_espera_cliente); int numero_funcionario_chamado; int on_loop = 1; while(on_loop) { int *senhas = show_current_tickets(pc); for (int i = 0; i < numClerks; i++) { if (senhas[i] == senha_cliente) { numero_funcionario_chamado = i; on_loop = 0; } } free(senhas); } client_think_order(); order_t pedido; pedido.password_num = senha_cliente; pedido.client_id = client.id; // Libera o funcionário client_inform_order(&pedido, numero_funcionario_chamado); client_wait_order(&pedido); } void* clerk(void *args) { clerk_t clerk = *(clerk_t *) args; while(true) { while (true) { // Espera um cliente sem_wait(&sem_espera_cliente); // Pega uma senha já retirada pelo cliente pthread_mutex_lock(&mutex_retrieved_ticket); int senha_cliente = get_retrieved_ticket(pc); pthread_mutex_unlock(&mutex_retrieved_ticket); // Coloca set_current_ticket(pc, senha_cliente, clerk.id); if (senha_cliente != -1) { break; } else { sem_post(&sem_espera_cliente); return 0; } } // Espera o client fazer o pedido sem_wait(&sem_clerk[clerk.id]); clerk_annotate_order(); order_t* order = pc->clerks_order_spot[clerk.id]; pc->clerks_order_spot[clerk.id] = NULL; anounce_clerk_order(order); clerk_create_order(order); } } void* cooker(void *args) { int num_plates = 0; while(num_plates < numClients) { sem_wait(&sem_cooker); pthread_mutex_lock(&mutex_queue); order_t *poped_data = dequeue(); pthread_mutex_unlock(&mutex_queue); if (poped_data == NULL) { continue; } num_plates++; cooker_wait_cook_time(); anounce_cooker_order(poped_data); sem_post(&sem_client[poped_data->client_id]); } sem_post(&sem_espera_cliente); } int main(int argc, char *argv[]) { parseArgs(argc, argv); pc = init_ticket_caller(); pthread_mutex_init(&mutex_cliente,NULL); pthread_mutex_init(&mutex_retrieved_ticket,NULL); pthread_mutex_init(&mutex_queue,NULL); sem_init(&sem_espera_cliente,0,0); sem_init(&sem_cooker,0,0); sem_client = malloc(numClients*sizeof(sem_t)); sem_clerk = malloc(numClerks*sizeof(sem_t)); for (int i = 0; i < numClients; i++) { sem_init(&sem_client[i], 0, 0); } for (int i = 0; i < numClerks; i++) { sem_init(&sem_clerk[i], 0, 0); } client_t cliente[numClients]; clerk_t atendente[numClerks]; pthread_t thread_clientes[numClients]; pthread_t thread_funcionarios[numClerks]; pthread_t thread_cooker; if (numClerks != 0) { for (int i = 0; i < numClients; i++) { cliente[i].id = i; pthread_create(&thread_clientes[i], NULL, client, (void *)&cliente[i]); } for (int i = 0; i < numClerks; i++) { atendente[i].id = i; pthread_create(&thread_funcionarios[i],NULL,clerk, (void *)&atendente[i]); } pthread_create(&thread_cooker, NULL, cooker, NULL); for (int i = 0; i < numClients; i++) { pthread_join(thread_clientes[i], NULL); } for (int i = 0; i < numClerks; i++) { pthread_join(thread_funcionarios[i],NULL); } pthread_join(thread_cooker, NULL); } for (int i = 0; i < numClients; i++) { sem_destroy(&sem_client[i]); } for (int i = 0; i < numClerks; i++) { sem_destroy(&sem_clerk[i]); } sem_destroy(&sem_espera_cliente); sem_destroy(&sem_cooker); pthread_mutex_destroy(&mutex_queue); pthread_mutex_destroy(&mutex_retrieved_ticket); pthread_mutex_destroy(&mutex_cliente); return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <fcntl.h> #include <signal.h> #include "cmdline.h" #define BUFLEN 1024 #define OK 0 #define KO 1 /** * Test a command line "str" * * This function is static : it means that it is a local function, accessible only in this source file. * This function prints "TEST OK!" if line_parse() returns a value consistent with the one transmitted * via the parameter "expected", and another significant message otherwise * * @param str command line to test * @param expected OK if the command line is expected to be valid, KO otherwise */ static void try(const char *str, int expected) { static int n = 0; static struct line li; if (n == 0){ line_init(&li); } printf("TEST #%i\n", ++n); int err = line_parse(&li, str); if ((!!err) != (!!expected)) { printf("UNEXPECTED RETURN WITH: %s\n", str); } else { if (err){ printf("Command line : %s", str); } printf("TEST OK!\n"); } line_reset(&li); } int main() { // things working try("bar\n", OK); try("bar baz\n", OK); try("bar 123\n", OK); try("bar > baz\n", OK); try("bar < baz\n", OK); try("bar > baz < qux\n", OK); try("bar &\n", OK); try("bar > baz &\n", OK); try("bar < baz &\n", OK); try("bar > baz < qux &\n", OK); try("bar | baz\n", OK); try("bar | baz &\n", OK); try("bar | baz > qux\n", OK); try("bar | > qux baz\n", OK); try("bar < qux | baz\n", OK); try("< qux bar | baz\n", OK); try("< fic1 bar > fic2 bar1\n", OK); try("bar bar1 < qux | baz\n", OK); try("bar < qux baz\n", OK); try("bar > qux baz\n", OK); try("bar | baz | qux\n", OK); try("bar \"baz\"\n", OK); try("bar \"baz qux\"\n", OK); try(" \n", OK); try("\n", OK); // things not working try("bar \"bar\n", KO); try("bar & | baz\n", KO); try("bar > qux | baz\n", KO); try("bar > qux |\n", KO); try("bar | | barz\n", KO); try("|\n", KO); try("bar > qux > baz\n", KO); try("bar & > qux\n", KO); try("bar >\n", KO); try("bar > qu&x\n", KO); try("bar > >\n", KO); try("bar < qux < baz\n", KO); try("bar < qux <\n", KO); try("bar & < qux\n", KO); try("bar bar | baz < qux\n", KO); try("bar | < qux\n", KO); try("bar < \n", KO); try("bar <\n", KO); try("bar < < baz\n", KO); try("bar < <baz\n", KO); try("bar & &\n", KO); try("bar | &\n", KO); try("& \n", KO); try("bar & baz\n", KO); try("bar & ba&z\n", KO); try("bar << baz\n", KO); try("bar &ml baz\n", KO); try("bar |\n", KO); try("bar | > qux\n", KO); try("< qux \n", KO); try("< fic1 > fic2\n", KO); try("> qux \n", KO); return 0; }
C
#include <stdio.h> #include <stdlib.h> typedef struct Node Node; typedef struct Node { int data; Node* Node; }Node; void addNode(Node* head, int data); void DelNode(Node* head); int main() { int N; scanf("%d", &N); if (N == 1) { printf("0"); return 0; } int j; Node* head1 = (Node*)malloc(sizeof(Node)); head1->data = -1; head1->Node = NULL; addNode(head1, N); Node* head2 = (Node*)malloc(sizeof(Node)); head2->data = -1; head2->Node = NULL; int count = 0; Node* tmpNode; for (j = 0; j < N; j++) { count++; tmpNode = head1->Node; //printf("%d\n", tmpNode->data); while (tmpNode != NULL) { if(tmpNode->data%3 == 0) { if (tmpNode->data / 3 == 1) { j = N; break; } addNode(head2, tmpNode->data / 3); } if(tmpNode->data%2 == 0) { if (tmpNode->data / 2 == 1) { j = N; break; } addNode(head2, tmpNode->data / 2); } if (tmpNode->data == 1) { j = N; break; } addNode(head2, tmpNode->data - 1); tmpNode = tmpNode->Node; } DelNode(head1); head1->Node = head2->Node; head2->Node = NULL; } printf("%d", count); return 0; } void addNode(Node* head, int data) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = data; newNode->Node = head->Node; head->Node = newNode; } void DelNode(Node* head) { Node* tmpNode, *DelNode; tmpNode = head->Node; head->Node = NULL; while (tmpNode != NULL) { DelNode = tmpNode; tmpNode = tmpNode->Node; free(DelNode); } }
C
#include <stdio.h> int a=22; void print(){ a=2; printf("a is %i\n",a); } void print1() { a=9; printf("a is %i\n",a); } int main() { int c; printf("i is%i\n",c); print(); print1(); return 0; }
C
#include <unittests.h> #include <pb_encode.h> #include "short_array.pb.h" int main() { int status = 0; COMMENT("Test message length calculation for short arrays"); { uint8_t buffer[TestMessage_size] = {0}; pb_ostream_t ostream = pb_ostream_from_buffer(buffer, TestMessage_size); TestMessage msg = TestMessage_init_zero; msg.rep_uint32_count = 1; msg.rep_uint32[0] = ((uint32_t)1 << 31); TEST(pb_encode(&ostream, TestMessage_fields, &msg)); TEST(ostream.bytes_written == TestMessage_size); } return status; }
C
#include<stdio.h> #include<stdlib.h> void traversei (int arr[],int len); void traversei (int arr[],int len){ for(int i=0;i<len;i++) { printf("%d ",arr[i]); } }
C
#include <stdio.h> #include <stdlib.h> // on_exit static void exit_handler(int status, void *arg) { printf("exit status: %d, arg: %s\n", status, (char *)arg); } // atexit static void exit_handler2() { printf("exit_handler2()\n"); } // atexit static void exit_handler3() { printf("exit_handler3()\n"); } int main() { char* reason = "some reason"; int i; char strs[3][80]; for (i = 0; i < 3; i++) { sprintf(strs[i], "[%d] %s", i, reason); // 注意: 为了逻辑清晰, 忽略了检查返回值 on_exit(exit_handler, strs[i]); } // 注意: 为了逻辑清晰, 忽略了检查返回值 atexit(exit_handler2); atexit(exit_handler3); // exit_handler3() // exit_handler2() // exit status: 233, arg: � // exit status: 233, arg: // exit status: 233, arg: // return (233); // exit_handler3() // exit_handler2() // exit status: 233, arg: [2] some reason // exit status: 233, arg: [1] some reason // exit status: 233, arg: [0] some reason exit(233); }
C
/* $Id$ */ /* This file contains the expression evaluator. It exports the following routines: - int eval_cond(p_tree p) This routine evaluates the conditional expression indicated by p and returns 1 if it evaluates to TRUE, or 0 if it could not be evaluated for some reason or if it evalutes to FALSE. If the expression cannot be evaluated, an error message is given. - int eval_desig(p_tree p, t_addr *paddr, long **psize, p_type *ptp) This routine evaluates the expression indicated by p, which should result in a designator. The result of the expression is an address which is to be found in *paddr. *psize will contain the size of the designated object, and *ptp its type. If the expression cannot be evaluated or does not result in a designator, 0 is returned and an error message is given. Otherwise, 1 is returned. - int eval_expr(p_tree p, char **pbuf, long **psize, p_type *ptp) This routine evaluates the expression indicated by p. The result of the expression is left in *pbuf. *psize will contain the size of the value, and *ptp its type. If the expression cannot be evaluated, 0 is returned and an error message is given. Otherwise, 1 is returned. - int convert(char **pbuf, long *psize, p_type *ptp, p_type tp, long size) This routine tries to convert the value in pbuf of size psize and type ptp to type tp with size size. It returns 0 if this fails, while producing an error message. Otherwise, it returns 1 and the resulting value, type and size are left in pbuf, ptp, and psize, respectively. - long get_int(char *buf, long size, int class) Returns the value of size 'size', residing in 'buf', of 'class' T_INTEGER, T_UNSIGNED, or T_ENUM. - int put_int(char *buf, long size, long value) Stores the value 'value' of size 'size' in 'buf'. - double get_real(char *buf, long size) Returns the real value of size 'size', residing in 'buf'. T_INTEGER, T_UNSIGNED, or T_ENUM. - int put_real(char *buf, long size, double value) Stores the value 'value' of size 'size' in 'buf'. */ #include <stdio.h> #include <alloc.h> #include <assert.h> #include "position.h" #include "operator.h" #include "tree.h" #include "expr.h" #include "symbol.h" #include "type.h" #include "langdep.h" #include "scope.h" #include "idf.h" #include "misc.h" extern FILE *db_out; extern int stack_offset; extern char *strcpy(); extern t_addr *get_EM_regs(); extern char *memcpy(); extern char *malloc(), *realloc(); #define malloc_succeeded(p) if (! (p)) {\ error("could not allocate enough memory");\ return 0;\ } /* static t_addr get_addr(p_symbol sym; long *psize); Get the address of the object indicated by sym. Returns 0 on failure, address on success. *psize will contain size of object. For local variables or parameters, the 'stack_offset' variable is used to determine from which stack frame the search must start. */ static t_addr get_addr(sym, psize) register p_symbol sym; long *psize; { p_type tp = sym->sy_type; long size = tp->ty_size; t_addr *EM_regs; int i; p_scope sc, symsc; *psize = size; switch(sym->sy_class) { case VAR: /* exists if child exists; nm_value contains addres */ return (t_addr) sym->sy_name.nm_value; case VARPAR: case LOCVAR: /* first find the stack frame in which it resides */ symsc = base_scope(sym->sy_scope); /* now symsc contains the scope where the storage for sym is allocated. Now find it on the stack of child. */ i = stack_offset; for (;;) { sc = 0; if (! (EM_regs = get_EM_regs(i++))) { return 0; } if (! EM_regs[1]) { error("%s not available", sym->sy_idf->id_text); return 0; } sc = base_scope(get_scope_from_addr(EM_regs[2])); if (! sc || sc->sc_start > EM_regs[2]) { error("%s not available", sym->sy_idf->id_text); sc = 0; return 0; } if (sc == symsc) break; /* found it */ } if (sym->sy_class == LOCVAR) { /* Either local variable or value parameter */ return EM_regs[sym->sy_name.nm_value < 0 ? 0 : 1] + (t_addr) sym->sy_name.nm_value; } /* If we get here, we have a var parameter. Get the parameters of the current procedure invocation. */ { p_type proctype = sc->sc_definedby->sy_type; t_addr a; char *AB; size = proctype->ty_nbparams; if (has_static_link(sc)) size += pointer_size; AB = malloc((unsigned) size); if (! AB) { error("could not allocate enough memory"); break; } if (! get_bytes(size, EM_regs[1], AB)) { break; } if ((size = tp->ty_size) == 0) { size = compute_size(tp, AB); *psize = size; } a = (t_addr) get_int(AB+sym->sy_name.nm_value, pointer_size, T_UNSIGNED); free(AB); return a; } default: error("%s is not a variable", sym->sy_idf->id_text); break; } return 0; } static int get_v(a, pbuf, size) t_addr a; char **pbuf; long size; { if (a) { *pbuf = malloc((unsigned) size); if (! *pbuf) { error("could not allocate enough memory"); return 0; } if (! get_bytes(size, a, *pbuf)) return 0; return 1; } return 0; } /* static int get_value(p_symbol sym; char **pbuf; long *psize); Get the value of the symbol indicated by sym. Return 0 on failure, 1 on success. On success, 'pbuf' contains the value, and 'psize' contains the size. For 'pbuf', storage is allocated by malloc; this storage must be freed by caller (I don't like this any more than you do, but caller does not know sizes). For local variables or parameters, the 'stack_offset' variable is used to determine from which stack frame the search must start. */ static int get_value(sym, pbuf, psize) register p_symbol sym; char **pbuf; long *psize; { p_type tp = sym->sy_type; int retval = 0; t_addr a; long size = tp->ty_size; *pbuf = 0; switch(sym->sy_class) { case CONST: *pbuf = malloc((unsigned) size); if (! *pbuf) { error("could not allocate enough memory"); break; } switch(tp->ty_class) { case T_REAL: put_real(*pbuf, size, sym->sy_const.co_rval); break; case T_INTEGER: case T_SUBRANGE: case T_UNSIGNED: case T_ENUM: put_int(*pbuf, size, sym->sy_const.co_ival); break; case T_SET: memcpy(*pbuf, sym->sy_const.co_setval, (int) size); break; case T_STRING: memcpy(*pbuf, sym->sy_const.co_sval, (int) size); break; default: fatal("strange constant"); } retval = 1; break; case VAR: case VARPAR: case LOCVAR: a = get_addr(sym, psize); retval = get_v(a, pbuf, *psize); size = *psize; break; case UBOUND: a = get_addr(sym->sy_descr, psize); retval = get_v(a, pbuf, *psize); if (! retval) break; size = get_int(*pbuf, *psize, T_INTEGER); retval = get_v(a+*psize, pbuf, *psize); if (! retval) break; size += get_int(*pbuf, *psize, T_INTEGER); put_int(*pbuf, *psize, size); size = *psize; break; case LBOUND: a = get_addr(sym->sy_descr, psize); retval = get_v(a, pbuf, *psize); break; } if (retval == 0) { if (*pbuf) free(*pbuf); *pbuf = 0; *psize = 0; } else *psize = size; return retval; } /* buffer to integer and vice versa routines */ long get_int(buf, size, class) char *buf; long size; int class; { register long l; switch((int)size) { case sizeof(char): l = *buf; if (class == T_INTEGER && l >= 0x7F) l -= 256; else if (class != T_INTEGER && l < 0) l += 256; break; case sizeof(short): l = *((short *) buf); if (class == T_INTEGER && l >= 0x7FFF) l -= 65536; else if (class != T_INTEGER && l < 0) l += 65536; break; default: l = *((long *) buf); } return l; } put_int(buf, size, value) char *buf; long size; long value; { switch((int)size) { case sizeof(char): *buf = value; break; case sizeof(short): *((short *) buf) = value; break; default: *((long *) buf) = value; break; } /*NOTREACHED*/ } /* buffer to real and vice versa routines */ double get_real(buf, size) char *buf; long size; { switch((int) size) { case sizeof(float): return *((float *) buf); default: return *((double *) buf); } /*NOTREACHED*/ } put_real(buf, size, value) char *buf; long size; double value; { switch((int)size) { case sizeof(float): *((float *) buf) = value; break; default: *((double *) buf) = value; break; } /* NOTREACHED */ } int convert(pbuf, psize, ptp, tp, size) char **pbuf; long *psize; register p_type *ptp; register p_type tp; long size; { /* Convert the value in pbuf, of size psize and type ptp, to type tp and leave the resulting value in pbuf, the resulting size in psize, and the resulting type in ptp. */ long l; double d; if (*ptp == tp) return 1; if (size > *psize) { *pbuf = realloc(*pbuf, (unsigned int) size); malloc_succeeded(*pbuf); } if ((*ptp)->ty_class == T_SUBRANGE) *ptp = (*ptp)->ty_base; if (tp && *ptp) switch((*ptp)->ty_class) { case T_INTEGER: case T_UNSIGNED: case T_POINTER: case T_ENUM: l = get_int(*pbuf, *psize, (*ptp)->ty_class); if (tp == bool_type) l = l != 0; switch(tp->ty_class) { case T_SUBRANGE: case T_INTEGER: case T_UNSIGNED: case T_POINTER: case T_ENUM: put_int(*pbuf, size, l); *psize = size; *ptp = tp; return 1; case T_REAL: put_real(*pbuf, size, (*ptp)->ty_class == T_INTEGER ? (double) l : (double) (unsigned long) l); *psize = size; *ptp = tp; return 1; default: break; } break; case T_REAL: d = get_real(*pbuf, *psize); switch(tp->ty_class) { case T_ENUM: case T_SUBRANGE: case T_INTEGER: case T_UNSIGNED: case T_POINTER: if (tp == bool_type) put_int(*pbuf, size, (long) (d != 0)); else put_int(*pbuf, size, (long) d); *psize = size; *ptp = tp; return 1; case T_REAL: put_real(*pbuf, size, d); *psize = size; *ptp = tp; return 1; default: break; } break; default: break; } error("illegal conversion"); return 0; } int eval_cond(p) p_tree p; { char *buf; long size; p_type tp; long val; p_type target_tp = currlang->has_bool_type ? bool_type : int_type; if (eval_expr(p, &buf, &size, &tp)) { if (convert(&buf, &size, &tp, target_tp, target_tp->ty_size)) { val = get_int(buf, size, T_UNSIGNED); free(buf); return (int) (val != 0); } free(buf); } return 0; } /* one routine for each unary operator */ static int not_op(p, pbuf, psize, ptp) p_tree p; char **pbuf; long *psize; p_type *ptp; { p_type target_tp = currlang->has_bool_type ? bool_type : int_type; if (eval_expr(p->t_args[0], pbuf, psize, ptp) && convert(pbuf, psize, ptp, target_tp, target_tp->ty_size)) { put_int(*pbuf, *psize, (long) !get_int(*pbuf, *psize, T_UNSIGNED)); return 1; } return 0; } static int bnot_op(p, pbuf, psize, ptp) p_tree p; char **pbuf; long *psize; p_type *ptp; { if (eval_expr(p->t_args[0], pbuf, psize, ptp)) { switch((*ptp)->ty_class) { case T_INTEGER: case T_ENUM: case T_UNSIGNED: case T_SUBRANGE: put_int(*pbuf, *psize, ~get_int(*pbuf, *psize, T_UNSIGNED)); return 1; default: error("illegal operand type(s)"); break; } } return 0; } static int ptr_addr(p, paddr, psize, ptp) p_tree p; t_addr *paddr; long *psize; p_type *ptp; { char *buf; if (eval_expr(p->t_args[0], &buf, psize, ptp)) { switch((*ptp)->ty_class) { case T_POINTER: *ptp = (*ptp)->ty_ptrto; *psize = (*ptp)->ty_size; *paddr = get_int(buf, pointer_size, T_UNSIGNED); free(buf); return 1; default: error("illegal operand of DEREF"); free(buf); break; } } return 0; } static int deref_op(p, pbuf, psize, ptp) p_tree p; char **pbuf; long *psize; p_type *ptp; { t_addr addr; if (ptr_addr(p, &addr, psize, ptp)) { *pbuf = malloc((unsigned) *psize); malloc_succeeded(*pbuf); if (! get_bytes(*psize, addr, *pbuf)) { free(*pbuf); *pbuf = 0; return 0; } return 1; } return 0; } static int addr_op(p, pbuf, psize, ptp) p_tree p; char **pbuf; long *psize; p_type *ptp; { t_addr addr; if (eval_desig(p->t_args[0], &addr, psize, ptp)) { *pbuf = malloc((unsigned) pointer_size); malloc_succeeded(*pbuf); put_int(*pbuf, pointer_size, (long) addr); address_type->ty_ptrto = *ptp; *ptp = address_type; return 1; } return 0; } static int unmin_op(p, pbuf, psize, ptp) p_tree p; char **pbuf; long *psize; p_type *ptp; { if (eval_expr(p->t_args[0], pbuf, psize, ptp)) { switch((*ptp)->ty_class) { case T_SUBRANGE: case T_INTEGER: case T_ENUM: case T_UNSIGNED: put_int(*pbuf, *psize, -get_int(*pbuf, *psize, (*ptp)->ty_class)); return 1; case T_REAL: put_real(*pbuf, *psize, -get_real(*pbuf, *psize)); return 1; default: error("illegal operand of unary -"); break; } } return 0; } static int unplus_op(p, pbuf, psize, ptp) p_tree p; char **pbuf; long *psize; p_type *ptp; { if (eval_expr(p->t_args[0], pbuf, psize, ptp)) { switch((*ptp)->ty_class) { case T_SUBRANGE: case T_INTEGER: case T_ENUM: case T_UNSIGNED: case T_REAL: return 1; default: error("illegal operand of unary +"); break; } } return 0; } static int (*un_op[])() = { 0, not_op, deref_op, 0, 0, 0, 0, 0, 0, 0, 0, unplus_op, unmin_op, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, bnot_op, 0, 0, 0, addr_op }; static p_type balance(tp1, tp2) p_type tp1, tp2; { if (tp1->ty_class == T_SUBRANGE) tp1 = tp1->ty_base; if (tp2->ty_class == T_SUBRANGE) tp2 = tp2->ty_base; if (tp1 == tp2) return tp2; if (tp2->ty_class == T_REAL) { p_type tmp = tp1; tp1 = tp2; tp2 = tmp; } if (tp1->ty_class == T_REAL) { switch(tp2->ty_class) { case T_INTEGER: case T_UNSIGNED: case T_ENUM: return tp1; case T_REAL: return tp1->ty_size > tp2->ty_size ? tp1 : tp2; default: error("illegal type combination"); return 0; } } if (tp2->ty_class == T_POINTER) { p_type tmp = tp1; tp1 = tp2; tp2 = tmp; } if (tp1->ty_class == T_POINTER) { switch(tp2->ty_class) { case T_INTEGER: case T_UNSIGNED: case T_POINTER: case T_ENUM: return tp1; default: error("illegal type combination"); return 0; } } if (tp2->ty_class == T_UNSIGNED) { p_type tmp = tp1; tp1 = tp2; tp2 = tmp; } if (tp1->ty_class == T_UNSIGNED) { switch(tp2->ty_class) { case T_INTEGER: case T_UNSIGNED: if (tp1->ty_size >= tp2->ty_size) return tp1; return tp2; case T_ENUM: return tp1; default: error("illegal type combination"); return 0; } } if (tp2->ty_class == T_INTEGER) { p_type tmp = tp1; tp1 = tp2; tp2 = tmp; } if (tp1->ty_class == T_INTEGER) { switch(tp2->ty_class) { case T_INTEGER: if (tp1->ty_size >= tp2->ty_size) return tp1; return tp2; case T_ENUM: return tp1; default: error("illegal type combination"); return 0; } } error("illegal type combination"); return 0; } static int andor_op(p, pbuf, psize, ptp) p_tree p; char **pbuf; long *psize; p_type *ptp; { long l1, l2; char *buf = 0; long size; p_type tp; p_type target_tp = currlang->has_bool_type ? bool_type : int_type; if (eval_expr(p->t_args[0], pbuf, psize, ptp) && convert(pbuf, psize, ptp, target_tp, target_tp->ty_size) && eval_expr(p->t_args[1], &buf, &size, &tp) && convert(&buf, &size, &tp, target_tp, target_tp->ty_size)) { l1 = get_int(*pbuf, *psize, T_UNSIGNED); l2 = get_int(buf, size, T_UNSIGNED); put_int(*pbuf, *psize, p->t_whichoper == E_AND ? (long)(l1 && l2) : (long)(l1 || l2)); free(buf); return 1; } if (buf) free(buf); return 0; } static int arith_op(p, pbuf, psize, ptp) p_tree p; char **pbuf; long *psize; p_type *ptp; { long l1, l2; double d1, d2; char *buf = 0; long size; p_type tp, balance_tp; if (!(eval_expr(p->t_args[0], pbuf, psize, ptp) && eval_expr(p->t_args[1], &buf, &size, &tp))) { return 0; } if ((*ptp)->ty_class == T_POINTER) { if (currlang != c_dep || (p->t_whichoper != E_PLUS && p->t_whichoper != E_MIN)) { error("illegal operand type(s)"); free(buf); return 0; } l1 = get_int(*pbuf, *psize, T_UNSIGNED); if (tp->ty_class == T_POINTER) { if (p->t_whichoper != E_MIN) { error("illegal operand type(s)"); free(buf); return 0; } l2 = get_int(buf, size, T_UNSIGNED); free(buf); *pbuf = Realloc(*pbuf, (unsigned) long_size); put_int(*pbuf, long_size, (l1 - l2)/(*ptp)->ty_ptrto->ty_size); *ptp = long_type; return 1; } if (! convert(&buf, &size, &tp, long_type, long_size)) { free(buf); return 0; } l2 = get_int(buf, size, T_INTEGER) * (*ptp)->ty_ptrto->ty_size; free(buf); buf = 0; if (p->t_whichoper == E_PLUS) l1 += l2; else l1 -= l2; put_int(*pbuf, *psize, l1); return 1; } if ((balance_tp = balance(*ptp, tp)) && convert(pbuf, psize, ptp, balance_tp, balance_tp->ty_size) && convert(&buf, &size, &tp, balance_tp, balance_tp->ty_size)) { switch(balance_tp->ty_class) { case T_INTEGER: case T_ENUM: case T_UNSIGNED: l1 = get_int(*pbuf, *psize, balance_tp->ty_class); l2 = get_int(buf, size, balance_tp->ty_class); free(buf); buf = 0; switch(p->t_whichoper) { case E_BAND: l1 &= l2; break; case E_BOR: l1 |= l2; break; case E_BXOR: l1 ^= l2; break; case E_PLUS: l1 += l2; break; case E_MIN: l1 -= l2; break; case E_MUL: l1 *= l2; break; case E_DIV: case E_ZDIV: if (! l2) { error("division by 0"); return 0; } if (balance_tp->ty_class == T_INTEGER) { if ((l1 < 0) != (l2 < 0)) { if (l1 < 0) l1 = - l1; else l2 = -l2; if (p->t_whichoper == E_DIV) { l1 = -((l1+l2-1)/l2); } else { l1 = -(l1/l2); } } else l1 /= l2; } else l1 = (unsigned long) l1 / (unsigned long) l2; break; case E_MOD: case E_ZMOD: if (! l2) { error("modulo by 0"); return 0; } if (balance_tp->ty_class == T_INTEGER) { if ((l1 < 0) != (l2 < 0)) { if (l1 < 0) l1 = - l1; else l2 = -l2; if (p->t_whichoper == E_MOD) { l1 = ((l1+l2-1)/l2)*l2 - l1; } else { l1 = (l1/l2)*l2 - l1; } } else l1 %= l2; } else l1 = (unsigned long) l1 % (unsigned long) l2; break; } put_int(*pbuf, *psize, l1); break; case T_REAL: d1 = get_real(*pbuf, *psize); d2 = get_real(buf, size); free(buf); buf = 0; switch(p->t_whichoper) { case E_DIV: case E_ZDIV: if (d2 == 0.0) { error("division by 0.0"); return 0; } d1 /= d2; break; case E_PLUS: d1 += d2; break; case E_MIN: d1 -= d2; break; case E_MUL: d1 *= d2; break; } put_real(*pbuf, *psize, d1); break; default: error("illegal operand type(s)"); free(buf); return 0; } return 1; } if (buf) free(buf); return 0; } static int sft_op(p, pbuf, psize, ptp) p_tree p; char **pbuf; long *psize; p_type *ptp; { long l1, l2; char *buf = 0; long size; p_type tp; if (eval_expr(p->t_args[0], pbuf, psize, ptp) && eval_expr(p->t_args[1], &buf, &size, &tp) && convert(&buf, &size, &tp, int_type, int_size)) { tp = *ptp; if (tp->ty_class == T_SUBRANGE) { tp = tp->ty_base; } switch(tp->ty_class) { case T_INTEGER: case T_ENUM: case T_UNSIGNED: l1 = get_int(*pbuf, *psize, tp->ty_class); l2 = get_int(buf, size, T_INTEGER); free(buf); buf = 0; switch(p->t_whichoper) { case E_LSFT: l1 <<= (int) l2; break; case E_RSFT: if (tp->ty_class == T_INTEGER) l1 >>= (int) l2; else l1 = (unsigned long) l1 >> (int) l2; break; } break; default: error("illegal operand type(s)"); free(buf); return 0; } return 1; } if (buf) free(buf); return 0; } static int cmp_op(p, pbuf, psize, ptp) p_tree p; char **pbuf; long *psize; p_type *ptp; { long l1, l2; double d1, d2; char *buf = 0; long size; p_type tp, balance_tp; if (eval_expr(p->t_args[0], pbuf, psize, ptp) && eval_expr(p->t_args[1], &buf, &size, &tp) && (balance_tp = balance(*ptp, tp)) && convert(pbuf, psize, ptp, balance_tp, balance_tp->ty_size) && convert(&buf, &size, &tp, balance_tp, balance_tp->ty_size)) { switch(balance_tp->ty_class) { case T_INTEGER: case T_ENUM: case T_UNSIGNED: case T_POINTER: l1 = get_int(*pbuf, *psize, balance_tp->ty_class); l2 = get_int(buf, size, balance_tp->ty_class); free(buf); buf = 0; switch(p->t_whichoper) { case E_EQUAL: l1 = l1 == l2; break; case E_NOTEQUAL: l1 = l1 != l2; break; case E_LTEQUAL: if (balance_tp->ty_class == T_INTEGER) { l1 = l1 <= l2; } else l1 = (unsigned long) l1 <= (unsigned long) l2; break; case E_LT: if (balance_tp->ty_class == T_INTEGER) { l1 = l1 < l2; } else l1 = (unsigned long) l1 < (unsigned long) l2; break; case E_GTEQUAL: if (balance_tp->ty_class == T_INTEGER) { l1 = l1 >= l2; } else l1 = (unsigned long) l1 >= (unsigned long) l2; break; case E_GT: if (balance_tp->ty_class == T_INTEGER) { l1 = l1 > l2; } else l1 = (unsigned long) l1 > (unsigned long) l2; break; default: l1 = 0; assert(0); break; } break; case T_REAL: d1 = get_real(*pbuf, *psize); d2 = get_real(buf, size); free(buf); buf = 0; switch(p->t_whichoper) { case E_EQUAL: l1 = d1 == d2; break; case E_NOTEQUAL: l1 = d1 != d2; break; case E_LTEQUAL: l1 = d1 <= d2; break; case E_LT: l1 = d1 < d2; break; case E_GTEQUAL: l1 = d1 >= d2; break; case E_GT: l1 = d1 > d2; break; default: l1 = 0; assert(0); break; } break; default: error("illegal operand type(s)"); free(buf); return 0; } if (*psize < int_size) { *psize = int_size; *pbuf = realloc(*pbuf, (unsigned int) int_size); malloc_succeeded(*pbuf); } else *psize = int_size; if (currlang->has_bool_type) { *ptp = bool_type; } else *ptp = int_type; put_int(*pbuf, *psize, l1); return 1; } if (buf) free(buf); return 0; } static int in_op(p, pbuf, psize, ptp) p_tree p; char **pbuf; long *psize; p_type *ptp; { long l; char *buf = 0; long size; p_type tp; int sft = int_size == 2 ? 4 : 5; if (eval_expr(p->t_args[0], pbuf, psize, ptp) && eval_expr(p->t_args[1], &buf, &size, &tp)) { if (tp->ty_class != T_SET) { error("right-hand side of IN not a set"); free(buf); return 0; } if (! convert(pbuf, psize, ptp, tp->ty_setbase, int_size)) { free(buf); return 0; } l = get_int(*pbuf, *psize, (*ptp)->ty_class) - tp->ty_setlow; l = l >= 0 && l <= (size << 3) && (((int *) buf)[(int)(l>>sft)] & (1 << (l & ((1 << sft)-1)))); free(buf); *pbuf = realloc(*pbuf, (unsigned) int_size); malloc_succeeded(*pbuf); *psize = int_size; *ptp = currlang->has_bool_type ? bool_type : int_type; put_int(*pbuf, *psize, l); return 1; } return 0; } static int array_addr(p, paddr, psize, ptp) p_tree p; t_addr *paddr; long *psize; p_type *ptp; { long l; char *buf = 0; long size; p_type tp; if (eval_desig(p->t_args[0], paddr, psize, ptp) && eval_expr(p->t_args[1], &buf, &size, &tp)) { if ((*ptp)->ty_class != T_ARRAY && (*ptp)->ty_class != T_POINTER) { error("illegal left-hand side of ["); free(buf); return 0; } if ((*ptp)->ty_class == T_POINTER) { if (! get_bytes(pointer_size, *paddr, (char *) paddr)) { free(buf); return 0; } *paddr = get_int((char *) paddr, pointer_size, T_UNSIGNED); } if (! convert(&buf, &size, &tp, int_type, int_size)) { free(buf); return 0; } l = get_int(buf, size, T_INTEGER); free(buf); buf = 0; if ((*ptp)->ty_class == T_ARRAY) { if (l < (*ptp)->ty_lb || l > (*ptp)->ty_hb) { error("array bound error"); return 0; } l -= (*ptp)->ty_lb; *ptp = (*ptp)->ty_elements; l *= (*currlang->arrayelsize)((*ptp)->ty_size); } else { *ptp = (*ptp)->ty_ptrto; l *= (*ptp)->ty_size; } *psize = (*ptp)->ty_size; *paddr += l; return 1; } return 0; } static int array_op(p, pbuf, psize, ptp) p_tree p; char **pbuf; long *psize; p_type *ptp; { t_addr a; if (array_addr(p, &a, psize, ptp)) { *pbuf = malloc((unsigned int) *psize); malloc_succeeded(*pbuf); if (! get_bytes(*psize, a, *pbuf)) { return 0; } return 1; } return 0; } static int select_addr(p, paddr, psize, ptp) p_tree p; t_addr *paddr; long *psize; p_type *ptp; { register p_type tp; register struct fields *f; register int nf; if (eval_desig(p->t_args[0], paddr, psize, ptp)) { tp = *ptp; if (tp->ty_class != T_STRUCT && tp->ty_class != T_UNION) { error("SELECT on non-struct"); return 0; } if (p->t_args[1]->t_oper != OP_NAME) { error("right-hand side of SELECT not a name"); return 0; } for (nf = tp->ty_nfields, f = tp->ty_fields; nf; nf--, f++) { if (! strcmp(f->fld_name, p->t_args[1]->t_str)) break; } if (! nf) { error("'%s' not found", p->t_args[1]->t_str); return 0; } /* ??? this needs some work for bitfields ??? */ *paddr += f->fld_pos>>3; *psize = f->fld_bitsize >> 3; *ptp = f->fld_type; return 1; } return 0; } static int select_op(p, pbuf, psize, ptp) p_tree p; char **pbuf; long *psize; p_type *ptp; { t_addr a; if (select_addr(p, &a, psize, ptp)) { *pbuf = malloc((unsigned int) *psize); malloc_succeeded(*pbuf); if (! get_bytes(*psize, a, *pbuf)) { free(*pbuf); *pbuf = 0; return 0; } return 1; } return 0; } static int derselect_op(p, pbuf, psize, ptp) p_tree p; char **pbuf; long *psize; p_type *ptp; { int retval; t_tree t; t.t_oper = OP_UNOP; t.t_whichoper = E_DEREF; t.t_args[0] = p->t_args[0]; p->t_args[0] = &t; p->t_whichoper = E_SELECT; retval = eval_expr(p, pbuf, psize, ptp); p->t_args[0] = t.t_args[0]; p->t_whichoper = E_DERSELECT; return retval; } static int (*bin_op[])() = { 0, 0, 0, andor_op, andor_op, arith_op, arith_op, arith_op, arith_op, in_op, array_op, arith_op, arith_op, arith_op, cmp_op, cmp_op, cmp_op, cmp_op, cmp_op, cmp_op, select_op, arith_op, arith_op, arith_op, 0, derselect_op, sft_op, sft_op, 0 }; int eval_expr(p, pbuf, psize, ptp) p_tree p; char **pbuf; long *psize; p_type *ptp; { register p_symbol sym; int retval = 0; *pbuf = 0; switch(p->t_oper) { case OP_FORMAT: if (eval_expr(p->t_args[0], pbuf, psize, ptp)) retval = 1; break; case OP_NAME: case OP_SELECT: sym = identify(p, VAR|REGVAR|LOCVAR|VARPAR|CONST|LBOUND|UBOUND); if (! sym) return 0; if (! get_value(sym, pbuf, psize)) { break; } *ptp = sym->sy_type; retval = 1; break; case OP_INTEGER: *pbuf = malloc((unsigned int) long_size); malloc_succeeded(*pbuf); *psize = long_size; *ptp = long_type; put_int(*pbuf, long_size, p->t_ival); retval = 1; break; case OP_REAL: *pbuf = malloc((unsigned int) double_size); malloc_succeeded(*pbuf); *psize = double_size; *ptp = double_type; put_real(*pbuf, double_size, p->t_fval); retval = 1; break; case OP_STRING: *psize = strlen(p->t_sval)+1; *pbuf = malloc((unsigned int)*psize); malloc_succeeded(*pbuf); *ptp = string_type; strcpy(*pbuf, p->t_sval); retval = 1; break; case OP_UNOP: retval = (*un_op[p->t_whichoper])(p, pbuf, psize, ptp); break; case OP_BINOP: retval = (*bin_op[p->t_whichoper])(p, pbuf, psize, ptp); break; default: assert(0); break; } if (! retval) { if (*pbuf) { free(*pbuf); *pbuf = 0; } *psize = 0; } else { if ((*ptp)->ty_class == T_CROSS) { *ptp = (*ptp)->ty_cross; if (! *ptp) *ptp = void_type; } } return retval; } int eval_desig(p, paddr, psize, ptp) p_tree p; t_addr *paddr; long *psize; p_type *ptp; { register p_symbol sym; int retval = 0; t_addr a; switch(p->t_oper) { case OP_NAME: case OP_SELECT: sym = identify(p, VAR|REGVAR|LOCVAR|VARPAR); if (! sym) return 0; if (! (a = get_addr(sym, psize))) { break; } *paddr = a; *ptp = sym->sy_type; retval = 1; break; case OP_UNOP: switch(p->t_whichoper) { case E_DEREF: if (ptr_addr(p, paddr, psize, ptp)) { retval = 1; } break; default: print_node(db_out, p, 0); fputs(" not a designator\n", db_out); break; } break; case OP_BINOP: switch(p->t_whichoper) { case E_ARRAY: if (array_addr(p, paddr, psize, ptp)) { retval = 1; } break; case E_SELECT: if (select_addr(p, paddr, psize, ptp)) { retval = 1; } break; default: print_node(db_out, p, 0); fputs(" not a designator\n", db_out); break; } break; default: error("illegal designator"); break; } if (! retval) { *psize = 0; } else { if ((*ptp)->ty_class == T_CROSS) { *ptp = (*ptp)->ty_cross; if (! *ptp) { *ptp = void_type; print_node(db_out, p, 0); fputs(" designator has unknown type\n", db_out); retval = 0; *psize = 0; } } } return retval; }
C
/* * CS362 Software Engineering II * Summer 2019 * * Daniel S Wagner * [email protected] * * Assignment 3 * * unittest4.c * Testing the refactored tribute case function */ // STANDARD C LIBRAIRIES #include <string.h> #include <stdio.h> #include <assert.h> #include <stdlib.h> // SPECIFIC DOMINION HEADER FILES #include "dominion.h" #include "dominion_helpers.h" #include "rngs.h" void nb_assert(int, int); int main(){ // Variables to initialize game --START int numPlayers = 2; int randSeed = 1000; struct gameState baseGame, testGame; int kingdomSupply[10] = {adventurer, council_room, feast, gardens, remodel, smithy, village, great_hall, steward, salvager}; // Variable to pass to card functions int checkPlayer = 0; int nextPlayer = checkPlayer + 1; initializeGame(numPlayers, kingdomSupply, randSeed, &baseGame); // Manually initialize nextPlayer hand and set last two cards of nextplayers deck to same action card printf("Base deck count: %d\n", baseGame.deckCount[nextPlayer]); baseGame.deck[nextPlayer][baseGame.deckCount[nextPlayer] - 1] = embargo; baseGame.deck[nextPlayer][baseGame.deckCount[nextPlayer] - 2] = embargo; memcpy(&testGame, &baseGame, sizeof(struct gameState)); printf("\nTESTING TRIBUTE CASE\n"); printf("/nTesting two action cards revealed by next player that are identical yields +2 actions\n"); tributeCase(&testGame, checkPlayer, nextPlayer); nb_assert(testGame.numActions, baseGame.numActions +2); printf("\nTesting two cards were added to nextPlayers DiscardPile\n"); nb_assert(testGame.discardCount[nextPlayer], baseGame.discardCount[nextPlayer] + 2); printf("\nTesting two cards were removed from nextPlayers deck\n"); nb_assert(testGame.deckCount[nextPlayer], baseGame.deckCount[nextPlayer] - 2); printf("\nTesting when next player only has 1 card available\n"); // Manually initialize nextPlayer hand and set last two cards of nextplayers deck to same action card baseGame.deckCount[nextPlayer] = 1; baseGame.deck[nextPlayer][baseGame.deckCount[nextPlayer] - 1] = embargo; memcpy(&testGame, &baseGame, sizeof(struct gameState)); printf("\nTesting single action cards revealed by next player yields +2 actions\n"); tributeCase(&testGame, checkPlayer, nextPlayer); nb_assert(testGame.numActions, baseGame.numActions +2); printf("\nTesting single card was added to nextPlayers Discard Pile\n"); nb_assert(testGame.discardCount[nextPlayer], baseGame.discardCount[nextPlayer] + 1); printf("\nTesting single card was removed from nextPlayers deck\n"); nb_assert(testGame.deckCount[nextPlayer], baseGame.deckCount[nextPlayer] - 1); printf("\nTesting when next player only has 1 card in deck but multiple in discard all same cards\n"); // Manually initialize nextPlayer deck and set last card of nextplayers deck to action card baseGame.deckCount[nextPlayer] = 1; baseGame.deck[nextPlayer][baseGame.deckCount[nextPlayer] - 1] = embargo; baseGame.discardCount[nextPlayer] = 5; int i; for(i = 0; i < baseGame.discardCount[nextPlayer]; i++){ baseGame.discard[nextPlayer][i] = embargo; } memcpy(&testGame, &baseGame, sizeof(struct gameState)); tributeCase(&testGame, checkPlayer, nextPlayer); printf("\nTesting single action cards revealed by next player yields +2 actions\n"); nb_assert(testGame.numActions, baseGame.numActions +2); printf("\nTesting two cards was added to nextPlayers Discard Pile AFTER discard pile was shuffled back into deck\n"); nb_assert(testGame.discardCount[nextPlayer], 1); printf("\nTesting discard pile was added to deck and then single card from deck were discarded\n"); nb_assert(testGame.deckCount[nextPlayer], baseGame.deckCount[nextPlayer] + baseGame.discardCount[nextPlayer] - 1); printf("\nTesting identical treasure cards revealed by next player only yield +2\n"); // Manually initialize nextPlayer hand and set last two cards of nextplayers deck to same action card baseGame.deckCount[nextPlayer] = 10; baseGame.discardCount[nextPlayer] = 0; baseGame.deck[nextPlayer][baseGame.deckCount[nextPlayer] - 1] = copper; baseGame.deck[nextPlayer][baseGame.deckCount[nextPlayer] - 2] = copper; memcpy(&testGame, &baseGame, sizeof(struct gameState)); tributeCase(&testGame, checkPlayer, nextPlayer); nb_assert(testGame.coins, baseGame.coins +2); printf("\nTesting different treasure cards revealed by next player yield +4 coins\n"); // Manually initialize nextPlayer hand and set last two cards of nextplayers deck to same action card baseGame.deckCount[nextPlayer] = 10; baseGame.discardCount[nextPlayer] = 0; baseGame.deck[nextPlayer][baseGame.deckCount[nextPlayer] - 1] = copper; baseGame.deck[nextPlayer][baseGame.deckCount[nextPlayer] - 2] = gold; memcpy(&testGame, &baseGame, sizeof(struct gameState)); tributeCase(&testGame, checkPlayer, nextPlayer); nb_assert(testGame.coins, baseGame.coins +4); printf("\nTesting if 'if' statements did not pick up treasure, or victory, defaulted to action by checking numAction variable\n"); nb_assert(testGame.numActions, baseGame.numActions); printf("\nTesting different victory cards revealed by next player yield +4 cards\n"); // Manually initialize nextPlayer hand and set last two cards of nextplayers deck to same action card baseGame.deckCount[nextPlayer] = 10; baseGame.discardCount[nextPlayer] = 0; baseGame.deck[nextPlayer][baseGame.deckCount[nextPlayer] - 1] = estate; baseGame.deck[nextPlayer][baseGame.deckCount[nextPlayer] - 2] = province; memcpy(&testGame, &baseGame, sizeof(struct gameState)); tributeCase(&testGame, checkPlayer, nextPlayer); nb_assert(testGame.deckCount[nextPlayer], baseGame.deckCount[nextPlayer] +4); printf("\nTesting different action cards revealed by next player yield +4 actions\n"); // Manually initialize nextPlayer hand and set last two cards of nextplayers deck to same action card baseGame.deckCount[nextPlayer] = 10; baseGame.discardCount[nextPlayer] = 0; baseGame.deck[nextPlayer][baseGame.deckCount[nextPlayer] - 1] = smithy; baseGame.deck[nextPlayer][baseGame.deckCount[nextPlayer] - 2] = steward; memcpy(&testGame, &baseGame, sizeof(struct gameState)); tributeCase(&testGame, checkPlayer, nextPlayer); nb_assert(testGame.numActions, baseGame.numActions + 4); return 0; } void nb_assert(int test, int base){ printf("Expected %d, result was %d\n", base, test); if(base == test){ printf("TEST PASSED\n"); } else{ printf("TEST FAILED\n"); } return; }
C
#include <stdio.h> #include <string.h> int main() { char str[] = "!looc os si 2103AD"; int n = strlen(str); for (int i = 0; i<=n-1; i++) { printf("%c", str[n-i] ); } printf("\n"); return 0; }
C
#include "monty.h" /** * op_sub - subtracts the values from the top two elements of the stack * @head: double pointer to head node * @line_number: line number being intrepreted from Monty file */ void op_sub(stack_t **head, unsigned int line_number) { int first, second; if (!head || !*head || !(*head)->next) sub_error(head, line_number); first = (*head)->n; second = (*head)->next->n; *head = (*head)->next; free((*head)->prev); (*head)->prev = NULL; (*head)->n = second - first; }
C
#include <stdio.h> #include <stdlib.h> typedef struct _node{ int data; struct _node *next; } node; typedef struct _stack{ node* top; node* end; } stack; void stackPrint( stack* s){ node* n; if(NULL != s && NULL != s->top) n= s->top; while( NULL != n){ printf("%d ",n->data); n = n->next; } } stack *stackNew(){ stack* s = (stack*)malloc(sizeof(stack)); s->end = s->top = NULL; return s; } stack *push( stack* s, int d){ if ( NULL == s) { s = stackNew(); } node* n = (node*)malloc(sizeof(node)); n->data = d; n->next = s->top; s->top = n; if ( NULL == s->end) { s->end = n; } return s; } node *pop( stack*s ){ if ( NULL == s || NULL == s->top) return NULL; node *n = s->top; s->top = s->top->next; return n; } void stackFree( stack* s) { while( NULL != s && NULL !=s->top ){ free( pop(s) ); } } int main(){ stack *s = NULL; node *n; int d; do{ printf("push?\n"); scanf("%d",&d); if ( 0 != d ) { s = push( s, d); } }while( 0 != d ); stackPrint(s); printf("pop\n"); while( NULL !=( n = pop(s) ) ){ printf("%d ",n->data); free(n); } stackFree( s ); free (s ); return 0; }
C
#include <stdio.h> #include <math.h> int f(double n,double c,double t) { if(c*n*(log(n)/log(2.0))<=t)return 1; return 0; } int main() { int c,t; scanf("%d%d",&c,&t ); double low=0,high=t,n=0; while(low<high) { double n=(high+low)/2; if(f(n,c,t)==1) low=n; else high=ceil(n-1); // for reducing absolute error } printf("%.10lf\n", low); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* process_command.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbenoit <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/03/27 16:13:51 by dbenoit #+# #+# */ /* Updated: 2014/03/27 23:03:37 by dbenoit ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include "shell.h" #include <unistd.h> static void st_search_pathlist(char **args, char **pathlist, int *j, char **envp) { execve(ft_strglue(pathlist[*j], "/", args[0]), args, envp); (*j)++; } static void st_execve(char ***args, char **envp) { char **pathlist; int j; j = 0; if (ft_strlen((*args)[0]) > 2 && ft_strstr((*args)[0], "./") == (*args)[0]) execve((*args)[0], *args, envp); if (ft_strlen((*args)[0]) > 1 && *args[0][0] == '/') execve((*args)[0], *args, envp); pathlist = get_pathlist(); while (pathlist[j]) st_search_pathlist(*args, pathlist, &j, envp); ft_delfulltab((void ***)&pathlist); } void process_command(char *line, char **envp) { char **args; if (!line) exit(1); if (!is_built_in(line)) { args = ft_strsplit_cmd(line); if (args && ft_strncmp(args[0], "./", 2) == 0 && access(args[0], F_OK) == 0 && access(args[0], X_OK) == -1) { ft_error_cd(args[0], 7, NULL); ft_putchar('\n'); ft_delfulltab((void ***)&args); exit(1); } st_execve(&args, envp); if (args) ft_delfulltab((void ***)&args); ft_putstr_fd(line, 2); ft_error(9); } else check_built_in(line); exit(1); }
C
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <string.h> int main(int argc, char** argv) { int bytesWritten = 0; int i = 15; int f = open("myfifo", O_WRONLY | O_APPEND | O_NONBLOCK); if (f < 0) { perror("Cannot open"); return 1; } else fprintf(stderr, "open: ok\n"); sleep(1); while (i) { char buffer[1000]; sprintf(buffer, "2012-07-05 14:42:47.016 DEBUG txt-000102030405060708090A0B0C0D0E0F-AAAA-EEEE, i=%d\n", i); int n = write(f, buffer, strlen(buffer)); fprintf(stderr, "write: n=%d, i=%d, bytesWritten=%d\n", n, i, bytesWritten); if (n < 0) { perror("Cannot write"); } else { i--; bytesWritten += n; } usleep(10000); // 10 ms } close(f); fprintf(stderr, "end.\n"); return 0; }
C
#include <stdlib.h> #include <stdio.h> int main( int argc, char **argv ) { int v; int array[1024]; int i = 0; while ( scanf("%d", &v) != EOF ) { array[i++] = v; if ( i > 1023 ) break; } print_array( array, i ); printf( "------------\n" ); quicksort( array, i ); print_array( array, i ); } /* vim: set autoindent expandtab sw=4 : */
C
#define _CRT_SECURE_NO_WARNINGS 1 #pragma warning(disable:6031) #include "List.h" //ڵ㴴 ListNode* BuyListNode(LTDateType x) { ListNode* node = (ListNode*)malloc(sizeof(ListNode)); if (node == NULL) { printf("ٽڵʧܣ"); exit(-1); } node->next = NULL; node->prev = NULL; node->date = x; return node; } //β庯 void ListPushBack(ListNode* phead, LTDateType x) { assert(phead); ListNode* tail = phead->prev; ListNode* newnode = BuyListNode(x); tail->next = newnode; newnode->prev = tail; newnode->next = phead; phead->prev = newnode; } //ڵݴӡ void ListPrint(ListNode* phead) { assert(phead); ListNode* cur = phead->next; while (cur != phead) { printf("%d ",cur->date); cur = cur->next; } printf("\n"); } //ڵʼ //ʽ1 /* void ListInit(ListNode** pphead) { *pphead = BuyListNode(0); (*pphead)->next = *pphead; (*pphead)->prev = *pphead; } */ //ʽ2 ListNode* ListInit() { ListNode* phead = BuyListNode(0); phead->next = phead; phead->prev = phead; return phead; } //βɾ void ListPopBack(ListNode* phead) { assert(phead); assert(phead->next != phead); ListNode* tail = phead->prev; ListNode* tailPrev = tail->prev; tailPrev->next = phead; phead->prev = tailPrev; free(tail); tail = NULL; } //ͷ庯ʵ void ListPushFront(ListNode* phead, LTDateType x) { ListNode* pheadNext = phead->next; ListNode* newphead = BuyListNode(x); phead->next = newphead; newphead->prev = phead; newphead->next = pheadNext; pheadNext->prev = newphead; newphead->date = x; } //ͷɾʵ void ListPopFront(ListNode* phead) { assert(phead); assert(phead->next != phead); ListNode* Fist = phead->next; phead->next = Fist->next; Fist->next->prev = phead; free(Fist); Fist = NULL; } //ҽڵԪصĺʵ ListNode* ListFind(ListNode* phead, LTDateType x) { assert(phead); ListNode* cur = phead->next; while (cur) { if (cur->date == x) { return cur; } cur = cur->next; } return NULL; } //ListFindҵԪǰһڵ void ListInsert(ListNode* phead, LTDateType x,LTDateType y) { assert(phead); ListNode* pos = ListFind(phead,x); ListNode* posPrev = pos->prev; ListNode* newNode = BuyListNode(y); posPrev->next = newNode; newNode->prev = posPrev; newNode->next = pos; pos->prev = newNode; newNode->date = y; } //ListFindɾҵǸ void ListErase(ListNode* phead,LTDateType x) { assert(phead); ListNode* pos = ListFind(phead, x); ListNode* posPrve = pos->prev; ListNode* posNext = pos->next; posPrve->next = posNext; posNext->prev = posPrve; free(pos); pos = NULL; }
C
#include<stdio.h> unsigned long rand0(void); void seed(void); long count[10]; int main(void) { for(int i=0;i<10;i++)count[i]=0; printf("%5d%5d%5d%5d%5d%5d%5d%5d%5d%5d\n",1,2,3,4,5,6,7,8,9,10); for(int i=0;i<10;i++) { rand0(); for(int i=0;i<10;i++) { printf("%5ld",count[i]); } printf("\n"); seed(); for(int i=0;i<10;i++)count[i]=0; } printf("\n"); return 0; }
C
#include <stdio.h> int main(){ printf("Enter a floating point number : "); float f; scanf("%f", &f); printf("%d \n%d \n%d", (int)f%10, (int)f%100, (int)f); return f; }
C
#include <stdio.h> #include <stdlib.h> #include <conio.h> //#define clrscr() system("clear") //#define getch() system("echo ") int* cargar(int* U,int* conj); void menup (); void menuop (); void imprimir(int * conj); void uni(int * conj1, int * conj2); void impe(int * conj); void card(int * conj); void inter(int *r, int *t); void relativo(int *e, int *s); int i; #define inn 10 int main() { menup(); return 0; } void menup() { int op, cont=1; char * opp=malloc(sizeof(char)); do { clrscr(); printf("\t\t\tMENU PRINCIPAL\n"); printf("1. Presentacion\n"); //TODO: Under construction printf("2. Operaciones\n"); printf("3. Salir\n"); printf("Ingrese una opcion: "); scanf("%s",opp); op=atoi(opp); switch (op) { case 1: break; case 2: menuop(); break; case 3: cont=0; break; default: printf("Escriba una opcion correcta.\n"); break; } } while( cont ); } void menuop() { int* U=malloc(inn*sizeof(int)); int* A=malloc(inn*sizeof(int)); int* B=malloc(inn*sizeof(int)); int op, cont=1, carr=0, lmp=1; char * opp=malloc(sizeof(char)); clrscr(); for(i=0;i<inn;i++) //{0,1,2,3,4,5,6,7,8,9} U[i]=1; do { if (lmp) clrscr(); printf("\t\t\tOPERACIONES\n"); printf("1. Cargar\n"); printf("2. Union\n"); printf("3. Interseccion\n"); printf("4. Complemento relativo\n"); //TODO: Under construction printf("5. Complemento absoluto\n"); //TODO: Under construction printf("6. Diferencia Simetrica\n"); //TODO: Under construction printf("7. Retornar al menu principal\n"); printf("Ingrese una opcion: "); scanf("%s",opp); op=atoi(opp); switch (op) { case 1: printf("Cargando el conjunto A: "); A=cargar(U,A); printf("Cargando el conjunto B: "); B=cargar(U,B); impe(A); impe(B); carr=1; lmp=0; getch(); break; case 2: if (carr) { uni(A,B); lmp=0; } else printf("No ha cargado los arreglos"); //cargar(A,B); getch(); break; case 3: if (carr) { inter(A,B); lmp=0; } else printf("No ha cargado los arreglos"); //cargar(A,B); getch(); break; case 4: lmp=0; getch(); break; case 5: lmp=0; getch(); break; case 6: lmp=0; getch(); break; case 7: cont=0; break; default: printf("Escriba una opcion correcta.\n"); break; } } while( cont ); } int * cargar(int * U,int* conj) //Ver como se trabaja con U. FIXME: U no es usado... { int j; char * numero=malloc(sizeof(char)); char * res=malloc(sizeof(char)); clrscr(); U[0]=1; for (i=0;i<inn;i++) { conj[i]=0; } do { do { printf("Ingrese un elemento (Del 0 al 9): "); scanf("%s",numero); j=atoi(numero); } while(j<0 || j>9); conj[j]=1; impe(conj); printf("\nContinuar ingresando (S/n/b (para borrar el ultimo ingresado)): "); //Opción borrar por si hay equivocaciones. Como un char. Bug as feature xD. scanf("%s",res); //Se está leyendo con string, porque char causa problemas. if (res[0]=='b' || res[0]=='B') { conj[j]=0; printf("Elemento Borrado: %d\n",j);//FIXME: No debería leer de nuevo un elemento, debería preguntar si continuar ingresando. impe(conj); } } while(res[0]=='s' || res[0]=='S'|| res[0]=='b' || res[0]=='B'); return conj; } void impe(int * conj) { int emp=0; for (i=0;i<inn;i++) { if (conj[i] == 0) emp=1; else { emp=0; break; } } if (emp == 1) printf("{}\n"); else { printf("{"); for(i=0;i<inn;i++) { if (conj[i] == 1) { printf("%d,",i); } } printf("\b}\n"); } card(conj); } void uni(int * conj1, int * conj2) { int* unio=malloc(inn*sizeof(int)); for (i=0;i<inn;i++) { unio[i]=0; } for (i=0;i<inn;i++) { if ( unio[i]== 0) { unio[i]=conj1[i]; } if (unio[i]==0) { unio[i]=conj2[i]; } } clrscr(); printf("La union es: "); impe(unio); } void inter(int *r,int *t) { int* unio=malloc(inn*sizeof(int)); printf("La interseccion es: \n"); for(i=0;i<inn;i++) { unio[i]=0; } for(i=0;i<inn;i++) { if(r[i]==t[i]) { unio[i]=r[i]; } } clrscr(); impe(unio); getch(); } void relativo(int *e, int *s) { int m=0; int* unio=malloc(inn*sizeof(int)); printf("A-B\n"); for(i=0;i<inn;i++) { for(m=0;m<inn;m++) { unio[i]=0; unio[m]=0; } } for(i=0;i<inn;i++) { if (e[i]!=s[i]) { unio[i]=e[i]; } } clrscr(); impe(unio); getch(); } void card(int * conj) { int count=0; for (i=0;i<inn;i++) { if(conj[i] == 1) { count++; } } printf("La cardinalidad es de %d\n",count); }
C
#include<stdio.h> int main(){ int a = 0; float b = 0.0f; scanf("%d%f",&a,&b); printf("a=%d\n",a); printf("b=%f\n",b); return 0; }
C
#include <math.h> #include <stdio.h> #include <stdlib.h> #include "tpool.h" #define PRECISION 100 /* upper bound in BPP sum */ /* Use Bailey–Borwein–Plouffe formula to approximate PI */ static void *bpp(void *arg) { int k = *(int *) arg; double sum = (4.0 / (8 * k + 1)) - (2.0 / (8 * k + 4)) - (1.0 / (8 * k + 5)) - (1.0 / (8 * k + 6)); double *product = malloc(sizeof(double)); if (product) *product = 1 / pow(16, k) * sum; return (void *) product; } int main() { int bpp_args[PRECISION + 1]; double bpp_sum = 0; tpool_t pool = tpool_create(4); tpool_future_t futures[PRECISION + 1]; for (int i = 0; i <= PRECISION; i++) { bpp_args[i] = i; futures[i] = tpool_apply(pool, bpp, (void *) &bpp_args[i]); } for (int i = 0; i <= PRECISION; i++) { double *result = tpool_future_get(futures[i], 0 /* blocking wait */); bpp_sum += *result; tpool_future_destroy(futures[i]); free(result); } tpool_join(pool); printf("PI calculated with %d terms: %.15f\n", PRECISION + 1, bpp_sum); return 0; }
C
#define _CRT_SECURE_NO_WARNINGS 1 //static ξֲ //1 //ֲӰ //#include <stdio.h> //void test() //{ // int i = 0; // i++; // printf("%d", i); // //} //int main() //{ // // for (int i = 0; i < 10; i++) // { // test(); // } // system("pause"); //} // 2 // static ξֲ ı˱ڣ̬Ȼ // ֱ //#include <stdio.h> //void test() //{ // // static int i = 0; // i++; // printf("%d ", i); //} //int main() //{ // int i = 0; // for (i = 0; i < 10; i++) // { // test(); // } // system("pause"); // return 0; //}
C
//ǽ 5-1 factorial /* #include<stdio.h> int factorial(int n) { if (n > 0) return n * factorial(n - 1); else return 1; } int main() { int x; printf(" Էϼ : "); scanf("%d", &x); printf("%d %dԴϴ.\n", x, factorial(x)); return 0; } */ //ǽ 5-2 Euclidean method of mutual division /* #include<stdio.h> int gcd(int x, int y) { if (y == 0) return x; else return gcd(y, x % y); } int main() { int x, y; puts(" ִ մϴ."); printf(" Էϼ : "); scanf("%d", &x); printf(" Էϼ : "); scanf("%d", &y); printf("ִ %dԴϴ.\n", gcd(x, y)); return 0; } */
C
#include "pieces.h" void initChessBoard() { for (int i = 0; i < 8; i += 2) { for (int j = 0; j < 8; j += 2) //def chessboard { board[i][j] = white; board[i][j + 1] = black; board[i + 1][j] = black; board[i + 1][j + 1] = white; } } for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { pieces[i][j] = empty; } } for (int i = 0; i < 8; i++) //place pawns { pieces[i][1] = blackPawn; pieces[i][6] = whitePawn; } for (int i = 0; i < 8; i += 7) //place rooks { pieces[i][0] = blackRook; pieces[i][7] = whiteRook; } for (int i = 1; i < 7; i += 5) //place knights { pieces[i][0] = darkKnight; pieces[i][7] = whiteKnight; } for (int i = 2; i < 6; i += 3) //place bishops { pieces[i][0] = blackBishop; pieces[i][7] = whiteBishop; } pieces[3][0] = blackQueen; pieces[3][7] = whiteQueen; pieces[4][0] = blackKing; pieces[4][7] = whiteKing; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { possible[i][j].YoN = 0; possible[i][j].file= "images/possible.bmp"; } } } void displayBoard(SDL_Window* window) { SDL_Surface* surface = NULL; SDL_Rect pos; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { pos.x = i * 100; pos.y = j * 100; switch (board[i][j]) { case white: surface = SDL_LoadBMP("images/whiteBG.bmp"); break; case black: surface = SDL_LoadBMP("images/blackBG.bmp"); break; } SDL_BlitSurface(surface, NULL, SDL_GetWindowSurface(window), &pos); surface = SDL_LoadBMP(pieces[i][j].file); if (pieces[i][j].select == 0) { SDL_SetColorKey(surface, SDL_TRUE, SDL_MapRGB(surface->format, 0, 255, 0)); } SDL_BlitSurface(surface, NULL, SDL_GetWindowSurface(window), &pos); if (possible[i][j].YoN == 1) { surface = SDL_LoadBMP(possible[i][j].file); SDL_SetColorKey(surface, SDL_TRUE, SDL_MapRGB(surface->format, 0, 255, 0)); SDL_BlitSurface(surface, NULL, SDL_GetWindowSurface(window), &pos); } } } SDL_UpdateWindowSurface(window); SDL_FreeSurface(surface); }