language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
// Graph ADT interface // Taken from COMP2521 wk05 lecture (ashesh) #ifndef GRAPH_H #define GRAPH_H #include <stdbool.h> #include "list.h" typedef struct GraphRep *Graph; // vertices are strings typedef char* Vertex; // edges are pairs of vertices (end-points) typedef struct Edge { Vertex start; Vertex end; } Edge; // graph operations Graph newGraph(int); void fillGraph (Graph, Vertex*); void insertEdge(Graph, Edge); void removeEdge(Graph, Edge); bool adjacent(Graph, Vertex, Vertex); void showGraph(Graph); void freeGraph(Graph); int findIndex(Graph, Vertex); int numVertices(Graph); double numIn(Graph, Vertex); double sumNumIn(Graph, Vertex); double numOut(Graph, Vertex); double sumNumOut(Graph, Vertex); List* adjList(Graph); #endif
C
#ifndef __NODE_H__ #define __NODE_H__ struct ListNode { int val; struct ListNode *next; }; struct ListNode* makeList(int *a, int n) { struct ListNode *tmp, *head = NULL, *cur; if(a == NULL || n == 0) return NULL; for(int i = 0; i < n; i++) { tmp = (struct ListNode *)calloc(1, sizeof(struct ListNode)); tmp->val = a[i]; if(i == 0) head = tmp; else cur->next = tmp; cur = tmp; } return head; } void dump_list_node(struct ListNode *l) { if(!l) return; while(l) { printf("%d ", l->val); l = l->next; } printf("\n"); } #endif
C
/* * Copyright (c) 2011, C-Talks and/or its owners. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact C-Talks owners, Matias Dumrauf or Facundo Viale * or visit https://sites.google.com/site/utnfrbactalks/ if you need additional * information or have any questions. */ /* * @FILE: collections/queue.c * @AUTOR: Facundo Viale * @VERSION: 1.6 (2/09/2009) * - Mayor funcionalidad con Closures * 1.5 (28/08/2009) * - Full Revision * 1.0 (26/08/2008) * - Base Version */ #include <stdlib.h> #include <semaphore.h> #include "queue.h" /* * @NAME: collection_queue_create * @DESC: Crea y devuelve un puntero a una cola */ t_queue *collection_queue_create(){ t_queue* queue = malloc( sizeof(t_queue) ); queue->head = NULL; queue->tail = NULL; queue->elements_count = 0; if( sem_init( &queue->semaforo, 0, 1) == -1 ){ return NULL; } return queue; } /* * @NAME: collection_queue_clean * @DESC: Elimina todos los elementos de la cola. */ void collection_queue_clean( t_queue *queue, void (*data_destroyer)(void*) ){ t_link_element* element; sem_wait( &queue->semaforo ); while(queue->head != NULL){ element = queue->head; queue->head = queue->head->next; data_destroyer(element->data); free(element); } queue->elements_count = 0; sem_post( &queue->semaforo ); } /* * @NAME: collection_queue_destroy * @DESC: Destruye una cola, reciviendo como argumento el metodo encargado de liberar cada * elemento de la cola. */ void collection_queue_destroy( t_queue *queue, void (*data_destroyer)(void*) ){ collection_queue_clean(queue, data_destroyer); sem_destroy( &queue->semaforo ); free(queue); } /* * @NAME: collection_queue_push * @DESC: Agrega un elemento al final de la cola */ void collection_queue_push( t_queue *queue, void *element ){ sem_wait( &queue->semaforo ); if( element != NULL ){ t_link_element *auxelement = malloc( sizeof(t_link_element) ); auxelement->data = element; auxelement->next = NULL; if( queue->tail != NULL ){ queue->tail->next = auxelement; queue->tail = queue->tail->next; }else{ queue->head = auxelement; queue->tail = auxelement; } queue->elements_count++; } sem_post( &queue->semaforo ); } /* * @NAME: collection_queue_pop * @DESC: Saca un elemento del principio de la cola */ void* collection_queue_pop( t_queue *queue ){ void* data = NULL; sem_wait( &queue->semaforo ); if( queue->head != NULL ){ t_link_element *element = queue->head; queue->head = queue->head->next; if( queue->head == NULL ){ queue->tail = NULL; } data = element->data; free(element); queue->elements_count--; } sem_post( &queue->semaforo ); return data; } /* * @NAME: collection_queue_iterator * @DESC: Itera la lista llamando al closure por cada elemento */ void collection_queue_iterator( t_queue* queue, void (*closure)(void*) ){ t_link_element *element = queue->head; sem_wait( &queue->semaforo ); while( element != NULL ){ closure(element->data); element = element->next; } sem_post( &queue->semaforo ); } /* * @NAME: collection_queue_size * @DESC: Devuelve la cantidad de elementos de la cola */ int collection_queue_size( t_queue* queue ){ return queue->elements_count; } /* * @NAME: collection_queue_isEmpty * @DESC: Verifica si la cola esta vacia */ int collection_queue_isEmpty( t_queue *queue ){ return collection_queue_size(queue) == 0; }
C
/* * IncFile2.h * * Created: 01.12.2018 20:06:04 * Author: MarcinS */ #ifndef INCFILE2_H_ #define INCFILE2_H_ /*SUM OF NIDDLE COLORS CANNOT BE GREATER THAN 255 */ /*Second niddle is the largest while Houre niddle is the smallest */ #include <avr/io.h> #include "CDiagNeopixel.h" void createLines(); /*NIDDLES*/ #define SECOND_SIZE 9 #define SECOND_RED 10 #define SECOND_GREEN 0 #define SECOND_BLUE 0 #define MINUTE_SIZE 7 #define MINUTE_RED 0 #define MINUTE_GREEN 10 #define MINUTE_BLUE 0 #define HOUR_SIZE 5 #define HOUR_RED 0 #define HOUR_GREEN 0 #define HOUR_BLUE 10 /*Background */ #define BACKGROUND_RED 0 #define BACKGROUND_GREEN 0 #define BACKGROUND_BLUE 0 /*Dots */ #define DOT_RED 10 #define DOT_GREEN 10 #define DOT_BLUE 10 /*No Niddle frames */ uint8_t NoNiddleOneDot[3*NUMBER_OF_DIAG_LEDS]; uint8_t NoNiddleTwoDots[3*NUMBER_OF_DIAG_LEDS]; uint8_t NoNiddleThreeDots[3*NUMBER_OF_DIAG_LEDS]; /*No covering */ /*Only Second Frames */ uint8_t OnylSecondsOnTwoDots[3*NUMBER_OF_DIAG_LEDS]; uint8_t OnylSecondsOnThreeDots[3*NUMBER_OF_DIAG_LEDS]; /*Only Minutes Frames*/ uint8_t OnylMinuteOnOneDot[3*NUMBER_OF_DIAG_LEDS]; uint8_t OnylMinuteOnTwoDots[3*NUMBER_OF_DIAG_LEDS]; uint8_t OnylMinuteOnThreeDots[3*NUMBER_OF_DIAG_LEDS]; /*Only Houres Frames*/ uint8_t OnylHoureOnOneDot[3*NUMBER_OF_DIAG_LEDS]; uint8_t OnylHoureOnTwoDots[3*NUMBER_OF_DIAG_LEDS]; uint8_t OnylHoureOnThreeDots[3*NUMBER_OF_DIAG_LEDS]; /*Covering */ /*Houre with minute */ uint8_t HoureAndMinutesOnOneDot[3*NUMBER_OF_DIAG_LEDS]; uint8_t HoureAndMinutesOnTwoDots[3*NUMBER_OF_DIAG_LEDS]; uint8_t HoureAndMinutesOnThreeDots[3*NUMBER_OF_DIAG_LEDS]; /*Houre with second */ uint8_t HouresAndSecondsOnTwoDots[3*NUMBER_OF_DIAG_LEDS]; uint8_t HouresAndSecondsOnThreeDots[3*NUMBER_OF_DIAG_LEDS]; /*Minute with second */ uint8_t MinuteAndSecondsOnTwoDots[3*NUMBER_OF_DIAG_LEDS]; uint8_t MinuteAndSecondsOnThreeDots[3*NUMBER_OF_DIAG_LEDS]; /*Minute houre and second together */ uint8_t HoureMinuteSecondOnTwoDots[3*NUMBER_OF_DIAG_LEDS]; uint8_t HoureMinuteSecondOnThreeDots[3*NUMBER_OF_DIAG_LEDS]; #endif /* INCFILE2_H_ */
C
#include "stm32spi1.h" #include "bikeRC522.h" #include "delay.h" /* *************************************************************** * : bikeRC522_delay_ns * : ʱ * : NULL * : NULL * : NULL * : *************************************************************** */ void bikeRC522_delay_ns(u32 ns) { u32 i; for (i = 0; i < ns; i++) { __nop(); __nop(); __nop(); } } /* *************************************************************** * : bikeRC522_ReadRawRC * : RC522Ĵ * : 1. AddressĴַ * : NULL * : NULL * : *************************************************************** */ u8 bikeRC522_ReadRawRC(u8 Address) { u8 ucAddr; u8 ucResult = 0; BIKERC522_NSS_0; ucAddr = ((Address<<1)&0x7E) | 0x80; SPI1_ReadWriteByte(ucAddr); ucResult = SPI1_ReadWriteByte(0x00); BIKERC522_NSS_1; return ucResult; } /* *************************************************************** * : bikeRC522_WriteRawRC * : дRC522Ĵ * : 1. AddressĴַ * 2. value: дֵ * : NULL * : NULL * : *************************************************************** */ void bikeRC522_WriteRawRC(u8 Address, u8 value) { u8 ucAddr; BIKERC522_NSS_0; ucAddr = ((Address<<1)&0x7E); SPI1_ReadWriteByte(ucAddr); SPI1_ReadWriteByte(value); BIKERC522_NSS_1; } /* *************************************************************** * : bikeRC522_SetBitMask * : RC522Ĵλ * : 1. regĴַ * 2. mask: λֵ * : NULL * : NULL * : *************************************************************** */ void bikeRC522_SetBitMask(u8 reg, u8 mask) { u8 tmp = 0x0; tmp = bikeRC522_ReadRawRC(reg); bikeRC522_WriteRawRC(reg, tmp | mask); // set bit mask } /* *************************************************************** * : bikeRC522_ClearBitMask * : RC522Ĵλ * : 1. regĴַ * 2. mask: λֵ * : NULL * : NULL * : *************************************************************** */ void bikeRC522_ClearBitMask(u8 reg, u8 mask) { u8 tmp = 0x0; tmp = bikeRC522_ReadRawRC(reg); bikeRC522_WriteRawRC(reg, tmp & (~mask)); // clear bit mask } /* *************************************************************** * : bikeRC522_PcdAntennaOn * : * : NULL * : NULL * : NULL * : ÿرշ֮Ӧ1msļ *************************************************************** */ void bikeRC522_PcdAntennaOn(void) { u8 i; i = bikeRC522_ReadRawRC(TxControlReg); if (!(i & 0x03)) { bikeRC522_SetBitMask(TxControlReg, 0x03); } } /* *************************************************************** * : bikeRC522_PcdAntennaOff * : ر * : NULL * : NULL * : NULL * : ÿرշ֮Ӧ1msļ *************************************************************** */ void bikeRC522_PcdAntennaOff(void) { bikeRC522_ClearBitMask(TxControlReg, 0x03); } /* *************************************************************** * : bikeRC522_PcdReset * : λRC522 * : NULL * : NULL * : NULL * : *************************************************************** */ u8 bikeRC522_PcdReset(void) { BIKERC522_RST_1; bikeRC522_delay_ns(10); BIKERC522_RST_0; bikeRC522_delay_ns(10); BIKERC522_RST_1; bikeRC522_delay_ns(10); bikeRC522_WriteRawRC(CommandReg, PCD_RESETPHASE); bikeRC522_WriteRawRC(CommandReg, PCD_RESETPHASE); bikeRC522_delay_ns(10); bikeRC522_WriteRawRC(ModeReg, 0x3D); //MifareͨѶCRCʼֵ0x6363 bikeRC522_WriteRawRC(TReloadRegL, 30); bikeRC522_WriteRawRC(TReloadRegH, 0); bikeRC522_WriteRawRC(TModeReg, 0x8D); bikeRC522_WriteRawRC(TPrescalerReg, 0x3E); bikeRC522_WriteRawRC(TxAutoReg, 0x40);//Ҫ return MI_OK; } /* *************************************************************** * : bikeRC522_M500PcdConfigISOType * : RC522Ĺʽ * : 1. type : ѡRC522ʽ * : NULL * : NULL * : *************************************************************** */ u8 bikeRC522_M500PcdConfigISOType(u8 type) { if (type == 'A') // ISO14443_A { bikeRC522_ClearBitMask(Status2Reg, 0x08); bikeRC522_WriteRawRC(ModeReg, 0x3D);//3F bikeRC522_WriteRawRC(RxSelReg, 0x86);//84 bikeRC522_WriteRawRC(RFCfgReg, 0x7F); //4F bikeRC522_WriteRawRC(TReloadRegL, 30);//tmoLength);// TReloadVal = 'h6a =tmoLength(dec) bikeRC522_WriteRawRC(TReloadRegH, 0); bikeRC522_WriteRawRC(TModeReg, 0x8D); bikeRC522_WriteRawRC(TPrescalerReg, 0x3E); bikeRC522_delay_ns(1000); bikeRC522_PcdAntennaOn(); } else { return 1; } return MI_OK; } /* *************************************************************** * : bikeRC522_InitRc522 * : ʼгǩRC522 * : NULL * : NULL * : NULL * : *************************************************************** */ void bikeRC522_InitRc522(void) { GPIO_InitTypeDef GPIO_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6; //NRST GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_Init(GPIOC, &GPIO_InitStructure); SPI1_Init(); bikeRC522_PcdReset(); bikeRC522_PcdAntennaOff(); delay_ms(2); bikeRC522_PcdAntennaOn(); bikeRC522_M500PcdConfigISOType('A'); } /* *************************************************************** * : bikeRC522_Reset_RC522 * : λгǩRC522 * : NULL * : NULL * : NULL * : *************************************************************** */ void bikeRC522_Reset_RC522(void) { bikeRC522_PcdReset(); bikeRC522_PcdAntennaOff(); delay_ms(2); bikeRC522_PcdAntennaOn(); } /* *************************************************************** * : bikeRC522_CalulateCRC * : MF522CRC16 * : 1. *pIn: * 2. len: * : 1. *pOut: * : NULL * : *************************************************************** */ void bikeRC522_CalulateCRC(u8 *pIn, u8 len, u8 *pOut) { u8 i, n; bikeRC522_ClearBitMask(DivIrqReg, 0x04); bikeRC522_WriteRawRC(CommandReg, PCD_IDLE); bikeRC522_SetBitMask(FIFOLevelReg, 0x80); for (i = 0; i < len; i++) { bikeRC522_WriteRawRC(FIFODataReg, *(pIn +i)); } bikeRC522_WriteRawRC(CommandReg, PCD_CALCCRC); i = 0xFF; do { n = bikeRC522_ReadRawRC(DivIrqReg); i--; } while ((i!=0) && !(n&0x04)); pOut[0] = bikeRC522_ReadRawRC(CRCResultRegL); pOut[1] = bikeRC522_ReadRawRC(CRCResultRegM); } /* *************************************************************** * : bikeRC522_PcdComMF522 * : ͨRC522ISO14443ͨѶ * : 1. Command: ֤ * 2. *pIn: * 3. InLenByteݵֽڳ * : 1. *pOut: * 2. pOutLenBitݵλ * : NULL * : *************************************************************** */ char bikeRC522_PcdComMF522(u8 Command, u8 *pIn, u8 InLenByte, u8 *pOut, u8 *pOutLenBit) { u8 status = MI_ERR; u8 irqEn = 0x00; u8 waitFor = 0x00; u8 lastBits; u8 n; u16 i; switch (Command) { case PCD_AUTHENT: irqEn = 0x12; waitFor = 0x10; break; case PCD_TRANSCEIVE: irqEn = 0x77; waitFor = 0x30; break; default: break; } bikeRC522_WriteRawRC(ComIEnReg, irqEn|0x80); bikeRC522_ClearBitMask(ComIrqReg, 0x80); //жλ bikeRC522_WriteRawRC(CommandReg, PCD_IDLE); bikeRC522_SetBitMask(FIFOLevelReg, 0x80); //FIFO for (i = 0; i < InLenByte; i++) { bikeRC522_WriteRawRC(FIFODataReg, pIn [i]); } bikeRC522_WriteRawRC(CommandReg, Command); n = bikeRC522_ReadRawRC(CommandReg); if (Command == PCD_TRANSCEIVE) // ʼ { bikeRC522_SetBitMask(BitFramingReg, 0x80); } //i = 600;//ʱƵʵM1ȴʱ25ms i = 2000; do { n = bikeRC522_ReadRawRC(ComIrqReg); i--; } while ((i!=0) && !(n&0x01) && !(n&waitFor)); bikeRC522_ClearBitMask(BitFramingReg, 0x80); if (i != 0) { if (!(bikeRC522_ReadRawRC(ErrorReg)&0x1B)) { status = MI_OK; if (n & irqEn & 0x01) { status = MI_NOTAGERR; } if (Command == PCD_TRANSCEIVE) { n = bikeRC522_ReadRawRC(FIFOLevelReg); lastBits = bikeRC522_ReadRawRC(ControlReg) & 0x07; if (lastBits) { *pOutLenBit = (n-1)*8 + lastBits; } else { *pOutLenBit = n*8; } if (n == 0) { n = 1; } if (n > MAXRLEN) { n = MAXRLEN; } for (i = 0; i < n; i++) { pOut [i] = bikeRC522_ReadRawRC(FIFODataReg); } } } else { status = MI_ERR; } } bikeRC522_SetBitMask(ControlReg, 0x80); // stop timer now bikeRC522_WriteRawRC(CommandReg, PCD_IDLE); return status; } /* *************************************************************** * : bikeRC522_PcdRequest * : Ѱ * : 1. req_code: Ѱʽ * 0x52 = ѰӦз14443A׼Ŀ * 0x26 = Ѱδ״̬Ŀ * : 1. *pTagType: Ƭʹ * 0x4400 = Mifare_UltraLight * 0x0400 = Mifare_One(S50) * 0x0200 = Mifare_One(S70) * 0x0800 = Mifare_Pro(X) * 0x4403 = Mifare_DESFire * : ״̬ * : *************************************************************** */ u8 bikeRC522_PcdRequest(u8 req_code, u8 *pTagType) { u8 status; u8 unLen; u8 ucComMF522Buf[MAXRLEN]; bikeRC522_ClearBitMask(Status2Reg, 0x08); bikeRC522_WriteRawRC(BitFramingReg, 0x07); bikeRC522_SetBitMask(TxControlReg, 0x03); ucComMF522Buf[0] = req_code; status = bikeRC522_PcdComMF522(PCD_TRANSCEIVE, ucComMF522Buf, 1, ucComMF522Buf, &unLen); if ((status == MI_OK) && (unLen == 0x10)) { *pTagType = ucComMF522Buf[0]; *(pTagType+1) = ucComMF522Buf[1]; } else { status = MI_ERR; } return status; } /* *************************************************************** * : bikeRC522_PcdAnticoll * : ͻ * : 1. *pSnr: Ƭкţ4ֽ * : * : MI_OK * : *************************************************************** */ u8 bikeRC522_PcdAnticoll(u8 *pSnr) { u8 status; u8 i, snr_check = 0; u8 unLen; u8 ucComMF522Buf[MAXRLEN]; bikeRC522_ClearBitMask(Status2Reg, 0x08); bikeRC522_WriteRawRC(BitFramingReg, 0x00); bikeRC522_ClearBitMask(CollReg, 0x80); ucComMF522Buf[0] = PICC_ANTICOLL1; ucComMF522Buf[1] = 0x20; status = bikeRC522_PcdComMF522(PCD_TRANSCEIVE, ucComMF522Buf, 2, ucComMF522Buf, &unLen); if (status == MI_OK) { for (i = 0; i < 4; i++) { *(pSnr+i) = ucComMF522Buf[i]; snr_check ^= ucComMF522Buf[i]; } if (snr_check != ucComMF522Buf[i]) { status = MI_ERR; } } bikeRC522_SetBitMask(CollReg, 0x80); return status; } /* *************************************************************** * : bikeRC522_PcdSelect * : ѡƬ * : 1. *pSnr: Ƭкţ4ֽ * : * : MI_OK * : *************************************************************** */ u8 bikeRC522_PcdSelect(u8 *pSnr) { u8 status; u8 i; u8 unLen; u8 ucComMF522Buf[MAXRLEN]; ucComMF522Buf[0] = PICC_ANTICOLL1; ucComMF522Buf[1] = 0x70; ucComMF522Buf[6] = 0; for (i = 0; i < 4; i++) { ucComMF522Buf[i+2] = *(pSnr+i); ucComMF522Buf[6] ^= *(pSnr+i); } bikeRC522_CalulateCRC(ucComMF522Buf, 7, &ucComMF522Buf[7]); bikeRC522_ClearBitMask(Status2Reg, 0x08); status = bikeRC522_PcdComMF522(PCD_TRANSCEIVE, ucComMF522Buf, 9, ucComMF522Buf, &unLen); if ((status == MI_OK) && (unLen == 0x18)) { status = MI_OK; } else { status = MI_ERR; } return status; } /* *************************************************************** * : bikeRC522_PcdAuthState * : ֤Ƭ * : 1. auth_mode: ֤ģʽ * 0x60 = ֤AԿ * 0x61 = ֤BԿ * 2. addr: ַ * 3. *pKey: * 4. *pSnr: к * : * : MI_OK * : *************************************************************** */ u8 bikeRC522_PcdAuthState(u8 auth_mode, u8 addr, u8 *pKey, u8 *pSnr) { u8 status; u8 unLen; u8 ucComMF522Buf[MAXRLEN]; ucComMF522Buf[0] = auth_mode; ucComMF522Buf[1] = addr; memcpy(&ucComMF522Buf[2], pKey, 6); memcpy(&ucComMF522Buf[8], pSnr, 4); status = bikeRC522_PcdComMF522(PCD_AUTHENT, ucComMF522Buf, 12, ucComMF522Buf, &unLen); if ((status != MI_OK) || (!(bikeRC522_ReadRawRC(Status2Reg) & 0x08))) { status = MI_ERR; } return status; } /* *************************************************************** * : bikeRC522_PcdRead * : ȡM1һ * : 1. addr: ҪĿַ * : 1. *p * : MI_OK * : *************************************************************** */ u8 bikeRC522_PcdRead(u8 addr, u8 *p) { u8 status; u8 unLen; u8 i, ucComMF522Buf[MAXRLEN]; ucComMF522Buf[0] = PICC_READ; ucComMF522Buf[1] = addr; bikeRC522_CalulateCRC(ucComMF522Buf, 2, &ucComMF522Buf[2]); status = bikeRC522_PcdComMF522(PCD_TRANSCEIVE,ucComMF522Buf,4,ucComMF522Buf,&unLen); if ((status == MI_OK) && (unLen == 0x90)) { for (i=0; i<16; i++) { *(p + i) = ucComMF522Buf[i]; } } else { status = MI_ERR; } return status; } /* *************************************************************** * : bikeRC522_PcdWrite * : дݵM1һ * : 1. addr: ҪĿַ * 2. *pҪд * : * : MI_OK * : *************************************************************** */ u8 bikeRC522_PcdWrite(u8 addr, u8 *p) { u8 status; u8 unLen; u8 i, ucComMF522Buf[MAXRLEN]; ucComMF522Buf[0] = PICC_WRITE; ucComMF522Buf[1] = addr; bikeRC522_CalulateCRC(ucComMF522Buf, 2, &ucComMF522Buf[2]); status = bikeRC522_PcdComMF522(PCD_TRANSCEIVE,ucComMF522Buf,4,ucComMF522Buf,&unLen); if ((status != MI_OK) || (unLen != 4) || ((ucComMF522Buf[0] & 0x0F) != 0x0A)) { status = MI_ERR; } if (status == MI_OK) { //memcpy(ucComMF522Buf, p , 16); for (i = 0; i < 16; i++) { ucComMF522Buf[i] = *(p + i); } bikeRC522_CalulateCRC(ucComMF522Buf, 16, &ucComMF522Buf[16]); status = bikeRC522_PcdComMF522(PCD_TRANSCEIVE, ucComMF522Buf, 18, ucComMF522Buf, &unLen); if ((status != MI_OK) || (unLen != 4) || ((ucComMF522Buf[0] & 0x0F) != 0x0A)) { status = MI_ERR; } } return status; } /* *************************************************************** * : bikeRC522_PcdHalt * : Ƭ״̬ * : * : * : MI_OK * : *************************************************************** */ u8 bikeRC522_PcdHalt(void) { u8 status; u8 unLen; u8 ucComMF522Buf[MAXRLEN]; ucComMF522Buf[0] = PICC_HALT; ucComMF522Buf[1] = 0; bikeRC522_CalulateCRC(ucComMF522Buf, 2, &ucComMF522Buf[2]); status = bikeRC522_PcdComMF522(PCD_TRANSCEIVE, ucComMF522Buf, 4, ucComMF522Buf, &unLen); return status; }
C
#include <math.h> #include <stdio.h> typedef struct point { float x, y, z; } point; float magnitude(point p1) { float mag = sqrt(p1.x * p1.x + p1.y * p1.y + p1.z * p1.z); return mag; } point resultantVector (point p1, point p2) { point resultant = {p2.x - p1.x, p2.y - p1.y, p2.z - p1.z}; return resultant; } float dotProduct (point p1, point p2) { float product = p1.x * p2.x + p1.y * p2.y + p1.z + p2.z; return product; } point crossProduct ( point p1, point p2) { point pCross = {p1.y * p2.z - p1.z * p2.y, p1.z * p2.x - p1.x * p2.z, p1.x * p2.y - p1.y * p2.x}; return pCross; } float scalarProjection (point p1, point p2) { float sProj = dotProduct(p1, p2)/magnitude(p2); return sProj; } point vectorProjection (point p1, point p2) { float multiplier = scalarProjection(p1, p2) * 1/magnitude(p2); point vProj = {p2.x * multiplier, p2.y * multiplier, p2.z * multiplier}; return vProj; } main(){}
C
#include <stdio.h> #include <math.h> int main() { /** * Escreva a sua soluo aqui * Code your solution here * Escriba su solucin aqu */ int tempo, velo; double x , y; y = 12; scanf ("%d", &tempo); scanf ("%d", &velo); x = (tempo * velo) / y; printf ("%.3lf\n", x); return 0; }
C
#include "buddy.h" // Stupid & simple tests int main(int argc, char* argv[]) { size_t size = 0x100 + sizeof(buddy_alloc_t); uintptr_t address = (uintptr_t) malloc(size); buddy_alloc_t* buddy = buddy_init(address, size); printf("[T] Initialization finished...\n"); buddy_status(buddy); printf("\n"); printf("[T] Allocating 12 bytes...\n"); void* test = buddy_alloc(buddy, 12); buddy_status(buddy); printf("\n"); printf("[T] Received %08x\n", test); buddy_dealloc(buddy, test, 12); buddy_status(buddy); printf("\n"); free(address); }
C
/* Program for polynomial addition */ /* Date: 09 Mar 2003 */ /* Author: Srinivas Nayak */ /* Compile using Turbo C++ */ /* This code is distributed under the GPL License. */ /* For more info check: */ /* http://www.gnu.org/copyleft/gpl.html */ #include<stdio.h> #include<conio.h> main() { int a[20],b[20],c[20],i,j,k,m,n,p,check; clrscr(); printf("how many terms in 1st ?") ; scanf("%d",&m); printf("how many terms in 2nd ?") ; scanf("%d",&n); printf("enter coff.& exp's of 1st poly"); for(i=1;i<=2*m;i++) scanf("%d",&a[i]); printf("enter coff.& exp's of 2nd poly"); for(i=1;i<=2*n;i++) scanf("%d",&b[i]); k=1; for(i=2;i<=2*m;i+=2) { check=0; for(j=2;j<=2*n;j+=2) { if(a[i]==b[j]) { check++; c[k]=a[i-1]+b[j-1]; c[k+1]=a[i]; k+=2; b[j]=-100; } } if(check==0) { c[k]=a[i-1];c[k+1]=a[i];k+=2;} } for(j=2;j<=2*n;j+=2) { if(b[j]>-100) {c[k]=b[j-1];c[k+1]=b[j]; k+=2; } } k--; p=k; for(k=1;k<=p;k+=2) {printf("+(%dx^%d) ",c[k],c[k+1]);} getch(); return 0; }
C
#ifndef __BOUNDINGBOX__H__ #define __BOUNDINGBOX__H__ #include "Triangulo.h" #include "Plane.h" #include "Esfera.h" typedef struct { float3 minimum; float3 maximum; } BoundingBox; void BoundingBoxSetMinMax(BoundingBox* bb, float3 min, float3 max); /* Setea el minimo y el maximo del bounding box los vectores min y max */ void BoundingBoxSetMin(BoundingBox* bb, float x, float y, float z); /* Setea el minimo del bounding box los los valores x, y y z */ void BoundingBoxSetMax(BoundingBox* bb, float x, float y, float z); /* Setea el maximo del bounding box los los valores x, y y z */ void BoundingBoxCalculateCenter(BoundingBox bb, float3* centro); /* Calcula el centro del Bounding Box bb */ void BoundingBoxMerge(BoundingBox bb1, BoundingBox bb2, BoundingBox* bbResult); /* Retorna en bbResult un BB que contiene a los BB bb1 y bb2. */ bool BoundingBoxOvelapTriangle(Triangulo t, BoundingBox bb); /* Retorna TRUE si el triangulo t intersecta al BoundingBox bb */ bool BoundingBoxOverlapPlane(Plane p, BoundingBox bb); /* Retorna TRUE si el plano p intersecta al BoundingBox bb */ bool BoundingBoxOverlapEsfera(Esfera e, BoundingBox bb); /* Retorna TRUE si la esfera e intersecta al BoundingBox bb */ void BoundingBoxCalcularTriangulo(Triangulo* t, BoundingBox* bb); /* Calcula el Bounding Box del triangulo t. */ void BoundingBoxCalcularEsfera(Esfera s, BoundingBox* bb); /* Calcula el Bonding Box de la esfera s. */ #endif
C
#include<stdio.h> int stack[100],top=-1,n,flag; main() { printf("The max size of stack: "); scanf("%d",&n); while(flag!=1) { int ch; printf("1. Push\n"); printf("2. Pop\n"); printf("3. Peek\n"); printf("4. isEmpty\n"); printf("5. isFull\n"); printf("6. Leave\n"); printf("7. Show\n"); printf("Enter the option number: "); scanf("%d",&ch); switch(ch) { case 1: { Push(); break; } case 2: { Pop(); break; } case 3: { Peek(); break; } case 4: { Empty(); break; } case 5: { Full(); break; } case 6: { Leave(); break; } case 7: { Show(); break; } } } } void Push() { if(top==n-1) { printf("Stack is full\n"); } else { int val; printf("Enter the element:"); scanf("%d",&val); top=top+1; stack[top]=val; } } void Pop() { if(top==-1) printf("Stack is Empty\n"); else { printf("%d is popped\n",stack[top]); top = top-1; } } void Peek() { printf("%d is at the top\n",stack[top]); } void Empty() { if(top==-1) printf("Yes\n"); else printf("No\n"); } void Full() { if(top==n-1) printf("Yes\n"); else printf("No\n"); } void Leave() { flag=1; printf("Exiting.....\n"); } int Show() { for(int i=0;i<=top;i++) printf("%d ",stack[i]); }
C
/* * display.c - Error handling and menu display functions. */ #include "display.h" void exit_conn(PGconn *conn) { PQfinish(conn); exit(EXIT_FAILURE); } void exit_success(PGconn *conn) { time_t t; struct tm tm; t = time(NULL); tm = *localtime(&t); printf("\n=========== %d-%02d-%02d %02d:%02d:%02d =========== \n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); printf("=========== Connection closed ===========\n"); PQfinish(conn); exit(EXIT_FAILURE); } void delete_error(PGresult *res, PGconn *conn) { if (PQresultStatus(res) != PGRES_COMMAND_OK) { fprintf(stderr, "DELETE failed: %s", PQerrorMessage(conn)); PQclear(res); exit_conn(conn); } } void select_error(PGresult *res, PGconn *conn) { if (PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, "SELECT failed: %s", PQerrorMessage(conn)); PQclear(res); exit_conn(conn); } } void insert_error(PGresult *res, PGconn *conn) { if (PQresultStatus(res) != PGRES_COMMAND_OK) { fprintf(stderr, "INSERT failed: %s", PQerrorMessage(conn)); PQclear(res); exit_conn(conn); } } void display_insertion_menu(PGresult *res) { int nFields; /* Print attributes. */ nFields = PQnfields(res); for (int i = 0; i < nFields; i++) printf("%s, ", PQfname(res, i)); printf("\n"); } void display_results(PGresult *res) { int nFields; /* Print attributes. */ nFields = PQnfields(res); for (int i = 0; i < nFields; i++) printf("%-30.25s", PQfname(res, i)); printf("\n"); /* Print rows. */ for (int i = 0; i < PQntuples(res); i++) { for (int j = 0; j < nFields; j++) printf("%-30.25s", PQgetvalue(res, i, j)); printf("\n"); } PQclear(res); }
C
//------------------------------------------------------------------------ // Common functions for file system module.All file systems,include FAT32, // NTFS or others,will use several or all functions in this module. // // Author : Garry.Xin // Initial date : Jul 05,2013 // Last updated : Jul 05,2013 // Last updated author : Garry.Xin // Last udpated content : //------------------------------------------------------------------------ #ifndef __STDAFX_H__ #include <StdAfx.h> #endif #ifndef __FSSTR_H__ #include "fsstr.h" #endif //A helper routine to check the validity of a file name. //For a regular file name,the first three characters must be file system identifier,a colon, //and a slash character. BOOL NameIsValid(CHAR* pFullName) { if(NULL == pFullName) { return FALSE; } if(0 == pFullName[0]) { return FALSE; } if(0 == pFullName[1]) { return FALSE; } if(0 == pFullName[2]) { return FALSE; } if(':' != pFullName[1]) //File system identifier colon must exist. { return FALSE; } if('\\' != pFullName[2]) //The third character must be splitter. { return FALSE; } return TRUE; } //Get the directory level given a string. //For the string only contains the file system identifier and only one file name, //which resides in root directory,the level is 0. BOOL GetFullNameLevel(CHAR* pFullName,DWORD* pdwLevel) { int i = 0; DWORD dwLevel = 0; if((NULL == pFullName) || (NULL == pdwLevel)) //Invalid parameters. { return FALSE; } if(!NameIsValid(pFullName)) //Is not a valid file name. { return FALSE; } while(pFullName[i]) { if(pFullName[i] == '\\') { dwLevel += 1; } i ++; } *pdwLevel = dwLevel - 1; //Substract the splitter between FS identifier and name. return TRUE; } //Get the desired level subdirectory from a full name. //pSubDir will contain the sub-directory name if successfully,so it must long //enough to contain the result. BOOL GetSubDirectory(CHAR* pFullName,DWORD dwLevel,CHAR* pSubDir) { BOOL bResult = FALSE; BYTE buffer[256] = {0}; //Contain sub-directory name temporary. DWORD dwTotalLevel = 0; DWORD i = 0; DWORD j = 0; if((NULL == pFullName) || (NULL == pSubDir) || (0 == dwLevel)) //Level shoud not be zero. { return FALSE; } if(!GetFullNameLevel(pFullName,&dwTotalLevel)) { return FALSE; } if(dwLevel > dwTotalLevel) //Exceed the total level. { return FALSE; } dwTotalLevel = 0; while(pFullName[i]) { if(pFullName[i] == '\\') //Splitter encountered. { j = 0; i ++; //Skip the slash. while((pFullName[i] != '\\') && (pFullName[i])) { buffer[j] = pFullName[i]; i ++; j ++; } buffer[j] = 0; //Set the terminator. dwTotalLevel += 1; if(dwLevel == dwTotalLevel) //Subdirectory found. { bResult = TRUE; break; } i --; //If the slash is skiped,the next sub-directory maybe eliminated. } i ++; } if(bResult) { //strcpy((CHAR*)pSubDir,(CHAR*)&buffer[0]); StrCpy((CHAR*)&buffer[0],(CHAR*)pSubDir); } return bResult; } //Segment one full file name into directory part and file name part. //pDir and pFileName must be long enough to contain the result. //If the full name's level is zero,that no subdirectory in the full name, //the pDir[0] will contain the file system identifier to indicate this. //If the full name only contain a directory,i.e,the last character of //the full name is a slash character,then the pFileName[0] will be set to 0. BOOL GetPathName(CHAR* pFullName,CHAR* pDir,CHAR* pFileName) { BYTE DirName[MAX_FILE_NAME_LEN]; BYTE FileName[MAX_FILE_NAME_LEN]; BYTE tmp; int i = 0; int j = 0; if((NULL == pFullName) || (NULL == pDir) || (NULL == pFileName)) //Invalid parameters. { return FALSE; } if(!NameIsValid(pFullName)) //Not a valid file name. { return FALSE; } //strcpy((CHAR*)&DirName[0],(CHAR*)pFullName); StrCpy((CHAR*)pFullName,(CHAR*)&DirName); i = StrLen((CHAR*)pFullName); i -= 1; if(pFullName[i] == '\\') //The last character is a splitter,means only dir name present. { //DirName[i] = 0; //Eliminate the slash. //strcpy((CHAR*)pDir,(CHAR*)&DirName[0]); StrCpy((CHAR*)&DirName[0],(CHAR*)pDir); pFileName[0] = 0; return TRUE; } j = 0; while(pFullName[i] != '\\') //Get the file name part. { FileName[j ++] = pFullName[i --]; } DirName[i + 1] = 0; //Keep the slash. FileName[j] = 0; //Now reverse the file name string. for(i = 0;i < (j / 2);i ++) { tmp = FileName[i]; FileName[i] = FileName[j - i - 1]; FileName[j - i - 1] = tmp; } //strcpy((CHAR*)pDir,(CHAR*)&DirName[0]); StrCpy((CHAR*)&DirName[0],(CHAR*)pDir); //strcpy((CHAR*)pFileName,(CHAR*)&FileName[0]); StrCpy((CHAR*)&FileName[0],(CHAR*)pFileName); return TRUE; } // //UNICODE string operations. // //Convert a byte string to UNICODE string,return the unicode string's pointer. //Make sure the dest buffer's length must equal or larger than src length. WCHAR* byte2unicode(WCHAR* dest,const char* src) { int index = 0; if((NULL == src) || (NULL == dest)) { return NULL; } while(src[index]) { dest[index] = src[index]; index ++; } dest[index] = 0; return dest; } //Campare two unicode strings check if they are equal,0 will be returned //if equal,otherwise return -1. int wstrcmp(const WCHAR* src,const WCHAR* dst) { if((NULL == src) && (NULL == dst)) { return 0; } if((NULL == src) || (NULL == dst)) { return -1; } while((*src) && (*dst) && (*src == *dst)) { src ++; dst ++; } return (*src == *dst) ? 0 : -1; } //Copy src to dest,return the dest. WCHAR* wstrcpy (WCHAR* dest,const WCHAR* src) { WCHAR c; WCHAR *s = (WCHAR *)src; const int off = dest - s - 1; do{ c = *s++; s[off] = c; }while (c != '\0'); return dest; } //Returns one unicode string's length. int wstrlen(const WCHAR* src) { WCHAR* s = (WCHAR*)src; int length = 0; if(NULL == s) { return -1; } while(*s) { length ++; s ++; } return length; } //Convert characters to capital. void tocapital(WCHAR* src) { WCHAR* cp = src; if(NULL == cp) { return; } while(*cp) { if((*cp >= 'a') && (*cp <= 'z')) { *cp += 'A' - 'a'; } cp ++; } } //A helper routine to check the validity of a file name. //For a regular file name,the first three characters must be file system identifier,a colon, //and a slash character. BOOL wNameIsValid(WCHAR* pFullName) { if(NULL == pFullName) { return FALSE; } if(0 == pFullName[0]) { return FALSE; } if(0 == pFullName[1]) { return FALSE; } if(0 == pFullName[2]) { return FALSE; } if(':' != pFullName[1]) //File system identifier colon must exist. { return FALSE; } if('\\' != pFullName[2]) //The third character must be splitter. { return FALSE; } return TRUE; } //Get the directory level given a string. //For the string only contains the file system identifier and only one file name, //which resides in root directory,the level is 0. BOOL wGetFullNameLevel(WCHAR* pFullName,DWORD* pdwLevel) { int i = 0; DWORD dwLevel = 0; if((NULL == pFullName) || (NULL == pdwLevel)) //Invalid parameters. { return FALSE; } if(!wNameIsValid(pFullName)) //Is not a valid file name. { return FALSE; } while(pFullName[i]) { if(pFullName[i] == '\\') { dwLevel += 1; } i ++; } *pdwLevel = dwLevel - 1; //Substract the splitter between FS identifier and name. return TRUE; } //Get the desired level subdirectory from a full name. //pSubDir will contain the sub-directory name if successfully,so it must long //enough to contain the result. BOOL wGetSubDirectory(WCHAR* pFullName,DWORD dwLevel,WCHAR* pSubDir) { BOOL bResult = FALSE; DWORD dwTotalLevel = 0; DWORD i = 0; DWORD j = 0; WCHAR buffer[256]; //Contain sub-directory name temporary. if((NULL == pFullName) || (NULL == pSubDir) || (0 == dwLevel)) //Level shoud not be zero. { return FALSE; } if(!wGetFullNameLevel(pFullName,&dwTotalLevel)) { return FALSE; } if(dwLevel > dwTotalLevel) //Exceed the total level. { return FALSE; } dwTotalLevel = 0; while(pFullName[i]) { if(pFullName[i] == '\\') //Splitter encountered. { j = 0; i ++; //Skip the slash. while((pFullName[i] != '\\') && (pFullName[i])) { buffer[j] = pFullName[i]; i ++; j ++; } buffer[j] = 0; //Set the terminator. dwTotalLevel += 1; if(dwLevel == dwTotalLevel) //Subdirectory found. { bResult = TRUE; break; } i --; //If the slash is skiped,the next sub-directory maybe eliminated. } i ++; } if(bResult) { //strcpy((CHAR*)pSubDir,(CHAR*)&buffer[0]); wstrcpy(pSubDir,&buffer[0]); } return bResult; } //Segment one full file name into directory part and file name part. //pDir and pFileName must be long enough to contain the result. //If the full name's level is zero,that no subdirectory in the full name, //the pDir[0] will contain the file system identifier to indicate this. //If the full name only contain a directory,i.e,the last character of //the full name is a slash character,then the pFileName[0] will be set to 0. BOOL wGetPathName(WCHAR* pFullName,WCHAR* pDir,WCHAR* pFileName) { WCHAR DirName[MAX_FILE_NAME_LEN]; WCHAR FileName[13]; WCHAR tmp; int i = 0; int j = 0; if((NULL == pFullName) || (NULL == pDir) || (NULL == pFileName)) //Invalid parameters. { return FALSE; } if(!wNameIsValid(pFullName)) //Not a valid file name. { return FALSE; } //strcpy((CHAR*)&DirName[0],(CHAR*)pFullName); wstrcpy(DirName,pFullName); i = wstrlen(pFullName); i -= 1; if(pFullName[i] == '\\') //The last character is a splitter,means only dir name present. { //DirName[i] = 0; //Eliminate the slash. //strcpy((CHAR*)pDir,(CHAR*)&DirName[0]); wstrcpy(pDir,&DirName[0]); pFileName[0] = 0; return TRUE; } j = 0; while(pFullName[i] != '\\') //Get the file name part. { FileName[j ++] = pFullName[i --]; } DirName[i + 1] = 0; //Keep the slash. FileName[j] = 0; //Now reverse the file name string. for(i = 0;i < (j / 2);i ++) { tmp = FileName[i]; FileName[i] = FileName[j - i - 1]; FileName[j - i - 1] = tmp; } //strcpy((CHAR*)pDir,(CHAR*)&DirName[0]); wstrcpy(pDir,&DirName[0]); //strcpy((CHAR*)pFileName,(CHAR*)&FileName[0]); wstrcpy(pFileName,&FileName[0]); return TRUE; }
C
/*! * @file main.c * @brief IRGesture2 Click example * * # Description * This example demonstrates the use of IR Gesture 2 click board by reading and displaying * the raw ADC values of entire 60-pixel IR photodiode array. * * The demo application is composed of two sections : * * ## Application Init * Initializes the driver and performs the click default configuration. * * ## Application Task * Waits for an end of conversion interrupt and then reads the raw ADC values of entire * 60-pixel IR photodiode array and displays the results on the USB UART as a 10x6 matrix * every 100ms approximately. * * @author Stefan Filipovic * */ #include "board.h" #include "log.h" #include "irgesture2.h" static irgesture2_t irgesture2; static log_t logger; void application_init ( void ) { log_cfg_t log_cfg; /**< Logger config object. */ irgesture2_cfg_t irgesture2_cfg; /**< Click config object. */ /** * Logger initialization. * Default baud rate: 115200 * Default log level: LOG_LEVEL_DEBUG * @note If USB_UART_RX and USB_UART_TX * are defined as HAL_PIN_NC, you will * need to define them manually for log to work. * See @b LOG_MAP_USB_UART macro definition for detailed explanation. */ LOG_MAP_USB_UART( log_cfg ); log_init( &logger, &log_cfg ); log_info( &logger, " Application Init " ); // Click initialization. irgesture2_cfg_setup( &irgesture2_cfg ); IRGESTURE2_MAP_MIKROBUS( irgesture2_cfg, MIKROBUS_1 ); if ( SPI_MASTER_ERROR == irgesture2_init( &irgesture2, &irgesture2_cfg ) ) { log_error( &logger, " Communication init." ); for ( ; ; ); } if ( IRGESTURE2_ERROR == irgesture2_default_cfg ( &irgesture2 ) ) { log_error( &logger, " Default configuration." ); for ( ; ; ); } log_info( &logger, " Application Task " ); } void application_task ( void ) { // Wait for an end of conversion interrupt while ( irgesture2_get_int_pin ( &irgesture2 ) ); int16_t pixels[ IRGESTURE2_NUM_SENSOR_PIXELS ]; if ( IRGESTURE2_OK == irgesture2_read_pixels ( &irgesture2, pixels, false ) ) { for ( uint8_t cnt = 0; cnt < IRGESTURE2_NUM_SENSOR_PIXELS; cnt++ ) { if ( 0 == ( cnt % IRGESTURE2_SENSOR_X_SIZE ) ) { log_printf( &logger, "\r\n" ); } log_printf( &logger, "%d\t", pixels[ cnt ] ); } log_printf( &logger, "\r\n" ); } } void main ( void ) { application_init( ); for ( ; ; ) { application_task( ); } } // ------------------------------------------------------------------------ END
C
#include<stdio.h> #define N 10 int main(void) { double ident [N] [N]; int row, col; for (row = 0; row < N; row++) for (col = 0; col < N; col++) if (row == col) ident [row] [col] = 1.0; else ident [row] [col] = 0.0; printf("%f", ident [N] [N]); return 0; }
C
#include <stdio.h> #include <stdlib.h> char buf[128]; struct student { int id; char name[32]; int score; }; typedef struct student datatype; struct rb_node { datatype data; struct rb_node *left, *right; int black; }; struct rb_node* get_rbtree(){ struct rb_node *t; char c; if(fgets(buf,sizeof(buf),stdin)==NULL || buf[0]=='.') return NULL; else { t = (struct rb_node*)malloc(sizeof(struct rb_node)); sscanf(buf,"[%c]%d,%[^,],%d",&c,&t->data.id,t->data.name,&t->data.score); t->black = (c=='b'); t->left = get_rbtree(); t->right = get_rbtree(); return t; } } int is_red(struct rb_node *t){ return t != NULL && !t->black; } void print_rbtree(struct rb_node *t){ if(t==NULL) printf(".\n"); else { printf("[%c]%d,%s,%d\n",t->black?'b':'r',t->data.id,t->data.name,t->data.score); print_rbtree(t->left); print_rbtree(t->right); } } struct rb_node* rotate_right(struct rb_node *t){ if(t==NULL || t->left==NULL) return t; struct rb_node *tmp = t->left; t->left = tmp->right; tmp->right = t; return tmp; } struct rb_node* rotate_left(struct rb_node *t){ if(t==NULL || t->right==NULL) return t; struct rb_node *tmp = t->right; t->right = tmp->left; tmp->left = t; return tmp; } struct rb_node* resolve_red_pair(struct rb_node *t){ if(is_red(t->left)&&is_red(t->left->left)){ if(is_red(t->right)){ t->right->black = 1; t->black = 0; t->left->black = 1; }else if(!is_red(t->right)){ t = rotate_right(t); t->right->black = 0; t->black = 1; } }else if(is_red(t->left)&&is_red(t->left->right)){ if(is_red(t->right)){ t->right->black = 1; t->black = 0; t->left->black = 1; }else if(!is_red(t->right)){ t->left = rotate_left(t->left); t = rotate_right(t); t->right->black = 0; t->black = 1; } }else if(is_red(t->right)&&is_red(t->right->left)){ if(is_red(t->left)){ t->left->black = 1; t->black = 0; t->right->black = 1; }else if(!is_red(t->left)){ t->right = rotate_right(t->right); t = rotate_left(t); t->left->black = 0; t->black = 1; } }else if(is_red(t->right)&&is_red(t->right->right)){ if(is_red(t->left)){ t->left->black = 1; t->black = 0; t->right->black = 1; }else if(!is_red(t->left)){ t = rotate_left(t); t->left->black = 0; t->black = 1; } } return t; } struct rb_node* rb_insert_rec(struct rb_node *t, struct student d){ if(t==NULL){ t = (struct rb_node*)malloc(sizeof(struct rb_node)); t->data = d; t->left = t->right = NULL; return t; }else{ if(d.id < t->data.id) t->left = rb_insert_rec(t->left, d); else if(d.id > t->data.id) t->right = rb_insert_rec(t->right, d); t = resolve_red_pair(t); return t; } } struct rb_node* rb_insert(struct rb_node *t, struct student d){ t = rb_insert_rec(t, d); t->black = 1; return t; } int main(){ struct student d; struct rb_node *t=NULL; while(fgets(buf,sizeof(buf),stdin)!=NULL){ sscanf(buf,"%d,%[^,],%d",&d.id,d.name,&d.score); t = rb_insert(t, d); } print_rbtree(t); return 0; }
C
#include<stdio.h> #include<stdlib.h> typedef struct stackArray { int top; int capacity; int *array; }stackArray; stackArray * createStack() { stackArray *stack=(stackArray*)malloc(sizeof(stackArray)); if(stack==NULL) { printf("No memory allocated"); exit(0); } stack->capacity=10; stack->top=-1; stack->array=(int*)malloc(stack->capacity*sizeof(int)); if(!stack->array) { printf("No memory allocated"); exit(0); } return stack; } void push(stackArray *sl1,int num) { sl1->array[++(sl1->top)]=num; } int pop(stackArray *sl1) { int num=sl1->array[sl1->top]; sl1->top--; return num; }
C
// gcc -g -O2 -o parameter_ref parameter_ref.c volatile int vv; /* Don't inline, but do allow clone to create specialized versions. */ static __attribute__((noinline)) int foo (int x, int y, int z) { int a = x * 2; int b = y * 2; int c = z * 2; vv++; return x + z; } int main (int x, char **argv) { return foo (x, 2, 3) + foo (x, 4, 3) + foo (x + 6, x, 3) + x; }
C
#include "libblinkstick.h" bool print_debug = false; void debug(const char* fmt, ...) { if (print_debug) { char buffer[256]; va_list ap; va_start(ap, fmt); vsprintf(buffer, fmt, ap); va_end(ap); puts(buffer); } } void blinkstick_debug() { print_debug = true; debug("STARTING LIBBLINKSTICK WITH DEBUG LOGGING"); } unsigned char* rgb_to_char(int red, int green, int blue) { unsigned char* bytes = malloc(sizeof(unsigned char[3])); bytes[0] = (red & 0xff); bytes[1] = (green & 0xff); bytes[2] = (blue & 0xff); return bytes; } blinkstick_device* blinkstick_factory(hid_device* handle) { blinkstick_device* device = malloc(sizeof(blinkstick_device)); device->handle = handle; return device; } blinkstick_device** blinkstick_find_many(int count) { blinkstick_device** devices = malloc(sizeof(blinkstick_device*) * count); debug("initializing usb context"); int res = hid_init(); if (res != 0) { debug("failed to initialize hid"); exit(1); } struct hid_device_info* device_info; device_info = hid_enumerate(BLINKSTICK_VENDOR_ID, BLINKSTICK_PRODUCT_ID); devices[0] = blinkstick_factory(hid_open_path(device_info->path)); debug("found device: %s", device_info->path); int num = 1; while ((device_info = device_info->next)) { devices[num] = blinkstick_factory(hid_open_path(device_info->path)); debug("found device: %s", device_info->path); num++; } if (count > num) { printf("did not find the number of devices wanted: %d, but found %d\n", count, num); exit(1); } return devices; } blinkstick_device* blinkstick_find() { return blinkstick_find_many(1)[0]; } unsigned char* build_control_message(int index, unsigned char* color) { // Write to the first LED present // this will be the _only_ led for the original blinkstick if (index == 0) { unsigned char* msg = malloc(sizeof(unsigned char) * BLINKSTICK_SINGLE_LED_MSG_SIZE); msg[0] = 0x1; msg[1] = color[0]; msg[2] = color[1]; msg[3] = color[2]; return msg; } // Writing to the other LEDs requires a different payload // this changes the write mode (first two bytes) and then // assigns the index. unsigned char* msg = malloc(sizeof(unsigned char) * BLINKSTICK_INDEXED_LED_MSG_PACKET_SIZE); msg[0] = 0x0005; msg[1] = 0x05; msg[2] = index; msg[3] = color[0]; msg[4] = color[1]; msg[5] = color[2]; return msg; } void blinkstick_set_color(blinkstick_device* blinkstick, int index, int red, int green, int blue) { unsigned char* color = rgb_to_char(red, green, blue); unsigned char* msg = build_control_message(index, color); hid_write(blinkstick->handle, msg, sizeof(msg)); free(msg); free(color); } void blinkstick_off(blinkstick_device* blinkstick, int index) { blinkstick_set_color(blinkstick, index, 0, 0, 0); } void blinkstick_destroy(blinkstick_device* device) { hid_close(device->handle); free(device); }
C
/*---------------------------------------------------------------------------------------------- * Module: Timer * File Name: timer. * AUTHOR: Bassnat Yasser * Data Created: 5 / 9 / 2021 * Description: Header file for the Timer AVR driver ------------------------------------------------------------------------------------------------*/ #ifndef TIMER_H_ #define TIMER_H_ #include "registers.h" #include "micro_config.h" #include "std_types.h" typedef enum { NORMAL, COMPARE, COMPAREA, COMPAREB }Timer_Mode; typedef enum { Timer0, Timer1, Timer2 }Timer_Number; typedef enum { NO_CLOCK,F_CPU_CLOCK,F_CPU_8,F_CPU_32,F_CPU_64,F_CPU_256,F_CPU_1024 }Timer_Clock; typedef struct { Timer_Mode mode; uint16 initial_value; Timer_Clock clock; uint16 compare_value; Timer_Number timer_number; }Timer_ConfigType; /******************************************************************************* * Functions Prototypes * *******************************************************************************/ void Timer_init(const Timer_ConfigType * Config_Ptr); void Timer_setCallBack(void(*a_ptr)(void)); void Timer_stop(uint8 timer_number); #endif /* TIMER_H_ */
C
#include "mode.h" #include "debug.h" #include <string.h> #include <stdlib.h> char* get_tm_interactive_input_mode_mask() { return getenv("TM_INTERACTIVE_INPUT"); } bool mode_contains(char *target) { // Because strsep modifies the string in place, we need to make a copy. char *mode_mask = get_tm_interactive_input_mode_mask(); if (mode_mask == NULL) return false; char *mode_mask_copy = strdup(mode_mask); char *strsep_index = mode_mask_copy; char *mode_flag = NULL; bool contains = false; while ((mode_flag = strsep(&strsep_index, "|")) != NULL) { if (strcmp(mode_flag, target) == 0) { contains = true; break; } } free(mode_mask_copy); return contains; } bool tm_interactive_input_is_active() { return (get_tm_interactive_input_mode_mask() != NULL && mode_contains("NEVER") == false); } bool tm_interactive_input_is_in_always_mode() { return mode_contains("ALWAYS"); } bool tm_interactive_input_is_in_echo_mode() { return mode_contains("ECHO"); }
C
#include <stdio.h> #include <stdlib.h> #define MIN(x,y) (((x) > (y)) ? (y) : (x)) typedef struct __Point { int x,y; } Point; int main() { int numberOfSpeakers; int index; int sizeOfSpeakers[100000] = { 0 }; int volumeOfSpeakers = 1000000; Point pointOfSpeakers[100000]; // Input 처리 부분 scanf("%d", &numberOfSpeakers); for(index = 0; index < numberOfSpeakers; ++index) { scanf("%d", &sizeOfSpeakers[index]); } for(index = 0; index < numberOfSpeakers; ++index) { scanf("%d %d", &pointOfSpeakers[index].x, &pointOfSpeakers[index].y); } // Calculation 부분 for(index = 0; index < numberOfSpeakers; ++index) { int calcIndex; int calcTemp; for(calcIndex = 0; calcIndex < numberOfSpeakers; ++calcIndex) { if(index != calcIndex) { calcTemp = (abs(pointOfSpeakers[index].x - pointOfSpeakers[calcIndex].x) + abs(pointOfSpeakers[index].y - pointOfSpeakers[calcIndex].y)); calcTemp /= (sizeOfSpeakers[index] + sizeOfSpeakers[calcIndex]); volumeOfSpeakers = MIN(volumeOfSpeakers, calcTemp); } } } printf("%d", volumeOfSpeakers); return 0; }
C
#include <stdio.h> int main (int argc, char *argv[]){ int i; double n; double soma = 0; scanf("%lf", &n); for (i = 1; i <= n; i++){ soma += i / (n - i + 1); } printf("%.4lf\n", soma); return 0; }
C
#include <stdio.h> #include <stdlib.h> void intercala(int *vetor, int l, int meio, int r) { int *aux = malloc(sizeof(int) * (r - l + 1)); int a = l, b = meio + 1, c = 0; while (a <= meio && b <= r) { if (*(vetor + a) <= *(vetor + b)) { *(aux + c++) = *(vetor + a++); } else { *(aux + c++) = *(vetor + b++); } } while (a <= meio) { *(aux + c++) = *(vetor + a++); } while (b <= r) { *(aux + c++) = *(vetor + b++); } for (int i = l, j = 0; i <= r; i++, j++) { *(vetor + i) = *(aux + j); } free(aux); } void mergeSort(int *vetor, int l, int r) { if (l >= r) return; int meio = (l + r) / 2; mergeSort(vetor, l, meio); mergeSort(vetor, meio + 1, r); intercala(vetor, l, meio, r); } int main() { int count = 1; int *v = malloc(sizeof(int) * count); while (scanf("%d", v + count - 1) == 1) { count++; // printf("%d\n", count); v = realloc(v, sizeof(int) * count); } mergeSort(v, 0, count - 2); for (int i = 0; i < count - 1; i++) { printf("%d ", *(v + i)); } free(v); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <sys/stat.h> #ifdef WITH_NEAT #include "server_neat.h" #else #include "server_sockets.h" #endif void usage(char *argv[]) { printf("Usage:\n"); printf("\t%s [-p 5001] <file 1> [file 2 ... file N]\n", argv[0]); } int main(int argc, char *argv[]) { const char* port = "5001"; for (;;) { int rc = getopt(argc, argv, "p:"); if (rc == -1) { break; } else if (rc == 'p') { port = optarg; } else { usage(argv); return EXIT_SUCCESS; } } if (argc - optind == 0) { usage(argv); return EXIT_SUCCESS; } for (int i = optind; i < argc; ++i) { int rc; struct stat sbuf; if ((rc = stat(argv[i], &sbuf)) != 0) { printf("Could not open %s: %s\n", argv[i], strerror(errno)); return EXIT_FAILURE; } } #ifdef WITH_NEAT setup_neat(port, argc-optind, argv+optind); #else setup_listen_socket(port, argc-optind, argv+optind); do_poll(); #endif return EXIT_SUCCESS; }
C
/* i2c_test.c D.J.Whale 18/07/2014 * * A simple I2C port exerciser. */ /***** INCLUDES *****/ #include <stdio.h> #include <stdlib.h> #include <time.h> #include "gpio.h" #include "i2c.h" /***** CONSTANTS *****/ /* GPIO numbers on Raspberry Pi REV2 */ #define SDA 2 #define SCL 3 /* ms */ #define TSETTLE (1UL) /* ns */ #define THOLD (1UL) #define TFREQ (1UL) #define TAG_DETECT 4 #define ADDRESS 0x50 #define CMD_GET_FIRMWARE 0xF0 static struct timespec TIME_10MS = {0, 10L * 1000000L}; static struct timespec TIME_50MS = {0, 50L * 1000000L}; static void delay(struct timespec time) { nanosleep(&time, NULL); } int main(int argc, char **argv) { I2C_CONFIG i2cConfig = {SCL, SDA, 1, 1, {0,TSETTLE}, {0,THOLD}, {0,TFREQ}}; int i; /* INIT */ gpio_init(); i2c_Init(&i2cConfig); gpio_setin(TAG_DETECT); /* WAIT FOR TAG */ printf("Card absent\n"); while (gpio_read(TAG_DETECT) != 0) { delay(TIME_10MS); } printf("Card present\n"); /* REPORT FIRMWARE ID */ while (gpio_read(TAG_DETECT) == 0) { unsigned char buffer[15+1] = {0}; /* space for terminator */ unsigned char request[] = {1, CMD_GET_FIRMWARE}; I2C_RESULT result; /* request firmware id read [tx:addr] tx:<len> tx:<cmd> */ result = i2c_Write(ADDRESS, request, sizeof(request)); delay(TIME_50MS); if (I2C_RESULT_IS_ERROR(result)) { printf("request error:%d\n", (int) result); } else { /* read the firmware id back: tx:<addr> rx:<len> rx:<cmd> rx:<ver>... */ result = i2c_Read(ADDRESS, buffer, sizeof(buffer)); if (I2C_RESULT_IS_ERROR(result)) { printf("response error:%d\n", (int) result); } else { int i; unsigned char len = buffer[0]; unsigned char cmd = buffer[1]; unsigned char status = buffer[2]; buffer[len] = 0; /* terminate string */ //printf("len %d cmd %d status %d\n", (int)len, (int)cmd, (int)status); printf("firmware version: %s\n", (char*)(buffer+3)); //for (i=3; i<len; i++) //{ // printf("buffer[%d] = %02X\n", i, (int)buffer[i]); //} } } } /***** FINISHED *****/ i2c_Finished(); return 0; } /***** END OF FILE *****/
C
/*******************************************/ /* BUSQUEDA.C */ /* */ /* Asignatura: Inteligencia Artificial */ /* Grado en Ingenieria Informatica - UCA */ /*******************************************/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "puzle.h" #include "nodo.h" #include "listaia.h" #include "busquedaAlum.h" #include "puzleAlum.c" #include "listaia.c" int contador_estados_visit = 0; int heuristica_estandar = 1; int busq_voraz = 0; void dispCamino(tNodo *nodo) { if (nodo->padre == NULL) { printf("\n\nInicio:\n"); dispEstado(nodo->estado); } else { dispCamino(nodo->padre); dispOperador(nodo->operador); dispEstado(nodo->estado); printf("\n"); } } void dispSolucion(tNodo *nodo, Lista l, Lista n) { dispCamino(nodo); printf("Profundidad=%d\n",nodo->profundidad); printf("Coste=%d\n",nodo->costeCamino); printf("El numero de estados visitados es => %d.\n", contador_estados_visit); printf("El numero de nodos abiertos es => %d.\n", n->Nelem); printf("El numero de nodos cerrados es => %d.\n", l->Nelem); } /* Crea el nodo raiz. */ tNodo *nodoInicial() { tNodo *inicial=(tNodo *) malloc(sizeof(tNodo)); inicial->estado=estadoInicial(); inicial->padre=NULL; inicial->costeCamino=0; inicial->profundidad=0; inicial->num_veces_visitado = 1; return inicial; } int obtener_fila(int valor, tEstado *t) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if(t->celdas[i][j] == valor) return i; } } return -1; } int obtener_columna(int valor, tEstado *t) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if(t->celdas[i][j] == valor) return j; } } return -1; } int heuristica_est(tEstado *t) { int total = 0; tEstado *s = estadoObjetivo(); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if(t->celdas[i][j] != s->celdas[i][j]) total++; } } return total; } int heuristica_man(tEstado *t) { int total = 0; tEstado *s = estadoObjetivo(); for(int k = 0; k < N; k++) { int f = obtener_fila(k, t) - obtener_fila(k, s); int g = obtener_columna(k, t) - obtener_columna(k, s); total += abs(f) + abs(g); } return total; } Lista insertar_orden(Lista abiertos, tNodo *n) { int n_insert = 0; int i = abiertos->inicio; Lista aux = (Lista) CrearLista(MAXI); while(i != abiertos->fin) { if(i == abiertos->Lmax) { i = 0; } tNodo *nod = (tNodo*) malloc(sizeof(tNodo)); nod = (void *) ExtraerElem(abiertos, i); if(nod->valHeuristica > n->valHeuristica && !n_insert) { InsertarUltimo((void *) n, aux); n_insert = 1; } InsertarUltimo((void *) nod, aux); i++; } if(!n_insert) { InsertarUltimo((void *) n, aux); } return aux; } Lista a_estrella(Lista abiertos, Lista sucesores) { /* *printf("(1)Numero de elementos de abiertos => %d.\n", abiertos->Nelem); *printf("(1)Numero de elementos de sucesores => %d.\n", sucesores->Nelem); */ if(ListaVacia(abiertos) && !ListaVacia(sucesores)) { InsertarUltimo(ExtraerPrimero(sucesores), abiertos); EliminarPrimero(sucesores); } while(!ListaVacia(sucesores)) { tNodo *n = (tNodo *) ExtraerPrimero(sucesores); abiertos = insertar_orden(abiertos, n); EliminarPrimero(sucesores); } /* *printf("(2)Numero de elementos de abiertos => %d.\n", abiertos->Nelem); *printf("(2)Numero de elementos de sucesores => %d.\n", sucesores->Nelem); */ return abiertos; } Lista voraz(Lista abiertos, Lista sucesores) { if(ListaVacia(abiertos) && !ListaVacia(sucesores)) { InsertarUltimo(ExtraerPrimero(sucesores), abiertos); EliminarPrimero(sucesores); } if(!ListaVacia(sucesores)) { tNodo *n = (tNodo *) ExtraerPrimero(sucesores); EliminarPrimero(sucesores); abiertos = insertar_orden(abiertos, n); } return abiertos; } /* Expande un nodo. */ Lista expandir(tNodo *nodo) { unsigned op; Lista sucesores=CrearLista(MAXI); for (op=1;op<=NUM_OPERADORES;op++) { if (esValido(op,nodo->estado)) { tNodo *nuevo=(tNodo *) malloc(sizeof(tNodo)); tEstado *s=(tEstado *) malloc(sizeof(tEstado)); s=aplicaOperador(op,nodo->estado); nuevo->estado=s; nuevo->padre=nodo; nuevo->operador=op; nuevo->costeCamino=nodo->costeCamino + coste(op,nodo->estado); nuevo->profundidad=nodo->profundidad + 1; nuevo->valHeuristica = (heuristica_estandar) ? heuristica_est(s) : heuristica_man(s); if (!ListaLlena(sucesores)){ InsertarUltimo((void *) nuevo,sucesores); } } } /*printf("(0)Numero de elementos de sucesores => %d.\n", sucesores->Nelem);*/ return sucesores; } int busqueda() { int objetivo = 0; int repetido = 0; tNodo *Actual=(tNodo*) malloc(sizeof(tNodo)); tNodo *Inicial=nodoInicial(); //tEstado *Final=estadoObjetivo(); Lista Abiertos = (Lista) CrearLista(MAXI); Lista Cerrados = (Lista) CrearLista(MAXI); Lista Sucesores; InsertarUltimo((void *) Inicial, Abiertos); while (!ListaVacia(Abiertos) && !objetivo) { Actual = (void *) ExtraerPrimero(Abiertos); printf("\n ACTUAL: \n"); dispEstado(Actual->estado); objetivo = testObjetivo(Actual->estado); EliminarPrimero(Abiertos); // Esto pa el linux, la calidad suprema. /*printf("Press 'Enter' to continue: ... ");*/ /*while ( getchar() != '\n');*/ repetido = buscaRepe(Actual->estado, Cerrados); if(!ListaLlena(Cerrados)) { InsertarUltimo((void *) Actual, Cerrados); } else { puts(ANSI_COLOR_RED); puts("ERROR: NO HAY SUFICIENTE MEMORIA."); puts(ANSI_COLOR_RESET); } if (!objetivo && !repetido) { contador_estados_visit++; Sucesores = expandir(Actual); /*Abiertos = Concatenar(Abiertos, Sucesores);*/ if(!busq_voraz) Abiertos = a_estrella(Abiertos, Sucesores); else Abiertos = voraz(Abiertos, Sucesores); } /*printf("(3)Numero de elementos de abiertos => %d.\n", Abiertos->Nelem);*/ } dispSolucion(Actual, Cerrados, Abiertos); return objetivo; } int buscaRepe(tEstado *s, Lista l1) { int i = l1->inicio, equal = 0; while(i != l1->fin && !equal) { if(i == l1->Lmax) { i = 0; } tNodo *nod = (tNodo*) malloc(sizeof(tNodo)); nod = (void *) ExtraerElem(l1, i); if(iguales(nod->estado, s)) { puts(ANSI_COLOR_YELLOW); puts("--Atención-- NODO REPETIDO."); puts(ANSI_COLOR_RESET); equal = 1; } i++; } return equal; } int main(void) { /*iguales(estadoInicial(), estadoObjetivo());*/ /*esValido(3, estadoInicial());*/ busq_voraz = 0; heuristica_estandar = 1; busqueda(); return 0; }
C
/* * This example program runs a full instance of chiventure with an in-memory game, * and where the CLI is monkeypatched to accept a new operation: * * - TASTE: A "kind 1" action that operates on an item. We support customization for the * output string upon running the action. */ #include <stdio.h> #include <custom-scripts/get_custom_type.h> #include <cli/operations.h> #include "common/ctx.h" #include "ui/ui.h" const char *banner = "THIS IS AN EXAMPLE PROGRAM"; /* Creates a sample in-memory game */ chiventure_ctx_t *create_sample_ctx() { game_t *game = game_new("Welcome to Chiventure!"); /* Create two rooms (room1 and room2). room1 is the initial room */ room_t *room0 = room_new("Journey's Other End", "This is room 0", "Here, our journey begins."); room_t *room1 = room_new("McDonalds", "This is room 1", "The greasy smell of fries beckons you closer"); room_t *room2 = room_new("Wingstop", "This is room 2", "The saucy smell of wings call to you"); room_t *room3 = room_new("Subway", "This is room 3", "The fresh smell of sammies summons."); room_t *room5 = room_new("room5", "This is room 5", "Strangely, this is only the fourth room."); add_room_to_game(game, room1); add_room_to_game(game, room2); add_room_to_game(game, room0); add_room_to_game(game, room3); add_room_to_game(game, room5); game->curr_room = room0; create_connection(game, "Journey's Other End", "McDonalds", "NORTH"); create_connection(game, "McDonalds", "Journey's Other End", "SOUTH"); create_connection(game, "Journey's Other End", "Wingstop", "EAST"); create_connection(game, "Wingstop", "Journey's Other End", "WEST"); create_connection(game, "Journey's Other End", "Subway", "SOUTH"); create_connection(game, "Subway", "Journey's Other End", "NORTH"); create_connection(game, "Journey's Other End", "room5", "WEST"); create_connection(game, "room5", "Journey's Other End", "EAST"); create_connection(game, "Subway", "room5", "SOUTH"); create_connection(game, "room5", "Subway", "NORTH"); /* Create a rock in room1 */ item_t *Lost_McDonalds_Order = item_new("McDonalds?","It seems to be an order of McDonalds.", "It seems like someone didn't get their order... Hopefully it can get back to them!"); add_item_to_room(room1, Lost_McDonalds_Order); item_t *Lost_Wingstop_Order = item_new("Wingstop?","It seems to be an order of Wingstop.", "It seems like someone didn't get their order... Hopefully it can get back to them!"); add_item_to_room(room2, Lost_Wingstop_Order); item_t *Lost_Subway_Order = item_new("Subway?","It seems to be an order of Subway.", "It seems like someone didn't get their order... Hopefully it can get back to them!"); add_item_to_room(room3, Lost_Subway_Order); /* Where custom_type comes into play, create a dynamic string (hold different values) depending on what the user enters at the start of the game */ data_t d1init, d2init, d3init; data_t d1, d2, d3, mcd, wng, sub; data_t rv2, rv3; d1.s = (char*)malloc(sizeof(char) * 500); d2.s = (char*)malloc(sizeof(char) * 500); d3.s = (char*)malloc(sizeof(char) * 500); mcd.s = "McDonalds"; wng.s = "Wingstop"; sub.s = "Subway"; char* name; name = (char*)malloc(sizeof(char) * 500); printf("Please enter your name: "); scanf("%s", name); strcpy(d1.s, name); strcpy(d2.s, name); strcpy(d3.s, name); object_t *ot1 = obj_t_init(d1init, STR_TYPE, "../../../../src/custom-scripts/examples/lua/lost_order.lua"); ot1 = obj_add_arg(obj_add_arg(ot1, d1, STR_TYPE), mcd, STR_TYPE); char* custom_string1 = (char*)malloc(sizeof(char*) * 500); data_t rv1 = arg_t_get(ot1); custom_string1 = rv1.s; object_t *ot2 = obj_t_init(d2init, STR_TYPE, "../../../../src/custom-scripts/examples/lua/lost_order2.lua"); ot2 = obj_add_arg(obj_add_arg(ot2, d2, STR_TYPE), wng, STR_TYPE); char* custom_string2 = (char*)malloc(sizeof(char*) * 500); rv2 = arg_t_get(ot2); custom_string2 = rv2.s; object_t *ot3 = obj_t_init(d3init, STR_TYPE, "../../../../src/custom-scripts/examples/lua/lost_order3.lua"); ot3 = obj_add_arg(obj_add_arg(ot3, d3, STR_TYPE), sub, STR_TYPE); char* custom_string3 = (char*)malloc(sizeof(char*) * 500); rv3 = arg_t_get(ot3); custom_string3 = rv3.s; /* Associate action "INSPECT" with each order. * It has no conditions, so it should succeed unconditionally. */ agent_t McDonalds = (agent_t){.item = Lost_McDonalds_Order, .npc = NULL}; add_action(&McDonalds, "INSPECT", custom_string1, "It smells greasy!"); agent_t Wingstop = (agent_t){.item = Lost_Wingstop_Order, .npc = NULL}; add_action(&Wingstop, "INSPECT", custom_string2, "It smells saucy!"); agent_t Subway = (agent_t){.item = Lost_Subway_Order, .npc = NULL}; add_action(&Subway, "INSPECT", custom_string3, "It smells... fresh?"); /* Create context */ chiventure_ctx_t *ctx = chiventure_ctx_new(game); free(name); return ctx; } int main(int argc, char **argv) { chiventure_ctx_t *ctx = create_sample_ctx(); /* Monkeypatch the CLI to add a new "kind 1" action * (i.e., an action that operates on an item) */ action_type_t inspect_action = {"INSPECT", ITEM}; add_entry(inspect_action.c_name, kind1_action_operation, &inspect_action, ctx->cli_ctx->table); /* Start chiventure */ start_ui(ctx, banner); game_free(ctx->game); return 0; }
C
#include<stdio.h> #include<unistd.h> #include<sys/types.h> /* * Primeiro executa o pai, depois o filho. */ int main(void) { write(STDOUT_FILENO, "1\n", 3); if (fork() > 0) { //Papai write(STDOUT_FILENO, "2", 1); write(STDOUT_FILENO, "3", 1); } else { //Filho write(STDOUT_FILENO, "4", 1); write(STDOUT_FILENO, "5", 1); } write(STDOUT_FILENO, "\n", 1); return 0; }
C
#include <stdio.h> int main(void) { int input = 0; //get input from the program user scanf("%i", &input); printf("The value is: %i", input); }
C
#include <stdio.h> #include <string.h> void main () { int a, b, c, d;// = 1,2,3,4; //strlen("Rishabh"), strlen ("Puri"), 90, 81; a = 1; b = 2; c = 3; d = 4; printf ("a %d,b %d ,c %d ,d %d",a,b,c,d); }
C
/* ** EPITECH PROJECT, 2020 ** directory ** File description: ** fonction */ #include "my.h" char **map(int ac, char **av) { int av1 = my_atoi(av[1]); int z = 0; int y = 0; char **square = malloc(sizeof(char *) * av1 + 2); for (int i = 0; i != av1 + 2; i++) square[i] = malloc(sizeof(char) * av1 * 2 + 1); for (int i = 1; i <= av1 + 2; i++) { for (int j = 1; j <= (av1 * 2) + 1; j++) { if (i == 1 || i == av1 + 2 || j == 1 || j == (av1 * 2) + 1) square[z][y++] = '*'; else square[z][y++] = ' '; } square[z++][y] = '\n'; y = 0; } int i = av1; for (int bas = 1, badg = av1 * 2 - 1; i > 0; bas++, badg--, i--) for (int bas2 = bas; bas2 <= badg; bas2++) square[i][bas2] = '|'; return square; } char **removepipe(int nbline, int nbmatches, char **map1) { int i; int z; for (i = 0; map1[nbline][i] != '|'; i++); for (z = i; map1[nbline][z] == '|'; z++); z--; for (int rm = 0; rm != nbmatches; rm++, z--) map1[nbline][z] = ' '; return map1; }
C
#include <stdio.h> #include <stdlib.h> int main() { int i=0; int nro; printf("\Ingrese un numero: "); scanf("%d",&nro); printf("\n\tTabla del nro %d con WHILE", nro); while(i<11){ printf("\n %d x %d = %d", nro, i, nro*i); i++; } printf("\n\n\tTabla del nro %d con FOR", nro); for(i=0;i<11;i++){ printf("\n %d x %d = %d", nro, i, nro*i); } printf("\n Hello world! %d \n", i); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* sortStone.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hypark <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/27 14:44:04 by hypark #+# #+# */ /* Updated: 2020/02/27 15:59:08 by hypark ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdio.h> //printf, scanf, ... #include <string.h> //memcpy, strlen, ... #include <unistd.h> //fork, write, sleep... #include <stdlib.h> //malloc, free, exit... #include <time.h> #include "header.h" void sortStones(struct s_stone **stone) { struct s_stone *start; struct s_stone *prev; struct s_stone *current_start; struct s_stone *current_end; struct s_stone *next_start; struct s_stone *next_end; int sort_end; start = *stone; sort_end = 1; while (sort_end) { current_start = start; current_end = start; prev = start; sort_end = 0; while (current_end->next) { next_start = current_end->next; if (current_end->size == next_start->size) current_end = next_start; else if (current_end->size > next_start->size) { sort_end = 1; next_end = next_start; while (next_end->next) { if (next_start->size == next_end->next->size) next_end = next_end->next; else break ; } if (prev == start) { current_end->next = next_end->next; next_end->next = current_start; prev = next_end; start = next_start; } else { current_end->next = next_end->next; next_end->next = current_start; prev->next = next_start; prev = next_end; } } else { prev = current_end; current_end = next_start; current_start = current_end; } } } *stone = start; }
C
#include "../ft_btree.h" void btree_apply_suffix(t_btree *root, void (*applyf)(void *)) { if (!root) return; btree_apply_suffix(left, &applyf); btree_apply_suffix(right, &applyf); applyf(root->item); }
C
#include "common.h" #include "common/string_util.h" #include <sys/types.h> #include <unistd.h> #include <signal.h> static crash_func_t crash_func = NULL; static void *usr = NULL; static bool sigsegv_handler_init = false; static const char *log_path = NULL; static FILE *debug_file = NULL; #define DEBUG_FILENAME "debug.log" static void sigsegv_handler(int signum) { do_crash(); signal(signum, SIG_DFL); kill(getpid(), signum); } void set_crash_func(crash_func_t crash_func_, void *usr_) { crash_func = crash_func_; usr = usr_; // register the sigsegv handler if(!sigsegv_handler_init) { signal(SIGSEGV, sigsegv_handler); sigsegv_handler_init = true; } } bool do_crash() { if(crash_func != NULL) { crash_func(usr); } return false; } FILE *common_get_debug_file(void) { if(debug_file == NULL) { const char *path = DEBUG_FILENAME; char *path_str = NULL; if(log_path != NULL) { path = path_str = string_util_concat(log_path, "/", DEBUG_FILENAME); } debug_file = fopen(path, "w"); if(debug_file == NULL) { fprintf(stderr, "Fatal Error: failed to open debug_file: '%s'\n", path); exit(1); } setbuf(debug_file, NULL); // disable buffering // cleanup if(path_str != NULL) free(path_str); } return debug_file; } void common_set_log_path(const char *path) { log_path = path; } void common_redirect_stderr(void) { FILE *debug_file = common_get_debug_file(); stderr = debug_file; }
C
#include <stdio.h> int main() { int a = 10, b = 4, res; // post-increment example: // res is assigned 10 only, a is not updated yet res = a++; printf("a is %d and res is %d\n", a, res); // a becomes 11 now // post-decrement example: // res is assigned 11 only, a is not updated yet res = a--; printf("a is %d and res is %d\n", a, res); // a becomes 10 now // pre-increment example: // res is assigned 11 now since a is updated here itself res = ++a; // a and res have same values = 11 printf("a is %d and res is %d\n", a, res); // pre-decrement example: // res is assigned 10 only since a is updated here itself res = --a; // a and res have same values = 10 printf("a is %d and res is %d\n", a, res); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include "pomiar_czasu.h" #include <time.h> #include <math.h> //#include <unistd.h // build: gcc -I/usr/include -L/usr/lib64 main.c -lpthread -L pomiar_czasu.h pomiar_czasu.c typedef struct Dane {int a,b; int n, id, k; } Dane; double wynik = .0; pthread_mutex_t m; inline double fun (double x) { return x*x + x + 4; } double licz_pole (int a, int b, int n) { double h = (b-a)/(double)n; //wysokosć trapezów double S = 0.0; //zmienna będzie przechowywać sumę pól trapezów double podstawa_a = fun(a), podstawa_b; int i; for(i=1;i<=n;i++) { podstawa_b = fun(a+h*i); S += (podstawa_a+podstawa_b); podstawa_a = podstawa_b; } return (.5 * S * h); } void * watek_licz_pole (void *arg) { Dane *dane = arg; int a = dane->a; int b = dane->b; double n = dane->n; /* Dane dane = *((Dane*) arg); double a = dane.a; double b = dane.b; double n = dane.n; */ double h = (b-a)/n; //wysokosć trapezów double S = 0.0; //zmienna będzie przechowywać sumę pól trapezów double podstawa_a = fun(a), podstawa_b; int i; for(i=1;i<=n;i++) { podstawa_b = fun(a+h*i); S += (podstawa_a+podstawa_b); podstawa_a = podstawa_b; } // synchronizacja: pthread_mutex_lock (&m); wynik += (.5 * S * h); pthread_mutex_unlock (&m); return (NULL); } void * watek_licz_pole2 (void * arg) { Dane *dane = arg; int a = dane->a; int b = dane->b; double n = dane->n; int i, j, id = dane->id; int k = dane->k; double S =.0; double h = (b-a)/n; j = n/k; i=(j*id)+1; double podstawa_a = fun(a*i*h), podstawa_b; for( ;i<=j*(id+1);++i) { podstawa_b = fun(a+h*i); S += (podstawa_a+podstawa_b); podstawa_a = podstawa_b; } // synchronizacja: pthread_mutex_lock (&m); wynik += (.5 * S * h); pthread_mutex_unlock (&m); return (NULL); } int main() { int n, a, b; printf("Podaj a: "); scanf("%d", &a); printf("Podaj b: "); scanf("%d", &b); printf("Podaj dokladnosc: "); scanf("%d", &n); if (b<a) { return 0; } pthread_mutex_init (&m, NULL); // sekwencyjnie inicjuj_czas(); double w = licz_pole(a, b, n); printf("\tWynik calki sekwencyjnie: %f\n", w); drukuj_czas(); int k=2; for ( ;k<=6;k+=2) { wynik = .0; int i; //k=4; Dane dane[k]; for (i=0;i<k;i++) { dane[i].a=a; dane[i].b=a; dane[i].n=n; } // dekompozycja pthread_t watki[k]; double x = (b-a)/k; // x-wielkosc przedzialow dla k-watkow inicjuj_czas(); for(i=0;i<k;i++){ dane[i].b += x; pthread_create(&watki[i], NULL, watek_licz_pole, &dane[i]); //sleep(1); dane[i+1].a = dane[i].b; dane[i+1].b = dane[i].b; } // czekamy na watki for (i=0;i<k;i++) { pthread_join(watki[i], NULL); } printf("\tWynik calki liczonej na %d watkach (dekompozycja): %f \n", k, wynik); drukuj_czas(); // zrownoleglenie petli wynik = .0; Dane dane2[k]; for (i=0;i<k;i++) { dane2[i].a=a; dane2[i].b=b; dane2[i].n=n; dane2[i].id=i; dane2[i].k=k; } pthread_t threads[k]; inicjuj_czas(); for (i=0;i<k;i++) { pthread_create(&threads[i], NULL, watek_licz_pole2, &dane2[i]); } for (i=0;i<k;i++) pthread_join(threads[i], NULL); printf("\tWynik calki liczonej na %d watkach (loop paralleism): %f \n", k, wynik); drukuj_czas(); printf("\n"); } pthread_exit(NULL); //return (EXIT_SUCCESS); }
C
/*Задача 13.Опишете времето: часове:минути:секунди като структура tagTMyTime. Използвайки тази структура, дефинирайте следните функции: добавяне на секунди, добавяне на минути. добавяне на часове към дадена променлива от тип struct tagTMyTime. Напишете следните функции: връщане на броя секунди за дадена променлива от въведения тип и обратна функция от секундите да се генерира променлива tagTMyTime. Напишете две функции, които изваждат и събират две променливи от тип struct tagMyTime и връщат променлива от същия тип. Използвайте тези функции, за да се уверите, че работят коректно. В решението трябва да се използва динамично заделяне на памет и typedef.*/ #include <stdio.h> #include <stdlib.h> typedef struct { int hours; int minutes; int seconds; } tagTMyTime; void fixTime(tagTMyTime *variable); void addSeconds(tagTMyTime *variable, int seconds); void addMinnutes(tagTMyTime *variable, int minutes); void addHours(tagTMyTime *variable, int hours); int seconds(tagTMyTime *variable); tagTMyTime *secondsIntoTime(int seconds); tagTMyTime *addTwoTimers(tagTMyTime *variable1, tagTMyTime *variable2); tagTMyTime *substractTwoTimers(tagTMyTime *variable1, tagTMyTime *variable2); int main() { tagTMyTime *clock1 = NULL; clock1 = (tagTMyTime *)malloc(sizeof(tagTMyTime)); clock1->hours = 12; clock1->minutes = 30; clock1->seconds = 44; addSeconds(clock1, 50); /*add 50s to 12:30:44 => 12:31:34*/ addMinnutes(clock1, 30); /*add 30m to 12:31:34 => 13:01:34*/ addHours(clock1, 12); /*add 12h to 12:1:34 => 01:01:34*/ printf("%.2d:%.2d:%.2d\n", clock1->hours, clock1->minutes, clock1->seconds); clock1->hours = 2; clock1->minutes = 1; clock1->seconds = 0; printf("%d\n", seconds(clock1)); /* print how many seconds there are in clock1*/ clock1 = secondsIntoTime(8274); /*we convert given seconds to a new time structure*/ printf("%.2d:%.2d:%.2d\n", clock1->hours, clock1->minutes, clock1->seconds); tagTMyTime *clock2 = (tagTMyTime *)malloc(sizeof(tagTMyTime)); tagTMyTime *clock3 = (tagTMyTime *)malloc(sizeof(tagTMyTime)); clock1->hours = 12, clock1->minutes = 30, clock1->seconds = 44; clock2->hours = 13, clock2->minutes = 21, clock2->seconds = 30; clock3 = addTwoTimers(clock1, clock2); /*we add the two timers together and assign them to a new one 12:30:44 + 13:21:30 => 1:51:14*/ printf("%.2d:%.2d:%.2d\n", clock3->hours, clock3->minutes, clock3->seconds); clock1 = substractTwoTimers(clock3, clock2); printf("%.2d:%.2d:%.2d\n", clock1->hours, clock1->minutes, clock1->seconds); /*we substract clock2 from clock1 and see if we get clock1 back*/ free(clock1); free(clock2); free(clock3); return 0; } /*Function to fix the time when seconds minutes of hours are overflowing*/ void fixTime(tagTMyTime *variable) { if (variable->seconds >= 60) { variable->minutes++; variable->seconds = variable->seconds - 60; } if (variable->minutes >= 60) { variable->hours++; variable->minutes = variable->minutes - 60; } if (variable->hours >= 24) { variable->hours = variable->hours - 24; } if (variable->seconds < 0) { variable->minutes--; variable->seconds = variable->seconds + 60; } if (variable->minutes < 0) { variable->hours--; variable->minutes = variable->minutes + 60; } if (variable->hours < 0) { variable->hours = variable->hours + 24; } } /*Function to add given seconds to a timer*/ void addSeconds(tagTMyTime *variable, int seconds) { variable->seconds += seconds; fixTime(variable); } /*Function to add given minutes to a timer*/ void addMinnutes(tagTMyTime *variable, int minutes) { variable->minutes += minutes; fixTime(variable); } /*Function to add given hours to a timer*/ void addHours(tagTMyTime *variable, int hours) { variable->hours += hours; fixTime(variable); } /*Function to return how many seconds there are in a timer*/ int seconds(tagTMyTime *variable) { int sumSeconds = 0; sumSeconds += variable->seconds; sumSeconds += variable->minutes * 60; sumSeconds += variable->hours * 3600; return sumSeconds; } /*Function to return a timer by given seconds*/ tagTMyTime *secondsIntoTime(int seconds) { tagTMyTime *clock = (tagTMyTime *)malloc(sizeof(tagTMyTime)); int h, m, s; h = seconds / 3600; m = (seconds - (3600 * h)) / 60; s = (seconds - (3600 * h) - (m * 60)); clock->hours = h; clock->minutes = m; clock->seconds = s; return clock; } /*Function to add two timers together into a new one*/ tagTMyTime *addTwoTimers(tagTMyTime *variable1, tagTMyTime *variable2) { tagTMyTime *newClock = (tagTMyTime *)malloc(sizeof(tagTMyTime)); newClock->seconds = variable1->seconds + variable2->seconds; fixTime(newClock); newClock->minutes = variable1->minutes + variable2->minutes; fixTime(newClock); newClock->hours = variable1->hours + variable2->hours; fixTime(newClock); return newClock; } tagTMyTime *substractTwoTimers(tagTMyTime *variable1, tagTMyTime *variable2) { tagTMyTime *newClock = (tagTMyTime *)malloc(sizeof(tagTMyTime)); newClock->seconds = variable1->seconds - variable2->seconds; fixTime(newClock); newClock->minutes = variable1->minutes - variable2->minutes; fixTime(newClock); newClock->hours = variable1->hours - variable2->hours; fixTime(newClock); return newClock; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *array[4]; int x = 0; array[0] = "hello"; array[1] = "red"; array[2] = "blue"; array[3] = "green"; for(x = 0; x < 3; x++) { printf("%s", array[x]); printf("\n"); } return 0; }
C
/************************************************************************* > File Name: test.h > Author: ChongH > Mail: [email protected] > Created Time: 2018年10月06日 星期六 10时14分58秒 ************************************************************************/ #ifndef _TEST_H #define _TEST_H #include <stdlib.h> typedef struct TestFuncData { int total, expect; }TestFuncData; typedef void (*test_func_t)(TestFuncData *); typedef struct FuncData { const char *a_str, *b_str; test_func_t func; struct FuncData *next; }FuncData; void addFuncData( const char *a, const char *b, test_func_t func ); #define TEST(a, b) \ void a##_haizeix_##b(TestFuncData *); \ __attribute__((constructor)) \ void ADDFUNC_##a##_haizeix_##b() { \ addFuncData(#a, #b, a##_haizeix_##b); \ } \ void a##_haizeix_##b(TestFuncData *_data) #define EXPECT(a, b) ({ \ int temp; \ printf("%s = %s %s\n", #a, #b, (temp = (a == b)) ? "True" : "False"); \ _data->total++; \ _data->expect += temp; \ }) int RUN_ALL_TEST(); #endif
C
/*+ * United States Geological Survey * * PROJECT : Modular Modeling System (MMS) * FUNCTION : str_to_vals * COMMENT : decodes a string into values, and loads memory addresses * Examples of legal strings for this routine: * * "1 2 3 4 5" * "1.0, 2.2, 19e9" * "1*23.5, 7*1 13 12*3" * * Blanks, commas, tabs and newlines may delimit the values. * The repeat count is optional, but must be greater than 0 if included. * If the total number of entries is less than required, the sequence * is repeated. * * $Id$ * -*/ /**1************************ INCLUDE FILES ****************************/ #define STR_TO_VALS_C #include <stdio.h> #include <string.h> #include <math.h> #include <errno.h> #include <stdlib.h> #include "mms.h" #define S2V_ERROR 1l #define S2V_SUCCESS 0l /*--------------------------------------------------------------------*\ | FUNCTION : str_to_vals | COMMENT : | PARAMETERS : | RETURN VALUE : | RESTRICTIONS : \*--------------------------------------------------------------------*/ long str_to_vals (char *encoded_string, long size, long type, char *store_addr) { long i, isource; long ndecoded, repeat; char *scopy, *token, *valstr, *asterisk, *end_point; static char *tcopy = NULL; double dvalue, *dval; float fvalue, *fval; int lvalue, *lval; char *svalue, **sval; // 2016-01-13 PAN: added string pointers if (tcopy == NULL) { tcopy = (char *) umalloc(max_data_ln_len * sizeof(char)); } /* * set up pointer for data type */ dval = NULL; fval = NULL; lval = NULL; sval = NULL; // 2016-01-13 PAN: added sval init svalue = NULL; switch (type) { case M_DOUBLE: dval = (double *) store_addr; break; case M_FLOAT: fval = (float *) store_addr; break; case M_LONG: lval = (int *) store_addr; break; // 2016-01-13 PAN: added case for string values case M_STRING: sval = (char **) store_addr; break; } /* * copy encoded_string before tokenizing */ scopy = strdup (encoded_string); token = strtok (scopy, " ,\t\n"); ndecoded = 0; while (token != NULL) { (void)strncpy(tcopy, token, max_data_ln_len); asterisk = strrchr(tcopy, '*'); /* search for '*' */ if (asterisk == NULL ) { /* no repeat count */ valstr = tcopy; repeat = 1; } else { valstr = asterisk + 1; *asterisk = '\0'; /* terminate repeat count str */ repeat = strtol(tcopy, &end_point, 10l); if (repeat <= 0 || *end_point != '\0') { (void)fprintf(stderr, "ERROR - str_to_vals - decoding string into values.\n"); (void)fprintf(stderr, "Illegal repeat count.\n"); return S2V_ERROR; } } /* * set errno to 0 so that previous errors are cancelled */ errno = 0; dvalue = 0.0; fvalue = 0.0; lvalue = 0; switch (type) { case M_DOUBLE: dvalue = strtod(valstr, &end_point); break; case M_FLOAT: fvalue = (float) strtod(valstr, &end_point); break; case M_LONG: lvalue = (int)strtol(valstr, &end_point, 10); break; // 2016-01-13 PAN: added case for string values case M_STRING: svalue = valstr; break; } if (errno == EDOM) { (void)fprintf(stderr, "ERROR - str_to_vals - decoding string into values.\n"); (void)fprintf(stderr, "Illegal value.\n"); return S2V_ERROR; } if (errno == ERANGE) { (void)fprintf(stderr, "ERROR - str_to_vals - decoding string into values.\n"); (void)fprintf(stderr, "Value out of range.\n"); return S2V_ERROR; } if (ndecoded + repeat > size) { repeat = size - ndecoded; } switch (type) { case M_DOUBLE: for (i = 0; i < repeat; i++) { dval[ndecoded] = dvalue; ndecoded++; } break; case M_FLOAT: for (i = 0; i < repeat; i++) { fval[ndecoded] = fvalue; ndecoded++; } break; case M_LONG: for (i = 0; i < repeat; i++) { lval[ndecoded] = lvalue; ndecoded++; } break; // 2016-01-13 PAN: added case for string values case M_STRING: for (i = 0; i < repeat; i++) { *(sval + i) = strdup(svalue); ndecoded++; } break; } token = strtok(NULL, " ,\n\t"); } /* * If too few elements decoded, repeat the sequence */ if (ndecoded < size) { isource = 0; switch (type) { case M_DOUBLE: for (i = ndecoded; i < size; i++) { dval[i] = dval[isource]; isource++; if (isource == ndecoded) isource = 0; } break; case M_FLOAT: for (i = ndecoded; i < size; i++) { fval[i] = fval[isource]; isource++; if (isource == ndecoded) isource = 0; } break; case M_LONG: for (i = ndecoded; i < size; i++) { lval[i] = lval[isource]; isource++; if (isource == ndecoded) isource = 0; } break; // 2016-01-13 PAN: added case for string values case M_STRING: for (i = ndecoded; i < size; i++) { *(sval + i) = strdup(*(sval + isource)); isource++; if (isource == ndecoded) isource = 0; } break; } } return S2V_SUCCESS; }
C
/*SORU 1) Bir integer sayy parametre olarak alan ve bu saynn kpn hesaplayarak return eden fonksiyonu yaznz. */ #include <stdio.h> #include <conio.h> int kupbul(int a) { int carp=1; int i; for(i=1; i<=3; i++) { carp = carp * a; } return carp; } int main(void) { int z; z = kupbul(2); printf("%d",z); }
C
#include <pebble.h> #include "utility.h" static int outsideRange(int digit,int min,int max) { if (digit >= min && digit <= max) { return 0; } else { return 1; } } static void split_string (char **inarray, char *delimiter, char *instring) { int i; char *p; // for (i=0;i<3; ++i) { // APP_LOG(APP_LOG_LEVEL_DEBUG, "before -->string split loop inarray[%d]: %s", i, inarray[i]); // } i = 0; p = myStrtok (instring,delimiter); while (p != NULL) { inarray[i++] = p; p = myStrtok (NULL, delimiter); } // for (i=0;i<3; ++i) { // APP_LOG(APP_LOG_LEVEL_ERROR, "after-->string split loop inarray[%d]: %s", i, inarray[i]); // } } static int first_digit(int digit) { int firstPart; if (digit >= 100 && digit < 1000) { firstPart = digit / 100; } else { firstPart = 0; } return firstPart; } // function to convert Battery % to temp scale static int battery_to_temp(int a) { int temperature = 0; temperature = (int)(float)(-a / 2 + 35); return (temperature); // APP_LOG(APP_LOG_LEVEL_DEBUG, "battery_to_temp:"); } static char *myStrtok(char *parseStr, char *splitChars) { // from here // http://www.cs.uah.edu/~rcoleman/Common/CodeVault/Code/Code501_Goodies.html // Note: The first var is declared as "static" this // means that after the initial call to the function it // will retain its last value with each subsequent call // to this function. It is initialized on the very first // call to this function to NULL. static char *pStr = NULL; // Pointer to string to be tokenized. char *tok; // Pointer to start of next token char *temp; // Misc. use temporary pointer. int found; // Boolean flag to indicate a split character was found //---------------------------------------------------------------- // Case 1: See if a new string to be parsed was passed in. This // will be true if parseStr is not NULL //---------------------------------------------------------------- if(parseStr != NULL) pStr = parseStr; // If yes, then hold the pointer to it //---------------------------------------------------------------- // Case 2: Check to see if the last call to this function returned // the last token in the string. If pStr is now pointing // to the NULL terminator this will be true //---------------------------------------------------------------- if(*pStr == '\0') return NULL; // Tell user all tokens have been returned //---------------------------------------------------------------- // Case 3: Find the next token. // Step 1: Starting from the end of the last token returned // or the beginning of the new string to parse skip any // leading characters that are the same as characters found // in the splitChars array. We also look for the NULL // terminator indicating we have reached the end of parseStr. //---------------------------------------------------------------- found = 0; // Initialize to FALSE tok = pStr; // Initialize tok pointer to start current point in parseStr // Skip any leading splitChars while((!found) && (*tok != '\0')) { temp = splitChars; // Point to start of splitChars array while(*temp != '\0') // Scan entire splitChars array each time { if(*tok != *temp) { temp++; // Advance to next character in splitChars } else // Found a split char { tok++; // Advance to next character in parseStr break; // and end this scan of the splitChars array } } // Check to see if we made it through the entire splitChars // array without finding a match, i.e. we have the first char // in the next token if(*temp == '\0') found = 1; // Mark as TRUE to end search // Note: If tok was advanced to point to the NULL terminator at the // end of parseStr this will also terminate the loop } // Check to see if we reached the end of parseStr without finding another // token. If so set pStr so we can recognize this at the next call if(*tok == '\0') { pStr = tok; // Point pStr to the NULL terminator at the end of parseStr return tok; // Return NULL to indicate the end of the string was reached. } // When we reach this point tok points to the first non-splitChars character //---------------------------------------------------------------- // Step 2: Find the end of this token. This will be the next // occurance of one of the characters in splitChars or the // NULL terminator marking the end of parseStr //---------------------------------------------------------------- found = 0; // Initialize to FALSE pStr = tok; // Initialize pStr to tok // Search for first occurance of a splitChars character marking the end // of this token. Also look to see if we reach the end of parseStr while((!found) && (*pStr != '\0')) { temp = splitChars; // Point to start of splitChars array // Scan entire splitChars array to see if the char pStr points to // is one of the split chars. while((*temp != '\0') && (*pStr != *temp)) temp++; // if this char was OK advance to the next and try again if(*temp == '\0') pStr++; else found = 1; // Found the end of the token so end the while() loop // Note: If pStr was advanced to point to the NULL terminator at the // end of parseStr this will also terminate the loop } // At this point we have tok pointing to the first character of the // next token in parseStr and pStr pointing to the first character // after the end of the next token. //---------------------------------------------------------------- // Step 3: Set up for the return and next call. //---------------------------------------------------------------- // When we reach this point if pStr is pointing to the NULL terminator // at the end of parseStr we leave pStr pointing to this NULL terminator // so we will know this on the next call to this function. if(*pStr != '\0') { // However, if pStr is not pointing to a NULL terminator then it // must be pointing to a split character so we replace the character // pStr is pointing to with a NULL terminator so the caller can get // the token by itself and advance pStr to the first character after // that so it is ready to parse the next token on the next call to // this function. *pStr = '\0'; // Put a NULL terminator at the end of this token pStr++; // Advance pStr to the next character in parseStr } return tok; // Return the pointer to the next token }
C
/* * sleepenh.c - enhanced sleep command * * Copyright (C) 2003 Pedro Zorzenon Neto * Copyright (C) 2014 Nicolas Schier <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, * MA 02110-1301, USA. * * USAGE INSTRUCTIONS * * this program is an enhanced version of sleep, you can use as * a simple sleep program, with microseconds * Example: (sleeps 45.123234 seconds) * sleepenh 45.123234 * * if it is called with two arguments, it acts as a sleep program * that can be called in sequence and will not have cumulative * errors from one call to another. * Example: (time from one 'ls' to other is 12.4 seconds) * VAL=`sleepenh 0` ; while true; do ls; VAL=`sleepenh 12.4`; done * * Exit status: * 0 - success. I needed to sleep sometime * 1 - success. I did not need to sleep * >9 - failure. * 10 - failure. not enough command line arguments * 11 - failure. did not receive sigalrm * 12 - failure. argument is not a finite number * 13 - failure. could not get current time (gettimeofday) * * shell script usage example: see manpage */ #define _GNU_SOURCE #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <sys/time.h> #include <time.h> #include <signal.h> #include <unistd.h> #include <math.h> #include <string.h> #define SHORTEST_SLEEP 0.00001 /* 10msec, a timeslice */ static int sigflag=0; void got_signal() { sigflag=1; } void version(FILE *f) { fprintf(f, "sleepenh " VCSVERSION "\n" "\n" "Copyright (C) 2003 Pedro Zorzenon Neto\n" "Copyright (C) 2014 Nicolas Schier\n" "License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl.html>.\n" "This is free software: you are free to change and redistribute it.\n" "There is NO WARRANTY, to the extent permitted by law.\n"); } void usage(FILE *f) { fprintf(f, "Usage: %s [[--warp|-w] INITIALTIME] TIMETOSLEEP\n" "\n" "An enhanced sleep program.\n" "\n" "Options:\n" " -h, --help display this help and exit\n" " -w, --warp warp resulting timestamp, when there is no need\n" " to sleep. An immediatly following call of\n" " sleepenh with the resulting TIMESTAMP would\n" " most probably result in a real sleep.\n" " -V, --version output version information and exit\n" "\n" "TIMETOSLEEP is in seconds, microsecond resolution, ex: 80.123456.\n" "INITIALTIME is the output value of a previous execution of sleepenh.\n", program_invocation_short_name); } int main(int argc, char *argv[]) { struct timeval tv; struct timezone tz; struct itimerval itv; struct sigaction sigact; double st; /* sleep time */ double et; /* end time */ double now; /* now */ double it; /* initial time */ double sleep_time; /* effective time to sleep */ int warp = 0; if ((argc > 1) && (!strcmp(argv[1], "--warp") || !strcmp(argv[1], "-w"))) { warp = 1; argc--, argv++; } if (argc==1) { version(stderr); fprintf(stderr, "\n"); usage(stderr); return 10; /* failure, bad arguments */ } if (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h") || !strcmp(argv[1], "--usage") || !strcmp(argv[1], "-u")) { usage(stdout); return 0; } if (!strcmp(argv[1], "--version") || !strcmp(argv[1], "-V")) { version(stdout); return 0; } if(gettimeofday(&tv,&tz)!=0) { return 13; /* failure, could not get current time */ } st=strtod(argv[argc-1],NULL); if(finite(st)==0) { return 12; /* failure, argument is not a finite number */ } now=tv.tv_sec+(tv.tv_usec*0.000001); if (argc==2) { /* without initialtime */ it=now; } else { /* with initialtime */ it=strtod(argv[1],NULL); if(finite(it)==0) { return 12; /* failure, argument is not a finite number */ } } et=it+st; sleep_time = et - now; if (sleep_time < SHORTEST_SLEEP) { if (warp) { /* warp in time -> loose events, but keep event regularity */ int tmp; tmp = (now - it) / st; et = it + tmp * st; } /* has already timed out, shorted than a timeslice */ printf("%f\n",et); return 1; /* success, time out */ } /* set signal handler */ memset(&sigact, 0, sizeof(sigact)); sigact.sa_handler=&got_signal; sigaction (SIGALRM, &sigact, NULL); /* set timer */ itv.it_value.tv_sec=(long int) sleep_time; itv.it_value.tv_usec=((long int) (sleep_time*1000000)) % 1000000; itv.it_interval.tv_sec=0; itv.it_interval.tv_usec=0; setitimer(ITIMER_REAL,&itv,NULL); pause(); /* wait for signal */ printf("%f\n",et); if (sigflag==1) { return 0; /* success */ } return 11; /* failure */ }
C
/* * Copyright (c) 2010-2016 TIBCO Software Inc. * All Rights Reserved. Confidential & Proprietary. * For more information, please contact: * TIBCO Software Inc., Palo Alto, California, USA * * $Id: fldref.h 90137 2016-12-13 19:04:42Z $ */ #ifndef _INCLUDED_tib_fldref_h #define _INCLUDED_tib_fldref_h #include "tib/tibexp.h" #include "tib/except.h" #if defined(__cplusplus) extern "C" { #endif /** * @file fldref.h * * @brief Field references enable efficiency gains when accessing message fields. * * This file defines field reference objects and the calls that manipulate them. */ /** @brief Field reference object type. * * The API provides two versions of each message field accessor call -- * one accepts a \e field \e name, while the other accepts a \e field \e * reference \e object (@ref tibFieldRef). Access by field * reference is more efficient than access by name alone. * * Field reference objects contain a field name, along with internal * information that enables efficient access. * * Programs can repeatedly use a field reference object to efficiently * access a field -- even across messages of different formats. * * For example, if formats \c A and \c B both have a field named \c * foo, then a field reference object with field name \c foo accesses * the correct field in messages of either format. * * Field reference objects are thread-safe. (However, the field * reference that @ref tibMessageIterator_GetNext returns is an * exception to this rule.) */ typedef struct __tibFieldRef *tibFieldRef; /** @brief Create a field reference object. * * This call uses its field name argument to look up internal * information that enables efficient access, and caches that * information in the new field reference object. * * @param e The exception object captures information about failures. * @param fieldName The call embeds this field name in the new field reference object. * * @return a new @ref tibFieldRef object */ TIB_API tibFieldRef tibFieldRef_Create( tibEx e, const char* fieldName); /** @brief Destroy a field reference object. * * Destroying a field reference object frees all resources associated * with the field reference. * * It is illegal to destroy a field reference object obtained from * @ref tibMessageIterator_GetNext. * * @param e The exception object captures information about failures. * @param f The call destroys this field reference object. * * @return void */ TIB_API void tibFieldRef_Destroy( tibEx e, tibFieldRef f); /** @brief Get the field name from a field reference object. * * The name that this call returns becomes invalid when the field * reference object becomes invalid. * * @param e The exception object captures information about failures. * @param f The call returns the name from this field reference object. * * @return the field name of the reference */ TIB_API const char* tibFieldRef_GetFieldName( tibEx e, tibFieldRef f); #if defined(__cplusplus) } #endif #endif /* _INCLUDED_tib_fldhndl_h */
C
#include <stdio.h> char * my_strstr(char * text_to_be_searched, char * text_first_occurrence_is_serched_for); /* int main() { char a[] = "1234567aa"; char b[] = "aaaaaa"; printf("%s\n", my_strstr(a, b)); } */ char * my_strstr(char* lc, char* sc){ if(sc[0]=='\0') goto emptyNeedle; int i; int j; //boolean: if sc and lc looped thru and no difference was found => 1 int similar=0; for(i=0; lc[i]!='\0'; i++){ //printf("looping to %c\n", lc[i]); if (lc[i]==sc[0]){ similar = 1; for(j=0; sc[j] != '\0'; j++){ if(lc[j+i] == sc[j]){ //printf("\t%c and %c are similar\n", lc[j+i], sc[j]); continue; }else { similar=0; //printf("\t%c and %c NOT similar\n", lc[j+i], sc[j]); break; } } } if(similar) break; } if(similar!=0) return lc+i; else return NULL;// "NULL"; emptyNeedle: return lc; }
C
/** ****************************************************************************** * @file lcd16x2.c * @author Yohanes Erwin Setiawan * @version 1.0 * @date 6 Februay 2016 ****************************************************************************** */ /** Includes ---------------------------------------------------------------- */ #include "lcd16x2.h" /** For access DDR and PIN by PORT as a parameter input --------------------- */ #define DDR(x) (*(&x - 1)) // Address DDRx = address of PORTx - 1 #define PIN(x) (*(&x - 2)) // Address PINx = address of PORTx - 2 /** Private function prototypes --------------------------------------------- */ static void lcd16x2_toggle_e(void); static void lcd16x2_write(uint8_t data, uint8_t rs); static uint8_t lcd16x2_read(uint8_t rs); static uint8_t lcd16x2_wait_busy(void); static inline void lcd16x2_new_line(uint8_t pos); static uint8_t display_cursor_on_off_control; /** Public functions -------------------------------------------------------- */ /** ****************************************************************************** * @brief Initialize the LCD 16x2 with 4-bit I/O mode. * @param Display, cursor underline, and cursor blink settings. See * LCD display and cursor attributes define in lcd16x2.h file. * @retval None ****************************************************************************** */ void lcd16x2_init(uint8_t disp_attr) { // Configure I/O for control and data lines as output if ((&LCD16X2_PORT_D4 == &LCD16X2_PORT_D5) && (&LCD16X2_PORT_D5 == &LCD16X2_PORT_D6) && (&LCD16X2_PORT_D6 == &LCD16X2_PORT_D7) && (&LCD16X2_PORT_D7 == &LCD16X2_PORT_RS) && (&LCD16X2_PORT_D7 == &LCD16X2_PORT_RW) && (&LCD16X2_PORT_D7 == &LCD16X2_PORT_EN) && (LCD16X2_PIN_RS == 0) && (LCD16X2_PIN_RW == 1) && (LCD16X2_PIN_EN == 2) && (LCD16X2_PIN_D4 == 4) && (LCD16X2_PIN_D5 == 5) && (LCD16X2_PIN_D6 == 6) && (LCD16X2_PIN_D7 == 7)) { /* LCD control and data lines on same port */ DDR(LCD16X2_PORT_D7) |= 0xF7; } else if ((&LCD16X2_PORT_D4 == &LCD16X2_PORT_D5) && (&LCD16X2_PORT_D5 == &LCD16X2_PORT_D6) && (&LCD16X2_PORT_D6 == &LCD16X2_PORT_D7) && (LCD16X2_PIN_D4 == 4) && (LCD16X2_PIN_D5 == 5) && (LCD16X2_PIN_D6 == 6) && (LCD16X2_PIN_D7 == 7)) { /* LCD control lines on different port, but data lines on same port */ DDR(LCD16X2_PORT_RS) |= (1 << LCD16X2_PIN_RS); DDR(LCD16X2_PORT_RW) |= (1 << LCD16X2_PIN_RW); DDR(LCD16X2_PORT_EN) |= (1 << LCD16X2_PIN_EN); DDR(LCD16X2_PORT_D7) |= 0xF0; } else { /* LCD control and data lines on different port */ DDR(LCD16X2_PORT_RS) |= (1 << LCD16X2_PIN_RS); DDR(LCD16X2_PORT_RW) |= (1 << LCD16X2_PIN_RW); DDR(LCD16X2_PORT_EN) |= (1 << LCD16X2_PIN_EN); DDR(LCD16X2_PORT_D4) |= (1 << LCD16X2_PIN_D4); DDR(LCD16X2_PORT_D5) |= (1 << LCD16X2_PIN_D5); DDR(LCD16X2_PORT_D6) |= (1 << LCD16X2_PIN_D6); DDR(LCD16X2_PORT_D7) |= (1 << LCD16X2_PIN_D7); } // Delay power on _delay_us(LCD16X2_DELAY_POWER_ON); // Initialize 8-bit mode first LCD16X2_PORT_D5 |= (1 << LCD16X2_PIN_D5); // Function set LCD16X2_PORT_D4 |= (1 << LCD16X2_PIN_D4); // 8-bit mode lcd16x2_toggle_e(); // Delay, busy flag can't be checked here _delay_us(LCD16X2_DELAY_INIT); // Repeat last command lcd16x2_toggle_e(); // Delay, busy flag can't be checked here _delay_us(LCD16X2_DELAY_INIT_REP); // Repeat last command for third time lcd16x2_toggle_e(); // Delay, busy flag can't be checked here _delay_us(LCD16X2_DELAY_INIT_REP); // Initialize 4-bit mode LCD16X2_PORT_D5 |= (1 << LCD16X2_PIN_D5); // Function set LCD16X2_PORT_D4 &= ~(1 << LCD16X2_PIN_D4); // 4-bit mode lcd16x2_toggle_e(); _delay_us(LCD16X2_DELAY_INIT_4BIT); /* From now the LCD only accepts 4 bit I/O */ // 4-bit interface, 2 lines, 5x7 dot format font lcd16x2_write_command(LCD16X2_FUNCTION_SET | LCD16X2_4BIT_INTERFACE | LCD16X2_2LINE_MODE | LCD16X2_5X7DOT_FORMAT); // Display off lcd16x2_write_command(LCD16X2_DISPLAY_CURSOR_ON_OFF | LCD16X2_DISPLAY_OFF); // Clear screen lcd16x2_clrscr(); // Entry mode lcd16x2_entry_inc(); // Display cursor on off display_cursor_on_off_control = disp_attr; lcd16x2_write_command(LCD16X2_DISPLAY_CURSOR_ON_OFF | display_cursor_on_off_control); } /** ****************************************************************************** * @brief Write a command to the LCD. * @param The LCD instructions set. * @retval None ****************************************************************************** */ void lcd16x2_write_command(uint8_t cmd) { lcd16x2_wait_busy(); lcd16x2_write(cmd, 0); } /** ****************************************************************************** * @brief Write a data byte to the LCD. * @param Data which want to written to the LCD. * @retval None ****************************************************************************** */ void lcd16x2_write_data(uint8_t data) { lcd16x2_wait_busy(); lcd16x2_write(data, 1); } /** ****************************************************************************** * @brief Clear the LCD display and return cursor to home position. * @param None * @retval None ****************************************************************************** */ void lcd16x2_clrscr() { lcd16x2_write_command(LCD16X2_CLEAR_DISPLAY); } /** ****************************************************************************** * @brief Return cursor to home position. * @param None * @retval None ****************************************************************************** */ void lcd16x2_home() { lcd16x2_write_command(LCD16X2_CURSOR_HOME); } /** ****************************************************************************** * @brief Set LCD cursor to specific position. * @param LCD column (x) * @param LCD row (y) * @retval None ****************************************************************************** */ void lcd16x2_gotoxy(uint8_t x, uint8_t y) { #if LCD16X2_LINES == 1 lcd16x2_write_command(LCD16X2_SET_DDRAM_ADDRESS | (LCD16X2_START_LINE_1 + x)); #elif LCD16X2_LINES == 2 if (y == 0) lcd16x2_write_command(LCD16X2_SET_DDRAM_ADDRESS | (LCD16X2_START_LINE_1 + x)); else lcd16x2_write_command(LCD16X2_SET_DDRAM_ADDRESS | (LCD16X2_START_LINE_2 + x)); #endif } /** ****************************************************************************** * @brief Get LCD cursor/ DDRAM address. * @param None * @retval LCD cursor/ DDRAM address. ****************************************************************************** */ uint8_t lcd16x2_getxy() { return lcd16x2_wait_busy(); } /** ****************************************************************************** * @brief Set LCD entry mode: increment cursor. * @param None * @retval None ****************************************************************************** */ void lcd16x2_entry_inc() { lcd16x2_write_command(LCD16X2_CHARACTER_ENTRY_MODE | LCD16X2_INCREMENT | LCD16X2_DISPLAY_SHIFT_OFF); } /** ****************************************************************************** * @brief Set LCD entry mode: decrement cursor. * @param None * @retval None ****************************************************************************** */ void lcd16x2_entry_dec() { lcd16x2_write_command(LCD16X2_CHARACTER_ENTRY_MODE | LCD16X2_DECREMENT | LCD16X2_DISPLAY_SHIFT_OFF); } /** ****************************************************************************** * @brief Set LCD entry mode: increment cursor and shift character to left. * @param None * @retval None ****************************************************************************** */ void lcd16x2_entry_inc_shift() { lcd16x2_write_command(LCD16X2_CHARACTER_ENTRY_MODE | LCD16X2_INCREMENT | LCD16X2_DISPLAY_SHIFT_ON); } /** ****************************************************************************** * @brief Set LCD entry mode: decrement cursor and shift character to right. * @param None * @retval None ****************************************************************************** */ void lcd16x2_entry_dec_shift() { lcd16x2_write_command(LCD16X2_CHARACTER_ENTRY_MODE | LCD16X2_DECREMENT | LCD16X2_DISPLAY_SHIFT_ON); } /** ****************************************************************************** * @brief Turn on display (can see character(s) on display). * @param None * @retval None ****************************************************************************** */ void lcd16x2_display_on() { display_cursor_on_off_control |= LCD16X2_DISPLAY_ON; lcd16x2_write_command(LCD16X2_DISPLAY_CURSOR_ON_OFF | display_cursor_on_off_control); } /** ****************************************************************************** * @brief Turn off display (blank/ can't see character(s) on display). * @param None * @retval None ****************************************************************************** */ void lcd16x2_display_off() { display_cursor_on_off_control &= ~LCD16X2_DISPLAY_ON; lcd16x2_write_command(LCD16X2_DISPLAY_CURSOR_ON_OFF | display_cursor_on_off_control); } /** ****************************************************************************** * @brief Turn on underline cursor. * @param None * @retval None ****************************************************************************** */ void lcd16x2_cursor_on() { display_cursor_on_off_control |= LCD16X2_CURSOR_UNDERLINE_ON; lcd16x2_write_command(LCD16X2_DISPLAY_CURSOR_ON_OFF | display_cursor_on_off_control); } /** ****************************************************************************** * @brief Turn off underline cursor. * @param None * @retval None ****************************************************************************** */ void lcd16x2_cursor_off() { display_cursor_on_off_control &= ~LCD16X2_CURSOR_UNDERLINE_ON; lcd16x2_write_command(LCD16X2_DISPLAY_CURSOR_ON_OFF | display_cursor_on_off_control); } /** ****************************************************************************** * @brief Turn on blinking cursor. * @param None * @retval None ****************************************************************************** */ void lcd16x2_blink_on() { display_cursor_on_off_control |= LCD16X2_CURSOR_BLINK_ON; lcd16x2_write_command(LCD16X2_DISPLAY_CURSOR_ON_OFF | display_cursor_on_off_control); } /** ****************************************************************************** * @brief Turn off blinking cursor. * @param None * @retval None ****************************************************************************** */ void lcd16x2_blink_off() { display_cursor_on_off_control &= ~LCD16X2_CURSOR_BLINK_ON; lcd16x2_write_command(LCD16X2_DISPLAY_CURSOR_ON_OFF | display_cursor_on_off_control); } /** ****************************************************************************** * @brief Shift the LCD display to the left. * @param None * @retval None ****************************************************************************** */ void lcd16x2_display_shift_left() { lcd16x2_write_command(LCD16X2_DISPLAY_CURSOR_SHIFT | LCD16X2_DISPLAY_SHIFT | LCD16X2_LEFT_SHIFT); } /** ****************************************************************************** * @brief Shift the LCD display to the right. * @param None * @retval None ****************************************************************************** */ void lcd16x2_display_shift_right() { lcd16x2_write_command(LCD16X2_DISPLAY_CURSOR_SHIFT | LCD16X2_DISPLAY_SHIFT | LCD16X2_RIGHT_SHIFT); } /** ****************************************************************************** * @brief Shift the LCD cursor to the left (DDRAM address incremented). * @param None * @retval None ****************************************************************************** */ void lcd16x2_cursor_shift_left() { lcd16x2_write_command(LCD16X2_DISPLAY_CURSOR_SHIFT | LCD16X2_DISPLAY_CURSOR_SHIFT | LCD16X2_LEFT_SHIFT); } /** ****************************************************************************** * @brief Shift the LCD cursor to the right (DDRAM address decremented). * @param None * @retval None ****************************************************************************** */ void lcd16x2_cursor_shift_right() { lcd16x2_write_command(LCD16X2_DISPLAY_CURSOR_SHIFT | LCD16X2_DISPLAY_CURSOR_SHIFT | LCD16X2_RIGHT_SHIFT); } /** ****************************************************************************** * @brief Put a character on the LCD display. * @param Character that want to be displayed. * @retval None ****************************************************************************** */ void lcd16x2_putc(const char c) { uint8_t pos = lcd16x2_getxy(); if (c == '\n') { lcd16x2_new_line(pos); } else { #if LCD16X2_LINES == 1 if (pos == (LCD16X2_START_LINE_1 + LCD16X2_DISP_LENGTH)) lcd16x2_write(LCD16X2_SET_DDRAM_ADDRESS | LCD16X2_START_LINE_1, 0); #elif LCD16X2_LINES == 2 if (pos == (LCD16X2_START_LINE_1 + LCD16X2_DISP_LENGTH)) lcd16x2_write(LCD16X2_SET_DDRAM_ADDRESS | LCD16X2_START_LINE_2, 0); else if (pos == (LCD16X2_START_LINE_2 + LCD16X2_DISP_LENGTH)) lcd16x2_write(LCD16X2_SET_DDRAM_ADDRESS | LCD16X2_START_LINE_1, 0); #endif lcd16x2_write_data(c); } } /** ****************************************************************************** * @brief Put string on the LCD display. * @param String that want to be displayed. * @retval None ****************************************************************************** */ void lcd16x2_puts(const char* s) { register char c; while ((c = *s++)) { lcd16x2_putc(c); } } /** ****************************************************************************** * @brief Put string on the LCD display from program memory. * @param String that want to be displayed. * @retval None ****************************************************************************** */ void lcd16x2_puts_p(const char* progmem_s) { register char c; while ((c = pgm_read_byte(progmem_s++))) { lcd16x2_putc(c); } } /** ****************************************************************************** * @brief Create a custom character on CGRAM location. * @param CGRAM location (0-7). * @param Custom character pattern (8 bytes). * @retval None ****************************************************************************** */ void lcd16x2_create_custom_char(uint8_t location, uint8_t* data_bytes) { // We only have 8 locations 0-7 for custom chars location &= 0x07; // Set CGRAM address lcd16x2_write_command(LCD16X2_SET_CGRAM_ADDRESS | (location << 3)); // Write 8 bytes custom char pattern for (int i = 0; i < 8; i++) { lcd16x2_write_data(data_bytes[i]); } } /** ****************************************************************************** * @brief Put a custom character on specific LCD display location. * @param LCD column * @param LCD row * @param Custom character location on CGRAM (0-7). * @retval None ****************************************************************************** */ void lcd16x2_put_custom_char(uint8_t x, uint8_t y, uint8_t location) { lcd16x2_gotoxy(x, y); lcd16x2_write_data(location); } /** Private functions ------------------------------------------------------- */ /** ****************************************************************************** * @brief Give enable pulse to LCD EN pin. * @param None * @retval None ****************************************************************************** */ static void lcd16x2_toggle_e() { // EN pin = HIGH LCD16X2_PORT_EN |= (1 << LCD16X2_PIN_EN); // Pulse length in us _delay_us(LCD16X2_DELAY_ENABLE_PULSE); // EN pin = LOW LCD16X2_PORT_EN &= ~(1 << LCD16X2_PIN_EN); } /** ****************************************************************************** * @brief Write instruction or data to LCD. * @param Instruction/ data that want to sent to LCD. * @param Instruction or data register select. If write instruction, then * RS = 0. Otherwise, RS = 1. * @retval None ****************************************************************************** */ static void lcd16x2_write(uint8_t data, uint8_t rs) { uint8_t data_bits_tmp; // Write mode (RW = 0) LCD16X2_PORT_RW &= ~(1 << LCD16X2_PIN_RW); if (rs) // Write data (RS = 1) LCD16X2_PORT_RS |= (1 << LCD16X2_PIN_RS); else // Write instruction (RS = 0) LCD16X2_PORT_RS &= ~(1 << LCD16X2_PIN_RS); if ((&LCD16X2_PORT_D4 == &LCD16X2_PORT_D5) && (&LCD16X2_PORT_D5 == &LCD16X2_PORT_D6) && (&LCD16X2_PORT_D6 == &LCD16X2_PORT_D7) && (LCD16X2_PIN_D4 == 4) && (LCD16X2_PIN_D5 == 5) && (LCD16X2_PIN_D6 == 6) && (LCD16X2_PIN_D7 == 7)) { // Configure all data pins as output DDR(LCD16X2_PORT_D7) |= 0xF0; // Backup low nibble of LCD port data_bits_tmp = LCD16X2_PORT_D7 & 0x0F; // Output high nibble first LCD16X2_PORT_D7 = (data & 0xF0) | data_bits_tmp; lcd16x2_toggle_e(); // Output low nibble LCD16X2_PORT_D7 = ((data << 4 ) & 0xF0) | data_bits_tmp; lcd16x2_toggle_e(); // All data pins high (inactive) LCD16X2_PORT_D7 = 0xF0 | data_bits_tmp; } else { // Configure all data pins as output DDR(LCD16X2_PORT_D4) |= (1 << LCD16X2_PIN_D4); DDR(LCD16X2_PORT_D5) |= (1 << LCD16X2_PIN_D5); DDR(LCD16X2_PORT_D6) |= (1 << LCD16X2_PIN_D6); DDR(LCD16X2_PORT_D7) |= (1 << LCD16X2_PIN_D7); // Output high nibble first LCD16X2_PORT_D7 &= ~(1 << LCD16X2_PIN_D7); LCD16X2_PORT_D6 &= ~(1 << LCD16X2_PIN_D6); LCD16X2_PORT_D5 &= ~(1 << LCD16X2_PIN_D5); LCD16X2_PORT_D4 &= ~(1 << LCD16X2_PIN_D4); if (data & 0x80) LCD16X2_PORT_D7 |= (1 << LCD16X2_PIN_D7); if (data & 0x40) LCD16X2_PORT_D6 |= (1 << LCD16X2_PIN_D6); if (data & 0x20) LCD16X2_PORT_D5 |= (1 << LCD16X2_PIN_D5); if (data & 0x10) LCD16X2_PORT_D4 |= (1 << LCD16X2_PIN_D4); lcd16x2_toggle_e(); // Output low nibble LCD16X2_PORT_D7 &= ~(1 << LCD16X2_PIN_D7); LCD16X2_PORT_D6 &= ~(1 << LCD16X2_PIN_D6); LCD16X2_PORT_D5 &= ~(1 << LCD16X2_PIN_D5); LCD16X2_PORT_D4 &= ~(1 << LCD16X2_PIN_D4); if (data & 0x08) LCD16X2_PORT_D7 |= (1 << LCD16X2_PIN_D7); if (data & 0x04) LCD16X2_PORT_D6 |= (1 << LCD16X2_PIN_D6); if (data & 0x02) LCD16X2_PORT_D5 |= (1 << LCD16X2_PIN_D5); if (data & 0x01) LCD16X2_PORT_D4 |= (1 << LCD16X2_PIN_D4); lcd16x2_toggle_e(); // All data pins high (inactive) LCD16X2_PORT_D4 |= (1 << LCD16X2_PIN_D4); LCD16X2_PORT_D5 |= (1 << LCD16X2_PIN_D5); LCD16X2_PORT_D6 |= (1 << LCD16X2_PIN_D6); LCD16X2_PORT_D7 |= (1 << LCD16X2_PIN_D7); } } /** ****************************************************************************** * @brief Read DDRAM address + busy flag or data from LCD. * @param DDRAM address + busy flag or data register select. * If read DDRAM address + busy flag, then RS = 0. Otherwise, RS = 1. * @retval DDRAM address + busy flag or data value. ****************************************************************************** */ static uint8_t lcd16x2_read(uint8_t rs) { uint8_t data = 0; // Read mode (RW = 1) LCD16X2_PORT_RW |= (1 << LCD16X2_PIN_RW); if (rs) // Read data (RS = 1) LCD16X2_PORT_RS |= (1 << LCD16X2_PIN_RS); else // Read busy flag and DDRAM address (RS = 0) LCD16X2_PORT_RS &= ~(1 << LCD16X2_PIN_RS); if ((&LCD16X2_PORT_D4 == &LCD16X2_PORT_D5) && (&LCD16X2_PORT_D5 == &LCD16X2_PORT_D6) && (&LCD16X2_PORT_D6 == &LCD16X2_PORT_D7) && (LCD16X2_PIN_D4 == 4) && (LCD16X2_PIN_D5 == 5) && (LCD16X2_PIN_D6 == 6) && (LCD16X2_PIN_D7 == 7)) { // Configure all data pins as input DDR(LCD16X2_PORT_D7) &= 0x0F; // EN pin = HIGH LCD16X2_PORT_EN |= (1 << LCD16X2_PIN_EN); // Pulse length in us _delay_us(LCD16X2_DELAY_ENABLE_PULSE); // Read high nibble first data = PIN(LCD16X2_PORT_D7) & 0xF0; // EN pin = LOW LCD16X2_PORT_EN &= ~(1 << LCD16X2_PIN_EN); // EN pin LOW delay _delay_us(LCD16X2_DELAY_ENABLE_PULSE); // EN pin = HIGH LCD16X2_PORT_EN |= (1 << LCD16X2_PIN_EN); // Pulse length in us _delay_us(LCD16X2_DELAY_ENABLE_PULSE); // Read low nibble data |= PIN(LCD16X2_PORT_D7) >> 4; // EN pin = LOW LCD16X2_PORT_EN &= ~(1 << LCD16X2_PIN_EN); } else { // Configure all data pins as input DDR(LCD16X2_PORT_D4) &= ~(1 << LCD16X2_PIN_D4); DDR(LCD16X2_PORT_D5) &= ~(1 << LCD16X2_PIN_D5); DDR(LCD16X2_PORT_D6) &= ~(1 << LCD16X2_PIN_D6); DDR(LCD16X2_PORT_D7) &= ~(1 << LCD16X2_PIN_D7); // EN pin = HIGH LCD16X2_PORT_EN |= (1 << LCD16X2_PIN_EN); // Pulse length in us _delay_us(LCD16X2_DELAY_ENABLE_PULSE); /* Read high nibble first */ if (PIN(LCD16X2_PORT_D4) & (1 << LCD16X2_PIN_D4)) data |= 0x10; if (PIN(LCD16X2_PORT_D5) & (1 << LCD16X2_PIN_D5)) data |= 0x20; if (PIN(LCD16X2_PORT_D6) & (1 << LCD16X2_PIN_D6)) data |= 0x40; if (PIN(LCD16X2_PORT_D7) & (1 << LCD16X2_PIN_D7)) data |= 0x80; // EN pin = LOW LCD16X2_PORT_EN &= ~(1 << LCD16X2_PIN_EN); // EN pin LOW delay _delay_us(LCD16X2_DELAY_ENABLE_PULSE); // EN pin = HIGH LCD16X2_PORT_EN |= (1 << LCD16X2_PIN_EN); // Pulse length in us _delay_us(LCD16X2_DELAY_ENABLE_PULSE); /* Read low nibble */ if (PIN(LCD16X2_PORT_D4) & (1 << LCD16X2_PIN_D4)) data |= 0x01; if (PIN(LCD16X2_PORT_D5) & (1 << LCD16X2_PIN_D5)) data |= 0x02; if (PIN(LCD16X2_PORT_D6) & (1 << LCD16X2_PIN_D6)) data |= 0x04; if (PIN(LCD16X2_PORT_D7) & (1 << LCD16X2_PIN_D7)) data |= 0x08; // EN pin = LOW LCD16X2_PORT_EN &= ~(1 << LCD16X2_PIN_EN); } return data; } /** ****************************************************************************** * @brief Wait for LCD until finish it's job. * @param None * @retval DDRAM address + busy flag value. ****************************************************************************** */ static uint8_t lcd16x2_wait_busy() { register uint8_t tmp; // Wait until busy flag is cleared while ((tmp = lcd16x2_read(0)) & (LCD16X2_BUSY_FLAG)); // Delay needed for address counter is updated after busy flag is cleared _delay_us(LCD16X2_DELAY_BUSY_FLAG); // Read and return address counter return lcd16x2_read(0); } /** ****************************************************************************** * @brief Give new line character * @param Current cursor/ DDRAM address position. * @retval None ****************************************************************************** */ static inline void lcd16x2_new_line(uint8_t pos) { register uint8_t address_counter; #if LCD16X2_LINES == 1 address_counter = 0; #elif LCD16X2_LINES == 2 if (pos < LCD16X2_START_LINE_2) address_counter = LCD16X2_START_LINE_2; else address_counter = LCD16X2_START_LINE_1; #endif lcd16x2_write_command(LCD16X2_SET_DDRAM_ADDRESS | address_counter); } /********************************* END OF FILE ********************************/ /******************************************************************************/
C
#ifndef __STACK_H__ #define __STACK_H__ #include <stdbool.h> // structure struct stack_element { int value; struct stack_element *next; }; struct stack { struct stack_element *head; }; // fonctions struct stack *stack_new(); void stack_push(struct stack *, int); int stack_pop(struct stack *); int stack_head(struct stack *); bool stack_is_empty(struct stack *); void stack_free(struct stack *); void stack_print(struct stack *); #endif
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include <time.h> // Train priorities #define HIGH 1 #define LOW 0 // Directions #define EAST 0 #define WEST 1 // Timer setup from Tutorial 7 #define BILLION 1000000000.0; struct timespec start, stop; double accum; /* * Struct to hold train information */ typedef struct Train { int number; char direction; int priority; int loading_time; int crossing_time; pthread_cond_t *train_convar; } train; /*=========================================== Priority Queue Code Adopted from the following sources: 1.) https://www.geeksforgeeks.org/priority-queue-using-linked-list/ 2.) https://rosettacode.org/wiki/Priority_queue#C ===========================================*/ /* * Queue node struct */ typedef struct node { train* data; int priority; struct node* next; } node; /* * Creates a new node */ node* newNode(train* data) { node* temp = (node*)malloc(sizeof(node)); temp->data = data; temp->priority = data->priority; temp->next = NULL; } /* * Returns the node with the highest priority */ train* peek(node** head) { return (*head)->data; } /* * Removes the node with the highest priority/head node */ void dequeue(node** head) { node* temp = *head; (*head) = (*head)->next; free(temp); } /* * Determines if the queue is empty */ int isEmpty(node** head) { return (*head) == NULL; } /* * Returns the priority of the highest priority node in the queue */ int peekPriority(node** head) { return (*head)->priority; } /* * Adds a new train/node to the queue */ void enqueue(node** head, train* data) { node* start = *head; node* temp = newNode(data); if (*head == NULL) { *head = temp; return; } // If priority and load times are equal, the train with the lowest # gets higher priority in the queue if ((*head)->priority < temp->priority || ((*head)->data->loading_time == temp->data->loading_time && (*head)->data->number > temp->data->number)) { temp->next = *head; (*head) = temp; } else { while (start->next != NULL && start->next->priority >= temp->priority) { if (start->next->data->loading_time == temp->data->loading_time && start->next->data->number > temp->data->number) { temp->next = start->next; start->next = temp; return; } start = start->next; } temp->next = start->next; start->next = temp; } } /*=========================================== MTS Code ===========================================*/ pthread_mutex_t station, track; pthread_cond_t loaded, start_crossing_n; node* stationWestHead; node* stationEastHead; // Number of trains int n; int builtTrains; // Tracks the streak of deployed train in each direction int numWest, numEast = 0; /* * Counts the number of lines in the trains.txt file * Returns the number of trains */ int countLines(char *f) { FILE *fp = fopen(f, "r"); char c; int count = 0; for (c = fgetc(fp); c != EOF; c = fgetc(fp)) { if (c == '\n') count++; } fclose(fp); return count; } /* * Returns the priority of a train * 1 = High Priority * 0 = Low Priority */ int priority(char direction) { if (direction == 'W' || direction == 'E') return HIGH; else return LOW; } /* * Builds the trains in the array of structs * from the given input file and array of conditions */ void buildTrains(train *trains, char *f, pthread_cond_t *train_conditions) { // Initiate the condition variables for (int i = 0; i < n; i++) { pthread_cond_init(&train_conditions[i], NULL); } char direction[3], loading_time[3], crossing_time[3]; int train_number = 0; FILE *fp = fopen(f, "r"); while (fscanf(fp, "%s %s %s", direction, loading_time, crossing_time) != EOF) { trains[train_number].number = train_number; trains[train_number].direction = direction[0]; trains[train_number].priority = priority(direction[0]); trains[train_number].loading_time = atoi(loading_time); trains[train_number].crossing_time = atoi(crossing_time); trains[train_number].train_convar = &train_conditions[train_number]; train_number++; builtTrains++; } fclose(fp); } /* * Returns the full value of the direction the train is heading */ char* directionString(char dir){ char* dirString; if (dir == 'e' || dir == 'E') dirString = "East"; else dirString = "West"; return dirString; } /* * Prints the time * Based on tutorial slides */ void printTime() { if (clock_gettime(CLOCK_REALTIME, &stop) == -1) { perror("clock gettime"); exit(EXIT_FAILURE); } accum = (stop.tv_sec - start.tv_sec) + (stop.tv_nsec - start.tv_nsec) / BILLION; int minutes = (int)accum/60; int hours = (int)accum/3600; printf("%02d:%02d:%04.1f ", hours, minutes, accum); } /* * Main routine for the train threads */ void *start_routine(void *args) { train* ptrain = (train*)args; unsigned int loadTime = (ptrain->loading_time) * 100000; // Wait until all trains are built to start loading while (builtTrains < n) {} usleep(loadTime); printTime(); printf("Train %2d is ready to go %4s.\n", ptrain->number, directionString(ptrain->direction)); pthread_mutex_lock(&station); if (ptrain->direction == 'E' || ptrain->direction == 'e') { enqueue(&stationEastHead, ptrain); } else { enqueue(&stationWestHead, ptrain); } pthread_mutex_unlock(&station); pthread_cond_signal(&loaded); pthread_cond_wait(ptrain->train_convar, &track); printTime(); printf("Train %2d is ON on the main track going %4s\n", ptrain->number, directionString(ptrain->direction)); unsigned int crossTime = (ptrain->crossing_time) * 100000; usleep(crossTime); printTime(); printf("Train %2d is OFF the main track going %4s\n", ptrain->number, directionString(ptrain->direction)); n--; pthread_mutex_unlock(&track); pthread_cond_signal(&start_crossing_n); pthread_cond_destroy(ptrain->train_convar); pthread_exit(0); } /* * Determines which queue to take the new train from * 0 = East * 1 = West */ int nextTrain(int previous) { if (!isEmpty(&stationEastHead) && !isEmpty(&stationWestHead)) { // Below 2 conditionals ensure trains in 1 direction do not exceed 3 in a row if (numEast == 3) { numEast = 0; return WEST; } if (numWest == 3) { numWest = 0; return EAST; } if (peekPriority(&stationEastHead) > peekPriority(&stationWestHead)) { return EAST; } else if (peekPriority(&stationEastHead) < peekPriority(&stationWestHead)) { return WEST; } else { if (previous == 1 || previous == -1) return EAST; else return WEST; } } else if (!isEmpty(&stationEastHead) && isEmpty(&stationWestHead)) { return EAST; } else if (isEmpty(&stationEastHead) && !isEmpty(&stationWestHead)) { return WEST; } return -10; } /* * Starts the timer */ void startTimer() { if(clock_gettime(CLOCK_REALTIME, &start) == -1) { perror("clock gettime"); exit(EXIT_FAILURE); } } /* * Dispatching algorithm * Implements the majority of the scheduling rules */ void dispatch() { int previous = -1; while (n) { pthread_mutex_lock(&track); if (isEmpty(&stationEastHead) && isEmpty(&stationWestHead)) { pthread_cond_wait(&loaded, &track); } previous = nextTrain(previous); sleep(0.001); switch(previous) { case EAST: numEast++; numWest = 0; pthread_cond_signal(peek(&stationEastHead)->train_convar); pthread_mutex_lock(&station); dequeue(&stationEastHead); pthread_mutex_unlock(&station); break; case WEST: numWest++; numEast = 0; pthread_cond_signal(peek(&stationWestHead)->train_convar); pthread_mutex_lock(&station); dequeue(&stationWestHead); pthread_mutex_unlock(&station); break; default: break; } pthread_cond_wait(&start_crossing_n, &track); pthread_mutex_unlock(&track); } } /* * Main */ int main(int argc, char *argv[]) { if (argc < 2) { printf("Error: Add a trains.txt file.\n"); return 1; } // Get the # of trains n = countLines(argv[1]); builtTrains = 0; // Initiate mutex's pthread_mutex_init(&station, NULL); pthread_mutex_init(&track, NULL); // Initiate condition variable pthread_cond_init(&start_crossing_n, NULL); pthread_t train_threads[n]; pthread_cond_t train_conditions[n]; // Build the trains train *trains = malloc(n * sizeof(*trains)); buildTrains(trains, argv[1], train_conditions); startTimer(); // Create the threads for each train for (int i = 0; i < n; i++) { int rc = pthread_create(&train_threads[i], NULL, start_routine, (void *) &trains[i]); } // Sleep to prevent "jitter" sleep(0.001); // Start dispatchment algorithm dispatch(); // Cleanup and exit free(trains); pthread_mutex_destroy(&station); pthread_mutex_destroy(&track); pthread_cond_destroy(&loaded); pthread_cond_destroy(&start_crossing_n); return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> char* crcRem(char* bitString, char* gPoly, int bsl, int gpl); char* crcGen(char* bitString, char* gPoly); char* crcCheck(char* codedString, char* gPoly); char xor(char a, char b); int main(int argc, char** argv) { if(argc != 3) { printf("Usage: ./crc msgString GeneratingPolynomial\n"); exit(-1); } char* decodedString; printf("rem: %s\n", crcRem(argv[1], argv[2], strlen(argv[1]), strlen(argv[2]))); printf("gen: %s\n", crcGen(argv[1], argv[2])); printf("check: %s\n", (decodedString=crcCheck(crcGen(argv[1], argv[2]), argv[2]))==NULL?"False":decodedString); } char* crcRem(char* bitString, char* gPoly, int bsl, int gpl) { int i, j; // counter char* dividend = (char*) malloc(sizeof(char) * (bsl + gpl - 1 + 1)); char* rem = (char*) malloc(sizeof(char) * (gpl-1+1)); strcpy(dividend, bitString); for(i=bsl; i<bsl+gpl-1; i++) { dividend[i] = '0'; } dividend[i] = '\0'; for(i=0;; i++) { while(dividend[i] != '1' && i<bsl) { i++; } if (i == bsl) { break; } for(j=0; j<gpl; j++) { dividend[i+j] = xor(dividend[i+j], gPoly[j]); } printf("rem: dividend = %s\n", dividend); } for(i=bsl; i<bsl+gpl-1; i++) { rem[i-bsl] = dividend[i]; } rem[gpl-1] = '\0'; return rem; } char* crcGen(char* bitString, char* gPoly) { int bsl = strlen(bitString); int gpl = strlen(gPoly); char* rem = crcRem(bitString, gPoly, bsl, gpl); char* new = (char*) malloc(sizeof(char) * (bsl+gpl-1+1)); strcpy(new, bitString); strcat(new, rem); return new; } char* crcCheck(char* codedString, char* gPoly) { int i, j; int gpl = strlen(gPoly); int bsl = strlen(codedString) - gpl + 1; char* decodedString = (char*) malloc(sizeof(char) * (bsl+1)); strncpy(decodedString, codedString, bsl); decodedString[bsl] = '\0'; for(i=0; i<bsl; i++) { while(codedString[i] != '1' && i<bsl) { i++; } if(i == bsl) { break; } for(j=0; j<gpl; j++) { codedString[i+j] = xor(codedString[i+j], gPoly[j]); } } while(codedString[i] == '0' && i<gpl+bsl-1) i++; if (i == gpl+bsl-1) { return decodedString; } return NULL; } char xor(char a, char b) { if(a == '1') { if(b == '1') return '0'; return '1'; } else { if(b == '1') return '1'; return '0'; } }
C
#include "holberton.h" /** * string_toupper - function to change the case to uppercase * * @string: string of which the case is to be changed * * Return: returns the string */ char *string_toupper(char *string) { char *p = string; while (*string != '\0') { if (*string >= 'a' && *string <= 'z') { *string = *string - 32; } string++; } return (p); }
C
#include <stdio.h> #include <math.h> #include <limits.h> /** 1 2 3 5 8 9 3 7 9 12 14 2 1 0 2 i 0 1 j 0 0 Min 2 1 */ int getMin(int a, int b){ return a<b?a:b; } int findClosestElements(int a[], int b[]){ int counter, min, diff; int ai=0; int bi=0; min = INT_MAX; for(counter=0; counter<6; counter++){ diff = abs(a[ai]-b[bi]); if(diff < min){ min = diff; } if(a[ai]<=b[bi]){ ai++; }else{ bi++; } } return min; } int main(){ int a[6] = {1,5,10,15,20}; int b[6] = {3,7,9,12,17}; int result; result = findClosestElements(a, b); printf("%d\n", result); return 0; }
C
#include <stdio.h> #include <stdlib.h> int my_add(int x, int y); int main(int argc, char ** argv) { if (argc != 3) { printf("Usage: c_simple <x> <y>\n"); return 1; } int x = atoi(argv[1]); int y = atoi(argv[2]); int z = my_add(x, y); printf("%d + %d == %d\n", x, y, z); return 0; }
C
#include "header.h" /** * free_list_p - free list * @head: head node list */ void free_list_p(path_t *head) { path_t *tmp; tmp = head; while (head != NULL) { tmp = head; head = head->next; free(tmp->str); free(tmp); } free(head); } /** * node_len_p - length list * @h: list path * Return: integer length */ size_t node_len_p(const path_t *h) { size_t count = 0; while (h) h = h->next, count++; return (count); } /** * *add_node_p - add node in list * @head: head * @str: string * Return: List_t */ path_t *add_node_p(path_t **head, char *str) { path_t *new; if (head == NULL) return (NULL); new = malloc(sizeof(path_t)); if (new == NULL) return (NULL); new->str = malloc((_strlen(str) + 2) * sizeof(char)); if (new->str == NULL) return (NULL); new->str = _strcpy(new->str, str); new->str = _strcat(new->str, "/"); new->len = _strlen(str); new->next = *head; *head = new; return (new); } /** * *create_node_p - create a node * @data: data from create * @separator: delimiter inside data * Return: new node */ path_t *create_node_p(char *data, char *separator) { path_t *new; char *token; char *tmp; tmp = malloc((_strlen(data) + 1) * sizeof(char)); tmp = _strcpy(tmp, data); new = NULL; token = strtok(tmp, separator); while (token) add_node_p(&new, token), token = strtok(NULL, separator); free(tmp); return (new); }
C
#include <stdio.h> #include <stdlib.h> // malloc, calloc, realloc // malloc doesn't do implicit initialization to the allocated space int main(){ //dynamic memory is always in the heap section int *p; int n; printf("Enter how many integers: "); scanf("%d", &n); //p = (int *)malloc(100); // malloc allocates 100 bytes and returns address p = (int *)malloc(n * sizeof(int)); if (p == NULL){ printf("Unable to allocate memory\n Exiting the program\n"); exit(1); } // use the allocated space pointed by p for keeping values int i; for(i=0; i<n; i++){ printf("Next Number: "); scanf("%d", p+i); } printf("Content of the array: "); for(i=0;i<n;i++){ printf("%4d", *(p+i)); } free(p); // IMPORTANT!!! return 0; }
C
#include <stdio.h> #include <string.h> int main(){ char nome[30]; int qtdLetras; printf("Digite uma palavra:"); scanf("%s", &nome); // while até que a pos do nome fosse = /0 // strlen qtdLetras = strlen(nome); printf("TOTAL DE LETRAS: %i", qtdLetras); return 0; }
C
/* Example of instantiating a WebAssembly which uses WASI imports. You can compile and run this example on Linux with: cargo build --release -p wasmtime-c-api cc examples/wasi/main.c \ -I crates/c-api/include \ -I crates/c-api/wasm-c-api/include \ target/release/libwasmtime.a \ -lpthread -ldl -lm \ -o wasi ./wasi Note that on Windows and macOS the command will be similar, but you'll need to tweak the `-lpthread` and such annotations. */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <wasm.h> #include <wasi.h> #include <wasmtime.h> #define MIN(a, b) ((a) < (b) ? (a) : (b)) static void exit_with_error(const char *message, wasmtime_error_t *error, wasm_trap_t *trap); int main() { int ret = 0; // Set up our context wasm_engine_t *engine = wasm_engine_new(); assert(engine != NULL); wasm_store_t *store = wasm_store_new(engine); assert(store != NULL); wasm_byte_vec_t wasm; // Load our input file to parse it next FILE* file = fopen("target/wasm32-wasi/debug/wasi.wasm", "rb"); if (!file) { printf("> Error loading file!\n"); exit(1); } fseek(file, 0L, SEEK_END); size_t file_size = ftell(file); wasm_byte_vec_new_uninitialized(&wasm, file_size); fseek(file, 0L, SEEK_SET); if (fread(wasm.data, file_size, 1, file) != 1) { printf("> Error loading module!\n"); exit(1); } fclose(file); // Compile our modules wasm_module_t *module = NULL; wasmtime_error_t *error = wasmtime_module_new(engine, &wasm, &module); if (!module) exit_with_error("failed to compile module", error, NULL); wasm_byte_vec_delete(&wasm); // Instantiate wasi wasi_config_t *wasi_config = wasi_config_new(); assert(wasi_config); wasi_config_inherit_argv(wasi_config); wasi_config_inherit_env(wasi_config); wasi_config_inherit_stdin(wasi_config); wasi_config_inherit_stdout(wasi_config); wasi_config_inherit_stderr(wasi_config); wasm_trap_t *trap = NULL; wasi_instance_t *wasi = wasi_instance_new(store, "wasi_snapshot_preview1", wasi_config, &trap); if (wasi == NULL) exit_with_error("failed to instantiate WASI", NULL, trap); wasmtime_linker_t *linker = wasmtime_linker_new(store); error = wasmtime_linker_define_wasi(linker, wasi); if (error != NULL) exit_with_error("failed to link wasi", error, NULL); // Instantiate the module wasm_name_t empty; wasm_name_new_from_string(&empty, ""); wasm_instance_t *instance = NULL; error = wasmtime_linker_module(linker, &empty, module); if (error != NULL) exit_with_error("failed to instantiate module", error, NULL); // Run it. wasm_func_t* func; wasmtime_linker_get_default(linker, &empty, &func); if (error != NULL) exit_with_error("failed to locate default export for module", error, NULL); wasm_val_vec_t args_vec = WASM_EMPTY_VEC; wasm_val_vec_t results_vec = WASM_EMPTY_VEC; error = wasmtime_func_call(func, &args_vec, &results_vec, &trap); if (error != NULL) exit_with_error("error calling default export", error, trap); // Clean up after ourselves at this point wasm_name_delete(&empty); wasm_module_delete(module); wasm_store_delete(store); wasm_engine_delete(engine); return 0; } static void exit_with_error(const char *message, wasmtime_error_t *error, wasm_trap_t *trap) { fprintf(stderr, "error: %s\n", message); wasm_byte_vec_t error_message; if (error != NULL) { wasmtime_error_message(error, &error_message); wasmtime_error_delete(error); } else { wasm_trap_message(trap, &error_message); wasm_trap_delete(trap); } fprintf(stderr, "%.*s\n", (int) error_message.size, error_message.data); wasm_byte_vec_delete(&error_message); exit(1); }
C
// 7 december 2014 // TODO verify header events (double-clicking on a divider, for example) static void makeHeader(struct table *t, HINSTANCE hInstance) { t->header = CreateWindowExW(0, WC_HEADERW, L"", // don't set WS_VISIBLE; according to MSDN we create the header hidden as part of setting the initial position (http://msdn.microsoft.com/en-us/library/windows/desktop/ff485935%28v=vs.85%29.aspx) // TODO WS_BORDER? // TODO is HDS_HOTTRACK needed? WS_CHILD | HDS_FULLDRAG | HDS_HORZ | HDS_HOTTRACK, 0, 0, 0, 0, // no initial size t->hwnd, (HMENU) 100, hInstance, NULL); if (t->header == NULL) panic("error creating Table header"); } static void destroyHeader(struct table *t) { if (DestroyWindow(t->header) == 0) panic("error destroying Table header"); } // to avoid weird bugs, the only functions allowed to call this one are the horizontal scroll functions // when we need to reposition the header in a situation other than a user-initiated scroll, we use a dummy scroll (hscrollby(t, 0)) // see update() in update.h static void repositionHeader(struct table *t) { RECT r; WINDOWPOS wp; HDLAYOUT l; if (GetClientRect(t->hwnd, &r) == 0) panic("error getting client rect for Table header repositioning"); // we fake horizontal scrolling here by extending the client rect to the left by the scroll position r.left -= t->hscrollpos; l.prc = &r; l.pwpos = &wp; if (SendMessageW(t->header, HDM_LAYOUT, 0, (LPARAM) (&l)) == FALSE) panic("error getting new Table header position"); if (SetWindowPos(t->header, wp.hwndInsertAfter, wp.x, wp.y, wp.cx, wp.cy, // see above on showing the header here instead of in the CreateWindowExW() call wp.flags | SWP_SHOWWINDOW) == 0) panic("error repositioning Table header"); t->headerHeight = wp.cy; } static void headerAddColumn(struct table *t, WCHAR *name) { HDITEMW item; ZeroMemory(&item, sizeof (HDITEMW)); item.mask = HDI_WIDTH | HDI_TEXT | HDI_FORMAT; item.cxy = 200; // TODO item.pszText = name; item.fmt = HDF_LEFT | HDF_STRING; // TODO replace 100 with (t->nColumns - 1) if (SendMessage(t->header, HDM_INSERTITEM, (WPARAM) (100), (LPARAM) (&item)) == (LRESULT) (-1)) panic("error adding column to Table header"); } // TODO is this triggered if we programmatically move headers (for autosizing)? HANDLER(headerNotifyHandler) { NMHDR *nmhdr = (NMHDR *) lParam; if (nmhdr->hwndFrom != t->header) return FALSE; if (nmhdr->code != HDN_ITEMCHANGED) return FALSE; update(t, TRUE); // TODO make more intelligent // to do this, we have to redraw the column to the left of the divider that was dragged and scroll everything to the right normally (leaving the hole that was scrolled invalidated as well) // of course, this implies that dragging a divider only resizes the column of which it is the right side of and moves all others InvalidateRect(t->hwnd, NULL, TRUE); *lResult = 0; return TRUE; }
C
/*------------------------------------------------------------------------* Developer: Lucas Ferreira Location: São Paulo - SP Creation date: 02/05/2021 Course: Self student *------------------------------------------------------------------------*/ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <locale.h> #include "calc.h" int main() { float firstValue, secondValue, result; char input_firstValue[100], input_secondValue[100]; char operation; char operations[5] = {'+', '-', '*', '/'}; bool key = true; setlocale(LC_ALL, ""); while (true) { while (true){ fflush(stdin); arithmeticError_Control: // Get arithmetic operator from user do { // "-- SIMPLE CALC --" intro(); show_operation(); scanf("%c", &operation); if (operation == '+' || operation == '-' || operation == '*' || operation == '/') { key = false; break; } error(); key = true; fflush(stdin); system("cls"); } while (key); inputError_Control: // Getting first value from user while (true) { fflush(stdin); printf("FIRST VALUE: "); fgets(input_firstValue, sizeof(input_firstValue), stdin); sscanf(input_firstValue, "%f", &firstValue); int scanning = find(input_firstValue); /* Verify if there is any comma in input */ if (scanning) { break; } } if (!(sscanf(input_firstValue, "%f", &firstValue))){ goto Invalid_input; } // Getting second value from user while (true) { fflush(stdin); printf("SECOND VALUE: "); fgets(input_secondValue, sizeof(input_secondValue), stdin); sscanf(input_secondValue, "%f", &secondValue); int scanning = find(input_secondValue); if (scanning) { break; } } if (!(sscanf(input_secondValue, "%f", &secondValue))) { goto Invalid_input; } // Validate input if it is a floating point number if (sscanf(input_firstValue, "%f", &firstValue) && sscanf(input_secondValue, "%f", &secondValue)) { break; } // Continue the loop while user not enter a float number Invalid_input: printf("Invalid input!\nPlease enter only numbers...\n"); sleep(1); goto inputError_Control; } switch (operation) { case '+': result = sum(strtof(input_firstValue, NULL), strtof(input_secondValue, NULL)); break; case '-': result = sub(strtof(input_firstValue, NULL), strtof(input_secondValue, NULL)); break; case '*': result = mult(strtof(input_firstValue, NULL), strtof(input_secondValue, NULL)); break; case '/': result = divi(strtof(input_firstValue, NULL), strtof(input_secondValue, NULL)); break; } // Printing the result on Screen space(); printf("First Value: %.2f\n", firstValue); printf("Second Value: %.2f\n", secondValue); printf("\nRESULT: %.2f\n", result); space(); // Condition to continue the program while (true) { fflush(stdin); char answer; space(); printf("Want to Continue Y or N?: "); //getchar(); scanf(" %c", &answer); if (answer == 'y' || answer == 'Y') { system("cls"); break; } else if (answer == 'n' || answer == 'N') { printf("Finishing program..."); sleep(1); goto exit; } else { printf("Wrong answer! Try again\n"); sleep(1); //system("cls"); continue; } } } system("pause"); exit: return 0; }
C
//DYNAMIC HASHING #include<stdio.h> #include<stdlib.h> typedef struct NODE{ int data; int key; }node; node *a[15]; int count=0; void insert(int,int); void display(); int main() { FILE *fp; int emp,key; fp=fopen("emp.txt","r"); printf("\nENTRY OF DATA USING FILE\n"); while(fscanf(fp,"%d",&emp)!=EOF) { key=emp%100; if(count==15) { printf("HASH TABLE IS FULL\n"); exit(0); } insert(key,emp); } display(); fclose(fp); }//END OF THE MAIN FUNCTION void insert(int key,int emp) { int k; node *temp; temp=(node *)malloc(sizeof(node)); temp->data=emp; temp->key=key; k=key%10; while(a[k]!=NULL) { printf("\nCOLLISION DETECTED AT %d\n",k); k++; k=k%15; printf("\nAVOIDING COLLISION BY SOLVING THIS BY LINEAR PROBING\n"); } a[k]=temp; ++count; }//END OF THE INSERT FUNCTION void display() { int i; printf("\n\tKEY\tDATA\n"); for(i=0;i<15;i++) { if(a[i]==NULL) { printf("%d.\t-1\n",i); } else { printf("%d.\t%d\t%d\n",i,a[i]->key,a[i]->data); } } }//END OF THE DISPLAY FUNCTION
C
typedef struct { size_t capacity; size_t bucket_size; size_t length; void*** buckets; size_t slot_size; } Pool; void initialize_pool(Pool* pool, size_t slot_size, size_t bucket_count, size_t bucket_size) { pool->capacity = bucket_size * bucket_count; pool->bucket_size = bucket_size; pool->slot_size = slot_size; pool->length = 0; pool->buckets = malloc(bucket_count * sizeof(void*)); for (size_t i = 0; i < bucket_count; i++) { pool->buckets[i] = malloc(bucket_size * slot_size); } } Pool* new_pool(size_t slot_size, size_t bucket_count, size_t bucket_size) { assert(slot_size > 0); assert(bucket_count > 0); assert(bucket_size > 0); Pool* ret = malloc(sizeof(Pool)); initialize_pool(ret, slot_size, bucket_count, bucket_size); return ret; } void* pool_get(Pool* pool) { if (pool->length >= pool->capacity) { size_t bucket_count = pool->capacity / pool->bucket_size; pool->buckets = realloc(pool->buckets, (bucket_count + 1) * sizeof(void*)); pool->buckets[bucket_count] = malloc(pool->bucket_size * pool->slot_size); pool->capacity += pool->bucket_size; } size_t bucket = pool->length / pool->bucket_size; size_t bucket_idx = pool->length % pool->bucket_size; pool->length += 1; return (void*) (((size_t) pool->buckets[bucket]) + (bucket_idx * pool->slot_size)); } void* pool_to_array(Pool* pool) { char* array = malloc(pool->length * pool->slot_size); size_t bucket_count = pool->capacity / pool->bucket_size; size_t items_remaining = pool->length; for (size_t i = 0; i < bucket_count; i++) { size_t items_to_copy; if (items_remaining >= pool->bucket_size) { items_to_copy = pool->bucket_size; } else { items_to_copy = items_remaining; } size_t offset = i * pool->bucket_size * pool->slot_size; memcpy(&array[offset], pool->buckets[i], items_to_copy * pool->slot_size); items_remaining -= pool->bucket_size; if (items_to_copy < pool->bucket_size) break; } return (void*) array; } void free_pool(Pool* pool) { size_t bucket_count = pool->capacity / pool->bucket_size; for (size_t i = 0; i < bucket_count; i++) { free(pool->buckets[i]); } free(pool->buckets); free(pool); }
C
#include "shell.h" #include "fs_cmd.h" char ps_buffer[64]; // ourShell的主函数 void osh() { // 初始化 char cmd[MAX_COMMAND_LENGTH]; kernel_clear_screen(); // 原ZJUNIX怎么还PowerShell的 kernel_puts("OurShell Starts!\n\n"); print_prompt(); while (1) { // 从标准输入读入,传给解析器解析 if (read_line(cmd, MAX_COMMAND_LENGTH)) { parse_cmd(cmd); } print_prompt(); } } // 命令格式统一只许argument,不许option // ls help -> YES // ls -h -> NO void parse_cmd(char* cmd) { char thisArgument[MAX_ARGUMENT_LENGTH]; // 有限状态机,0为读命令,1为读参数,做管道和重定向时加状态 // 状态:读入命令名 int status = 0; // 目前为单个命令,如果支持多条命令,也用链表 struct command* thisCmd = (struct command*)kmalloc(sizeof(struct command)); kernel_memset(thisCmd->cmdName, 0, MAX_ARGUMENT_LENGTH); // 参数链表 thisCmd->argList = (struct argumentNode*)kmalloc(sizeof(struct argumentNode)); struct argumentNode* thisArg = thisCmd->argList; thisArg->nextArg = (void*)0; int cmdIndex = 0, argIndex = 0; int len = kernel_strlen(cmd) + 1; // 扫描一遍字符串 // 看不懂两个月前写的代码系列 while (cmd[cmdIndex] && cmdIndex < MAX_COMMAND_LENGTH) { // 正常字符 if (' ' != cmd[cmdIndex] && '\0' != cmd[cmdIndex] && '\n' != cmd[cmdIndex]) { if (argIndex < MAX_ARGUMENT_LENGTH - 1) { thisArgument[argIndex++] = cmd[cmdIndex++]; continue; } else { kernel_printf_error("argument too long!\n"); break; } } // 遇到空格或结束 else { // 一个参数读入完毕,要放进链表,准备读下一个或结束 if (argIndex) { thisArgument[argIndex] = '\0'; // 这是命令名 if (0 == status) { kernel_strcpy(thisCmd->cmdName, thisArgument); status = 1; } // 这是参数 else if (1 == status) { thisArg = newArg(thisArg); kernel_strcpy(thisArg->argName, thisArgument); } // 结束 if ('\0' == cmd[cmdIndex] || '\n' == cmd[cmdIndex]) { break; } // 读下一个 else { argIndex = 0; continue; } } // 连续的空格 else { // 读完了 if ('\0' == cmd[cmdIndex] || '\n' == cmd[cmdIndex]) { break; } // 连续空格 else { cmdIndex++; continue; } } } } exec_cmd(thisCmd); } // 子进程执行命令 void exec_cmd(struct command* cmd) { kernel_printf("\n"); if(kernel_strcmp(cmd->cmdName, "") == 0) { } else if(kernel_strcmp(cmd->cmdName, "pwd") == 0) { pwd(); } else if (kernel_strcmp(cmd->cmdName, "ls") == 0) { char* name = cmd->argList->nextArg ? cmd->argList->nextArg->argName : nullptr; ls(name); } else if (kernel_strcmp(cmd->cmdName, "cd") == 0) { char* name = cmd->argList->nextArg ? cmd->argList->nextArg->argName : nullptr; cd(name); } else if (kernel_strcmp(cmd->cmdName, "cat") == 0) { if(!cmd->argList->nextArg) { kernel_printf("%s: not enough arguments. \n", cmd->cmdName); return; } cat(cmd->argList->nextArg->argName); } else if (kernel_strcmp(cmd->cmdName, "exec") == 0) { if(!cmd->argList->nextArg) { kernel_printf("%s: not enough arguments. \n", cmd->cmdName); return; } loadUserProgram(cmd->argList->nextArg->argName); } else if (kernel_strcmp(cmd->cmdName, "print") == 0) { if(!cmd->argList->nextArg) { kernel_printf("%s: not enough arguments. \n", cmd->cmdName); return; } else if (kernel_strcmp(cmd->argList->nextArg->argName, "buddy") == 0) { print_buddy_info(); } else if (kernel_strcmp(cmd->argList->nextArg->argName, "slab") == 0) { print_slab_info(); } else if (kernel_strcmp(cmd->argList->nextArg->argName, "tlb") == 0) { print_tlb(); } } else if (kernel_strcmp(cmd->cmdName, "test") == 0) { if(!cmd->argList->nextArg) { kernel_printf("%s: not enough arguments. \n", cmd->cmdName); return; } else if (kernel_strcmp(cmd->argList->nextArg->argName, "buddy") == 0) { if(cmd->argList->nextArg->nextArg) { test_buddy(cmd->argList->nextArg->nextArg->argName[0] - '0'); } else { kernel_printf("%s: not enough arguments. \n", cmd->cmdName); return; } } else if (kernel_strcmp(cmd->argList->nextArg->argName, "slab") == 0) { test_slab(); } else if (kernel_strcmp(cmd->argList->nextArg->argName, "pf") == 0) { if(cmd->argList->nextArg->nextArg) { page_fault_debug = 1; test_page_fault(cmd->argList->nextArg->nextArg->argName[0] - '0'); page_fault_debug = 0; } else { kernel_printf("%s: not enough arguments. \n", cmd->cmdName); return; } } } else if (kernel_strcmp(cmd->cmdName, "sig") == 0) { test_sig(); } else if (kernel_strcmp(cmd->cmdName, "ipc") == 0) { test_shm(); } else if (kernel_strcmp(cmd->cmdName, "rm") == 0) { if(!cmd->argList->nextArg) { kernel_printf("%s: not enough arguments. \n", cmd->cmdName); return; } rm(cmd->argList->nextArg->argName); } else if (kernel_strcmp(cmd->cmdName, "mkdir") == 0) { if(!cmd->argList->nextArg) { kernel_printf("%s: not enough arguments. \n", cmd->cmdName); return; } mkdir(cmd->argList->nextArg->argName); } else if (kernel_strcmp(cmd->cmdName, "touch") == 0) { if(!cmd->argList->nextArg) { kernel_printf("%s: not enough arguments. \n", cmd->cmdName); return; } touch(cmd->argList->nextArg->argName); } else if (kernel_strcmp(cmd->cmdName, "mv") == 0) { if(!cmd->argList->nextArg || !cmd->argList->nextArg->nextArg) { kernel_printf("%s: not enough arguments. \n", cmd->cmdName); return; } mv(cmd->argList->nextArg->argName, cmd->argList->nextArg->nextArg->argName); } else if (kernel_strcmp(cmd->cmdName, "app") == 0) { if(!cmd->argList->nextArg) { kernel_printf("%s: not enough arguments. \n", cmd->cmdName); return; } app(cmd->argList->nextArg->argName, cmd->argList->nextArg->nextArg->argName); } else { kernel_printf("%s: unknown command. \n", cmd->cmdName); } } struct argumentNode* newArg(struct argumentNode* arg) { arg->nextArg = (struct argumentNode*)kmalloc(sizeof(struct argumentNode)); struct argumentNode* thisArg = arg->nextArg; kernel_memset(thisArg->argName, 0, MAX_ARGUMENT_LENGTH); thisArg->nextArg = (void*)0; return thisArg; } // 从标准输入获取一行 bool read_line(char* str, int length) { int c; int index = 0; while (1) { c = kernel_getchar(); // 回车,结束输入 if ('\n' == c) { // 确保字符串结尾是'\0' // 在自己的电脑上测试不需要结尾的\n // 但是在板子上测试必须加上\n // 否则最后一个字符必须是空格,正常字符读不到 str[index] = c; str[index + 1] = 0; return true; } // 回退,删除一个字符,将其从数组中删除,也从屏幕上消失 else if ('\b' == c) { if (index) { // 原ZJUNIX代码只有index--,这时按下回车不就出bug了 str[index--] = '\0'; // 删除字符,重置光标 kernel_putchar_at(' ', cursor.row, cursor.col - 1); cursor.col--; kernel_set_cursor(); } } // 输入了EOF,现在应该还遇不到 else if (-1 == c) { return false; } // 输入一般字符,存在字符串中并显示出来 else { // length要减1,结尾给'\0'留个位置 if (index < length - 1) { str[index++] = c; kernel_putchar(c); } } } }
C
/* ------------------------------------- File: 108t1.c Project: avl.c file description ------------------------------------- Author: Kathleen Milligan ID: 160458550 Email: mill8550 Version 2018-03-05 ------------------------------------- */ #include "avl.h" int main() { struct Node *root = NULL; /* Constructing tree given in the above figure */ /*root = insert(root, 9); root = insert(root, 5); root = insert(root, 10); root = insert(root, 0); root = insert(root, 6); root = insert(root, 11); root = insert(root, -1); root = insert(root, 1); root = insert(root, 2);*/ root = insert(root, 1); print_tree(root, 0); root = insert(root, 2); print_tree(root, 0); root = insert(root, 3); print_tree(root, 0); root = insert(root, 4); print_tree(root, 0); root = insert(root, 5); print_tree(root, 0); root = insert(root, 6); print_tree(root, 0); root = insert(root, 7); print_tree(root, 0); root = insert(root, 8); print_tree(root, 0); root = insert(root, 9); print_tree(root, 0); root = insert(root, 10); print_tree(root, 0); root = insert(root, 11); print_tree(root, 0); root = insert(root, 12); print_tree(root, 0); root = insert(root, 13); print_tree(root, 0); root = insert(root, 14); print_tree(root, 0); root = insert(root, 15); print_tree(root, 0); /* The constructed AVL Tree would be 9 / \ 1 10 / \ \ 0 5 11 / / \ -1 2 6 */ printf("Preorder traversal of the constructed AVL " "tree is \n"); preOrder(root); root = deleteNode(root, 10); /* The AVL Tree after deletion of 10 1 / \ 0 9 / / \ -1 5 11 / \ 2 6 */ printf("\nPreorder traversal after deletion of 10 \n"); preOrder(root); printf("\nIs balanced check (1 = true, 0= false) \n"); int i = is_balanced(root); printf("%d", i); return 0; }
C
/* * File: 1..c * Author: Christopher Roldan Sanchez * Mail: [email protected] * Date: * Description: * * Materia: Programacion avanzada * Universidad: Universidad Argentina De La Empresa (UADE) * Docente: Iervasi Scokin, Juan Jose * * Ejercicio: * 4. Realizar una funcin que devuelva la posicin en que se haya un valor dado mediante el mtodo de bsqueda binaria. * En caso que no lo encuentre devolver - 1 * */ #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdbool.h> // Declaro funciones void imprimir(int vec[], int n); int busqueda_binaria(int vec[], int n, int buscado); void ordenar(int vec[], int n); int main(void) { int vec[10] = { 4,5,1,0,9,6,7,24,9,2 }; int buscado; ordenar(vec, 10); imprimir(vec, 10); printf("Inserte valor a buscar: "); scanf("%d", &buscado); printf("Valor en la pos: %d", busqueda_binaria(vec, 10, buscado)); printf("\n"); system("PAUSE"); return 0; } void imprimir(int vec[], int n) { for (int i = 0; i < n; i++)printf("%d\n", vec[i]); } int busqueda_binaria(int vec[], int n, int buscado) { int inferior = 0; int superior = n; int mitad; int i = 0; while ((inferior <= superior) && (i < 5)) { mitad = (inferior + superior) / 2; if (vec[mitad] == buscado)return mitad; if (vec[mitad] > buscado) { superior = mitad; mitad = (inferior + superior) / 2; } if (vec[mitad] < buscado) { inferior = mitad; mitad = (inferior + superior) / 2; } i++; } return -1; } void ordenar(int vec[], int n) { int aux; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (vec[i] > vec[j]) { aux = vec[i]; vec[i] = vec[j]; vec[j] = aux; } } } }
C
/************************************************************************* > File Name: pthread.c > Author: bianyilin > Mail: [email protected] > Created Time: 2019年06月02日 星期日 19时48分46秒 ************************************************************************/ #include <stdio.h> #include <pthread.h> #include <unistd.h> #include <string.h> struct MyPara{ int age; char name[10]; }; void *output(void *arg){ struct MyPara *para; para = (struct MyPara *)arg; printf("hello %s,you are %d years old!\n",para->name,para->age); } int main() { pthread_t output_p; struct MyPara para; strcpy(para.name,"haizei"); para.age=10; pthread_create(&output_p,NULL,output,(void *)&para); pthread_join(output_p,NULL); return 0; }
C
struct Node { void *data; //holds data struct Node *next; }; struct stackPointer { struct Node *head; int size; }; int push(struct stackPointer *const sp, const void *data){ struct Node *newNode = (struct Node*) malloc(sizeof(struct Node)); if(newNode == NULL) //malloc fails { return -1; } newNode->data = (void *) malloc(sp->size); if(memcpy(newNode->data, data, sp->size) == NULL) return -1; newNode->next = sp->head; sp->head = newNode; return 0; } int pop( struct stackPointer *const sp, void *ptr) { if(ptr == NULL) return -1; } int createStack(struct stackPointer **sp, int size); int main() { return 0; } int createStack(struct stackPointer **sp, int size) { if(*sp != NULL) return -1; *sp = (struct stackPointer *) malloc(sizeof(struct stackPointer)); (*sp)->size = size; (*sp)->head = NULL; return 0; } foo( struct stackPointer * s ){ int a = 3; push( s, &a ); } main() { struct stackPointer *s; createStack( &s, sizeof( int ) ); foo( s); int p; p = (int * ) pop( s, &p ); assert( 3 == *p ); }
C
#include <stdio.h> #define PI_APPROXIMATION 3.14159 double area_of_circle(double radius) { return (PI_APPROXIMATION * radius * radius); } int main(void) { double radius; scanf("%lf", &radius); printf("A=%.4f\n", area_of_circle(radius)); return (0); }
C
// // 顺环队列的实现(数组实现) // 这种方案要注意的是 // 1、队列满空的判断条件是什么 // 2、以及为什么会出现空、满无法区分?根本原因? // 判别队列的状态,是根据front和rear的相对距离,这种相对距离,对于大小为N的数组,从0至(N-1),一共有N种情况 // 而队列装载的元素却可以有N+1种(从0到N)情况, 用N中相对距离,去区分N+1中情况,显然是做不到的 // 有两种解决方式: // 1、使用额外的标记, size(队列中元素个数,若个数达到MaxSize则满,若个数为0为空,对应了增加和删除操作时候对size的修改) // 或者tag(tag=1,最有一次操作为添加,tag=0,最后一次操作为删除) // 2、仅使用n-1个数组空间(本例中就是这么做的) // Created by 侯金鑫 on 16/5/23. // #include <stdlib.h> #include <stdio.h> #define MaxSize 3 typedef int ElementType; //typedef struct { // int key; //} ElementType; typedef struct { ElementType data[MaxSize]; int front; //记录队头元素位置 int rear; //记录队尾元素位置 } Queue; /** * 创建队列 */ Queue *CreateQueue() { Queue *q = malloc(sizeof(Queue)); q->front = 0; q->rear = 0; return q; } /** * 判断队列已满, * 顺坏队列不能仅根据front和rear的值是否相等来判断,因为不管是队列空和满时,都会有 front == rear,有两种方法可以用来判断队列是否已满 * 1、采用其他的标志位来标识队列是否为空,例如queue中增加一个tag标识队列上一个操作。若上一个操作为入栈,tag=1,否则tag=0。若tag==1且 * front==rear则队列满,若tag=0,且front==rear则队列空 * 2、保留队列中的一个位置始终为空,若队头与队尾相差一个单元 ,即(rear + 1) % MaxSize == front,这时认为队列满。 * 这列采用第二种方式 */ int IsFullQ(Queue *q) { if ((q->rear + 1) % MaxSize == q->front % MaxSize) return 1; else return 0; } /** * 添加元素 * 1、判断队列是否已满 * 2、在队尾处添加元素 * 3. rear++ */ void AddQ(Queue *q, ElementType e) { if (IsFullQ(q)) { printf("队列已满\r\n"); return; } else { q->data[q->rear % MaxSize] = e; q->rear++; } } /** * 判断队列是否为空,由于队列满的定义是队尾与队首元素相差一个单元,故当队列满时,rear != front 故当front==rear时,认为队列空 */ int IsEmptyQ(Queue *q) { if (q->front == q->rear) { return 1; } else { return 0; } } /** * 删除元素并返回 */ ElementType DeleteQ(Queue *q) { ElementType e; if (IsEmptyQ(q)) { printf("队列已空\r\n"); e = -1; } else{ e = q->data[q->front % MaxSize]; q->front++; } return e; } /** * 调试时参考这几个参数 * q->rear * q->front * IsFull(q) * q->front%MaxSize * (q->rear + 1) % MaxSize * isEmpty(q) */ int main() { Queue *q = CreateQueue(); AddQ(q, 1); DeleteQ(q); AddQ(q, 2); DeleteQ(q); AddQ(q, 3); DeleteQ(q); AddQ(q, 4); DeleteQ(q); AddQ(q, 5); DeleteQ(q); AddQ(q, 6); DeleteQ(q); AddQ(q, 7); AddQ(q, 8); // printf("队列%s\r\n", IsFullQ(q) ? "满" : "未满"); }
C
#include <stdio.h> #include <math.h> #define f(i,n) for(i=0;i<n;i++) #define sd(n) scanf("%d",&n) #define sc(n) scanf("%c",&n) #define slld(n) scanf("%lld",&n) #define mod 1000000007 #define ll long long #define gc getchar_unlocked #define pc putchar_unlocked inline unsigned long long uscan() { unsigned long long n=0,c=gc(); while(c<'0'||c>'9') c=gc(); while(c<='9'&&c>='0'){ n=n*10+c-'0'; c=gc();} return n; } inline long int lscan() { long int n=0,c=gc(); while(c<'0'||c>'9') c=gc(); while(c<='9'&&c>='0'){ n=n*10+c-'0'; c=gc();} return n; } inline int sscan() {register int n=0,c=gc(); while(c<'0'||c>'9') c=gc(); while(c<='9'&&c>='0') { n=n*10+c-'0'; c=gc(); } return n; } ll gcdExtended(ll a, ll b, ll *x, ll *y) { if (a == 0) { *x = 0, *y = 1; return b; } ll x1, y1; ll gcd = gcdExtended(b%a, a, &x1, &y1); *x = y1 - (b/a) * x1; *y = x1; return gcd; } ll modInverse(ll a, ll m) { ll x, y; ll g = gcdExtended(a, m, &x, &y); ll res = (x%m + m) % m; return res; } int main() { int t=sscan() ; while(t--){ long long n=uscan(),p=uscan(),q=uscan(); ll a[n]; ll factors[12][2]; ll nnn=p; for(int o=0;o<12;o++) { factors[o][0]=0; factors[o][1]=0; } ll count=0; while (nnn%2 == 0) { if(!count) { factors[count][0]=2; factors[count++][1]=2; } else { factors[count-1][0]*=2; } nnn = nnn/2; } for (ll i = 3; i <= sqrt(nnn); i = i+2) { while (nnn%i == 0) { if(count){ if(factors[count-1][0]%i!=0) { factors[count][0]=i; factors[count++][1]=i; } else { factors[count-1][0]*=i; } nnn = nnn/i; } else { factors[count][0]=i; factors[count++][1]=i; nnn/=i; } } } if(!count&&nnn>2){ factors[count][0]=nnn; factors[count++][1]=nnn; nnn=1; } if (nnn > 2) { if(factors[count-1][0]%nnn!=0) { factors[count][0]=nnn; factors[count++][1]=nnn; } else factors[count-1][0]*=nnn; } ll factsize=count;//max 9 ll prod[n][factsize],init[n][factsize]; ll coun[n][factsize]; ll modin[n][factsize]; ll i,j; f(i,n) { a[i]=uscan(); f(j,factsize){ coun[i][j]=0; if(i&&prod[i-1][j]){ coun[i][j]=coun[i-1][j]; prod[i][j]=(prod[i-1][j]*a[i])%(factors[j][0]); init[i][j]=init[i-1][j]; if(prod[i][j]!=0){ while(prod[i][j]%factors[j][1]==0){ prod[i][j]/=factors[j][1]; coun[i][j]++; } modin[i][j]=modInverse(prod[i][j],factors[j][0]);} else modin[i][j]=1; } else{ init[i][j]=i-1; prod[i][j]=a[i]%factors[j][0]; if(prod[i][j]!=0){ while(prod[i][j]%factors[j][1]==0){ prod[i][j]/=factors[j][1]; coun[i][j]++; } modin[i][j]=modInverse(prod[i][j],factors[j][0]);} else modin[i][j]=1; } } } /* f(i,n){ f(j,n){ printf("prod:%lld init:%lld count:%lld ",prod[i][j],init[i][j],coun[i][j]); } printf("\n"); }*/ ll blen=q/64; blen+=2; ll b[blen]; f(i,blen){ b[(int)i]=uscan(); } ll l,r,ans=0; ll modin2[factsize]; f(i,factsize){ modin2[i]=modInverse(p/factors[i][0],factors[i][0]); modin2[i]*=(p/factors[i][0]); modin2[i]%=p; } ll fact[factsize][40]; ll siz[factsize]; f(i,factsize){ j=1; while(pow(factors[i][1],j)!=factors[i][0]){ fact[i][j-1]=pow(factors[i][1],j); j++; } fact[i][j-1]=factors[i][0]; siz[i]=j; } f(j,q){ if((j&63)==0){ l= (b[(j/64)]+ans)%n; r=(b[(j/64)+1]+ans)%n; } else { l=(ans+l)%n;r=(r+ans)%n; } if(l>r){ ll t = l; l=r; r=t; } ans=0; f(i,factsize){ if(init[l][i]==init[r][i]){ ll rem=prod[r][i]; ll cou=coun[r][i]; if(l!=0){ cou-=coun[l-1][i]; } if(cou<siz[i]){ if(l!=0) rem=(rem*modin[l-1][i])%factors[i][0]; if(cou) {rem*=fact[i][cou-1]; rem%=factors[i][0];} ans=(ans+(rem*modin2[i]))%p; } } } ans++; if(ans==p)ans=0; } printf("%lld\n",(ans)); } return 0; }
C
#include "include/ptypes.h" void create_operation(operation* op, producer opr) { op->opt = opr; } void destroy_operation(operation* op) { free(op); } void create_decl(var_decl* declaration, char* identifier, int literal, operation* op, int value, int line) { declaration->identifier = identifier; declaration->literal = literal; declaration->op = op; declaration->value = value; declaration->line = line; } void create_empty_decl(var_decl* declaration) { declaration->identifier = NULL; declaration->literal = 0; declaration->op = NULL; declaration->value = 0; declaration->line = 0; } void destroy_decl(var_decl* decl) { destroy_operation(decl->op); free(decl); }
C
/******************************************************************************************************* * : RS485ͨ(뷢) * * * * 1.ͨ˽⴮ڵĻԭʹ ,ⲢնԴڽгʼ * * * * 2.ʹôڵ֣Baud 9600λ8ֹͣλ1ЧλޣΪλ()ݺ()ݣ * * ַַ(HEX),Ͱťۿܴʾ.ҲԶѭ͡ * * * * 3.RS485ҪRS232ת485תͷA485תͷA BӦ485תͷB.ӷҿԲοԭͼ * ********************************************************************************************************/ #include <reg52.h> #include <intrins.h> sbit RS485_DIR = P1^7; //RS485ѡ bit flagOnceTxd = 0; //ηɱ־һֽ bit cmdArrived = 0; //־յλ· unsigned char cntRxd = 0; unsigned char pdata bufRxd[40]; //ڽջ void ConfigUART(unsigned int baud) //úbaudΪ { RS485_DIR = 0; //RS485Ϊշ SCON = 0x50; //ôΪģʽ1 TMOD &= 0x0F; //T1Ŀλ TMOD |= 0x20; //T1Ϊģʽ2 TH1 = 256 - (11059200/12/32) / baud; //T1ֵ TL1 = TH1; //ֵֵ ET1 = 0; //ֹT1ж ES = 1; //ʹܴж TR1 = 1; //T1 } unsigned char UartRead(unsigned char *buf, unsigned char len) //ݶȡݽָbufȡݳlenֵΪʵʶȡݳ { unsigned char i; if (len > cntRxd) //ȡȴڽյݳʱ { len = cntRxd; //ȡΪʵʽյݳ } for (i=0; i<len; i++) //յ { *buf = bufRxd[ i]; buf++; } cntRxd = 0; //ռ return len; //ʵʶȡ } void DelayX10us(unsigned char t) //ʱʱʱ(t*10)us { do { _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); } while (--t); } void UartWrite(unsigned char *buf, unsigned char len) //д뺯ڷͺָbufݳlen { RS485_DIR = 1; //RS485Ϊ while (len--) // { flagOnceTxd = 0; SBUF = *buf; buf++; while (!flagOnceTxd); } DelayX10us(5); //ȴֹͣλɣʱʱɲʾ RS485_DIR = 0; //RS485Ϊ } void UartDriver() //յִӦ { unsigned char len; unsigned char buf[30]; if (cmdArrived) //ʱȡ { cmdArrived = 0; len = UartRead(buf, sizeof(buf)-2); //յȡ // buf[len++] = '\r'; //ڽյ֡ӻз󷢻 //buf[len++] = '\n'; UartWrite(buf, len); } } void UartRxMonitor(unsigned char ms) //ڽռغ { static unsigned char cntbkp = 0; static unsigned char idletmr = 0; if (cntRxd > 0) //ռʱ߿ʱ { if (cntbkp != cntRxd) //ռı䣬սյʱмʱ { cntbkp = cntRxd; idletmr = 0; } else { if (idletmr < 30) //ռδı䣬߿ʱۻʱ { idletmr += ms; if (idletmr >= 30) //ʱ䳬30msΪһ֡ { cmdArrived = 1; //־ } } } } else { cntbkp = 0; } } void InterruptUART() interrupt 4 //UARTжϷ { if (RI) //յֽ { RI = 0; //ֶжϱ־λ if (cntRxd < sizeof(bufRxd)) //ջδʱ { bufRxd[cntRxd++] = SBUF; //ֽڣ } } if (TI) //ֽڷ { TI = 0; //ֶ㷢жϱ־λ flagOnceTxd = 1; //õηɱ־ } } /***********************main.cļԴ*************************/ #include <reg52.h> unsigned char T0RH = 0; //T0ֵĸֽ unsigned char T0RL = 0; //T0ֵĵֽ void ConfigTimer0(unsigned int ms); extern void ConfigUART(unsigned int baud); extern void UartRxMonitor(unsigned char ms); extern void UartDriver(); void main () { EA = 1; //ж ConfigTimer0(1); //T0ʱ1ms ConfigUART(9600); //òΪ9600 while(1) { UartDriver(); } } void ConfigTimer0(unsigned int ms) //T0ú { unsigned long tmp; tmp = 11059200 / 12; //ʱƵ tmp = (tmp * ms) / 1000; //ļֵ tmp = 65536 - tmp; //㶨ʱֵ tmp = tmp + 34; //жӦʱɵ T0RH = (unsigned char)(tmp >> 8); //ʱֵΪߵֽ T0RL = (unsigned char)tmp; TMOD &= 0xF0; //T0Ŀλ TMOD |= 0x01; //T0Ϊģʽ1 TH0 = T0RH; //T0ֵ TL0 = T0RL; ET0 = 1; //ʹT0ж TR0 = 1; //T0 } void InterruptTimer0() interrupt 1 //T0жϷ { TH0 = T0RH; //ʱ¼ֵ TL0 = T0RL; UartRxMonitor(1); //ڽռ }
C
#ifndef STACK_H #define STACK_H /* This is C implementation of a stack data type containing integers * The stack is implemented using a dynamically allocated array. */ typedef struct { /* The poiter to the base of the stack * A new element will be insterted at base + LSize location. * A pop will return the element from base + LSize - 1 */ int* base; /* The logical size of the stack. * It is intialized to 0 and increses on push. * It decreses on pop */ int LSize; /* The allocated size. * It is doubled when top = Asize and an insertion happens. */ int ASize; } stack; /* The stack constructor. Pass a pointer to the stack structure * and this function will intialize the variables properly. */ void stackNew(stack *); /* The stack destructor. Pass a pointer to the stack structure and * this function will free the space occupied. */ void stackDispose(stack *); /* The push operation */ void stackPush(stack *, int); /* The pop operation */ int stackPop(stack *); #endif // STACK_H
C
#include "I2C.h" void I2C_write (uint8_t address, uint8_t thisRegister, uint8_t thisValue){ // Send START I2C_GenerateSTART(I2C1, ENABLE); while(!(I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT))); // Send address as transmitter I2C_Send7bitAddress(I2C1, address, I2C_Direction_Transmitter); while(!(I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED))); // Send register to write to I2C_SendData(I2C1, thisRegister); //while(!(I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTING)); while(!(I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED))); // Send data to be written I2C_SendData(I2C1, thisValue); //while(!(I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTING)); while(!(I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED))); // Send STOP I2C_GenerateSTOP(I2C1, ENABLE); } void I2C_read (uint8_t address, uint8_t startRegister, uint8_t* buffer, uint8_t number_of_registers){ // Send START I2C_GenerateSTART(I2C1, ENABLE); while(!(I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT))); // Send address as transmitter I2C_Send7bitAddress(I2C1, address, I2C_Direction_Transmitter); while(!(I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED))); // Send register to read from I2C_SendData(I2C1, startRegister); //while(!(I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTING))); while(!(I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED))); // Send START I2C_GenerateSTART(I2C1, ENABLE); while(!(I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT))); // Send address as receiver I2C_Send7bitAddress(I2C1, address | (1 << 7), I2C_Direction_Receiver); while(!(I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED))); while(!(I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_RECEIVED))); while (number_of_registers--){ while(!(I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_RECEIVED))); *buffer++ = I2C_ReceiveData(I2C1); if (number_of_registers == 1){ I2C_AcknowledgeConfig(I2C1, DISABLE); I2C_GenerateSTOP(I2C1, ENABLE); } } I2C_AcknowledgeConfig(I2C1, ENABLE); }
C
#include "node.h" sl_node_t* new_node(void* data, size_t size_data) { sl_node_t *node = malloc(sizeof *node); if ( node == NULL ) return NULL; node->data = malloc(size_data); if ( node->data == NULL ) return NULL; memcpy(node->data, data, size_data); node->next = NULL; return node; } void delete_node(sl_node_t *node) { free(node->data); free(node); } void* get_data(sl_node_t *node) { return node->data; } void set_next(sl_node_t *node, sl_node_t *next) { node->next = next; } sl_node_t* get_next(sl_node_t *node) { return node->next; }
C
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { srand(time(NULL)); int dizi[10],diziCift[10],diziTek[10]; int *diziPtr=&dizi; int *diziCptr=&diziCift; int *diziTptr=&diziTek; int i; printf("Random dizideki elemanlar\n\n"); for(i=0;i<10;i++){ *(diziPtr+i)=1+rand()%100; printf("%d. sayi= %d\n",i+1,*(diziPtr+i)); } printf("\n\n\n\n"); tekmiciftmi(diziPtr,diziTptr,diziCptr); return 0; } void tekmiciftmi(int *dizi,int *tek,int *cift){ int i; for(i=0;i<10;i++) { if(*(dizi+i)%2==0) { *(cift+i)=*(dizi+i); printf("%d sayisi cifttir.\n",*(dizi+i)); } else { *(tek+i)=*(dizi+i); printf("%d sayisi tektir.\n",*(dizi+i)); } } }
C
#include <stdio.h> #include <stdlib.h> // int addSelf(int n); int main(int argc, const char **argv) { if (argc < 2) { printf("Program needs an integer argument\n"); return(-1); } int n = atoi(argv[1]); int fact = n + 2; printf("plusTwo(%d) is %d\n",n, fact); printf("first element of argv is %s\n",argv[0]); return 0; } /* // recursive function; i.e. it calls itself int addSelf(int n) { if (n == 1) return 1; else return n*factorial(n-1); } */
C
#include <stdio.h> // puts() NULL printf() scanf() fopen() fgets() fclose() // fprintf() #include <strings.h> // strcasecmp() #include <string.h> // strchr() strlen() #include <time.h> // time() #include <stdlib.h> // srand() rand() atoi() #include <unistd.h> // sleep() access() // Function declaration void game(void); void plAgain(void); int main(void) { game(); plAgain(); } void game(void) { char data[255], chWins[255], chLoses[255], chDraws[255], pInput[8], *e; int lIndex, dIndex, wins, loses, draws, player, computer; FILE *fp; // If there is a file named "data" in the process folder // and if we have write permissions for it. if (access("./data", R_OK|W_OK) != -1) { // TODO: implement more ifs with different errors if file has read but no write permission etc. // Open the file "data" as read and write it's contents to data fp = fopen("./data", "r"); fgets(data, 255, (FILE*)fp); fclose(fp); e = strchr(data, 'l'); // Find the index of 'l' in char data lIndex = (int)(e - data); e = strchr(data, 'd'); // Find the index of 'd' in char data dIndex = (int)(e - data); strncpy(chWins, data + 1, lIndex - 1); // Copy the part of the char data // Which says the amount of wins strncpy(chLoses, (data + lIndex + 1), (dIndex - lIndex) - 1); strncpy(chDraws, (data + dIndex + 1), (strlen(data) - dIndex) - 2); // ASCII To Int wins = atoi(chWins); loses = atoi(chLoses); draws = atoi(chDraws); } else { fp = fopen("./data", "w+"); fputs("w0l0d0", fp); fclose(fp); wins = 0; loses = 0; draws = 0; } while (1) { printf("\nChoose Rock, Paper or Scissors:"); scanf("%8s", pInput); puts("\n"); if ((strcasecmp(pInput, "rock") == 0) || (strcasecmp(pInput, "r") == 0)) { puts("You have chosen Rock"); player = 1; break; } else if ((strcasecmp(pInput, "paper") == 0) || (strcasecmp(pInput, "p") == 0)) { puts("You have chosen Paper"); player = 2; break; } else if ((strcasecmp(pInput, "scissors") == 0) || (strcasecmp(pInput, "s") == 0)) { puts("You have chosen Scissors"); player = 3; break; } else { puts("Error: Incorrect Input"); continue; } } sleep(1); // random seed based on time srand(time(NULL)); // random integer 1-3 computer = rand() % 3 + 1; if (computer == 1) puts("Computer has chosen Rock"); else if (computer == 2) puts("Computer has chosen Paper"); else puts("Computer has chosen Scissors"); if (player == computer) { puts("It's a draw!"); draws++; } else if ((player == 1) && (computer == 2)) { puts("Computer has won!"); loses++; } else if ((player == 1) && (computer == 3)) { puts("You have won!"); wins++; } else if ((player == 2) && (computer == 1)) { puts("You have won!"); wins++; } else if ((player == 3) && (computer == 1)) { puts("Computer has won!"); loses++; } else if ((player == 2) && (computer == 3)) { puts("Computer has won!"); loses++; } else if ((player == 3) && (computer == 2)) { puts("You have won!"); wins++; } printf("\n" "=========================\n" "You have %d total wins\n" "You have %d total loses\n" "You have %d total draws\n" "\n" "You have played %d times\n" "=========================\n" , wins, loses, draws, wins+loses+draws); fp = fopen("./data", "w+"); fprintf(fp, "w%dl%dd%d\n", wins, loses, draws); fclose(fp); } void plAgain(void) { char again[5]; while (1) { printf("\n" "Type 'Yes' or 'No' if you either want to play again or close the program or\n" "'Reset' to reset your score and close the program:"); scanf("%5s", again); if ((strcasecmp(again, "yes") == 0) || (strcasecmp(again, "y") == 0)) { game(); continue; } else if ((strcasecmp(again, "no") == 0) || (strcasecmp(again, "n") == 0)) { break; } else if ((strcasecmp(again, "reset") == 0) || (strcasecmp(again, "r") == 0)) { FILE *fp; fp = fopen("./data", "w+"); fputs("w0l0d0", fp); fclose(fp); break; } else { puts("Error:Incorrect Input"); continue; } } }
C
#include <stdio.h> #define MAXLINE 1000 int mygetline(char line[], int maxline); int insert(char line[], char x, int l, int len); int myremove(char line[], int l, int len); void replspaces(char line[], int len, int n); /* write a program that replaces tabs with the proper number of blanks to space to * the next tab stop, say every n columns. */ int main() { int len, n; char line[MAXLINE]; n = 4; /* blanks per tab */ while ((len = mygetline(line, MAXLINE)) > 0) { replspaces(line, len, n); printf("%s", line); } return 0; } /* replspaces: given a string, replace spaces with the min num of tabs + necessary spaces */ void replspaces(char s[], int len, int n) { int i, j, count; char tab = 'X'; count = 0; for (i = 0; i < len; ++i) { if (s[i] == ' ') ++count; else count = 0; if (count == n) { for (j = 1; j <= n; ++j) { len = myremove(s, i-(n-1), len); //printf("%s", s); } len = insert(s, tab, i-(n-1), len); count = 0; i = 0; } } } /* getline: use getchar to read a line into s, return length which includes newline char */ int mygetline(char s[], int lim) { int c, i; // Q: Why do we make lim-2 the upper bound index? // A: To leave room for the newline char. for (i=0; i<lim-1 && (c=getchar()) != EOF && c!='\n'; ++i) s[i] = c; // Q: Why do we care about the newline char? // A: To distinguish between complete lines and truncated lines. if (c == '\n') { s[i] = c; ++i; } // Q: Why do we need to manually insert the null char? // A: To strip unnecessary length from the array. s[i] = '\0'; return i; } /* insert: given string s with length len, insert char x at index l, and return new len */ int insert(char s[], char x, int l, int len) { if (l < 0 || l >= len) { printf("insert: bad arg: l=%d, len=%d\n", l, len); return -1; } int high, i; s[len+1] = '\0'; // advance null ch to enlarge array for (i = len; i > l; --i) { s[i] = s[i-1]; } s[l] = x; return len + 1; } /* remove: given string s, remove the element at index l and return the new length */ int myremove(char s[], int l, int len) { if (len == 0 || l < 0 || l >= len) { printf("remove: bad arg, index out of bounds\n"); return -1; } int i; for (i = l; i <= len-1; ++i) { s[i] = s[i+1]; } return len - 1; }
C
/* * Check if usual arithmetic conversion is well done. * Here, type of one opernd is `unsigned short int'. */ #include <stdio.h> void test00(unsigned short int a, long double b) { printf("%d + %Lf = %Lf\n", a, b, a + b); } void test01(unsigned short int a, double b) { printf("%d + %f = %f\n", a, b, a + b); } void test02(unsigned short int a, float b) { printf("%d + %f = %f\n", a, b, a + b); } void test03(unsigned short int a, unsigned long long int b) { printf("%d + %lld = %lld\n", a, b, a + b); } void test04(unsigned short int a, long long int b) { printf("%d + %lld = %lld\n", a, b, a + b); } void test05(unsigned short int a, unsigned long int b) { printf("%d + %ld = %ld\n", a, b, a + b); } void test06(unsigned short int a, long int b) { printf("%d + %ld = %ld\n", a, b, a + b); } void test07(unsigned short int a, unsigned int b) { printf("%d + %d = %d\n", a, b, a + b); } void test08(unsigned short int a, int b) { printf("%d + %d = %d\n", a, b, a + b); } void test09(unsigned short int a, unsigned short int b) { printf("%d + %d = %d\n", a, b, a + b); } void test10(unsigned short int a, short int b) { printf("%d + %d = %d\n", a, b, a + b); } void test11(unsigned short int a, unsigned char b) { printf("%d + %d = %d\n", a, b, a + b); } void test12(unsigned short int a, signed char b) { printf("%d + %d = %d\n", a, b, a + b); } void test13(unsigned short int a, char b) { printf("%d + %d = %d\n", a, b, a + b); } int main(void) { test00(0, 1.5L); test01(1, 2.5); test02(2, 3.5F); test03(3, 4ULL); test04(4, 5LL); test05(5, 6UL); test06(6, 7L); test07(7, 8L); test08(8, 9U); test09(9, 10); test10(10, 11); test11(11, 12); test12(12, 13); test13(13, 14); return 0; }
C
// ======================================================================================= // Extremely minimal bootstrap library. // // This implements the bare minimum of libc needed in order to be able to compile our // image resizer code. A real application would probably use Emscripten, which provides a // full C library, but Emscripten requires more complicated support code on the JavaScript // side. For this simple demo, we're working from scratch. // ======================================================================================= // Basic types and decls. typedef signed char int8_t; typedef unsigned char uint8_t; typedef short int16_t; typedef unsigned short uint16_t; typedef int int32_t; typedef unsigned int uint32_t; typedef long long int64_t; typedef unsigned long long uint64_t; typedef unsigned long size_t; typedef unsigned char byte; typedef unsigned int uint; #define NULL ((void*)0) #define INT_MAX 0x7fffffff int abs(int i) { return i < 0 ? -i : i; } // stdarg.h is pretty simple to replace. typedef __builtin_va_list va_list; #define va_start(v,l) __builtin_va_start(v,l) #define va_end(v) __builtin_va_end(v) #define va_arg(v,l) __builtin_va_arg(v,l) // string.h. These implementations are poorly-optimized. Oh well. void* memcpy(void* restrict dst, const void* restrict src, size_t n) { byte* bdst = (byte*)dst; byte* bsrc = (byte*)src; while (n-- > 0) { *bdst++ = *bsrc++; } return dst; } void* memmove(void* dst, const void* src, size_t n) { byte* bdst = (byte*)dst; byte* bsrc = (byte*)src; if (bdst < bsrc) { while (n-- > 0) { *bdst++ = *bsrc++; } } else { bdst += n; bsrc += n; while (n-- > 0) { *--bdst = *--bsrc; } } return dst; } void* memset(void* restrict ptr, int c, size_t n) { byte* cptr = (byte*)ptr; while (n-- > 0) { *cptr++ = c; } return ptr; } int memcmp(const void* s1, const void* s2, size_t n) { byte* b1 = (byte*)s1; byte* b2 = (byte*)s2; while (n-- > 0) { int d = *b1++ - *b2++; if (d != 0) return d; } return 0; } // Try extra-hard to make sure the compiler uses its built-in intrinsics rather than // our crappy implementations. #define memcpy __builtin_memcpy #define memset __builtin_memset #define memcmp __builtin_memcmp #define memmove __builtin_memmove // Really trivial malloc() implementation. We just allocate bytes sequentially from the start of // the heap, and reset the whole heap to empty at the start of each request. extern byte __heap_base; // Start of heap -- symbol provided by compiler. byte* heap = NULL; // Current heap position. void* last_malloc = NULL; // Last value returned by malloc(), for trivial optimizations. void* malloc(size_t n) { last_malloc = heap; heap += n; return last_malloc; } void free(void* ptr) { if (ptr == last_malloc) { heap = last_malloc; } else { // Fragmentation. Just leak the memory. } } void* realloc(void* ptr, size_t n) { if (ptr == last_malloc) { heap = (byte*)last_malloc + n; return ptr; } else { void* result = malloc(n); memmove(result, ptr, n); return result; } } // Math functions used by our image library, but not by parts of the image library that we // actually call. We stub these out. double pow(double x, double e) { return 0; } double fabs(double x) { return 0; } double ceil(double x) { return 0; } double floor(double x) { return 0; } double frexp(double x, int *exp) { return 0; } // Our image library calls sprintf() in one place but we don't need that code to work. int sprintf(char *str, const char *format, ...) { return 0; }
C
/************************************************************* * The Suquential Solution of the N-Queens Problem * CIS750 * Yan Shi, CIS, Temple University * Oct., 1993 *************************************************************/ #include <stdio.h> #include <time.h> #include <sys/types.h> #define TRUE 1 #define FALSE 0 #define SLIMIT 10000 typedef struct { int stackarray[SLIMIT-1]; int top; } stack; typedef int rowcheck[SLIMIT]; typedef int diagonalcheck1[2*SLIMIT-1]; typedef int diagonalcheck2[2*SLIMIT-1]; rowcheck r; diagonalcheck1 d1; diagonalcheck2 d2; int count, probe_count; long t1,t0; double ti; main(argc,argv) int argc; char *argv[]; { stack s; int n,i,row,col,found; FILE *fd; char host[128]; gethostname(host,sizeof(host)); probe_count = 0; col=1; row=1; count=0; if (argc < 2) { printf(" Usage: queen total_positions\n"); exit (1); } n=atoi(argv[1]); for (i=0;i<=n-1;i++) r[i] = TRUE; for (i=0;i<=2*n-2;i++) d1[i] =TRUE; for (i=0;i<=2*n-2;i++) d2[i] = TRUE; found = FALSE; setstack(&s); t0 = time((long *)0); while (((col <n+1) &&(row <n+1)) || !empty(&s)) if ( (col<n+1) && (row<n+1) ) { /*if (feasible(row,col,r,d1,d2,n))*/ probe_count ++; if (r[row-1] && d1[row+col-2] && d2[row-col+n-1]) { process(row,col,&found,&s,n); push(row, &s); r[row-1] = FALSE; d1[row+col-2] = FALSE; d2[row-col+n-1] = FALSE; col = col+1; row =1; } else row = row+1; } else { pop(&s,&row); col = col-1; r[row-1] = TRUE; d1[row+col-2] = TRUE; d2[row-col+n-1] = TRUE; row = row+1; } t1 = time((long *)0) - t0; fd = fopen("nq_seq.time", "a"); if (!found ) { printf ("\n NO SOLUTIONS"); fprintf (fd, "\n NO SOLUTIONS"); } else { printf("\n--- WE FOUND TOTAL %d WAYS TO PLACE %d QUEENS\n", count,n); fprintf(fd, "%s %d %d Probes(%d) %d %d", host, count,n, probe_count,t1); } printf("--- THE TOTAL TIME USED IN THIS PROGRAM IS %d secs \n",t1); if (t1 > 0) fprintf(fd," %f Million probes/sec\n", (float) probe_count/t1/1000000); else fprintf(fd,"* Million probes/sec \n"); fflush(fd); fclose(fd); } process(row,col,pfound,ps,n) int row ,col,*pfound,n; stack *ps; { int i; int item(); if (col == n) { count +=1; *pfound = TRUE; } } setstack(ps) stack *ps; { (*ps).top = -1; } empty(ps) stack *ps; { return((*ps).top == -1); } push(value ,ps) int value; stack *ps; { if ((*ps).top == (SLIMIT -1)) overflow(ps); else { (*ps).top = (*ps).top +1; (*ps).stackarray[(*ps).top] =value; } } pop(ps,pvalue) stack *ps; int *pvalue; { if(empty(ps)) underflow(ps); else { *pvalue = (*ps).stackarray[(*ps).top]; (*ps).top = (*ps).top -1; } } int item(i,ps) stack *ps; { return((*ps).stackarray[(*ps).top-i]); } overflow(ps) stack *ps; { printf("\n stack overflow"); } underflow(ps) stack *ps; { printf("\n stack underflow"); }
C
// This is a program that takes 12 digits and sorts them in descending order, and checks whether they are numbers in it. It tells you how many digits are stored in it. #include <stdio.h> #define MAX 12 // 입력 값을 12개만 받는다. void swap(int* p, int* q) { // 정렬이 되지 않은 두 숫자의 위치를 바꿔주는 함수. int temp; temp = *p; *p = *q; *q = temp; } void insertion_sort(int* arr, int length) { // 삽입 정렬을 해주는 함수 int i, j, last; for (i = 1; i < length; i++) { // // 마지막 요소까지 돌면서 for (j = i; j > 0; j--) { if (arr[j - 1] > arr[j]) { // 왼쪽이 오른쪽 보다 크면 swap(&arr[j - 1], &arr[j]); // swap 함수를 불러 순서를 바꿔준다. } } } } int binary_search(int* arr, int search, int first, int last) { // 찾고 있는 값이 배열에 있는지 확인하는 함수. int middle; if (first > last) // 첫번째 인덱스가 마지막 인덱스보다 크거나 같으면 이 배열 안에 찾는 값이 없다. - base case return -1; middle = (first + last) / 2; // 범위 내의 가운데 인덱스 if (arr[middle] == search) // arr[middle] 값이 찾는 값과 같으면 내가 찾고 있는 값이다 return middle; else if (arr[middle] > search) // arr[middle] 값보다 찾는 값과 작으면 return binary_search(arr, search, first, middle - 1); // middle - 1 을 last 인덱스로 바꿔서 재귀함수 호출 else // arr[middle] 값보다 찾는 값이 크거나 같으면 return binary_search(arr, search, middle + 1, last); // middle + 1 을 first 인덱스로 바꿔서 재귀함수 호출 } int main() { int arr[MAX], search, result; printf("Enter twelve integers.\n"); for (int i = 0; i < MAX; i++) { scanf("%d", &arr[i]); // 입력받은 12개의 수들을 data 배열에 넣는다. } insertion_sort(arr, MAX); // 입력받은 수들을 오름차순으로 정렬한다. printf("Enter data to be searched.\n"); // 찾고 싶은 수를 입력받는다. scanf("%d", &search); result = binary_search(arr, search, 0, MAX - 1); if (result < 0) printf("No such data.\n"); else printf("It is in index %d.\n", result); return 0; }
C
/* * raylib-line-triangulator -- line triangulation algorithm for raylib * * LICENSE: zlib * * Copyright (c) 2020 Taras Radchenko (@petuzk) * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. * */ #include "raylib.h" #include "raymath.h" #define EPSILON 0.00001f typedef struct TriLine { // User values Vector2* points; int numPoints; float thickness; bool loop; // Calculated values Vector2* strip; int stripLen; int stripAlloc; } TriLine; //---------------------------------------------------------------------------------- // Functions definition - Utils math //---------------------------------------------------------------------------------- // Cross product of two points `a` and `b` float CrossProduct(Vector2 a, Vector2 b) { return a.x*b.y - b.x*a.y; } // Returns true if lines (`a1` - `a2`) and (`b1` - `b2`) intersect // Theoretically, works faster if lines do not intersect // live demo: https://martin-thoma.com/how-to-check-if-two-line-segments-intersect/ bool DoLinesIntersect(Vector2 a1, Vector2 a2, Vector2 b1, Vector2 b2) { Vector2 a = Vector2Subtract(a2, a1); Vector2 b = Vector2Subtract(b2, b1); return ( ( // b1 and b2 are on the different sides of line defined by a1 and a2 (CrossProduct(a, Vector2Subtract(b1, a1)) > 0) ^ (CrossProduct(a, Vector2Subtract(b2, a1)) > 0) ) && ( // a1 and a2 are on the different sides of line defined by b1 and b2 (CrossProduct(b, Vector2Subtract(a1, b1)) > 0) ^ (CrossProduct(b, Vector2Subtract(a2, b1)) > 0) ) ); } // Finds `right` and `left` perpendiculars to vector pointing to `dir`. // Perpendiculars are scaled to have length `perp_len`. // All vectors are located at `center`. void FindPerpendiculars(Vector2 center, Vector2 dir, float perp_len, Vector2* right, Vector2* left) { Vector2 vec = Vector2Subtract(dir, center); float scale = perp_len / Vector2Length(vec); *left = Vector2Add(center, (Vector2) { -vec.y * scale, vec.x * scale }); *right = Vector2Add(center, (Vector2) { vec.y * scale, -vec.x * scale }); } //---------------------------------------------------------------------------------- // Functions definition - "low-level" //---------------------------------------------------------------------------------- // Returns number of strip points needed to triangulate a line int GetStripLength(int numPoints, bool loop) { if (numPoints > 2) return 2 * (numPoints + loop); else if (numPoints == 2) return 4; // ignore `loop` else return 0; } // Converts line defined by `numPoints` `points` into a triangle strip. // Triangulation parameters are `thickness` and `loop`. // Stores the result into an array pointed by `strip`, // which must be at least `GetStripLength(numPoints, loop)` elements long. // The resulting array is ready to be drawn with DrawTriangleStrip(). void TriangulateLine(Vector2* points, int numPoints, float thickness, bool loop, Vector2* strip) { if (numPoints == 2) loop = false; else if (numPoints < 2) return; thickness /= 2.0f; Vector2 A, O, B, p1, p2; int offset, reverseOrder; if (loop) { A = points[numPoints - 1]; O = points[0]; } else { A = points[0]; O = points[1]; FindPerpendiculars(A, O, thickness, strip, strip + 1); } // main loop // skip first and last element if loop is false for (int i = !loop; i < numPoints - !loop; i++) { /* O is points[i], A is previous point and B is the next one. * a = OA, b = OB, s = OX is a bisector. * * O * ^ * /|\ * a/ |s\b * /__|__\ * A x B */ B = points[(i+1) % numPoints]; Vector2 s; Vector2 a = Vector2Subtract(A, O); Vector2 b = Vector2Subtract(B, O); float len_b = Vector2Length(b); float slopeDiff = CrossProduct(a, b); if (-EPSILON < slopeDiff && slopeDiff < EPSILON) { // a and b are (almost) parallel so triangle AOB (almost) doesn't exist // imagine A, O and B on the same line -- bisector s will be perpendicular to this line // so here we are calculating perpendicular vector float s_scale = thickness / len_b; s.x = -b.y * s_scale; s.y = b.x * s_scale; } else { // find bisector using angle bisector theorem float sides_len_ratio = Vector2Length(a) / len_b; Vector2 AB = Vector2Subtract(B, A); Vector2 AX = Vector2Scale(AB, sides_len_ratio / (sides_len_ratio + 1)); s = Vector2Add(a, AX); // scale s depending on thickness float len_s = Vector2Length(s); float cos_b_s = (b.x*s.x + b.y*s.y) / len_b / len_s; float sin_b_s = sqrtf(1 - cos_b_s * cos_b_s); float s_scale = thickness / sin_b_s / len_s; s = Vector2Scale(s, s_scale); } p1 = Vector2Add (O, s); p2 = Vector2Subtract(O, s); offset = 2*i; reverseOrder = // strip points order is important! // line between consequent strip points must cross the original line // `strip[offset-2]` is p1 from previous iteration ( i && DoLinesIntersect(A, O, strip[offset-2], p1)) || // the very first point must be on the left side relative to vector b (!i && CrossProduct(b, s) > 0); strip[offset + reverseOrder] = p1; strip[offset + !reverseOrder] = p2; A = O; O = B; } offset = GetStripLength(numPoints, loop) - 2; if (loop) { strip[offset + 0] = strip[0]; strip[offset + 1] = strip[1]; } else { FindPerpendiculars(points[numPoints-1], points[numPoints-2], thickness, &p1, &p2); reverseOrder = DoLinesIntersect(A, O, strip[offset-2], p1); strip[offset + reverseOrder] = p1; strip[offset + !reverseOrder] = p2; } } //---------------------------------------------------------------------------------- // Functions definition - "high-level" (using struct) //---------------------------------------------------------------------------------- // Perform triangulation // Call when changes are made (including initialization) void UpdateTriLine(TriLine* triline) { triline->stripLen = GetStripLength(triline->numPoints, triline->loop); if (triline->stripLen > triline->stripAlloc) { triline->stripAlloc = triline->stripLen; // realloc may perform copying which is not needed RL_FREE(triline->strip); triline->strip = RL_MALLOC(triline->stripAlloc * sizeof(Vector2)); } if (triline->stripLen) { TriangulateLine( triline->points, triline->numPoints, triline->thickness, triline->loop, triline->strip); } } // Free unused memory (TriLine.strip only grows in size when updating) void ShrinkTriLine(TriLine* triline) { if (triline->stripLen < triline->stripAlloc) { triline->stripAlloc = triline->stripLen; if (triline->stripAlloc == 0) { RL_FREE(triline->strip); triline->strip = NULL; } else { triline->strip = RL_REALLOC(triline->strip, triline->stripAlloc * sizeof(Vector2)); } } } // Draw triangle strip of a given color void DrawTriLine(TriLine triline, Color color) { DrawTriangleStrip(triline.strip, triline.stripLen, color); }
C
#include<stdio.h> int main() { int m; scanf("%d",&m); int n; scanf("%d",&n); int arr[m][n]; //inputting the array for(int i=0 ; i<m ; ++i) for(int j=0 ; j<n ; ++j) scanf("%d",&arr[i][j]); int x=1,j=0 ; for(int i=0 ; i<m ; ++i) { for(; j<n && j>=0 ; j+=x) printf("%d\t",arr[i][j]); printf("\n"); //updating value x=-x; j+=x; //initial value of j for next loop } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <netdb.h> #include <sys/socket.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <dirent.h> #include <sys/stat.h> #include <stdbool.h> #include <time.h> #include <arpa/inet.h> #define LINEMAX 256 char * permAvailable = "xwrxwrxwr-------"; char * permRestricted = "----------------"; struct hostent * host_entry; struct sockaddr_in server_addr, client_addr, name_addr; int server_socket, client_socket, server_port; char cwd[4096]; char line[LINEMAX + 1]; void lsFile(char * fileStr); void lsDir(char * dirStr); void server_init(char * name) { printf("Initializing server\n"); host_entry = gethostbyname(name); if (host_entry == NULL) { printf("unknown host\n"); exit(1); } printf("Server host info:\n"); printf(" hostname=%s\n", name); char ip[16]; inet_ntop(AF_INET, (struct in_addr *) host_entry->h_addr_list[0], ip, sizeof(ip)); printf(" IP=%s\n", ip); // printf("IP=%s\n", inet_ntoa(*((struct in_addr *) host_entry->h_addr_list[0]))); printf("Creating socket\n"); server_socket = socket(AF_INET, SOCK_STREAM, 0); if (server_socket < 0) { printf("failed to create socket\n"); exit(2); } server_addr.sin_family = AF_INET; server_addr.sin_addr = *((struct in_addr *) host_entry->h_addr_list[0]); // server_addr.sin_addr.s_addr = *(long *) host_entry->h_addr_list[0]; server_addr.sin_port = 0; // kernal will assign port number printf("Assigning name to socket\n"); if (bind(server_socket, (struct sockaddr *) & server_addr, sizeof(server_addr)) != 0) { printf("failed to bind socket to address\n"); exit(3); } printf("Getting port number from kernel\n"); int len_name_addr = sizeof(name_addr); if (getsockname(server_socket, (struct sockaddr *) & name_addr, & len_name_addr) != 0) { printf("failed getting socket name\n"); exit(4); } server_port = ntohs(name_addr.sin_port); printf(" port=%d\n", server_port); listen(server_socket, 5); printf("Server Initialized\n"); } void get(char * line) { strtok(line, " "); char * file = strtok(NULL, " "); if (access(file, F_OK) >= 0) { int fdesc = open(file, O_RDONLY); if (fdesc != -1) { struct stat fstat; stat(file, &fstat); long length = fstat.st_size; sprintf(line, "file found\n"); write(client_socket, line, LINEMAX); write(client_socket, &length, sizeof(long)); printf("sending total file length: %ld bytes\n", length); int n; while (length > LINEMAX) { n = read(fdesc, line, LINEMAX); length -= n; write(client_socket, line, LINEMAX); printf("wrote n=%d bytes to client, remaining length=%ld\n", n, length); } n = read(fdesc, line, LINEMAX); length -= n; write(client_socket, line, n); printf("wrote n=%d bytes to client, remaining length=%ld\n", n, length); close(fdesc); } else { write(client_socket, "Error: could not open file [ ", LINEMAX); write(client_socket, file, LINEMAX); write(client_socket, " ] for reading.\n", LINEMAX); } } else { write(client_socket, "Error: could not open file [ ", LINEMAX); write(client_socket, file, LINEMAX); write(client_socket, " ] for reading.\n", LINEMAX); } } void cat(char * line) { strtok(line, " "); char * file = strtok(NULL, " "); if (access(file, F_OK) >= 0) { int fdesc = open(file, O_RDONLY); if (fdesc != -1) { struct stat fstat; stat(file, &fstat); long length = fstat.st_size; sprintf(line, "file found\n"); write(client_socket, line, LINEMAX); write(client_socket, &length, sizeof(long)); printf("sending total file length: %ld bytes\n", length); int n; while (length > LINEMAX) { n = read(fdesc, line, LINEMAX); length -= n; write(client_socket, line, LINEMAX); printf("wrote n=%d bytes to client, remaining length=%ld\n", n, length); } n = read(fdesc, line, LINEMAX); length -= n; write(client_socket, line, n); printf("wrote n=%d bytes to client, remaining length=%ld\n", n, length); close(fdesc); } else { write(client_socket, "Error: could not open file [ ", LINEMAX); write(client_socket, file, LINEMAX); write(client_socket, " ] for reading.\n", LINEMAX); } } else { write(client_socket, "Error: could not open file [ ", LINEMAX); write(client_socket, file, LINEMAX); write(client_socket, " ] for reading.\n", LINEMAX); } } void ls(char * line) { char lsarg[256]; strcpy(lsarg, line); strtok(lsarg, " "); char * paramStr = strtok(NULL, " "); if (paramStr != NULL) { strncpy(lsarg, paramStr, LINEMAX); struct stat * stats = (struct stat *) malloc(sizeof(struct stat)); write(client_socket, "Permissions Links Group Owner Size Date Name\n", 46); if (lstat(lsarg, stats) == 0) { if (S_ISDIR(stats->st_mode)) { lsDir(lsarg); } else { lsFile(lsarg); } } else { write(client_socket, "Error: no such file or directory [ ", LINEMAX); write(client_socket, lsarg, LINEMAX); write(client_socket, " ] found.\n", LINEMAX); } free(stats); } else { write(client_socket, "Permissions Links Group Owner Size Date Name\n", LINEMAX); lsDir("./"); } } void lsDir(char * dirStr) { DIR * dir = opendir(dirStr); if (dir != NULL) { struct dirent * treebeard = readdir(dir); // "The world is changing: // I feel it in the water, // I feel it in the earth, // and I smell it in the air." // Treebeard, The Two Towers, J. R. R. Tolkien. char path[4356]; //max path length + entry name size = 4096 + 260 = 4356 characters while(treebeard != NULL) { bzero(path, 4356); strcat(path, dirStr); strcat(path, treebeard->d_name); lsFile(path); treebeard = readdir(dir); } } else { write(client_socket, "Error: no such directory [ ", LINEMAX); write(client_socket, dirStr, LINEMAX); write(client_socket, " ] found.\n", LINEMAX); } } void lsFile(char * fileStr) { if (access(fileStr, F_OK) == 0) { struct stat * stats = (struct stat *) malloc(sizeof(struct stat)); lstat(fileStr, stats); char permissions[10]; permissions[0] = 'd'; //Other/unknown type if (S_ISDIR(stats->st_mode)) { permissions[0] = 'd'; } else if (S_ISREG(stats->st_mode)) { permissions[0] = '-'; } /*else if (S_ISLINK(stats->st_mode)) { permissions[0] = 'l'; }*/ for (int i = 0; i < 8; i++) { if (stats->st_mode & (1 << i)) { // print r | w | x permissions[i+1] = permAvailable[i]; } else { permissions[i+1] = permRestricted[i]; } } char * fileTime = ctime(&(stats->st_ctime)); fileTime[strlen(fileTime) - 1] = '\0'; bzero(line, LINEMAX); sprintf( line, "%s %ld %d %d %ld %s %s\n", permissions, stats->st_nlink, stats->st_gid, stats->st_uid, stats->st_size, fileTime, fileStr + 2 ); write(client_socket, line, LINEMAX); free(stats); } else { write(client_socket, "Error: no such file [ ", LINEMAX); write(client_socket, fileStr, LINEMAX); write(client_socket, " ] found.\n", LINEMAX); } } int main (int argc, char * argv[], char * env[]) { char hostname[256]; int n; if (argc < 2) { strcpy(hostname, "localhost"); // gethostname(hostname, 256); } else strncpy(hostname, argv[1], 255); server_init(hostname); getcwd(cwd, 4096); int changed = chroot(cwd); if (changed != 0) { printf("error: chroot failed\n"); exit(8); } chdir("/"); getcwd(cwd, 4096); printf("server: changed root to current directory\n"); if (setgid(getgid()) == -1) { printf("error: failed to release permissions\n"); exit(9); } if (setuid(getuid()) == -1) { printf("error: failed to release permissions\n"); exit(10); } printf("server: released root privileges\n"); while (true) { printf("server: accepting new connections . . .\n"); int len_client_addr = sizeof(client_addr); client_socket = accept(server_socket, (struct sockaddr *) & client_addr, & len_client_addr); if (client_socket < 0) { printf("server: error accepting new client\n"); exit(5); } printf("server: accepted a client:\n"); char ip[24]; inet_ntop(AF_INET, &client_addr.sin_addr, ip, sizeof(ip)); printf(" IP=%s port=%d\n", ip, ntohs(client_addr.sin_port)); if (fork()) { // parent close(client_socket); printf("in parent process\n"); } else { while (true) { // processing loop printf("server: waiting for request from client . . .\n"); n = read(client_socket, line, LINEMAX); if (n == 0) { printf("server: client disconnected\n"); close(client_socket); exit(0); } printf("server: read n=%d bytes:\n %s\n", n, line); if (strncmp(line, "pwd", 3) == 0) { strncpy(line, cwd, LINEMAX); printf("sending: %s\n", line); write(client_socket, line, LINEMAX); } else if (strncmp(line, "ls", 2) == 0) { ls(line); } else if (strncmp(line, "cat", 3) == 0) { cat(line); } else if (!strncmp(line, "cd", 2)) { strtok(line, " "); char * dirpath = strtok(NULL, " "); if (chdir(dirpath) != 0) write(client_socket, "error: could not find directory\n", LINEMAX); getcwd(cwd, 4096); } else if (strncmp(line, "mkdir", 5) == 0) { strtok(line, " "); char * name = strtok(NULL, " "); printf("\t%s %s\n", name, "0755"); if ( name != NULL && opendir(name) == NULL ) { mkdir(name, 0755); write(client_socket, "Created directory [ ", LINEMAX); write(client_socket, name, LINEMAX); write(client_socket, " ].\n", LINEMAX); } else { write(client_socket, "Error: could not create directory [ ", LINEMAX); write(client_socket, name, LINEMAX); write(client_socket, " ].\n", LINEMAX); } } else if (!strncmp(line, "rmdir", 5)) { strtok(line, " "); char * name = strtok(NULL, " "); if ( name != NULL && opendir(name) != NULL ) { rmdir(name); write(client_socket, "Successfully removed directory [ ", LINEMAX); write(client_socket, name, LINEMAX); write(client_socket, " ].\n", LINEMAX); } else { write(client_socket, "Error: could not remove directory [ ", LINEMAX); write(client_socket, name, LINEMAX); write(client_socket, " ].\n", LINEMAX); } } else if (!strncmp(line, "rm", 2)) { strtok(line, " "); char * name = strtok(NULL, " "); if ( name != NULL && access(name, F_OK) == 0 ) { remove(name); write(client_socket, "Successfully removed filed [ ", LINEMAX); write(client_socket, name, LINEMAX); write(client_socket, " ].\n", LINEMAX); } else { write(client_socket, "Error: could not remove file [ ", LINEMAX); write(client_socket, name, LINEMAX); write(client_socket, " ].\n", LINEMAX); } } else if (!strncmp(line, "get", 3)) { get(line); } else if (!strncmp(line, "put", 3)) { char linecpy[LINEMAX + 1]; strcpy(linecpy, line); strtok(linecpy, " "); char * filename = strtok(NULL, " "); if (access(filename, F_OK) != 0) { int fdesc = open(filename, O_WRONLY|O_CREAT, 0644); if (fdesc != -1) { sprintf(line, "opened file for writing\n"); write(client_socket, line, LINEMAX); read(client_socket, line, LINEMAX); printf("client: %s\n", line); long length = 0; read(client_socket, &length, sizeof(long)); printf("Total File Length: %ld bytes:\n\n", length); int n; while (length > LINEMAX) { n = read(client_socket, line, LINEMAX); length -= n; write(fdesc, line, LINEMAX); printf("wrote n=%d bytes to file=%s, reamaining length=%ld\n", n, filename, length); } n = read(client_socket, line, length); write(fdesc, line, n); length -= n; printf("write n=%d bytes to file=%s, remaining length=%ld\n", n, filename, length); close(fdesc); } else { sprintf(line, "error: could not open file for writing\n"); write(client_socket, line, LINEMAX); } } else { sprintf(line, "error: file already exists\n"); write(client_socket, line, LINEMAX); } } else if (!strncmp(line, "quit", 4)) { printf("server: client quit program\n"); close(client_socket); exit(0); } else { strcpy(line, "server: command not found\n"); write(client_socket, line, LINEMAX); } write(client_socket, "", LINEMAX); } } } }
C
/* ******************************** ilist.h ********************************* */ /* Soubor: ilist.h */ /* Datum: prosinec.2016 */ /* Predmet: Formalni jazyky a prekladace (IFJ) */ /* Projekt: Implementace interpretu jazyka IFJ16 */ /* Varianta zadani: */ /* Titul,Autori, login: Javorka Martin xjavor18 */ /* Marušin Marek xmarus08 */ /* Utkin Kirill xutkin00 */ /* Mrva Marián xmrvam01 */ /* Shapochkin Victor xshapo00 */ /* ************************************************************************** */ #ifndef IFJ2016_ILIST_H #define IFJ2016_ILIST_H #include <stdio.h> #include <stdlib.h> // Types of instructions typedef enum { I_START, // - / - / - I_STOP, // - / - / - I_READLN_INT, // arg1 / - / - I_READLN_DOUBLE, // arg1 / - / - I_READLN_STRING, // arg1 / - / - I_PRINT, // arg_expr / - / - I_LENGTH, // arg1 / - / - I_SUBSTR, // arg1 / arg2 / arg3 I_COMPARE, // arg1 / arg2 / - I_FIND, // arg1 / arg2 / - I_SORT, // arg1 / arg2 / - I_ADD, // dst / op1 / op2 I_SUB, // dst / op1 / op2 I_MUL, // dst / op1 / op2 I_DIV, // dst / op1 / op2 I_CONCATENATE, // dst / op1 / op2 I_LESS, // dst / op1 / op2 I_MORE, // dst / op1 / op2 I_LESS_EQUAL, // dst / op1 / op2 I_MORE_EQUAL, // dst / op1 / op2 I_EQUAL, // dst / op1 / op2 I_NOT_EQUAL, // dst / op1 / op2 /* * Extension operations (BOOLEAN) */ I_NOT, // dst / op1 / - I_OR, // dst / op1 / op2 I_AND, // dst / op1 / op2 /* * End of extension operations */ I_ASSIGN, // dst / src / - I_CALL_FUNC, // dst / ptrSymbolItem / list_of_args I_RETURN, // ptr_to_function / return_val / - I_SET_PARAM, // dst / src / - I_JUMP, // ptr_instruction / - / - I_JUMP_IF_FALSE, // ptr_instruciton / dst / - I_LABEL // - / - / - // TODO JUMPS ... etc. } instructions; typedef struct { instructions instType; // type of instruction I_LESS void *addr1; // adress 1 - entry_s destination void *addr2; // adress 2 - entry_s operand 1 void *addr3; // adress 3 - entry_s operand 2 } tInstr; typedef struct listItem { tInstr Instruction; struct listItem *nextItem; } tListItem; typedef struct { struct listItem *first; // ukazatel na prvy prvok struct listItem *last; // ukazatel na posledny prvok struct listItem *active; // ukazatel na aktivny prvok } tListOfInstr; //prototypy funkcii void listInit(tListOfInstr *L); void listFree(tListOfInstr *L); void listInsertLast(tListOfInstr *L, tInstr I); void listFirst(tListOfInstr *L); void listNext(tListOfInstr *L); void listGoto(tListOfInstr *L, void *gotoInstr); void *listGetPointerLast(tListOfInstr *L); tInstr *listGetData(tListOfInstr *L); void listLastActive(tListOfInstr *L); void print_elements_of_list(tListOfInstr TL); void customPrintInstType(int instType); #endif //IFJ2016_ILIST_H
C
// c 的 .h 文件 // 头文件一般用于放置:需要向外暴露的宏定义,全局变量声明,函数声明 // 防止同一文件的二次编译。比如你有两个 c 文件,这两个 c 文件都 include 了同一个头文件,在编译时,这两个 c 文件就会被一同编译,那么就带来了声明冲突的问题 #ifndef _MYHEAD_HELLO_ // 是 if not defined 的缩写,如果没定义 _MYHEAD_HELLO_ 则执行这一块 #define _MYHEAD_HELLO_ // 定义 _MYHEAD_HELLO_ // 在 c++ 中写 c 语言代码 #ifdef __cplusplus // 如果当前是 c++ 环境 extern "C" // 告诉 c++ 下面的 { } 块中写的是 c 语言代码 { #endif // 函数声明 char *demo_cHello(char *name); #ifdef __cplusplus // 如果当前是 c++ 环境 } #endif /* // 在 windows 环境下,可以简写成这样 #ifdef __cplusplus extern "C" #endif char *demo_cHello(char *name); */ #endif // #ifndef _MYHEAD_HELLO_
C
#include <string.h> #include <stdlib.h> #include <stdio.h> /* special chars */ const char * const specialc_table[] = {"=", "<", ">", ";"}; /* keywords */ const char * const keywords[] = { "if", "else", "while", "then", "int", "float", "bool" }; size_t size_keywords = (sizeof(keywords) / sizeof(char *)); /* symbols */ typedef struct symbol { char* value; struct symbol *next; } symbol_t; symbol_t *first_symbol = NULL; symbol_t *last_symbol = NULL; //size_t sym_tb_size; int search_insert_sym(char* value) { symbol_t *s = first_symbol; int pos = 0; // search symbol while (s) { if (!strcmp(value, s->value)) return pos; s = s->next; pos++; } // insert symbol if (!first_symbol) { // empty table first_symbol = malloc(sizeof(symbol_t)); last_symbol = first_symbol; } else { last_symbol->next = malloc(sizeof(symbol_t)); last_symbol = last_symbol->next; } last_symbol->value = malloc(strlen(value) + 1); strcpy(last_symbol->value, value); last_symbol->next = NULL; return pos; } void print_symbol_table() { symbol_t *s = first_symbol; int pos = 0; printf("--- SYMBOL TABLE ---\n"); while(s) { printf("%2d %s\n", pos, s->value); pos++; s = s->next; } printf("\n"); }
C
#include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <fcntl.h> #define _OPEN_SYS #include <pwd.h> #include <libutil.h> #include <errno.h> #include <time.h> #include <string.h> #include <unistd.h> int pw_equal(const struct passwd *_pw1, const struct passwd *_pw2); int pw_copy(int ffd, int tfd, const struct passwd *pw, struct passwd *old_pw); //int putpwent(const struct passwd *p, FILE *stream); int main(int argc, char *argv[]) { struct passwd *p11; struct passwd p22; const struct passwd *ptemp; char user[]="arielb"; if ((p11 = getpwnam(user)) == NULL) perror("getpw() error"); else { printf("getpw() returned the following info for user %s:\n", user); p22.pw_name = "test1"; p22.pw_uid = (int)501; p22.pw_gid = (int)512; p22.pw_dir = "/home/test1"; p22.pw_shell = "/bin/bash"; p22.pw_class = "class"; p22.pw_gecos = "Test One"; p22.pw_dir = "/home/test1"; printf(" pw_name : %s\n", p11->pw_name); printf(" pw_uid : %d\n", (int) p11->pw_uid); printf(" pw_gid : %d\n", (int) p11->pw_gid); printf(" pw_dir : %s\n", p11->pw_dir); printf(" pw_class : %s\n", p11->pw_shell); printf(" pw_change : %ld\n", (long int)p11->pw_change); printf(" pw_expire : %ld\n", (long int)p11->pw_expire); printf(" pw_gecos : %s\n", p11->pw_gecos); printf(" pw_dir : %s\n", p11->pw_dir); printf("\n\n"); printf(" pw_name : %s\n", p22.pw_name); printf(" pw_uid : %d\n", (int) p22.pw_uid); printf(" pw_gid : %d\n", (int) p22.pw_gid); printf(" pw_dir : %s\n", p22.pw_dir); printf(" pw_class : %s\n", p22.pw_shell); printf(" pw_change : %ld\n", (long int)p22.pw_change); printf(" pw_expire : %ld\n", (long int)p22.pw_expire); printf(" pw_gecos : %s\n", p22.pw_gecos); printf(" pw_dir : %s\n", p22.pw_dir); ptemp = &p22; if (!pw_equal(p11, ptemp)) { int err = 0; int ffd, tfd; ffd = open("/etc/passwd", O_RDWR); tfd = open("/home/arielb/.passwd", O_RDWR); if (ffd < 0 ) { err = errno; printf("ERROR [%d] - %s\n",err, strerror(err)); }else{ int c; ptemp = &p22; c = pw_copy(ffd, tfd, ptemp, NULL); close(ffd); close(tfd); } } else { printf("user already exists"); } } return 0; }
C
#include <stdio.h> int main() { int k, count; printf("Ввести целое число\n"); scanf("%d", &k); for (count = 1; count < k; count++) { if (count % 5 == 0) continue; printf("\t%d\n", count); } return 0; }
C
#ifndef _LINKED_LIST_H_ #define _LINKED_LIST_H_ #include "common.h" /* Protocol data type nodes with the use of linked lists. */ typedef struct client_node { client_t *client; struct client_node *next_client; } client_node_t; typedef struct track_node { track_t *track; struct track_node *next_track; } track_node_t; typedef struct game_node { game_t *game; struct game_node *next_game; } game_node_t; /* Typical LL function return values */ enum result { RGOOD = 0, // Result Good. MFAIL = -1, // Memory allocation Failed. HNULL = -2, // Head is NULL. NFND = -3 // Not Found. }; /* Pushing instnace to its LL */ int push_client(client_node_t **head, client_t **value); int push_game(game_node_t **head, game_t **value); int push_track(track_node_t **head, track_t **value); /* Removing instance from the start of its LL */ int pop_client(FILE *fp, client_node_t **head); int pop_game(FILE *fp, game_node_t **head); int pop_track(FILE *fp, track_node_t **head); /* Removing instance from the end of its LL */ int remove_last_client(FILE *fp, client_node_t **head); int remove_last_game(FILE *fp, game_node_t **head); int remove_last_track(FILE *fp, track_node_t **head); /* Removing instance by id from its LL */ int remove_by_client_id(FILE *fp, client_node_t **head, int del_id); int remove_by_game_id(FILE *fp, game_node_t **head, int del_id); int remove_by_track_id(FILE *fp, track_node_t **head, int del_id); /* Getting instance by a given ID */ client_t *get_client_by_id(client_node_t **head, int want_id); game_t *get_game_by_id(game_node_t **head, int want_id); track_t *get_track_by_id(track_node_t **head, int want_id); /* Total removal of all the instances */ void remove_all_clients(FILE* fp, client_node_t **head); void remove_all_games(FILE* fp, game_node_t **head); void remove_all_tracks(FILE* fp, track_node_t **head); /* Other helper functions */ int spot_and_delete_client_duplicate( FILE *fp, client_node_t **head, int *client_count, int *g_client_count, int client_id ); /* Get all IDs of a type */ int get_game_ids(FILE *fp, game_node_t **head, int **gid_arr, int game_count); #endif
C
#include <assert.h> #include <stdio.h> #include <stdlib.h> #include <queue.h> #define TEST_ASSERT(assert) \ do { \ printf("ASSERT: " #assert " ... "); \ if (assert) { \ printf("PASS\n"); \ } else { \ printf("FAIL\n"); \ exit(1); \ } \ } while(0) /* static int inc_item(void *data, void *arg) { int *a = (int*)data; int inc = (int)(long)arg; *a += inc; return 0; }*/ /* Create */ void test_create(void) { fprintf(stderr, "*** TEST create ***\n"); TEST_ASSERT(queue_create() != NULL); } /* Destroy */ void test_destroy(void) { int data = 3; fprintf(stderr, "*** TEST destroy ***\n"); // Check: Return -1 if @queue is NULL queue_t newQueue= NULL; TEST_ASSERT(queue_destroy(newQueue) == -1); // Check: Return -1 if @queue is not empty newQueue = queue_create(); queue_enqueue(newQueue, &data); TEST_ASSERT(queue_destroy(newQueue) == -1); // Check: Queue is successfully destroyed newQueue = queue_create(); TEST_ASSERT(queue_destroy(newQueue) == 0); } /* Enqueue/Dequeue simple */ void test_queue_simple(void) { int data = 3, *ptr; queue_t q; fprintf(stderr, "*** TEST queue_simple ***\n"); q = queue_create(); queue_enqueue(q, &data); queue_dequeue(q, (void**)&ptr); TEST_ASSERT(ptr == &data); } /* Delete Queue */ void test_delete(void) { int dataArray[10] = {1,2,3,4,5,6,7,8,9,10}; queue_t newQueue = queue_create(); for(int i = 0; i < 10; i++) { queue_enqueue(newQueue, &dataArray[i]); } // Enqueue 1-10 print_queue(newQueue); queue_delete(newQueue, &dataArray[0]); // Delete '1' print_queue(newQueue); queue_delete(newQueue, &dataArray[4]); // Delete '5' print_queue(newQueue); queue_delete(newQueue, &dataArray[9]); // Delete '10' print_queue(newQueue); fprintf(stderr, "*** TEST queue_delete ***\n"); queue_delete(newQueue, &dataArray[4]); // Delete '1' TEST_ASSERT(queue_delete(newQueue, &dataArray[0]) != 0); // '1' should not be found queue_delete(newQueue, &dataArray[4]); // Delete '5' TEST_ASSERT(queue_delete(newQueue, &dataArray[4]) != 0); // '5' should not be found queue_delete(newQueue, &dataArray[9]); // Delete '10' TEST_ASSERT(queue_delete(newQueue, &dataArray[9]) != 0); // '10' should not be found } void test_length() { int dataArray[10] = {1,2,3,4,5,6,7,8,9,10}; queue_t newQueue = NULL; TEST_ASSERT(queue_length(newQueue) == -1); newQueue = queue_create(); TEST_ASSERT(queue_length(newQueue) == 0); for(int i = 0; i < 10; i++) { queue_enqueue(newQueue, &dataArray[i]); } // Enqueue 1-10 printf("%d\n", queue_length(newQueue)); TEST_ASSERT(queue_length(newQueue) == 10); } /* void test_iterate() { int dataArray[10] = {1,2,3,4,5,6,7,8,9,10}; queue_t newQueue = queue_create(); for(int i = 0; i < 10; i++) { queue_enqueue(newQueue, &dataArray[i]); } // Enqueue 1-10 print_queue(newQueue); queue_iterate(newQueue, add_n, &dataArray[9], NULL); print_queue(newQueue); } */ // Need add_n int main(void) { test_create(); test_queue_simple(); test_destroy(); test_delete(); test_length(); //test_iterate(); return 0; }
C
#include "string.h" /* Нахождение размера строки @param a [in] @return Возвращает количество элементов в строке */ int my_sizeof(const char *a) { int i = 0; while (a[i + 1] != '\0') i++; return ++i; } /* Получение из целого числа строки @param str [out] @param x [in] */ void int_to_str(char *str, long int x) { int i = 0; int buf = 0; if (x < 0) { x = -x; buf = 1; i++; } while (x > 0) { for (int j = i; j > 0; j--) str[j] = str[j - 1]; str[0] = x % 10 + '0'; x = x / 10; i++; } if (buf) { for (int j = i; j > 0; j--) str[j] = str[j - 1]; str[0] = '-'; } str[i] = '\0'; } /* Замена подстроки в строке @param str [out] @param replace [in] @param i [in] @param kol [in] @return Возвращает количество элементов в строке */ void replace(char *str, char *replace, int i, int kol) { int rep = my_sizeof(replace), st = my_sizeof(str); char *new = calloc(st + rep - kol, sizeof(char)); for (int j = 0; j < i; j++) new[j] = str[j]; for (int j = i; j < (i + rep); j++) new[j] = replace[j - i]; for (int j = i + kol; j < st; j++) new[j + rep - kol] = str[j]; st = st + rep - kol; for (int j = 0; j < st; j++) str[j] = new[j]; str[st] = '\0'; free(new); }
C
/* filename: seq.c * author: daniel collins ([email protected]) * date: 3/27/15 * brief: quicksort and bubble sort includes for lab5 */ #include <stdio.h> void quicksort (int *a, int n) { int i, j, p, t; if (n < 2) return; p = a[n / 2]; for (i = 0, j = n - 1;; i++, j--) { while (a[i] < p) i++; while (p < a[j]) j--; if (i >= j) break; t = a[i]; a[i] = a[j]; a[j] = t; } quicksort(a, i); quicksort(a + i, n - i); } void bubblesort (int *a, int n) { int i, t, s = 1; while (s) { s = 0; for (i = 1; i < n; i++) { if (a[i] < a[i - 1]) { t = a[i]; a[i] = a[i - 1]; a[i - 1] = t; s = 1; } } } } /* will's sorts */ void wbubblesort(int *a, int n) { int i, j, tmp; for (i = 0; i < n; i++) { for (j = 0; j < n-1; j++) { if (a[j] > a[j+1]) { tmp = a[j+1]; a[j+1] = a[j]; a[j] = tmp; } } } } void wquicksort(int *array, int lo, int hi, int flag) { int i = lo-1; int j = hi; int pivot= array[hi]; int temp; if (hi>lo) { do { if(flag == 1) /* a increase sort */ { do i++; while (array[i]<pivot); do j--; while (array[j]>pivot); } else /* a decrease sort */ { do i++; while (array[i]>pivot); do j--; while (array[j]<pivot); } temp = array[i]; /* swap values */ array[i] = array[j]; array[j] = temp; } while (j>i); array[j] = array[i]; /* swap values */ array[i] = pivot; array[hi] = temp; wquicksort(array,lo,i-1,flag); /* recursive until hi == lo */ wquicksort(array,i+1,hi,flag); } }
C
#include <stdio.h> #include <stdlib.h> #include <windows.h> #include "wintrace.h" void run_cmd(LPTSTR cmd) { STARTUPINFOA si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); ZeroMemory(&pi, sizeof(pi)); if (CreateProcess(NULL, cmd, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi)) { #if 0 WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); #endif } else { char message[512]; snprintf(message, 512, "Error code : %d", GetLastError()); MessageBox(0, TEXT(message), cmd, MB_OK); } } int WINAPI WinMain(HINSTANCE a1, HINSTANCE a2, LPSTR a3, int a4) { int answer = 0; answer = MessageBox(0, "Ready to exec WinTrace? (then click 'Yes')\nIf you're not sure, please click 'No'\n\n--\n[Prerequisites to exec WinTrace]\n(1) 'Microsoft Windows SDK'\n(2) 'Microsoft Windows Performance Toolkit'\n\nIf your system does not have these two\n(or if you don't know what these are)\nplease click 'No' to go to the download & install page", THIS_PROG_NAME, MB_YESNO); if (answer == IDYES) { #if 1 run_cmd(TRACE_CMD__START); #if 0 Sleep(TRACE_TIME__IN_MILLI_SECOND); run_cmd(TRACE_CMD__DUMP); run_cmd(TRACE_CMD__TRANSFORM); #endif #else WinExec(TRACE_CMD__START, SW_HIDE); Sleep(TRACE_TIME__IN_MILLI_SECOND); WinExec(TRACE_CMD__DUMP, SW_HIDE); WinExec(TRACE_CMD__TRANSFORM, SW_HIDE); #endif } else /* answer == IDNO */ { #if 1 answer = MessageBox(0, "Please click 'Yes' to get 'winsdk_web.exe' setup file to install\n'Microsoft Windows SDK for Windows 7 and .NET Framework 3.5 SP1'", THIS_PROG_NAME, MB_YESNO); if (answer == IDYES) { run_cmd(TRACE_CMD__GET_SDK); } else { MessageBox(0, "Nothing happened.\n\nMany Thanks,\nBrian", THIS_PROG_NAME, MB_OK); } #else // run_cmd("\"c:\\windows\\system32\\calc.exe\""); // WinExec("c:\\windows\\system32\\calc.exe", SW_HIDE); WinExec("calc", SW_HIDE); #endif } return 0; }
C
#include <stdio.h> int main(){ int i; for(i=1;i<=20;i++){ if (i==10) continue; //break; printf("%d\n",i); } }
C
#include <stdlib.h> #include <time.h> #include <stdio.h> /** * main - If * Description: Print the last number positive or negative * Return: 0 */ int main(void) { int n; int a; srand(time(0)); n = rand() - RAND_MAX / 2; a = n % 10; printf("Last digit of %i is %i and is ", n, a); if (a > 5) { printf("greater than 5\n"); } else if (a == 0) { printf("0\n"); } else { printf("less than 6 and not 0\n"); } return (0); }
C
#include "avltreedelete.h" void deleteNode(AVLTree *avltree, int value) { Node *node = findNode(avltree, value), *successor = NULL, *child, *parent; if(node) { // convert to a case with 1 or 0 child if(node->left && node->right) { // min max, successor and predecessor won't change successor = node->successor; node->data = successor->data; node = successor; } parent = node->parent; // redirecting successor and predecessor if(node->predecessor) node->predecessor->successor = node->successor; if(node->successor) node->successor->predecessor = node->predecessor; // case that node is root if(parent == NULL) { if((node->left == NULL) || (node->right == NULL)) avltree->root = NULL; else if(node->left) avltree->root = node->left; else avltree->root = node->right; child = avltree->root; } else { // left case if(node == parent->left) { if (node->left == NULL && node->right == NULL) { parent->minimum = parent; parent->left = NULL; child = parent; } else if (node->left) { parent->left = node->left; parent->left->parent = parent; child = parent->left; } else { parent->minimum = node->right->minimum; parent->left = node->right; parent->left->parent = parent; child = parent->left; } } // right case else { if(node->left == NULL && node->right == NULL) { parent->maximum = parent; parent->right = NULL; child = parent; } else if(node->left) { parent->maximum = node->left->maximum; parent->right = node->left; parent->right->parent = parent; child = parent->right; } else { parent->right = node->right; parent->right->parent = parent; child = parent->right; } } } free(node); balance(avltree, child); correctMinimumAndMaximum(child); } }
C
/************************************************************************* > File Name: str.c > Author: Datou_Nie > Mail: [email protected] > Created Time: 2017年08月02日 星期三 20时01分00秒 ************************************************************************/ #include<stdio.h> #include<string.h> int main() { const char *a = "aaa"; const char *b = "bbb"; char strfirst[10]; char strsecond[10]; strcpy( strfirst, a ); strcat( strfirst, b ); strcpy( strsecond, b ); strcat( strsecond, a ); printf("%s\n", strfirst); printf("%s\n", strsecond); return 0; }