language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> int main(){ char a = 'a', b = 'b', c, *p, *q, *r; const int f = -10; int * s = &f; // value pointer value can't be changed // int * const s = &f address that pointer points to cant changed // const int *const a value and address can't be changed // s = &a; //f = 11; *s = -1000; printf("%d",f); printf("The address of a is %p\n", &a); printf("The address of b is %p\n", &b); printf("The address of c is %p\n", &c); printf("The address of p is %p\n", &p); printf("The address of q is %p\n", &q); printf("The address of r is %p\n", &r); return 0; }
C
#include <stdio.h> #define IN 1 #define OUT 0 void drawBar (len) { for (int i = 0; i < len; i++) { putchar('#'); } putchar('\n'); } int main(void) { int c, whitespace; int state = OUT; int len = 0; while ((c = getchar()) != EOF) { whitespace = (c == '\t' || c == '\n' || c == ' '); if (whitespace && state == IN) { state = OUT; drawBar(len); len = 0; } else { state = IN; len++; } } return 0; }
C
#include <stdint.h> #include "reg.h" /** * * LED init * */ void led_init(unsigned int led) { SET_BIT(RCC_BASE + RCC_AHB1ENR_OFFSET, GPIO_EN_BIT(GPIO_PORTD)); //MODER led pin = 01 => General purpose output mode CLEAR_BIT(GPIO_BASE(GPIO_PORTD) + GPIOx_MODER_OFFSET, MODERy_1_BIT(led)); SET_BIT(GPIO_BASE(GPIO_PORTD) + GPIOx_MODER_OFFSET, MODERy_0_BIT(led)); //OT led pin = 0 => Output push-pull CLEAR_BIT(GPIO_BASE(GPIO_PORTD) + GPIOx_OTYPER_OFFSET, OTy_BIT(led)); //OSPEEDR led pin = 00 => Low speed CLEAR_BIT(GPIO_BASE(GPIO_PORTD) + GPIOx_OSPEEDR_OFFSET, OSPEEDRy_1_BIT(led)); CLEAR_BIT(GPIO_BASE(GPIO_PORTD) + GPIOx_OSPEEDR_OFFSET, OSPEEDRy_0_BIT(led)); //PUPDR led pin = 00 => No pull-up, pull-down CLEAR_BIT(GPIO_BASE(GPIO_PORTD) + GPIOx_PUPDR_OFFSET, PUPDRy_1_BIT(led)); CLEAR_BIT(GPIO_BASE(GPIO_PORTD) + GPIOx_PUPDR_OFFSET, PUPDRy_0_BIT(led)); } /** * * blink LED forever * */ void blink(unsigned int led) { led_init(led); unsigned int i; while (1) { //set GPIOD led pin SET_BIT(GPIO_BASE(GPIO_PORTD) + GPIOx_BSRR_OFFSET, BSy_BIT(led)); for (i = 0; i < 500000; i++) ; //reset GPIOD led pin SET_BIT(GPIO_BASE(GPIO_PORTD) + GPIOx_BSRR_OFFSET, BRy_BIT(led)); for (i = 0; i < 500000; i++) ; } } /** * * blink LED x count * */ void blink_count(unsigned int led, unsigned int count) { led_init(led); unsigned int i; while (count--) { //set GPIOD led pin SET_BIT(GPIO_BASE(GPIO_PORTD) + GPIOx_BSRR_OFFSET, BSy_BIT(led)); for (i = 0; i < 500000; i++) ; //reset GPIOD led pin SET_BIT(GPIO_BASE(GPIO_PORTD) + GPIOx_BSRR_OFFSET, BRy_BIT(led)); for (i = 0; i < 500000; i++) ; } }
C
#include<stdio.h> int main(){ int T = 0; int n = 0; int i = 1; char *D[30]; scanf("%d", &T); for(i=1;i<=T;i++){ scanf("%d", &n); if( n%2 == 0) D[i-1] = "even"; else D[i-1] = "odd"; } for(i=1;i<=T;i++) printf("%s\n", D[i-1]); }
C
#include "holberton.h" /** * reset_to_98 - a function that takes a *ip as parameter an reset it with 98. * @n: Parameters. * * Return: Void. */ void reset_to_98(int *n) { *n = 98; }
C
/* Garcia, Matthew Lab 2 poem */ #include <stdio.h> int main() { char input; while( input = getchar() ) { if(input == EOF) { break; } else if(input == 32) { printf("\n"); } else if(input >=33 && input <= 64) { printf(""); } else if(input >= 9 && input <= 11) { printf(""); } else { putchar(input); } } }
C
/* FILE : breathingLED.c PROJECT : Stm32f3 Discovery Board/Linux PROGRAMMER : Rohit Bhardwaj DESCRIPTION : The code is for STM32F303 board, it configure, and write to the Timers in PWM mode. Moreover,Commands present, and work to implement a 'Breathing' LED that autonomously cycles smoothly between 0 and 100%, and back to 0% again. The program make use of HAL(Hardware Abstraction Layer) which is C code that implements basic drivers for all the peripherals in the STM32 Family. It makes the code more portable over STM32 Family. */ #include <stdint.h> #include <stdio.h> #include "stm32f3xx_hal.h" #include "common.h" /*Global Handle Structure*/ TIM_HandleTypeDef tim1; TIM_OC_InitTypeDef sConfig; uint32_t enablebreathe = 0; // FUNCTION : pwminit() // DESCRIPTION : The function initialize the Timer 1 & GPIO Pins // PARAMETERS : The function accepts an int value // RETURNS : returns nothing void pwminit(int mode) { /* Turn on clocks to I/O */ __GPIOA_CLK_ENABLE(); /* Configure GPIO pins */ GPIO_InitTypeDef GPIO_InitStruct; GPIO_InitStruct.Pin = (GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10); GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; GPIO_InitStruct.Alternate = 6; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); uint32_t rc; /* Initialize the Timer(PWM) */ __TIM1_CLK_ENABLE(); tim1.Instance = TIM1; tim1.Init.Prescaler = HAL_RCC_GetPCLK2Freq()*2/1000000; tim1.Init.CounterMode = TIM_COUNTERMODE_UP; tim1.Init.Period = 1000; tim1.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; tim1.Init.RepetitionCounter = 0; /*Initalize the Timer*/ rc = HAL_TIM_Base_Init(&tim1); if(rc != HAL_OK) { printf("Unable to initalize Timer, rc=%d\n",(unsigned)rc); return; } /*Start the timer*/ rc = HAL_TIM_Base_Start(&tim1); if(rc != HAL_OK) { printf("Unable to start the timer, rc=%d\n",(unsigned)rc); return; } /*Configure output:*/ sConfig.OCMode = TIM_OCMODE_PWM1; sConfig.Pulse = 500; sConfig.OCPolarity = TIM_OCPOLARITY_HIGH; sConfig.OCNPolarity = TIM_OCNPOLARITY_LOW; sConfig.OCFastMode = TIM_OCFAST_DISABLE; sConfig.OCIdleState = TIM_OCIDLESTATE_RESET; sConfig.OCNIdleState =TIM_OCNIDLESTATE_RESET; HAL_TIM_PWM_ConfigChannel(&tim1,&sConfig,TIM_CHANNEL_1); HAL_TIM_PWM_ConfigChannel(&tim1,&sConfig,TIM_CHANNEL_2); HAL_TIM_PWM_ConfigChannel(&tim1,&sConfig,TIM_CHANNEL_3); HAL_NVIC_SetPriority(TIM1_UP_TIM16_IRQn, 0, 1); HAL_NVIC_EnableIRQ(TIM1_UP_TIM16_IRQn); TIM1->CNT = 0; /* Reset counter */ } ADD_CMD("pwminit",pwminit," Initialize the Timer & GPIO Pins"); // FUNCTION : pwm() // DESCRIPTION : The function sets PWM output value for desired channel // PARAMETERS : The function accepts an int value // RETURNS : returns nothing void pwm(int mode) { if(mode != CMD_INTERACTIVE) { return; } uint32_t channel; int32_t value; fetch_uint32_arg(&channel); fetch_int32_arg(&value); if(channel == 1) { /* Start the PWM output: */ HAL_TIM_PWM_Start(&tim1,TIM_CHANNEL_1); TIM1->CCR1 = value; } else if(channel == 2) { /* Start the PWM output: */ HAL_TIM_PWM_Start(&tim1,TIM_CHANNEL_2); TIM1->CCR2 = value; } else if(channel == 3) { /* Start the PWM output: */ HAL_TIM_PWM_Start(&tim1,TIM_CHANNEL_3); TIM1->CCR3 = value; } else if(channel == 0) { /* Stop the PWM output: */ HAL_TIM_PWM_Stop(&tim1,TIM_CHANNEL_1); HAL_TIM_PWM_Stop(&tim1,TIM_CHANNEL_2); HAL_TIM_PWM_Stop(&tim1,TIM_CHANNEL_3); } } ADD_CMD("pwm",pwm," pwm<channel><value>"); // FUNCTION : TIM1_UP_TIM16_IRQHandler() // DESCRIPTION : The function implement a 'Breathing' LED that autonomously cycles // smoothly between 0 and 100%, and back to 0% again // PARAMETERS : nothing // RETURNS : returns nothing void TIM1_UP_TIM16_IRQHandler(void) //startup_stm32f303xc.s { static int i = 0; static int increment = 1; TIM1 ->SR &= ~1;//~UIF reset the flag in timer if(enablebreathe) { TIM1->CCR1 = i;//start from zero by setting it to zero if (increment) { i++; //increment the value in i if(i >= 1000) //when it reaches to maximum ie 1000 { increment = 0; // change the condition by making it zero } } else //now start the decrementation { i--; //decrement it if(i == 0) //when it reaches to zero { increment = 1; //reanalyze it back to 1 } } } } // FUNCTION : monitor() // DESCRIPTION : The function fetches the value from the commands // PARAMETERS : The function accepts an int value // RETURNS : returns nothing void monitor(int mode) { if(mode != CMD_INTERACTIVE) { return; } fetch_uint32_arg(&enablebreathe); } ADD_CMD("enable",monitor," eneblebreathe");
C
/* 实现 int sqrt(int x) 函数。 计算并返回 x 的平方根,其中 x 是非负整数。 由于返回的类型是整数,结果只保留整数的部分,小数部分将被舍去。 */ #include <stdio.h> int mySqrt(int x); int main(void) { printf("%d\n", mySqrt(1213123323)); return 0; } int mySqrt(int x) { int result; unsigned int t; for (t = 1; t * t < x; t++) continue; if (t * t == x) result = t; else result = t - 1; /* return (int) (t - 1); */ return result; }
C
/*============================================================================= * Copyright (c) 2019, Miguel del Valle <[email protected]> * All rights reserved. * License: bsd-3-clause (see LICENSE.txt) * Date: 2019/08/23 * Version: rev0 *===========================================================================*/ /*! * @brief Example using sAPI, shows basic setup of sensor, * includes initialization of the interface and * performing the sensor initialization. */ /*=====[Inclusions of function dependencies]=================================*/ #include "bmp280.h" #include "sapi.h" /*=====[Definition macros of private constants]==============================*/ /*=====[Definitions of extern global variables]==============================*/ /*=====[Definitions of public global variables]==============================*/ /*=====[Definitions of private global variables]=============================*/ void delay_ms(uint32_t period_ms); int8_t i2c_reg_write(uint8_t i2c_addr, uint8_t reg_addr, uint8_t *reg_data, uint16_t length); int8_t i2c_reg_read(uint8_t i2c_addr, uint8_t reg_addr, uint8_t *reg_data, uint16_t length); int8_t spi_reg_write(uint8_t cs, uint8_t reg_addr, uint8_t *reg_data, uint16_t length); int8_t spi_reg_read(uint8_t cs, uint8_t reg_addr, uint8_t *reg_data, uint16_t length); void print_rslt(const char api_name[], int8_t rslt); /*=====[Main function, program entry point after power on or reset]==========*/ int main(void) { int8_t rslt; struct bmp280_dev bmp; struct bmp280_config conf; struct bmp280_uncomp_data ucomp_data; uint32_t pres32, pres64; int32_t temp32; double temp; double pres; static char uartBuff[10]; /* Map the delay function pointer with the function responsible for implementing the delay */ bmp.delay_ms = delay_ms; /* Assign device I2C address based on the status of SDO pin (GND for PRIMARY(0x76) & VDD for SECONDARY(0x77)) */ bmp.dev_id = BMP280_I2C_ADDR_PRIM; /* Select the interface mode as I2C */ bmp.intf = BMP280_I2C_INTF; /* Map the I2C read & write function pointer with the functions responsible for I2C bus transfer */ bmp.read = i2c_reg_read; bmp.write = i2c_reg_write; /* To enable SPI interface: comment the above 4 lines and uncomment the below 4 lines */ /* * bmp.dev_id = 0; * bmp.read = spi_reg_read; * bmp.write = spi_reg_write; * bmp.intf = BMP280_SPI_INTF; */ // ----- Setup ----------------------------------- boardInit(); uartConfig(UART_USB, 9600); // Inicializar periferico UART_USB i2cInit(I2C0, BME280_I2C_RATE); // ----- Init sensor ----------------------------------- rslt = bmp280_init(&bmp); print_rslt(" bmp280_init status", rslt); /* Always read the current settings before writing, especially when * all the configuration is not modified */ rslt = bmp280_get_config(&conf, &bmp); print_rslt(" bmp280_get_config status", rslt); /* configuring the temperature oversampling, filter coefficient and output data rate */ /* Overwrite the desired settings */ conf.filter = BMP280_FILTER_COEFF_2; /* Temperature oversampling set at 4x */ conf.os_temp = BMP280_OS_4X; /* Pressure over sampling none (disabling pressure measurement) */ conf.os_pres = BMP280_OS_4X; /* Setting the output data rate as 1HZ(1000ms) */ conf.odr = BMP280_ODR_1000_MS; rslt = bmp280_set_config(&conf, &bmp); print_rslt(" bmp280_set_config status", rslt); /* Always set the power mode after setting the configuration */ rslt = bmp280_set_power_mode(BMP280_NORMAL_MODE, &bmp); print_rslt(" bmp280_set_power_mode status", rslt); // ----- Repeat for ever ------------------------- while (true) { /* Reading the raw data from sensor */ rslt = bmp280_get_uncomp_data(&ucomp_data, &bmp); /* Getting the 32 bit compensated temperature */ rslt = bmp280_get_comp_temp_32bit(&temp32, ucomp_data.uncomp_temp, &bmp); /* Getting the compensated pressure using 32 bit precision */ rslt = bmp280_get_comp_pres_32bit(&pres32, ucomp_data.uncomp_press, &bmp); /* Getting the compensated pressure using 64 bit precision */ rslt = bmp280_get_comp_pres_64bit(&pres64, ucomp_data.uncomp_press, &bmp); /* Getting the compensated temperature as floating point value */ rslt = bmp280_get_comp_temp_double(&temp, ucomp_data.uncomp_temp, &bmp); /*printf("UT: %ld, T32: %ld, T: %f \r\n", ucomp_data.uncomp_temp, temp32, temp);*/ uartWriteString(UART_USB, "Temperature: "); floatToString(temp, uartBuff, 2); uartWriteString(UART_USB, uartBuff); uartWriteString(UART_USB, "\rGrados C"); uartWriteString(UART_USB, "\r\n"); uartWriteString(UART_USB, "Pressure: "); floatToString(pres, uartBuff, 2); uartWriteString(UART_USB, uartBuff); uartWriteString(UART_USB, "\rPa"); uartWriteString(UART_USB, "\r\n"); /* Getting the compensated pressure as floating point value */ rslt = bmp280_get_comp_pres_double(&pres, ucomp_data.uncomp_press, &bmp); /*printf("UP: %ld, P32: %ld, P64: %ld, P64N: %ld, P: %f\r\n", ucomp_data.uncomp_press, pres32, pres64, pres64 / 256, pres);*/ /* Sleep time between measurements = BMP280_ODR_1000_MS */ bmp.delay_ms(5000); gpioToggle(LED); } // YOU NEVER REACH HERE, because this program runs directly or on a // microcontroller and is not called by any Operating System, as in the // case of a PC program. return 0; } /*! * @brief Function that creates a mandatory delay required in some of the APIs such as "bmg250_soft_reset", * "bmg250_set_foc", "bmg250_perform_self_test" and so on. * * @param[in] period_ms : the required wait time in milliseconds. * @return void. * */ void delay_ms(uint32_t period_ms) { delay(period_ms); /* Implement the delay routine according to the target machine */ } /*! * @brief Function for writing the sensor's registers through I2C bus. * * @param[in] i2c_addr : sensor I2C address. * @param[in] reg_addr : Register address. * @param[in] reg_data : Pointer to the data buffer whose value is to be written. * @param[in] length : No of bytes to write. * * @return Status of execution * @retval 0 -> Success * @retval >0 -> Failure Info * */ int8_t i2c_reg_write(uint8_t i2c_addr, uint8_t reg_addr, uint8_t *reg_data, uint16_t length) { /* Implement the I2C write routine according to the target machine. */ int8_t rslt = 0; /* Return 0 for Success, non-zero for failure */ uint8_t nuevoLen = 2 * length; uint8_t transmitDataBuffer[nuevoLen]; uint8_t i = 0; for (i = 0; i < length; i += 2) { transmitDataBuffer[i] = reg_addr + i; transmitDataBuffer[i + 1] = reg_data[i]; } /* * The parameter dev_id can be used as a variable to store the I2C address of the device */ /* * Data on the bus should be like * |------------+----------------------| * | I2C action | Data | * |------------+----------------------| * | Start | - | * | Write | (reg_addr) | * | Write | (reg_data[0]) | * | Write | (reg_addr + 1) | * | Write | (reg_data[1]) | * | Write | (....) | * | Write | (reg_addr + len - 1) | * | Write | (reg_data[len - 1]) | * | Stop | - | * |------------+----------------------| */ if (i2cWrite(I2C0, i2c_addr, transmitDataBuffer, nuevoLen, TRUE)) { rslt = BMP280_OK; } else { rslt = 5; //@retval >0 -> Failure Info } return rslt; //return -1; } /*! * @brief Function for reading the sensor's registers through I2C bus. * * @param[in] i2c_addr : Sensor I2C address. * @param[in] reg_addr : Register address. * @param[out] reg_data : Pointer to the data buffer to store the read data. * @param[in] length : No of bytes to read. * * @return Status of execution * @retval 0 -> Success * @retval >0 -> Failure Info * */ int8_t i2c_reg_read(uint8_t i2c_addr, uint8_t reg_addr, uint8_t *reg_data, uint16_t length) { /* Implement the I2C read routine according to the target machine. */ int8_t rslt = 0; /* Return 0 for Success, non-zero for failure */ /* * Data on the bus should be like * |------------+---------------------| * | I2C action | Data | * |------------+---------------------| * | Start | - | * | Write | (reg_addr) | * | Stop | - | * | Start | - | * | Read | (reg_data[0]) | * | Read | (....) | * | Read | (reg_data[len - 1]) | * | Stop | - | * |------------+---------------------| */ if (i2cRead(I2C0, i2c_addr, &reg_addr, 1, TRUE, reg_data, length, TRUE)) { rslt = BMP280_OK; } else { rslt = 5; // } return rslt; //@retval >0 -> Failure Info // return -1; } /*! * @brief Function for writing the sensor's registers through SPI bus. * * @param[in] cs : Chip select to enable the sensor. * @param[in] reg_addr : Register address. * @param[in] reg_data : Pointer to the data buffer whose data has to be written. * @param[in] length : No of bytes to write. * * @return Status of execution * @retval 0 -> Success * @retval >0 -> Failure Info * */ int8_t spi_reg_write(uint8_t cs, uint8_t reg_addr, uint8_t *reg_data, uint16_t length) { /* Implement the SPI write routine according to the target machine. */ return -1; } /*! * @brief Function for reading the sensor's registers through SPI bus. * * @param[in] cs : Chip select to enable the sensor. * @param[in] reg_addr : Register address. * @param[out] reg_data : Pointer to the data buffer to store the read data. * @param[in] length : No of bytes to read. * * @return Status of execution * @retval 0 -> Success * @retval >0 -> Failure Info * */ int8_t spi_reg_read(uint8_t cs, uint8_t reg_addr, uint8_t *reg_data, uint16_t length) { /* Implement the SPI read routine according to the target machine. */ return -1; } /*! * @brief Prints the execution status of the APIs. * * @param[in] api_name : name of the API whose execution status has to be printed. * @param[in] rslt : error code returned by the API whose execution status has to be printed. * * @return void. */ void print_rslt(const char api_name[], int8_t rslt) { if (rslt != BMP280_OK) { printf("%s\t", api_name); if (rslt == BMP280_E_NULL_PTR) { printf("Error [%d] : Null pointer error\r\n", rslt); } else if (rslt == BMP280_E_COMM_FAIL) { printf("Error [%d] : Bus communication failed\r\n", rslt); } else if (rslt == BMP280_E_IMPLAUS_TEMP) { printf("Error [%d] : Invalid Temperature\r\n", rslt); } else if (rslt == BMP280_E_DEV_NOT_FOUND) { printf("Error [%d] : Device not found\r\n", rslt); } else { /* For more error codes refer "sapi_bmp280.h" */ printf("Error [%d] : Unknown error code\r\n", rslt); } } else { /* For more error codes refer "sapi_bmp280.h" */ printf("BMP280_OK code[%d]\r\n", rslt); } }
C
// // list.c // threads // // Created by Adam on 5/9/18. // Copyright © 2018 Adam. All rights reserved. // #include "list.h" #include <stdio.h> #include <stdlib.h> #include <assert.h> #ifdef PTHREADS #include <pthread.h> #endif struct node_t { unsigned int key; void * value; node_handle next; node_handle previous; }; node_handle create_node(unsigned int key, void * element) { node_handle new = (node_handle)malloc(sizeof(*new)); new->key = key; new->value = element; new->next = NULL; new->previous = NULL; return new; } void destroy_node(node_handle node) { free(node); } void List_Init(list_handle list) { list->head = NULL; list->count = 0; list->spinlock = (spinlock_handle)malloc(sizeof(spinlock_t)); #ifdef PTHREADS pthread_mutex_init(&list->spinlock->lock, NULL); #endif } void List_Insert(list_handle list, void * element, unsigned int key) { spinlock_acquire(list->spinlock); if (list->head) { node_handle new = create_node(key, element); new->next = list->head; list->head->previous = new; list->head = new; (list->count)++; } else { //list->head == NULL, list is empty assert(list->count == 0); list->head = create_node(key, element); (list->count)++; } spinlock_release(list->spinlock); } void List_Delete(list_handle list, unsigned int key) { spinlock_acquire(list->spinlock); node_handle node = list->head; while (node != NULL) { node_handle next = node->next; if (node->key == key) { //key matches, delete if (node == list->head) { //have to delete the head if (next) { next->previous = NULL; } destroy_node(node); list->head = next; (list->count)--; spinlock_release(list->spinlock); return; } else if (next == NULL) { //have to delete the tail node->previous->next = NULL; destroy_node(node); (list->count)--; spinlock_release(list->spinlock); return; } else { //some node in the middle node_handle previous = node->previous; previous->next = next; next->previous = previous; destroy_node(node); (list->count)--; spinlock_release(list->spinlock); return; } } node = next; } spinlock_release(list->spinlock); } void * List_Lookup(list_handle list, unsigned int key) { node_handle node = list->head; while (node != NULL) { if (node->key == key) { return node->value; } node = node->next; } return NULL; }
C
#include "binary_trees.h" /** * depth - measure the depth of a binary tree * @node: root of the binary tree * * Return: integer depth of the tree */ int depth(const binary_tree_t *node) { int d = 0; while (node != NULL) { d++; node = node->left; } return (d); } /** * is_perfect - check whether binary tree is perfect * @root: tree to check * @d: depth of the tree * @level: level of the current node * * Return: 1 if perfect, 0 otherwise */ int is_perfect(const binary_tree_t *root, int d, int level) { if (root == NULL) return (0); if (root->left == NULL && root->right == NULL) return (d == level + 1); if (root->left == NULL || root->right == NULL) return (0); return (is_perfect(root->left, d, level + 1) && is_perfect(root->right, d, level + 1)); } /** * binary_tree_is_perfect - check whether binary tree is perfect * @tree: tree to check * * Return: 1 if perfect, 0 otherwise */ int binary_tree_is_perfect(const binary_tree_t *tree) { int d = depth(tree); return (is_perfect(tree, d, 0)); }
C
#include "libft2.h" int ft_isalnum(int n) { return (ft_isalpha(n) || ft_isdigit(n)); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> void math_add( char *const data_string) { if(!data_string) return; char* data1 = NULL; char* data2 = NULL; char* start = data_string; while(*start != '\0' ) { if(*start == '=' && data1==NULL) { data1 = start+1; start++; continue; } if(*start == '&') { *start='\0'; } if(*start == '=' && data1!=NULL) { data2=start+1; break; } start++; } int int_data1 = atoi(data1); int int_data2 = atoi(data2); int add_res = int_data1+int_data2; printf("<p>math [add] result:%d</p>\n",add_res); } int main() { int content_length = -1; char method[1024]; char query_string[1024]; char post_data[4096]; memset(method,'\0',sizeof(method)); memset(query_string,'\0',sizeof(query_string)); memset(post_data,'\0',sizeof(post_data)); printf("<html>\n"); printf("<head>math </head>\n"); printf("<body>\n"); //printf("\t<h>hello world</h>\n"); printf("<p>heloo</p>\n"); strcpy(method,getenv("REQUEST_METHOD") ); if(strcasecmp("GET",method) == 0) { strcpy(query_string,getenv("QUERY_STRING")); math_add(query_string); // printf("<p>method: %s<br/>",method); // printf("query_string: %s</p><br/>",query_string); } else if(strcasecmp("POST",method) == 0) { content_length = atoi(getenv("CONTENT_LENGTH")); int i=0; for(;i<content_length;++i) { read(0,&post_data[i],1); } post_data[i]='\0'; printf("post data:%s</p><br/>",post_data); math_add(post_data); } else { //DO NOTHING return 1; } printf("</body>\n"); printf("</html>\n"); return 0; }
C
#include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next; }; struct node *head; struct node *temp; void add (int x) { struct node *newnode; newnode = (struct node *) malloc (sizeof (struct node)); newnode->next = NULL; newnode->data = x; if (head == NULL) { head = temp = newnode; } else { temp = head; while (temp->next != NULL) { temp = temp->next; } temp->next = newnode; newnode->next = NULL; } } void reverse(){ struct node *prevnode,*currentnode,*nextnode; prevnode=NULL; currentnode=nextnode=head; while(nextnode!=NULL){ nextnode=nextnode->next; currentnode->next=prevnode; prevnode=currentnode; currentnode=nextnode; } head=prevnode; } void printdata () { temp = head; while (temp != NULL) { printf ("%d ", temp->data); temp = temp->next; } } int main(){ add(1); add(2); add(3); printdata(); printf ("\n***********************************\n"); reverse(); printdata(); printf ("\n***********************************\n"); reverse(); printdata(); printf ("\n***********************************\n"); return 0; }
C
#define _CRT_SECURE_NO_WARNINGS #include <assert.h> #include <math.h> #include <stddef.h> #include <stdio.h> #include "equation.h" #include "helpfunction.h" #define CONST 0.001 int linear_equation(double k, double b, double* x1) { if (is_equal(fabs(k), 0) == 0) { *x1 = -b / k; return 1; } else { return -1; } } int unlinear_equation(double a, double b, double c, double* x1, double* x2) { double d = b * b - 4 * a * c; double sqrt_d = sqrt(d); if (d < 0) { return 0; } else if (is_equal(0, fabs(d)) == 1) { *x1 = -b / (2 * a); return 1; } else { *x1 = (-b + sqrt_d) / (2 * a); *x2 = (-b - sqrt_d) / (2 * a); return 2; } } int square_solver(double a, double b, double c, double x1, double x2) { int nRoots = -5; if (is_equal(fabs(a), 0) == 1) { nRoots = linear_equation(b, c, &x1); } else { nRoots = unlinear_equation(a, b, c, &x1, &x2); } output(nRoots, x1, x2); return nRoots; }
C
#include <math.h> #include <pthread.h> #include <signal.h> #include <string.h> #include <unistd.h> #include "./utils.h" struct image image; void load_image(char *filename); void save_image(char *filename); void negate(int threads_no, void *(*start_routine)(void *)); void *start_routine_numbers(void *context); void *start_routine_blocks(void *context); int main(int argc, char **argv) { if (argc != 5) { errno = EPERM; ERROR_MSG("Incrrect number of arguments! Required 4; provided %d\n", argc - 1); } int threads_no = strtol(argv[1], NULL, 10); char *ifilename = argv[3]; char *ofilename = argv[4]; int option; if (!strcmp(argv[2], "numbers")) option = NUMBERS; else if (!strcmp(argv[2], "block")) option = BLOCK; else { errno = EINVAL; ERROR_MSG("Option not recognised!\n"); } printf("File: %s\n", ifilename); printf("Number of threads: %d\n", threads_no); printf("Method: %s\n", argv[2]); load_image(ifilename); switch (option) { case NUMBERS: negate(threads_no, start_routine_numbers); break; case BLOCK: negate(threads_no, start_routine_blocks); break; default: errno = EINVAL; ERROR_MSG("Option not recognised!\n"); } save_image(ofilename); printf("\n\n\n"); return 0; } void load_image(char *filename) { FILE *file; if ((file = fopen(filename, "r")) == NULL) { ERROR_MSG("Cannot open file!\n"); } if (fgets(image.type, LINE_LEN, file) == NULL) { ERROR_MSG("Cannot image type!\n"); } char buf[MAX_LINE_LEN]; if (fgets(buf, MAX_LINE_LEN, file) == NULL) { ERROR_MSG("Cannot read to buffer!\n"); } char *tokbuf; tokbuf = strtok(buf, " "); image.width = strtol(tokbuf, NULL, 10); tokbuf = strtok(NULL, " "); image.height = strtol(tokbuf, NULL, 10); printf("Image size: %dx%d\n\n", image.width, image.height); if (fgets(buf, MAX_LINE_LEN, file) == NULL) { ERROR_MSG("Cannot read maximum pixel size!\n"); } image.pixel_max = strtol(buf, NULL, 10); int i = 0; while (fgets(buf, MAX_LINE_LEN, file) != NULL) { if ((tokbuf = strtok(buf, " \t\r\n")) != NULL) { do { image.cells[i++] = strtol(tokbuf, NULL, 10); } while ((tokbuf = strtok(NULL, " \t\r\n")) != NULL); } } if (fclose(file) == -1) { ERROR_MSG("Cannot close file!\n"); } } void save_image(char *filename) { FILE *file; if ((file = fopen(filename, "w")) == NULL) { ERROR_MSG("Cannot open file!\n"); } fprintf(file, "%c%c\n", image.type[0], image.type[1]); fprintf(file, "%d %d\n", image.width, image.height); fprintf(file, "%d\n", image.pixel_max); // Line width cannot be bigger than LINE_LEN int max_in_line = LINE_LEN / 4; for (int i = 0; i < image.width * image.height; i++) { fprintf(file, "%3hhu ", image.cells[i]); if ((i + 1) % max_in_line == 0) { fprintf(file, "\n"); } } if (fclose(file) == -1) { ERROR_MSG("Cannot close file!\n"); } } void negate(int threads_no, void *(*start_routine)(void *)) { pthread_t *threads = calloc(threads_no, sizeof(pthread_t)); struct context *contexts = calloc(threads_no, sizeof(struct context)); struct mtime_t times; mtime(&times, START, NULL); for (int i = 0; i < threads_no; i++) { contexts[i].threads_no = threads_no; contexts[i].index = i; pthread_create(&threads[i], NULL, start_routine, (void *)&contexts[i]); } for (int i = 0; i < threads_no; i++) { double *elapsed; pthread_join(threads[i], (void *)&elapsed); printf("Thread %d:\t%lf\n", i, *elapsed); free(elapsed); } mtime(&times, STOP, NULL); double acc; mtime(&times, GET, &acc); printf("Summary:\t%lf\n", acc); free(threads); free(contexts); } void *start_routine_numbers(void *arg) { struct context *context = (struct context *)arg; struct mtime_t times; mtime(&times, START, NULL); // This for loop is a naive approach – just to show that it is better // when the problem is parallelized for (int i = 0; i < image.width * image.height; i++) { // It is essential that complementary values as: i, PIXEL_MAX - i // are processed by one thread. int val = image.cells[i] > image.pixel_max/2 ? image.pixel_max - image.cells[i] : image.cells[i]; if (val % context->threads_no == context->index) { image.cells[i] = image.pixel_max - image.cells[i]; } } mtime(&times, STOP, NULL); double *acc = malloc(sizeof(double)); mtime(&times, GET, acc); pthread_exit((void *)acc); } // Due to its specification; number of threads should be smaller than image width. // Otherwise newly created threads will not convert any cells. void *start_routine_blocks(void *arg) { struct context *context = (struct context *)arg; struct mtime_t times; mtime(&times, START, NULL); int coeff = (int)ceil((double)image.width / context->threads_no); for (int i = context->index * coeff; i < (context->index + 1) * coeff && i < image.width; i++) { for (int j = i; j < image.width * image.height; j += image.width) { image.cells[j] = image.pixel_max - image.cells[j]; } } mtime(&times, STOP, NULL); double *acc = malloc(sizeof(double)); mtime(&times, GET, acc); pthread_exit((void *)acc); }
C
#include "usart3.h" /* * ʼIO 3 * bound: */ void usart3_init( u32 bound ) { NVIC_InitTypeDef NVIC_InitStructure; GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOB, ENABLE ); /* ʹGPIOBʱ */ RCC_APB1PeriphClockCmd( RCC_APB1Periph_USART3, ENABLE ); /* ʹUSART3ʱ */ USART_DeInit( USART3 ); /*λ3 */ /* USART3_TX PB10 */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; /* PB10 */ GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; /* */ GPIO_Init( GPIOB, &GPIO_InitStructure ); /* ʼPB10 */ /* USART3_RX PB11 */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; /* */ GPIO_Init( GPIOB, &GPIO_InitStructure ); /* ʼPB11 */ USART_InitStructure.USART_BaudRate = bound; /* */ USART_InitStructure.USART_WordLength = USART_WordLength_8b; /* ֳΪ8λݸʽ */ USART_InitStructure.USART_StopBits = USART_StopBits_2; /* ֹͣλ */ USART_InitStructure.USART_Parity = USART_Parity_No; /* żУλ */ USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; /* Ӳ */ USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; /* շģʽ */ USART_Init( USART3, &USART_InitStructure ); /* ʼ3 */ NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; /* ռȼ1 */ NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1; /* ȼ1 */ NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; /* IRQͨʹ */ NVIC_Init( &NVIC_InitStructure ); /* ָIJʼVICĴ */ USART_ITConfig( USART3, USART_IT_IDLE, ENABLE ); /* տж */ USART_Cmd( USART3, ENABLE ); /* ʹܴ */ USART_DMACmd( USART3, USART_DMAReq_Rx, ENABLE ); /* ʹܴ3DMA */ MYDMA_Config( DMA1_Channel3, (u32) & USART3->DR, (u32) USART3_RX_BUF, USART3_REC_LEN ); /* DMA1 Channel3 */ } #ifdef USART3_RX_EN /* ʹ˽ */ /* * ͨжϽ2ַ֮ʱ100msDzһ. * 2ַռ100ms,Ϊ1.Ҳdz100msûнյ * κ,ʾ˴ν. * յ״̬ * [15]:0,ûнյ;1,յһ. * [14:0]:յݳ */ u8 USART3_RX_BUF[USART3_REC_LEN]; /* ջ,USART_REC_LENֽ. */ u16 USART3_RX_STA = 0; void USART3_IRQHandler( void ) /* 2жϷ */ { u8 temp; #ifdef OS_TICKS_PER_SEC /* ʱӽ,˵ҪʹucosII. */ OSIntEnter(); #endif if ( USART_GetITStatus( USART3, USART_IT_IDLE ) != RESET ) /* տж */ { if( (USART3_RX_STA & 0x8000) == 0 ) { DMA_Cmd( DMA1_Channel3, DISABLE ); temp = USART3_REC_LEN - DMA_GetCurrDataCounter( DMA1_Channel3 ); USART3_RX_STA = temp | 0x8000; DMA_SetCurrDataCounter( DMA1_Channel3, USART3_REC_LEN ); DMA_Cmd( DMA1_Channel3, ENABLE ); temp = USART3->SR; temp = USART3->DR; /* ־λUSART_ClearITPendingBit(USART3, USART_IT_IDLE);û */ } } #ifdef OS_TICKS_PER_SEC /* ʱӽ,˵ҪʹucosII. */ OSIntExit(); #endif } #endif void uart3_SendByte( u8 data ) { while ( USART_GetFlagStatus( USART3, USART_FLAG_TC ) != SET ); USART_SendData( USART3, data ); } void uart3_SendString( u8 *str , u8 length ) { while(length--) { uart3_SendByte( *str++ ); } }
C
#include <assert.h> #include <per_support.h> static void put(asn_per_outp_t *po, size_t length) { fprintf(stderr, "put(%zd)\n", length); do { int need_eom = 123; ssize_t may_write = uper_put_length(po, length, &need_eom); fprintf(stderr, " put %zu\n", may_write); assert(may_write >= 0); assert(may_write <= length); assert(need_eom != 123); length -= may_write; if(need_eom) { assert(length == 0); if(uper_put_length(po, 0, 0)) { assert(!"Unreachable"); } fprintf(stderr, " put EOM 0\n"); } } while(length); fprintf(stderr, "put(...) in %zu bits\n", po->nboff); assert(po->nboff != 0); assert(po->flushed_bytes == 0); } static size_t get(asn_per_outp_t *po) { asn_bit_data_t data; memset(&data, 0, sizeof(data)); data.buffer = po->tmpspace; data.nboff = 0; data.nbits = 8 * (po->buffer - po->tmpspace) + po->nboff; fprintf(stderr, "get(): %s\n", asn_bit_data_string(&data)); size_t length = 0; int repeat = 0; do { ssize_t n = uper_get_length(&data, -1, 0, &repeat); fprintf(stderr, " get = %zu +%zd\n", length, n); assert(n >= 0); length += n; } while(repeat); fprintf(stderr, "get() = %zu\n", length); return length; } static void check_round_trip(size_t length) { fprintf(stderr, "\nRound-trip for %zu\n", length); asn_per_outp_t po; memset(&po, 0, sizeof(po)); po.buffer = po.tmpspace; po.nbits = 8 * sizeof(po.tmpspace); put(&po, length); size_t recovered = get(&po); assert(recovered == length); } int main() { check_round_trip(0); check_round_trip(1); check_round_trip(127); check_round_trip(128); check_round_trip(129); check_round_trip(255); check_round_trip(256); check_round_trip(65534); check_round_trip(65535); check_round_trip(65536); check_round_trip(65538); check_round_trip(128000); for(size_t i = 1; i < 10; i++) { check_round_trip(i*16384 - 1); check_round_trip(i*16384); check_round_trip(i*16384 + 1); } }
C
#include <stdio.h> int main(int argc, char *argv[]) { int i = 0; // go through each string in argv // why am I skipping argv[0]? for(i = 1; i < argc; i++) { printf("arg %d: %s\n", i, argv[i]); } // let's make our own array of strings char *states[] = { "California", "Oregon", "Washington", "Texas" }; int num_states = 4; for(i = 0; i < num_states; i++) { printf("state %d: %s\n", i, states[i]); } return 0; } /* EXTRA CREDITS NUM1: Figure out what kind of code you can put into the parts of a for-loop . 1. Declare something to configure. 2. Declare a conditional. 3. Declare an action that will happen after loops. NUM2: Look up how to use the ',' (comma) character to separate multiple statements The comma is used to separate parameters and functions and the semicolon to separate instructions. NUM3: Read what a NULL is and try to use it in one of the elements of the states array to see what it'll print. NULL is both a value and a pointer. It prints (null): state 0: (null) state 1: Texas state 2: Oregon state 3: Washington NUM4: See if you can assign an element from the states array to the argv array before printing both. Try the inverse. ./act10 prueba arg 1: prueba state 0: prueba state 1: Oregon state 2: Washington state 3: Texas */
C
#include "ac_allocator.h" #include <stdio.h> void uppercase(char *s) { while (*s) { if (*s >= 'a' && *s <= 'z') *s = *s - 'a' + 'A'; s++; } } int main(int argc, char *argv[]) { char **a = ac_split(NULL, ',', "alpha,beta,gamma"); char **b = ac_strdupa(a); for (size_t i = 0; a[i] != NULL; i++) { uppercase(b[i]); printf("%s=>%s", a[i], b[i]); if (a[i + 1] != NULL) printf(" "); else printf("\n"); } ac_free(a); ac_free(b); return 0; }
C
#include <stdio.h> #define MARK 4 #define NUM 13 int zero(int*); int main(){ int card[MARK][NUM]; char mark; int num; int roop; int i; int j; zero(&card[0][0]); scanf("%d", &roop); for(i = 0;i < roop;i++){ scanf("%c", &mark); if(mark == '\n'){ while(1){ scanf("%c", &mark); if(mark != '\n') break; } } scanf("%d", &num); --num; if(mark == 'S') card[0][num] = 1; else if(mark == 'H') card[1][num] = 1; else if(mark == 'C') card[2][num] = 1; else if(mark == 'D') card[3][num] = 1; } for(i = 0;i < MARK;i++){ for(j = 0;j < NUM;j++){ if(card[i][j] == 0){ if(i == 0) printf("S"); else if(i == 1) printf("H"); else if(i == 2) printf("C"); else if(i == 3) printf("D"); printf(" %d\n", j+1); } } } return 0; } int zero(int *x){ int *p = x; for(;p < x + MARK*NUM;p++) *p = 0; }
C
// 题目:输入二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的节点,只能调整树中节点指针的指向。 struct BinaryTreeNode { int m_nValue; BinaryTreeNode* m_pLeft; BinaryTreeNode* m_pRight; }; //按照中序遍历的顺序,当我们遍历转换到根结点(值为10的结点)时,它的左子树已经转换成一个排序的链表了,并且处在链表中的最后一个结点是当前值最大的结点。我们把值为8的结点和跟结点链接起来,此时链表中最后一个结点就是10了。接着我们去遍历转换右子树,并把根结点和右子树中最小的结点链接起来。我们可以写出如下代码 BinaryTreeNode* Convert(BinaryTreeNode* pRootOfTree) { BinaryTreeNode* pLastNodeInList=NULL; ConvertNode(pRootOfTree,&pLastNodeInList); //pLastNodeInList指向双向链表的尾结点 //我们需要返回头结点 BinaryTreeNode* pHeadOfList=pLastNodeList; while(PheadOfList!=NULL&&pHeadOfList->m_pLeft!=NULL)pHeadOfList=pHeadOfList->m_pLeft; return pHeadOfList; } void ConvertNode(BinaryTreeNode* pNode,BinaryTreeNode** pLastNodeInList) { if(pNode==NULL)return; BinaryTreeNode* pCurrent=pNode; if(pCurrent->m_pLeft!=NULL)ConvertNode(pCurrent->m_pLeft,pLastNodeInList); pCurrent->m_pLeft=*pLastNodeInList; if(*pLastNodeInList!=NULL)(*pLastNodeInList)->m_pRight=pCurrent; *pLastNodeInList=pCurrent; if(pCurrent->m_pRight!=NULL)ConvertNode(pCurrent->m_pRight,pLastNodeInList); } //在上面的代码中,我们用pLastNodeInList指向已经转换好的链表的最后一个结点(也是值最大的结点)。当我们遍历到值为10的节点的时候,它的左子树都已经转换好了,因此pLastNodeInList指向值为8的结点。接着把根节点链接到链表中之后,值为10的结点成了链表中最后一个结点(新的值最大的结点),于是pLastNodeInList指向了这个值为10的结点。接下来把pLastNodeInList作为参数传入函数递归遍历右子树。我们找到右子树中最左遍的子节点(值为12的结点,在右子树中值最小),并把该节点和10的节点链接起来。
C
#include "led.h" #include "delay.h" #include "key.h" #include "sys.h" #include "beep.h" /*主机启动后,再插入4G模块,以正确加载驱动; 单片机判断心跳信号,发现主机死机后,重启主机,再上电4G模块 */ int main(void) { vu8 key=0; u16 t =0; u8 pre = 0; delay_init(); //延时函数初始化 LED_Init(); //初始化与LED连接的硬件接口 BEEP_Init(); //初始化蜂鸣器端口 KEY_Init(); //初始化与按键连接的硬件接口 LED0=0; //先点亮红灯 while(1) { while(key == 0){ key = KEY_Scan(0); delay_ms(100); } P4G = 0; delay_ms(1000); delay_ms(1000); P4G = 1; while(1){ key=KEY_Scan(0); //得到键值 switch(key) { case WKUP_PRES: //控制蜂鸣器 BEEP=!BEEP; break; case KEY1_PRES: //控制LED1翻转 LED1=!LED1; break; case KEY0_PRES: //同时控制LED0,LED1翻转 LED0=!LED0; LED1=!LED1; break; default: if(pre == key) t++; else t=0; } delay_ms(10); if(t>600){ //多长个10ms没有dog信号则重启 RASP = 0; delay_ms(50); delay_ms(1000); delay_ms(1000); delay_ms(1000); delay_ms(1000); RASP = 1; delay_ms(50); t = 0; break; } pre = key; } } }
C
#include <stdio.h> char *vc_strnstr(const char *big, const char *little, size_t len) { const char *littleCounter = little; int littleNum = 0; while(little[littleNum] != '\0'){ littleNum++; } for(size_t i = 0; i < len; i++) { int num = 0; if(big[i] == little[num]) { int correctChar = 0; for(size_t j = 0; j < littleNum; j++) { if (big[i + j] == little[j]) { correctChar++; } } if (correctChar == littleNum) { return (char *)(big + i); } num++; } } return NULL; }
C
/* This program estimates the value of log 2.5 using third order Newton Interpolation polynomial from the given values of logx ( which here is fx[] values ) for 4 values (points) of x i.e. x = 1,2,3,4 */ #include <stdio.h> #include <conio.h> float newdiv(int u, int l); float multiple(int, float); float x[4] = { 1, 2, 3, 4 }; float fx[4] = { 0, 0.3010, 0.4771, 0.6021 }; int main() { int i, j, n = sizeof(x)/4; // n is number of points available float reqd_x = 2.5; // value of x for wihich we need f(x) value float px = fx[0]; for( i = 1; i < n; i++ ) { px += (newdiv(i,0) * multiple(i,reqd_x)); } printf("\nValue of f(%.2f) at p%d(%.2f) = %f\n",reqd_x, n-1, reqd_x, px); getch(); return 0; } //end main float newdiv(int u, int l) // this function returns Newton Divided Difference value for given boundries { float result =0.0; int lb = l, ub = u; if( (ub - lb) == 1 ){ result = ((fx[ub] - fx[lb])/(x[ub] - x[lb])); }else { result = ((newdiv(ub,lb+1) - newdiv(ub-1,lb))/(x[ub] - x[lb])); } return result; } // end function newdiv float multiple(int n, float var) // gives the value of multiple of (x-xj) where j is 0 to n { float result = 1.0; int i; for ( i = 0; i < n; i++ ) { result *= (var - x[i]); } return result; } //end function multiple
C
/****************************************************************************** All content 2017 Digipen Institute of Technology Singapore, all rights reserved filename BuffsDebuffs.c author Wong Zhihao DP email [email protected] course RTIS Brief Description: Contains the functions of every powerup in the game. ******************************************************************************/ #include <string.h> /* strncpy */ #include <stdio.h> /* printf */ #include <stdlib.h> /* rand */ #include "BuffsDebuffs.h" /* Function declarations */ #include "Ball.h" /* Ball object and functions */ #include "Player.h" /* Player object and functions */ #include "FMODInit.h" /* Sound object and functions */ #include "Stage.h" /* Stage object and data */ #include "WorldData.h" /* Misc Functions */ #include "TileMapManager.h" /* Tile manager object and functions */ /*********************** Buff and Debuffs to HP ***********************/ /* Increases player HP by one when player gets the buff */ void Buff_HP(Player *player, Sound *sound) { /* Increase player health by one */ ++player->health; /* Increase player score */ player->score += 50; loadSound(sound, "..\\CollisionDetectionTest\\SFX\\PlayerBuffCollect.wav"); playSound_Medium(sound); loadSound(sound, "..\\CollisionDetectionTest\\SFX\\HPBuff.wav"); playSound_High(sound); } /* Decreases player HP by one when player gets the debuff */ void Debuff_HP(Player *player, Sound *sound) { /* Clear health before adjusting */ Player_Clear_Health(player); /* Decrease player health by one */ --player->health; /* Increase player score */ player->score += 200; loadSound(sound, "..\\CollisionDetectionTest\\SFX\\PlayerDebuffCollect.wav"); playSound_Medium(sound); loadSound(sound, "..\\CollisionDetectionTest\\SFX\\HPDebuff.wav"); playSound_High(sound); } /********************************** Buff and Debuffs to Player Length **********************************/ #define PLAYER_HEIGHT 2 /* Updates the length of the player from buffs and debuffs */ void Player_LengthUpdate(Player *player, int new_length, TileMapManager *tileManager, Sound *sound) { /* Check if player length is not at the max when increasing */ if (new_length > 0) { loadSound(sound, "..\\CollisionDetectionTest\\SFX\\PlayerBuffCollect.wav"); playSound_Medium(sound); if (player->x_l <= 9) { /* Clear player before adjusting */ Player_Clear_Select(player, tileManager); /* Increase player length */ player->x_l += new_length; /* Increase player score */ player->score += 50; loadSound(sound, "..\\CollisionDetectionTest\\SFX\\LengthBuff.wav"); playSound_High(sound); } } /* Check if player length is not at the min when decreasing */ else if (new_length < 0) { loadSound(sound, "..\\CollisionDetectionTest\\SFX\\PlayerDebuffCollect.wav"); playSound_Medium(sound); if (player->x_l >= 5) { /* Clear player before adjusting */ Player_Clear_Select(player, tileManager); /* Increase player length */ player->x_l += new_length; /* Increase player score */ player->score += 100; loadSound(sound, "..\\CollisionDetectionTest\\SFX\\LengthDebuff.wav"); playSound_High(sound); } } /* Powerup only increases score */ else player->score += 200;; /* Sets player art to the correct art based on its length */ if (player->id == 1) { switch (player->x_l) { case 3: Player_Copy(player, player1downdown); break; case 5: Player_Copy(player, player1down); break; case 7: Player_Copy(player, player1); break; case 9: Player_Copy(player, player1up); break; case 11: Player_Copy(player, player1upup); break; } } /* For player 2 */ else if (player->id == 2) { switch (player->x_l) { case 3: Player_Copy(player, player2downdown); break; case 5: Player_Copy(player, player2down); break; case 7: Player_Copy(player, player2); break; case 9: Player_Copy(player, player2up); break; case 11: Player_Copy(player, player2upup); break; } } /* Print player */ Player_Print(player, tileManager); } /* Ensures the player length does not exceed borders if its length increases */ void Player_LengthBorderCheck(Stage *stage, Player *player) { /* Moves the player so its new length does not go out of game area */ if (player->x_p == (stage->size_x - player->x_l - 1)) player->x_p -= 2; if (player->x_p == (stage->size_x - player->x_l - 2)) player->x_p -= 1; } /* Copies the correct player ASCII */ void Player_Copy(Player *player, const char *play[]) { int i; /* Loop counter */ /* Updates player art */ for (i = 0; i < PLAYER_HEIGHT; ++i) strncpy_s(player->playerStyle[i], player->x_l + 1, play[i], player->x_l + 1); } /******************************** Buff and Debuffs to Ball Speeds *********************************/ /* Speeds up player's ball */ void Ball_Fast(Ball *ball, Player *player, Sound *sound) { /* Checks if it not at the max */ if (ball->base_timer <= 85) { ball->base_timer += 15; } /* Increases player's score */ player->score += 200; loadSound(sound, "..\\CollisionDetectionTest\\SFX\\PlayerDebuffCollect.wav"); playSound_Medium(sound); loadSound(sound, "..\\CollisionDetectionTest\\SFX\\BallDebuff.wav"); playSound_High(sound); } /* Slows down player's ball */ void Ball_Slow(Ball *ball, Player *player, Sound *sound) { /* Makes sure ball doesn't move too slowly */ if (ball->base_timer >= -60) { ball->base_timer -= 20; } /* Increases player's score */ player->score += 100; loadSound(sound, "..\\CollisionDetectionTest\\SFX\\PlayerBuffCollect.wav"); playSound_Medium(sound); loadSound(sound, "..\\CollisionDetectionTest\\SFX\\BallBuff.wav"); playSound_High(sound); } /**************************** Swap player controls debuff *****************************/ /* Swaps the player's left and right controls */ void PlayerControls_Swap(Player *player, Sound *sound) { /* Checks if player's controls are not already swapped */ if (player->swap_flag == 0) { int tmp; /* Store value for swapping */ /* Prints on the game sidebar that player controls are swapped */ Stage_Control_Swap_Print(1); /* Flags the player's controls as swapped */ player->swap_flag = 1; /* Swap the controls */ tmp = player->left; player->left = player->right; player->right = tmp; /* Increase player score */ player->score += 250; /* Sets the time where the player's controls are swapped */ player->swap_time = 15000; } /* Player's controls already swapped, reset the timing */ else player->swap_time = 15000; loadSound(sound, "..\\CollisionDetectionTest\\SFX\\PlayerDebuffCollect.wav"); playSound_Medium(sound); loadSound(sound, "..\\CollisionDetectionTest\\SFX\\ControlsSwap.wav"); playSound_High(sound); } /* Returns the player controls back to normal */ void PlayerControls_Revert(Player *player, Sound *sound) { int tmp; /* Store value for swapping */ /* Prints on the game sidebar that player controls are normal */ Stage_Control_Swap_Print(0); /* Swaps back player controls */ tmp = player->left; player->left = player->right; player->right = tmp; /* Player's controls no longer swapped */ player->swap_flag = 0; loadSound(sound, "..\\CollisionDetectionTest\\SFX\\ControlsRevert.wav"); playSound_High(sound); } /********************************** Buff and Debuffs to Player Speed **********************************/ /* Speeds player speed */ void PlayerSpeed_Fast(Player *player, Sound *sound) { /* Checks if player's speed is already at the max */ if (player->base_timer <= 38) player->base_timer += 7; /* Increases player score */ player->score += 100; loadSound(sound, "..\\CollisionDetectionTest\\SFX\\PlayerBuffCollect.wav"); playSound_Medium(sound); loadSound(sound, "..\\CollisionDetectionTest\\SFX\\PlayerSpeedBuff.wav"); playSound_High(sound); } /* Slows player speed */ void PlayerSpeed_Slow(Player *player, Sound *sound) { /* Drops the player's speed */ player->base_timer -= 7; /* Increases player's score */ player->score += 200; loadSound(sound, "..\\CollisionDetectionTest\\SFX\\PlayerDebuffCollect.wav"); playSound_Medium(sound); loadSound(sound, "..\\CollisionDetectionTest\\SFX\\PlayerSpeedDebuff.wav"); playSound_High(sound); } /****************** Ball Swap Powerup *******************/ /* Swaps the players' balls */ void Ball_Swap(Ball *ball, Sound *sound, TileMapManager *tileManager) { int x, y; /* Store values for swapping */ /* Check if either ball is not currently dead */ if (ball->ballisdeadflag == 0 && ball->enemyball->ballisdeadflag == 0) { /* Clears the ball position in game area */ TileMapManager_Ball(ball, tileManager, 0); WorldData_GoToXY(ball->x_ballpos, ball->y_ballpos); printf(" "); /* Clears the other ball position in game area */ TileMapManager_Ball(ball->enemyball, tileManager, 0); WorldData_GoToXY(ball->enemyball->x_ballpos, ball->enemyball->y_ballpos); printf(" "); /* Swaps the ball's positions */ x = ball->x_ballpos; y = ball->y_ballpos; ball->x_ballpos = ball->enemyball->x_ballpos; ball->y_ballpos = ball->enemyball->y_ballpos; ball->enemyball->x_ballpos = x; ball->enemyball->y_ballpos = y; /* This causes a bug when I print the balls in their new position so it's being commented */ //if (ball->ball_type == 1) //{ // TileMapManager_Ball(ball, tileManager, 3); // TileMapManager_Ball(ball->enemyball, tileManager, 4); //} //else if (ball->ball_type == 2) //{ // TileMapManager_Ball(ball, tileManager, 4); // TileMapManager_Ball(ball->enemyball, tileManager, 3); //} //WorldData_GoToXY(ball->x_ballpos, ball->y_ballpos); //printf("%c", ball->ballchar); //WorldData_GoToXY(ball->enemyball->x_ballpos, ball->enemyball->y_ballpos); //printf("%c", ball->enemyball->ballchar); /* If ball is still on player's peddle, fire it */ if (ball->ball_fired_flag == 0) { ball->ball_fired_flag = 1; ball->balldirection = (rand() % 2);/*between bottom left and bottom right*/ if (ball->ball_type == 1) ball->balldirection += 2;/*Ensures ball2 moves only top left and top right*/ loadSound(sound, "..\\CollisionDetectionTest\\SFX\\PlayerFire.wav"); playSound_High(sound); } if (ball->enemyball->ball_fired_flag == 0) { ball->enemyball->ball_fired_flag = 1; ball->enemyball->balldirection = (rand() % 2);/*between bottom left and bottom right*/ if (ball->enemyball->ball_type == 1) ball->enemyball->balldirection += 2;/*Ensures ball2 moves only top left and top right*/ loadSound(sound, "..\\CollisionDetectionTest\\SFX\\PlayerFire.wav"); playSound_High(sound); } ball->friendplayer->score += 400; loadSound(sound, "..\\CollisionDetectionTest\\SFX\\BallSwap.wav"); playSound_High(sound); } loadSound(sound, "..\\CollisionDetectionTest\\SFX\\PlayerDebuffCollect.wav"); playSound_Medium(sound); }
C
#ifndef _MATH_H_ #define _MATH_H_ #include "math_vector.h" #include "math_matrix.h" #define PI 3.141592654f #define TWOPI 6.283185307f #define IVVPI 0.318309886f #define INV2PI 0.159154943f #define PIDIV2 1.570796327f #define PIDIV4 0.785398163f inline float toRadians(float x) { return x * PI / 180.0f; } inline float Clamp(float low, float value, float high) { if (value < low) { return low; } else if (value > high) { return high; } else { return value; } } inline Vector3 Lerp(Vector3 left, float factor, Vector3 right) { return left * (1.0f - factor) + right * factor; } inline Vector4 Lerp(Vector4 left, float factor, Vector4 right) { return left * (1.0f - factor) + right * factor; } // The state must be initialized to non-zero value inline uint32_t XOrShift32(uint32_t *state) { // https://en.wikipedia.org/wiki/Xorshift uint32_t x = *state; x ^= x << 13; x ^= x >> 17; x ^= x << 5; *state = x; return x; } inline float RandomUnilateral(uint32_t *state) { return (float) XOrShift32(state) / (float) U32Max; } inline float RandomBilateral(uint32_t *state) { return 2.0f * RandomUnilateral(state) - 1.0f; } inline bool Refract(Vector3 incidentVector, Vector3 normal, float refractiveIndex, Vector3* refractionDirection) { // Clamp cos value for avoiding any NaN errors; float cosIncidentAngle = Clamp(-1.0f, DotProduct(incidentVector, normal), 1.0f); Vector3 hitNormal = normal; float refractiveIndexRatio; // NOTE: we assume incident ray comes from the air which has refraction index equals 1. if (cosIncidentAngle < 0.0f) { // We are coming from outside the surface cosIncidentAngle = -cosIncidentAngle; refractiveIndexRatio = 1.0f / refractiveIndex; } else { hitNormal = -normal; refractiveIndexRatio = refractiveIndex; // / 1.0f } float discriminant = 1 - refractiveIndexRatio * refractiveIndexRatio * (1 - cosIncidentAngle * cosIncidentAngle); // If discriminant lower than 0 we cannot refract. // This is called total internal reflection. if (discriminant < 0) { return false; } else { *refractionDirection = incidentVector * refractiveIndexRatio + hitNormal * (refractiveIndexRatio * cosIncidentAngle - sqrtf(discriminant)); return true; } } inline float Schlick(Vector3 incidentVector, Vector3 normal, float refractiveIndex) { float cosIncidentAngle = Clamp(-1.0f, DotProduct(incidentVector, normal), 1.0f); float cosine; if (cosIncidentAngle > 0) { cosine = cosIncidentAngle; } else { cosine = -cosIncidentAngle; } float r0 = (1 - refractiveIndex) / (1 + refractiveIndex); r0 = r0 * r0; return r0 + (1 - r0) * powf((1 - cosine), 5); } inline uint32_t RGBPackToUInt32(Vector3 color) { return (255 << 24 | (int32_t) (255 * color.x) << 16 | (int32_t) (255 * color.y) << 8 | (int32_t) (255 * color.z) << 0); } inline float LinearTosRGB(float value) { value = Clamp(0.0f, value, 1.0f); float result = value * 12.92f; if (value >= 0.0031308f) { result = (1.055f * powf(value, 1.0f / 2.4f)) - 0.055f; } return result; } inline uint32_t RGBPackToUInt32WithGamma2(Vector3 color) { return (255 << 24 | (int32_t) (255 * sqrtf(color.x)) << 16 | (int32_t) (255 * sqrtf(color.y)) << 8 | (int32_t) (255 * sqrtf(color.z)) << 0); } inline uint32_t RGBPackToUInt32WithsRGB(Vector3 color) { return (255 << 24 | (int32_t)(255 * LinearTosRGB(color.x)) << 16 | (int32_t)(255 * LinearTosRGB(color.y)) << 8 | (int32_t)(255 * LinearTosRGB(color.z)) << 0); } #endif
C
/** * \file semaphores.h * \author Christian Kruse, <[email protected]> * \brief Wrappers around the sem* functions * * This module provides some wrapper functions for the semaphore * functions provided by POSIX. These functions make the handling * of semaphores much easier */ /* {{{ Initial headers */ /* * $LastChangedDate$ * $LastChangedRevision$ * $LastChangedBy$ * */ /* }}} */ #ifndef _CF_SEMAPHORE_H #define _CF_SEMAPHORE_H #ifdef _SEM_SEMUN_UNDEFINED union semun { int val; struct semid_ds *buf; unsigned short int *array; struct seminfo *__buf; }; #endif /** * This macro decreases the value of the semaphore by 1 (equivalent to the P() action) */ #define CF_SEM_LOCK(id,sem) (cf_sem_pv(id,-1,sem)) /** * This macro decreases the value of a semaphore by 1 */ #define CF_SEM_DOWN(id,sem) (cf_sem_pv(id,-1,sem)) /** * This macro increases the value of the semaphore by 1 (equivalent to the V() action) */ #define CF_SEM_UNLOCK(id,sem) (cf_sem_pv(id,1,sem)) /** * This macro increases the value of the semaphore by 1 */ #define CF_SEM_UP(id,sem) (cf_sem_pv(id,1,sem)) /** * This macro blocks until the specified semaphore has reached a zero value */ #define CF_SEM_WAITZERO(id,sem) (cf_sem_pv(id,0,sem)) /** * \brief This function performs semaphore operations * \param id The semaphore id * \param operation The size to increase or decrease the value of the semaphore. * \param semnum The index of the semaphore in the set. * \return 0 on success, -1 on failure */ int cf_sem_pv(int id,int operation,int semnum); /** * This function returns the value of the selected semaphore * \param id The semaphore ide * \param semnum The semaphore index in the set * \param num The number of semaphores in the set * \param val Reference to a integer variable where to store the value * \return 0 on success, -1 on failure */ int cf_sem_getval(int id,int semnum,int num,unsigned short *val); #endif /* eof */
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "hiredis/hiredis.h" int main( int argc, char *argv[] ) { redisReply *reply; long int i; char buffer[256]; char* keyString; char* host; char* password; int port; if (argc < 2) { printf("Usage: redis-del \"some:key:*\" (host) (port)\n"); exit(1); } else { if (argc == 2) { keyString = argv[1]; host = "127.0.0.1"; port = 6379; } else if (argc == 3) { keyString = argv[1]; host = argv[2]; port = 6379; } else if (argc == 4) { keyString = argv[1]; host = argv[2]; port = atoi(argv[3]); } redisContext *c = redisConnect(host, port); if (c != NULL && c->err) { printf("Error: %s\n", c->errstr); exit(1); } char * password = getpass("Password (enter for none): "); if (strlen(password) > 0) { reply = redisCommand(c, "AUTH %s", password); if ( reply->type == REDIS_REPLY_ERROR ) { printf( "Error: %s\n", reply->str ); freeReplyObject(reply); exit(1); } freeReplyObject(reply); } reply = redisCommand(c, "KEYS %s", keyString); if ( reply->type == REDIS_REPLY_ERROR ) printf( "Error: %s\n", reply->str ); else if ( reply->type != REDIS_REPLY_ARRAY ) printf( "Unexpected type: %d\n", reply->type ); else if (reply->elements > 0) { printf("%zu matched keys. Delete them? [y/N]: ", reply->elements); scanf ("%s", buffer); printf("\n"); if (strcmp(buffer, "y") == 0 || strcmp(buffer, "Y") == 0) { for ( i=0; i<reply->elements; ++i ){ redisCommand(c, "DEL %s", reply->element[i]->str); printf( "%lu: %s\n", i, reply->element[i]->str ); } printf("%li objects removed\n", i); } else { printf("Cancelled!\n"); } } else printf("No keys matched!\n"); freeReplyObject(reply); exit(0); } }
C
// // doubly_circular_linkedlist.c // LinkedList // // Created by Seoksoon Jang on 2016. 11. 10.. // Copyright © 2016년 Seoksoon Jang. All rights reserved. // #include "doubly_circular_linkedlist.h" void dcll_deleteNode(DCLLNode* node) { if (node != NULL) { free(node); } else { perror("cannot free the node because node is already NULL.\n"); } } DCLLNode* dcll_createDCLLNode(int _data) { DCLLNode* newNode = (DCLLNode*)malloc(sizeof(DCLLNode)); newNode->next = NULL; newNode->prev = NULL; newNode->data= _data; return newNode; } DCLLNode* dcll_getNodeAt(DCLLNode* leadNode, int nodeIndex) { int runCount = 0; leadNode = leadNode->next; DCLLNode* runNode = leadNode; do { if(nodeIndex == runCount) { return runNode; } runCount++; runNode = runNode->next; } while (runNode != leadNode); return NULL; } int dcll_getAllNodeCount(DCLLNode* leadNode) { int runCount = 0; DCLLNode* runNode = leadNode->next; runCount++; do { runCount++; runNode = runNode->next; } while (runNode != leadNode); return runCount; } int dcll_searchNode(DCLLNode* leadNode, int data) { DCLLNode* runNode = leadNode->next; int runCount = 0; do { if (runNode->data == data) { return runCount; } runCount++; runNode = runNode->next; } while (runNode != leadNode); if (runNode->data == data) { return runCount; } return -1; } void dcll_removeNode(DCLLNode** leadNode, DCLLNode* removeNode) { // if there is no node to remove if (*leadNode == NULL || removeNode == NULL) { perror("there is no node specified to remove, please create node before remove.\n"); return ; } // Otherwise, else { DCLLNode* runNode = (*leadNode)->next; do { // if the node found, if (runNode->data == removeNode->data) { // if the node found is the first node(in the list traverse index, not head) linking the next node. if (runNode->prev == (*leadNode) && runNode->next != NULL) { runNode->prev->next = runNode->next; runNode->next->prev = runNode->prev; } // if the node found is the head node linking nothing.(the head node existing alone) else if (runNode->prev == runNode && runNode->next == runNode) { (*leadNode) = NULL; } // if the node found is in the middle of the list. else if (runNode->next != NULL && runNode->prev != NULL) { runNode->prev->next = runNode->next; runNode->next->prev = runNode->prev; } dcll_deleteNode(runNode); return ; } runNode = runNode->next; } while (runNode != (*leadNode)); if (runNode->data == removeNode->data) { // if the node found is the tail node if (runNode == *leadNode) { runNode->prev->next = runNode->next; runNode->next->prev = runNode->prev; (*leadNode) = runNode->prev; dcll_deleteNode(runNode); return ; } } } // after iteration finished, if the node not found. perror("tried to search to remove the node. However, no node to remove found.\n"); } void dcll_addNodeFirst(DCLLNode** leadNode, DCLLNode* newNode) { // if there is no head node. if ((*leadNode) == NULL) { (*leadNode) = newNode; newNode->next = newNode; newNode->prev = newNode; } // if there is alerady head node linking to nothing. else if ((*leadNode)->prev == (*leadNode) && (*leadNode)->next == (*leadNode)) { newNode->next = (*leadNode); newNode->prev = (*leadNode); (*leadNode)->next = newNode; (*leadNode)->prev = newNode; } // if there is already head node linking to next node. else { newNode->next = (*leadNode)->next; (*leadNode)->next->prev = newNode; (*leadNode)->next = newNode; newNode->prev = (*leadNode); } } void dcll_addNodeLast(DCLLNode** leadNode, DCLLNode* newNode) { // if there is no head node. if ((*leadNode) == NULL) { perror("there is no head node to link, please DCLL_addNodeFirst before using it.\n"); return ; } // else, good to go. else { newNode->next = (*leadNode)->next; (*leadNode)->next->prev = newNode; (*leadNode)->next = newNode; newNode->prev = (*leadNode); *leadNode = newNode; } } void dcll_addNodeAfter(DCLLNode* currentNode, DCLLNode* newNode) { // if there is no-node specified to link. if ((currentNode) == NULL) { perror("there is no node specified to link, please create node before linking.\n"); return ; } // Otherwise, else { newNode->prev = currentNode; newNode->next = currentNode->next; currentNode->next->prev = newNode; currentNode->next = newNode; } } void dcll_printAllDCLL(DCLLNode* leadNode) { DCLLNode* runNode = NULL; if (leadNode == NULL) { return ; } else { leadNode = leadNode->next; } runNode = leadNode; do { printf("%d ", runNode->data); runNode = runNode->next; } while (runNode != leadNode); printf("\n"); } void dcll_traverse(DCLLNode* leadNode) { printf("DCLL traverse begins!\n"); DCLLNode* runNode = NULL; if (leadNode == NULL) { return ; } else { leadNode = leadNode->next; } runNode = leadNode; do { printf("%d ", runNode->data); runNode = runNode->next; } while (runNode != leadNode); printf("\n"); } void dcll_reverseTraverse(DCLLNode* tailNode) { printf("DCLL reverse-traverse begins!\n"); DCLLNode* runNode = tailNode; do { printf("%d ", runNode->data); runNode = runNode->prev; } while (runNode != tailNode); printf("\n"); } void dcll_addNodeBefore(DCLLNode** currentNode, DCLLNode* newNode) { // if there is no-node specified to link. if ((currentNode) == NULL) { perror("there is no node specified to link, please create node before linking.\n"); return ; } // Otherwise, good to go. else { newNode->next = (*currentNode); newNode->prev = (*currentNode)->prev; (*currentNode)->prev->next = newNode; (*currentNode)->prev = newNode; } }
C
#include <netdb.h> #include <netinet/in.h> #include <stdio.h> #include <strings.h> #include <stdlib.h> #include <unistd.h> #include <getopt.h> #include <arpa/inet.h> #include <ctype.h> #include <string.h> #include <sys/socket.h> #include <pthread.h> #include <sys/stat.h> #include <sys/sendfile.h> #include <fcntl.h> #include <errno.h> /* CONSTANTS ============================================================ */ #define SOCKET_ERROR -1 #define BUFFER_SIZE 1024 /* pthread var ========================================================== */ pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t bossCond = PTHREAD_COND_INITIALIZER; pthread_cond_t workerCond = PTHREAD_COND_INITIALIZER; /* Options =============================================================== */ char *filePath = "."; int portNum = 8888; int threadNum = 1; /* Linked list constructor =============================================== */ struct linked_list { int val; struct linked_list *next; }; struct linked_list *head = NULL; struct linked_list *curr = NULL; struct linked_list* create_list(int val) { //printf("\n Creating list with headnode as [%d]\n",val); struct linked_list *ptr = (struct linked_list*)malloc(sizeof(struct linked_list)); if(NULL == ptr) { printf("\n Node creation failed \n"); return NULL; } ptr->val = val; ptr->next = NULL; head = ptr; curr = ptr; return ptr; } struct linked_list* add_to_list(int val) { if(NULL == head) { return (create_list(val)); } //printf("\n Adding list with headnode as [%d]\n",val); struct linked_list *ptr = (struct linked_list*)malloc(sizeof(struct linked_list)); if(NULL == ptr) { printf("\n Node creation failed \n"); return NULL; } ptr->val = val; ptr->next = NULL; curr->next = ptr; curr = ptr; return ptr; } int is_empty (void){ if(NULL == head) { return 1; } else { return 0; } } int delete_from_list(void) { struct linked_list *ptr = head; if(NULL == head) { return -1; } int result = head->val; ptr = head->next; head = ptr; return result; } /************************************ Worker function ***********************************/ void print_usage() { printf("Usage: webserver [options]\n"); printf("-p path to file (Default: .)\n"); printf("-p server port (Default: 8888)\n"); printf("-t number of worker threads (Default: 1, Range: 1-1000)\n"); printf("-h show help message\n"); } void *worker(void *threadarg){ while(1){ /* get the file name from the client */ struct stat stat_buf; /* argument to fstat */ off_t offset = 0; /* file offset */ char request[50]; /* filename to send */ int received; /* holds return code of system calls */ pthread_mutex_lock(&mtx); while(is_empty()) { pthread_cond_wait(&workerCond, &mtx); } int client_socket_fd = delete_from_list(); pthread_mutex_unlock(&mtx); pthread_cond_signal(&bossCond); received = recv(client_socket_fd, request, sizeof(request), 0); if (received == -1) { fprintf(stderr, "ERROR: recv failed: %s\n", strerror(errno)); exit(1); } printf("INFO: %s\n", request); char *temp_name = malloc(sizeof(temp_name)); strtok(request, " "); strtok(NULL, " "); temp_name = strdup(strtok(NULL, " ")); /* null terminate and strip any \r and \n from temp_name */ if (temp_name[strlen(temp_name)-1] == '\n') temp_name[strlen(temp_name)-1] = '\0'; if (temp_name[strlen(temp_name)-1] == '\r') temp_name[strlen(temp_name)-1] = '\0'; char * filename = malloc(snprintf(NULL, 0, "%s%s", filePath, temp_name) + 1); sprintf(filename, "%s%s", filePath, temp_name); printf("INFO: received request to send file %s\n", filename); /* open the file to be sent */ int fd = open(filename, O_RDONLY); char status[100]; if (fd == -1) { snprintf(status, sizeof(status), "GetFile FILE_NOT_FOUND 0 0"); write(client_socket_fd, status, sizeof(status)+1); fprintf(stderr, "ERROR: Cannot open requested file %s\n", filename); fprintf(stderr, "ERROR: Closing the socket\n"); } else { /* get the size of the file to be sent */ fstat(fd, &stat_buf); sprintf(status, "GetFile OK %d",(int)stat_buf.st_size); write(client_socket_fd, status, sizeof(status)+1); int remain_data = (int)stat_buf.st_size; int sent_bytes = 0; int total = 0; while (((sent_bytes = sendfile(client_socket_fd, fd, &offset, BUFFER_SIZE)) > 0) && (remain_data > 0)) { remain_data -= sent_bytes; total += sent_bytes; //fprintf(stdout, "Server has sent %d bytes from file's data, remaining data = %d\n", total, remain_data); } /* close socket */ printf("INFO: Sent %d bytes, Closing the socket\n", total); } close(fd); if(close(client_socket_fd) == SOCKET_ERROR) { printf("INFO: Could not close socket\n"); exit(1); } } } int main(int argc, char *argv[]) { printf("===== Hello, I am the web server =====\n"); int option = 0; while ((option = getopt(argc, argv,"hp:t:f:")) != -1) { switch (option) { case 'p': portNum = atoi(optarg); printf ("ARG: Port number is '%s'\n", optarg); break; case 't' : threadNum = atoi(optarg); threadNum = threadNum > 100 ? 100 : threadNum; threadNum = threadNum < 1 ? 1 : threadNum; printf ("ARG: Thread number is '%d'\n", threadNum); break; case 'f' : filePath = optarg; printf ("ARG: File path is '%s'\n", optarg); break; case 'h': print_usage(); exit (0); default: print_usage(); } } /* Thread initiation */ pthread_t threads[threadNum]; int i; for(i = 0; i < threadNum; i++) { pthread_create(&threads[i],NULL,worker,NULL); } /* Server initiation */ int socket_fd = 0; struct sockaddr_in server; struct sockaddr_in client; int client_addr_len = sizeof(client); int client_socket_fd; printf("INFO: Starting server\n"); printf("INFO: Making socket\n"); /* make a server socket */ ; if( (socket_fd=socket(AF_INET,SOCK_STREAM,0)) == SOCKET_ERROR ) { fprintf(stderr, "ERROR: Could not make a socket\n"); exit(1); } server.sin_addr.s_addr=htonl(INADDR_ANY); server.sin_port=htons(portNum); server.sin_family=AF_INET; /* Binding to port */ printf("INFO: Binding to port %d\n",portNum); if(bind(socket_fd,(struct sockaddr*)&server,sizeof(server)) == SOCKET_ERROR) { fprintf(stderr, "ERROR: Could not connect to host\n"); exit(1); } /* Listening to port */ if ( listen(socket_fd, threadNum) == SOCKET_ERROR ) { fprintf(stderr, "ERROR: Server could not listen to port %d\n", portNum); exit(1); } else { printf("INFO: server listening for a connection on port %d\n", portNum); } while (1){ pthread_mutex_lock(&mtx); printf("INFO: Waiting for a connection\n"); while(is_empty() == 0) { pthread_cond_wait (&bossCond, &mtx); } if( (client_socket_fd=accept(socket_fd,(struct sockaddr*)&client,(socklen_t *)&client_addr_len)) == SOCKET_ERROR ){ fprintf(stderr, "ERROR: Connection cannot be accepted\n"); } else { printf("INFO: Got a connection from %s on port %d\n", inet_ntoa(client.sin_addr), htons(client.sin_port)); } add_to_list(client_socket_fd); pthread_mutex_unlock(&mtx); pthread_cond_broadcast(&workerCond); } }
C
// slot.c - code to handle/schedule slot controllers // part of the robot.o robot process // InMotion2 robot system software // Copyright 2003-2013 Interactive Motion Technologies, Inc. // Watertown, MA, USA // http://www.interactive-motion.com // All rights reserved #include "rtl_inc.h" #include "ruser.h" #include "robdecls.h" // args: id, init, term, incr, fn, tag. // (init, term, incr) order a la C for loop. // args must be unsigned. // // if you want backwards stepping, do the math yourself, // with term - i // // to do 10 samples: // slot(sid, 0, 10, 0, fnid); // // to do 10 seconds: // slot(sid, 0, 10*ob->Hz, 1, fnid); // // to do until done: // slot(sid, 0, 1, 0, fnid); // (and set ob->slot.i when you're done). // set ob->slot_max by hand. // if you have one slot, with id=0, set slot_max to 1. // chaining slot controllers? // when you are finished, replace yourself with a new one? // call ob->slot_fns[ob->slot[id].fnid](id) // if slot is active. // // note the if statement comparing i < term. // this means that if i==0 and term==10, [0,10) // the interval is half-closed, i goes from 0 to 9, // in usual C for loop fashion. // if you want a different range, you can get it by setting // i and term as you wish, or by hacking your controller. void do_slot(void) { u32 id; u32 i; u32 zero_force; u32 ran_slot; // if we don't run any slots, make sure that motor_force // is zeroed here, so that it doesn't have vestigal values from a // previous cycle's safety damping etc. ran_slot = 0; zero_force = 0; // if slot_max ivcfs too big, then don't run slots if (ob->slot_max > 8) { ob->slot_max = 0; } // for each slot[i] for (id = 0; id < ob->slot_max; id++) { // don't assign intermediate values to ob->slot[id].i i = ob->slot[id].i; // did user ask to stop? if (ob->slot[id].running == 0) { // don't run it. continue; } // is fnid outside the slot_fns array? if (ob->slot[id].fnid >= 32) { // yes, something is wrong. zero_force = 1; break; } // if there is a function for it in slot_fns if (ob->slot_fns[ob->slot[id].fnid]) { // call it with id as parameter. ob->slot_fns[ob->slot[id].fnid] (id); ran_slot++; } // post-increment i i += ob->slot[id].incr; // when you get to the end of the slot, // let it run until canceled, with i = term. if (i > ob->slot[id].term) { i = ob->slot[id].term; // count samples after term, // in case you want to increase stiffness or something. ob->slot[id].termi++; } ob->slot[id].i = i; } if (zero_force || !ran_slot) { set_zero_torque(); } } void stop_slot(u32 id) { memset(&(ob->slot[id]), 0, sizeof(Slot)); } void stop_all_slots(void) { u32 id; for (id = 0; id < 8; id++) stop_slot(id); }
C
//Bible //How to pray? //Book of John //Learn C //Calculus //Teach yourself PHP // // One storage. Use pointer to just point to this storage. #include <stdio.h> int main(void) { char *books[] = { "Bible", "Learn C", "How to pray?", "Calculus", "Book of John", "Teach yourself PHP" }; char **ChristianBooks[3]; char **TextBooks[3]; int i; ChristianBooks[0] = &books[0]; ChristianBooks[1] = &books[2]; ChristianBooks[2] = &books[4]; TextBooks[0] = &books[1]; TextBooks[1] = &books[3]; TextBooks[2] = &books[5]; for( i=0; i<3; i++ ) printf( "%s\n", *ChristianBooks[i] ); for( i=0; i<3; i++ ) printf( "%s\n", *TextBooks[i] ); return 0; }
C
#include <stdio.h> #include <math.h> double delta(double a, double b, double c){ return (b*b) - 4*a*c; } int bhaskara(double a, double b, double c){ double x1, x2; double d = delta(a, b, c); if(d > 0){ x1 = (-b + sqrt(d))/(2*a); x2=(-b - sqrt(d))/(2*a); printf("%.2lf %.2lf\n", x1, x2); } else if(d == 0){ x1 = -b/(2*a); printf("%.2lf\n", x1); } else if(d < 0){ x1 = -b/(2*a); x2 = sqrt(-d)/(2*a); printf("%.2lf + %.2lfi %.2lf - %.2lfi\n", x1, x2, x1, x2); } return 0; } int main(){ double a, b, c; scanf("%lf %lf %lf", &a, &b, &c); bhaskara(a, b, c); return 0; }
C
#include <stdio.h> #include <string.h> #define STUNUMBER 20 char stu_data_file[] = "E:\\GitHub\\C_Learn_Demo\\student.dat"; /* ---学生结构体--- */ typedef struct{ char name[20]; char stuno[20]; double height; double weight; double chinese; double math; double english; } student; /* ---学生成绩数据--- */ student StuDat[STUNUMBER]; /* ---学生长度--- */ int StuLength=0; /* ---初始化学生数据--- */ void init_stu_data(void) { FILE *fp; int ninzu = 0; /* 人数 */ char name[20]; /* 姓名 */ char stuno[20]; /* 学号 */ double height,weight,chinese,math,english; /* 身高,体重,语文,数学,英语 */ double hsum = 0.0 ;/* 身高合计 */ double wsum = 0.0 ;/* 体重合计 */ double csum = 0.0 ; /* 语文成绩全合计 */ double msum = 0.0 ; /*数学成绩合计*/ double esum = 0.0 ;/* 英语成绩合计 */ double total = 0.0; int i=0; if((fp=fopen(stu_data_file,"r"))==NULL) printf("\aFile open failed!\n"); else{ while(fscanf(fp,"%s %s %lf %lf %lf %lf %lf",name,stuno,&height,&weight,&chinese,&math,&english)==7) { student st; strcpy(st.name,name); strcpy(st.stuno,stuno); st.height = height; st.weight = weight; st.chinese = chinese; st.math = math; st.english = english; StuDat[i] = st; i++; } } StuLength = i; } /* ---显示学生信息--- */ void get_stu_data(void){ printf("Name StuNo Height Weight Chinese Math English Total\n"); for(int index = 0;index < StuLength;index++){ printf("%-16s%-9s%-10.1f%-10.1f%-11.1f%-8.1f%-11.1f%-9.1f\n",StuDat[index].name,StuDat[index].stuno,StuDat[index].height,StuDat[index].weight,StuDat[index].chinese,StuDat[index].math,StuDat[index].english,StuDat[index].chinese+StuDat[index].math+StuDat[index].english); } } /* ---更新所有学生数据--- */ void update_stu_data(){ //ToDO:1.判断是否已达最大班级人数 FILE *fp; int ninzu = 0; /* 人数 */ char name[20]; /* 姓名 */ char stuno[20]; /* 学号 */ double height,weight,chinese,math,english; /* 身高,体重,语文,数学,英语 */ double hsum = 0.0 ;/* 身高合计 */ double wsum = 0.0 ;/* 体重合计 */ double csum = 0.0 ; /* 语文成绩全合计 */ double msum = 0.0 ; /*数学成绩合计*/ double esum = 0.0 ;/* 英语成绩合计 */ if((fp=fopen(stu_data_file,"w"))==NULL) printf("\aFile open failed!\n"); else{ for(int index = 0;index < StuLength;index++){ fprintf(fp,"%s %s %lf %lf %lf %lf %lf",StuDat[index].name,StuDat[index].stuno,StuDat[index].height,StuDat[index].weight,StuDat[index].chinese,StuDat[index].math,StuDat[index].english); } fclose(fp); } } void update_one_stu(student new){ int result = 0; for(int index = 0;index < StuLength;index++){ if(strcmp(StuDat[index].stuno,new.stuno)==0){ result = 1; strcpy(StuDat[index].name,new.name); StuDat[index].height = new.height; StuDat[index].weight = new.weight; StuDat[index].chinese = new.chinese; StuDat[index].math = new.math; StuDat[index].english = new.english; } } if(result == 1){ update_stu_data(); } } /* ---删除学生信息,1 删除成功 0 学生不存在---*/ int del_stu_data(char *no){ int result = 0; int index = 0; student s; for(;index < StuLength;index++){ if(result == 1) { StuDat[index-1] = StuDat[index]; } if(strcmp(StuDat[index].stuno,no)==0){ result = 1; } } if(result == 1){ StuDat[index] = s; StuLength--; update_stu_data(); } return result; } /* ---判断学生是否存在 1 存在 0 不存在--- */ int exsit_stu(char *no) { int result = 0; for(int index = 0;index < StuLength;index++){ if(strcmp(StuDat[index].stuno,no)==0){ result = 1; break; } } return result; } /* ---对x和y指向的学生进行交换--- */ void swap(student *x,student *y) { student temp = *x; *x = *y; *y = temp; } /* ---对数组Data的前n个元素按身高进行降序排序--- */ void sort_height(student data[],int n){ int k = n-1; while(k>=0){ int i,j; for(i=1,j=-1;i<=k;i++){ if(data[i-1].height < data[i].height){ swap(&data[i-1],&data[i]); j = i-1; } } k = j; }; } /* ---对数组Data的前n个元素按体重进行降序排序--- */ void sort_weight(student data[],int n){ int k = n-1; while(k>=0){ int i,j; for(i=1,j=-1;i<=k;i++){ if(data[i-1].weight < data[i].weight){ swap(&data[i-1],&data[i]); j = i-1; } } k = j; }; } /* ---对数组Data的前n个元素按名称进行降序排序--- */ void sort_name(student data[],int n){ int k = n-1; while(k>=0){ int i,j; for(i=1,j=-1;i<=k;i++){ if(data[i-1].name < data[i].name){ swap(&data[i-1],&data[i]); j = i-1; } } k = j; }; } /* ---对数组Data的前n个元素按学号进行降序排序--- */ void sort_stuno(student data[],int n){ int k = n-1; while(k>=0){ int i,j; for(i=1,j=-1;i<=k;i++){ if(data[i-1].stuno < data[i].stuno){ swap(&data[i-1],&data[i]); j = i-1; } } k = j; }; } /* ---对数组Data的前n个元素按语文成绩进行降序排序--- */ void sort_chinese(student data[],int n){ int k = n-1; while(k>=0){ int i,j; for(i=1,j=-1;i<=k;i++){ if(data[i-1].chinese < data[i].chinese){ swap(&data[i-1],&data[i]); j = i-1; } } k = j; }; } /* ---对数组Data的前n个元素按数学成绩进行降序排序--- */ void sort_math(student data[],int n){ int k = n-1; while(k>=0){ int i,j; for(i=1,j=-1;i<=k;i++){ if(data[i-1].math < data[i].math){ swap(&data[i-1],&data[i]); j = i-1; } } k = j; }; } /* ---对数组Data的前n个元素按英文成绩进行降序排序--- */ void sort_english(student data[],int n){ int k = n-1; while(k>=0){ int i,j; for(i=1,j=-1;i<=k;i++){ if(data[i-1].english < data[i].english){ swap(&data[i-1],&data[i]); j = i-1; } } k = j; }; } /* ---对数组Data的前n个元素按英文成绩进行降序排序--- */ void sort_total(student data[],int n){ int k = n-1; while(k>=0){ int i,j; for(i=1,j=-1;i<=k;i++){ if(data[i-1].english+data[i-1].math+data[i-1].chinese < data[i].english+data[i].math+data[i].chinese){ swap(&data[i-1],&data[i]); j = i-1; } } k = j; }; } /* ---学生排序--- */ void sort_stu_data(void) { int num; int flag = 0; /* ---学生成绩数据--- */ student StuDatTemp[STUNUMBER]; for(int i = 0;i<StuLength;i++){ strcpy(StuDatTemp[i].name,StuDat[i].name); strcpy(StuDatTemp[i].stuno,StuDat[i].stuno); StuDatTemp[i].height = StuDat[i].height; StuDatTemp[i].weight = StuDat[i].weight; StuDatTemp[i].chinese = StuDat[i].chinese; StuDatTemp[i].math = StuDat[i].math; StuDatTemp[i].english = StuDat[i].english; } printf("Please select the sort type!\n"); printf(" 1 by name;\n 2 by stuno;\n 3 by height;\n 4 by weight;\n 5 by chinese;\n 6 by math;\n 7 by english;\n 8 by total;\n"); scanf("%d",&num); switch(num){ case 1 : sort_name(StuDatTemp,StuLength); flag = 1; break; case 2 : sort_stuno(StuDatTemp,StuLength); flag = 1; break; case 3 : sort_height(StuDatTemp,StuLength); flag = 1; break; case 4 : sort_weight(StuDatTemp,StuLength); flag = 1; break; case 5 : sort_chinese(StuDatTemp,StuLength); flag = 1; break; case 6 : sort_math(StuDatTemp,StuLength); flag = 1; break; case 7 : sort_english(StuDatTemp,StuLength); flag = 1; break; case 8 : sort_total(StuDatTemp,StuLength); flag = 1; break; } if(flag ==1){ printf("\n------------------------------Show Data----------------------------\n"); printf("Name StuNo Height Weight Chinese Math English Total\n"); for(int index = 0;index < StuLength;index++){ printf("%-16s%-9s%-10.1f%-10.1f%-11.1f%-8.1f%-11.1f%-9.1f\n",StuDatTemp[index].name,StuDatTemp[index].stuno,StuDatTemp[index].height,StuDatTemp[index].weight,StuDatTemp[index].chinese,StuDatTemp[index].math,StuDatTemp[index].english,StuDatTemp[index].chinese+StuDatTemp[index].math+StuDatTemp[index].english); } } } /* ---添加学生数据--- */ void add_stu_data(void){ //ToDO:1.判断是否已达最大班级人数 if(STUNUMBER > StuLength){ FILE *fp; int ninzu = 0; /* 人数 */ char name[20]; /* 姓名 */ char stuno[20]; /* 学号 */ double height,weight,chinese,math,english; /* 身高,体重,语文,数学,英语 */ double hsum = 0.0 ;/* 身高合计 */ double wsum = 0.0 ;/* 体重合计 */ double csum = 0.0 ; /* 语文成绩全合计 */ double msum = 0.0 ; /*数学成绩合计*/ double esum = 0.0 ;/* 英语成绩合计 */ int flag = 1; if((fp=fopen(stu_data_file,"a"))==NULL) printf("\aFile open failed!\n"); else{ while(flag){ printf("Please input student name:"); scanf("%s",name); printf("Please input student No:"); scanf("%s",stuno); printf("Please input student Height:"); scanf("%lf",&height); printf("Please input student Weight:"); scanf("%lf",&weight); printf("Please input student Chinese:"); scanf("%lf",&chinese); printf("Please input student Math:"); scanf("%lf",&math); printf("Please input student English:"); scanf("%lf",&english); if(exsit_stu(stuno)){ printf("The student No: %s is exsit!Please input again!\n",stuno); }else{ student st; strcpy(st.name,name); strcpy(st.stuno,stuno); st.height = height; st.weight = weight; st.chinese = chinese; st.math = math; st.english = english; // TODO //1.检测数据合法性 //2.判断学生是否存在 //3.如果存在根据用户选择更新,放弃,重新输入 fprintf(fp,"%s %s %lf %lf %lf %lf %lf",name,stuno,height,weight,chinese,math,english); StuDat[StuLength] = st; StuLength++; flag = 0; } } fclose(fp); } }else{ printf("You can't add new student,because the number of students is max!"); } } int main(void) { int slct; char stuno[20]; char name[20]; /* 姓名 */ double height,weight,chinese,math,english; /* 身高,体重,语文,数学,英语 */ printf(" Welcome to student sorce system!\n"); //初始化学生数据 init_stu_data(); while(1){ printf("\n------------------------------Option Menu----------------------------\n"); printf(" 1.Input 1 to show student's sorce.\n"); printf(" 2.Input 2 to add student's sorce.\n"); printf(" 3.Input 3 to update student's sorce.\n"); printf(" 4.Input 4 to delete student's sorce.\n"); printf(" 5.Input 5 to sort and show student's sorce.\n"); printf(" 0.Input 0 to quit student sorce system.\n"); printf("------------------------------End Menu--------------------------------\n\n"); scanf("%d",&slct); if(slct==0){ printf("Quit student sorce system!\n"); break; }else if(slct==1){ printf("Show student's sorce!\n"); get_stu_data(); }else if(slct==2){ printf("Add student's sorce!\n"); add_stu_data(); }else if(slct==3){ printf("Please input the student no thant you want to update:"); scanf("%s",stuno); if(exsit_stu(stuno)==0){ printf("The student of no %s is not exsit!\n",stuno); }else{ printf("Please input student name:"); scanf("%s",name); printf("Please input student Height:"); scanf("%lf",&height); printf("Please input student Weight:"); scanf("%lf",&weight); printf("Please input student Chinese:"); scanf("%lf",&chinese); printf("Please input student Math:"); scanf("%lf",&math); printf("Please input student English:"); scanf("%lf",&english); student st; strcpy(st.name,name); strcpy(st.stuno,stuno); st.height = height; st.weight = weight; st.chinese = chinese; st.math = math; st.english = english; update_one_stu(st); } }else if(slct==4){ printf("Please input the student no thant you want to delete:"); scanf("%s",stuno); if(del_stu_data(stuno)==0){ printf("The student of no %s is not exsit!\n",stuno); } }else if(slct==5){ sort_stu_data(); } } return 0; }
C
#include<stdio.h> int main() { double c; scanf("%lf",&c); printf("%.2f\n",1.8*c+32); return 0; }
C
/* * Copyright (c) 2020 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "req_resp.h" #include "util.h" #include "gtpv2c_messages.h" /** * Encodes uint8_t value to buffer. * @param val * value to be encoded * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_uint8_t(uint8_t val, gtpv2c_buffer_t *buf) { gtpv2c_buf_memcpy(buf, &val, sizeof(uint8_t)); return sizeof(uint8_t); } /** * Encodes uint16_t value to buffer. * @param val * value to be encoded * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_uint16_t(uint16_t val, gtpv2c_buffer_t *buf) { val = htons(val); gtpv2c_buf_memcpy(buf, &val, sizeof(uint16_t)); return sizeof(uint16_t); } /** * Encodes uint32_t value to buffer. * @param val * value to be encoded * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_uint32_t(uint32_t val, gtpv2c_buffer_t *buf) { val = htonl(val); gtpv2c_buf_memcpy(buf, &val, sizeof(uint32_t)); return sizeof(uint32_t); } /** * Encodes seq number value to buffer. * @param val * value to be encoded * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_uint32_t_seq_no(uint32_t val, gtpv2c_buffer_t *buf) { uint8_t tmp[4]; tmp[0] = (val >> 16) & 0xff; tmp[1] = (val >> 8) & 0xff; tmp[2] = val & 0xff; tmp[3] = 0; gtpv2c_buf_memcpy(buf, &tmp, sizeof(uint32_t)); return sizeof(uint32_t); } /** * Encodes mbr value to buffer. * @param val * value to be encoded * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_uint64_t_mbr(uint64_t *val, gtpv2c_buffer_t *buf) { uint8_t tmp[MBR_BUF_SIZE]; tmp[0] = (*val >> 32) & 0xff; tmp[1] = (*val >> 24) & 0xff; tmp[2] = (*val >> 16) & 0xff; tmp[3] = (*val >> 8) & 0Xff; tmp[4] = (*val & 0Xff); gtpv2c_buf_memcpy(buf, tmp, MBR_BUF_SIZE); return MBR_BUF_SIZE; } /** * Encodes uint8_t array value to buffer. * @param val * value to be encoded * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_common_type(void *val, gtpv2c_buffer_t *buf, uint16_t val_len) { gtpv2c_buf_memcpy(buf, val, val_len); return val_len; } /** * Encodes gtpv2c header to buffer. * @param val * gtpv2c header value to be encoded * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_gtpv2c_header_t(gtpv2c_header_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; val->gtpc.message_len = htons(val->gtpc.message_len); gtpv2c_buf_memcpy(buf, &val->gtpc, sizeof(val->gtpc)); val->gtpc.message_len = ntohs(val->gtpc.message_len); if (val->gtpc.teid_flag) { encode_uint32_t(val->teid.has_teid.teid, buf); encode_uint32_t_seq_no(val->teid.has_teid.seq, buf); enc_len = GTPV2C_HEADER_LEN; } else { encode_uint32_t_seq_no(val->teid.has_teid.seq, buf); enc_len = GTPV2C_HEADER_LEN - sizeof(uint32_t); } return enc_len; } /** * Encodes ie header to buffer. * @param val * ie header * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_ie_header_t(ie_header_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_uint8_t(val->type, buf); enc_len += encode_uint16_t(val->len, buf); enc_len += encode_uint8_t(val->instance, buf); return enc_len; } /** * Encodes imsi to buffer. * @param val * imsi value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_imsi_ie_t(imsi_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_ie_header_t(&val->header, buf); /* TODO : Covert IMSI to tbcd format */ enc_len += encode_common_type(&val->imsi, buf, val->header.len); return enc_len; } /** * Encodes msisdn to buffer. * @param val * msisdn value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_msisdn_ie_t(msisdn_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_ie_header_t(&val->header, buf); enc_len += encode_common_type(&val->msisdn, buf, val->header.len); return enc_len; } /** * Encodes mei to buffer. * @param val * mei value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_mei_ie_t(mei_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_ie_header_t(&val->header, buf); enc_len += encode_common_type(&val->mei, buf, val->header.len); return enc_len; } /** * Encodes mcc-mnc to buffer. * @param val * mcc-mnc value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_mcc_mnc_t(mcc_mnc_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; uint8_t tmp[MNC_MCC_BUF_SIZE] = {0}; tmp[0] = val->mcc_digit_2 << 4 | val->mcc_digit_1; tmp[1] = val->mnc_digit_3 << 4 | val->mcc_digit_3; tmp[2] = val->mnc_digit_2 << 4 | val->mnc_digit_1; enc_len += encode_common_type(tmp, buf, MNC_MCC_BUF_SIZE); return enc_len; } /** * Encodes uli flags to buffer. * @param val * uli flags value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_uli_flags_t(uli_flags_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_common_type(val, buf, sizeof(*val)); return enc_len; } /** * Encodes ecgi to buffer. * @param val * ecgi value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_ecgi_t(ecgi_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_mcc_mnc_t(&(val->mcc_mnc), buf); enc_len += encode_uint32_t(val->eci, buf); return enc_len; } /** * Encodes tai to buffer. * @param val * tai value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_tai_t(tai_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_mcc_mnc_t(&(val->mcc_mnc), buf); enc_len += encode_uint16_t(val->tac, buf); return enc_len; } /** * Encodes uli to buffer. * @param val * uli value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_uli_ie_t(uli_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_ie_header_t(&val->header, buf); enc_len += encode_uli_flags_t(&val->flags, buf); if (val->flags.tai) enc_len += encode_tai_t(&val->tai, buf); if (val->flags.ecgi) enc_len += encode_ecgi_t(&val->ecgi, buf); /* TODO: Add handling for cgi, lai, sai, rai */ return enc_len; } /** * Encodes serving network to buffer. * @param val * serving network value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_serving_network_ie_t(serving_network_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_ie_header_t(&val->header, buf); enc_len += encode_mcc_mnc_t(&(val->mcc_mnc), buf); return enc_len; } /** * Encodes rat type to buffer. * @param val * rat type value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_rat_type_ie_t(rat_type_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_ie_header_t(&val->header, buf); enc_len += encode_uint8_t(val->rat_type, buf); return enc_len; } /* static int encode_indication_t(indication_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_common_type(val, buf, sizeof(*val)); return enc_len; } */ /** * Encodes indication to buffer. * @param val * indication value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_indication_ie_t(indication_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_ie_header_t(&val->header, buf); enc_len += encode_common_type(&val->indication_value, buf, val->header.len); return enc_len; } /** * Encodes fteid to buffer. * @param val * fteid value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_ftied_ie_t(fteid_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_ie_header_t(&val->header, buf); val->teid_gre = htonl(val->teid_gre); if (val->v4 == 1 && val->v6 == 1) { val->ip.ipv4.s_addr = htonl(val->ip.ipv4.s_addr); /* TODO: Covert ipv6 to network order */ } else if (val->v4 == 1) { val->ip.ipv4.s_addr = htonl(val->ip.ipv4.s_addr); } else if (val->v6 == 1) { /* TODO: Covert ipv6 to network order */ } enc_len += encode_common_type((uint8_t *)val + enc_len, buf, val->header.len); if (val->v4 == 1 && val->v6 == 1) { val->ip.ipv4.s_addr = ntohl(val->ip.ipv4.s_addr); /* TODO: Covert ipv6 to network order */ } else if (val->v4 == 1) { val->ip.ipv4.s_addr = ntohl(val->ip.ipv4.s_addr); } else if (val->v6 == 1) { /* TODO: Covert ipv6 to network order */ } return enc_len; } /** * Encodes apn to buffer. * @param val * apn value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_apn_ie_t(apn_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_ie_header_t(&val->header, buf); enc_len += encode_common_type(&val->apn, buf, val->header.len); return enc_len; } /** * Encodes ambr to buffer. * @param val * ambr value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_ambr_ie_t(ambr_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_ie_header_t(&val->header, buf); enc_len += encode_uint32_t(val->apn_ambr_ul, buf); enc_len += encode_uint32_t(val->apn_ambr_dl, buf); return enc_len; } /** * Encodes selection mode to buffer. * @param val * selection mode value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_selection_mode_ie_t(selection_mode_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_ie_header_t(&val->header, buf); enc_len += encode_uint8_t(val->selec_mode, buf); return enc_len; } /** * Encodes pdn type to buffer. * @param val * pdn type value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_pdn_type_ie_t(pdn_type_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_ie_header_t(&val->header, buf); enc_len += encode_uint8_t(val->pdn_type, buf); return enc_len; } /** * Encodes PAA to buffer. * @param val * PAA value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_paa_ie_t(paa_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_ie_header_t(&val->header, buf); if (val->pdn_type == PDN_TYPE_IPV4) { val->ip_type.ipv4.s_addr = htonl(val->ip_type.ipv4.s_addr); } else if (val->pdn_type == PDN_TYPE_IPV6) { /* TODO: Covert ipv6 to network order */ } else if (val->pdn_type == PDN_TYPE_IPV4_IPV6) { val->ip_type.ipv4.s_addr = htonl(val->ip_type.ipv4.s_addr); /* TODO: Covert ipv6 to network order */ } enc_len += encode_common_type((uint8_t *)val + enc_len, buf, val->header.len); if (val->pdn_type == PDN_TYPE_IPV4) { val->ip_type.ipv4.s_addr = ntohl(val->ip_type.ipv4.s_addr); } else if (val->pdn_type == PDN_TYPE_IPV6) { /* TODO: Covert ipv6 to network order */ } else if (val->pdn_type == PDN_TYPE_IPV4_IPV6) { val->ip_type.ipv4.s_addr = ntohl(val->ip_type.ipv4.s_addr); /* TODO: Covert ipv6 to network order */ } return enc_len; } /** * Encodes apn restriction to buffer. * @param val * apn restriction value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_apn_restriction_ie_t(apn_restriction_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_ie_header_t(&val->header, buf); enc_len += encode_uint8_t(val->restriction_type, buf); return enc_len; } /** * Encodes pco to buffer. * @param val * pco value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_pco_ie_t(pco_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; uint16_t tempVal = IPCP_PROTO_CONT_ID; /* Populate CSResp PCO params in val*/ val->header.len = sizeof(pco_flags_t) + sizeof(proto_cont_t) + sizeof(ppp_ipcp_t); val->prtCnt.proto_cont_id = htons(tempVal); val->prtCnt.proto_cont_len = sizeof(ppp_ipcp_t); val->ipcp.len = sizeof(ppp_ipcp_t); val->ipcp.len = htons(val->ipcp.len); val->ipcp.secondary_dns_type = SECONDARY_DNS_IP; /* Encode the PCO block */ enc_len += encode_ie_header_t(&val->header, buf); enc_len += encode_common_type(&val->flags, buf, sizeof(pco_flags_t)); enc_len += encode_common_type(&val->prtCnt, buf, sizeof(proto_cont_t)); enc_len += encode_common_type(&val->ipcp, buf, sizeof(ppp_ipcp_t)); return enc_len; } /** * Encodes recovery to buffer. * @param val * recovery value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_recovery_ie_t(recovery_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_ie_header_t(&val->header, buf); enc_len += encode_uint8_t(val->restart_counter, buf); return enc_len; } /** * Encodes ue timezone to buffer. * @param val * ue timezone value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_ue_timezone_ie_t(ue_timezone_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_ie_header_t(&val->header, buf); enc_len += encode_uint8_t(val->timezone, buf); enc_len += encode_uint8_t(val->ds_time, buf); return enc_len; } /** * Encodes eps bearer id to buffer. * @param val * eps bearer id value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_eps_bearer_id_ie_t(eps_bearer_id_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_ie_header_t(&val->header, buf); enc_len += encode_uint8_t(val->eps_bearer_id, buf); return enc_len; } /** * Encodes pci,pl,pvi value to buffer. * @param val * pci, pl, pvi value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_pci_pl_pvi_t(pci_pl_pvi_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_common_type(val, buf, sizeof(*val)); return enc_len; } /** * Encodes charging characteristics to buffer. * @param val * charging characteristics value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_charging_char_ie_t(charging_char_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_ie_header_t(&val->header, buf); enc_len += encode_uint16_t(val->value, buf); return enc_len; } /** * Encodes bearer qos to buffer. * @param val * bearer qos value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_bearer_qos_ie_t(bearer_qos_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_ie_header_t(&val->header, buf); enc_len += encode_pci_pl_pvi_t(&(val->pci_pl_pvi), buf); enc_len += encode_uint8_t(val->label_qci, buf); enc_len += encode_uint64_t_mbr(&(val->maximum_bit_rate_for_uplink), buf); enc_len += encode_uint64_t_mbr(&(val->maximum_bit_rate_for_downlink), buf); enc_len += encode_uint64_t_mbr(&(val->guaranteed_bit_rate_for_uplink), buf); enc_len += encode_uint64_t_mbr(&(val->guaranteed_bit_rate_for_downlink), buf); return enc_len; } /** * Encodes bearer context to be created to buffer. * @param val * bearer context value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_bearer_context_to_be_created_ie_t( bearer_context_to_be_created_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_ie_header_t(&val->header, buf); enc_len += encode_eps_bearer_id_ie_t(&(val->ebi), buf); if (val->s11u_mme_fteid.header.len) enc_len += encode_ftied_ie_t(&(val->s11u_mme_fteid), buf); enc_len += encode_bearer_qos_ie_t(&(val->bearer_qos), buf); return enc_len; } /** * Encodes cause to buffer. * @param val * cause value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_cause_ie_t(cause_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_ie_header_t(&val->header, buf); enc_len += encode_common_type((uint8_t *)val + enc_len, buf, val->header.len); return enc_len; } /** * Encodes bearer context created to buffer. * @param val * bearer context value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_bearer_context_created_ie_t(bearer_context_created_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_ie_header_t(&val->header, buf); enc_len += encode_eps_bearer_id_ie_t(&(val->ebi), buf); enc_len += encode_cause_ie_t(&(val->cause), buf); enc_len += encode_ftied_ie_t(&(val->s1u_sgw_ftied), buf); enc_len += encode_ftied_ie_t(&(val->s5s8_pgw), buf); return enc_len; } /** * Encodes bearer context to be modified to buffer. * @param val * bearer context value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_bearer_context_to_be_modified_ie_t( bearer_context_to_be_modified_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_ie_header_t(&val->header, buf); enc_len += encode_eps_bearer_id_ie_t(&(val->ebi), buf); enc_len += encode_ftied_ie_t(&(val->s1u_enodeb_ftied), buf); return enc_len; } /** * Encodes bearer context modified to buffer. * @param val * bearer context value * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ static int encode_bearer_context_modified_ie_t(bearer_context_modified_ie_t *val, gtpv2c_buffer_t *buf) { uint16_t enc_len = 0; enc_len += encode_ie_header_t(&val->header, buf); enc_len += encode_cause_ie_t(&(val->cause), buf); enc_len += encode_eps_bearer_id_ie_t(&(val->ebi), buf); enc_len += encode_ftied_ie_t(&(val->s1u_sgw_ftied), buf); return enc_len; } /** * Encodes create session request to buffer. * @param val * create session request * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ int encode_create_session_request_t(create_session_request_t *val, uint8_t *msg, uint16_t *msg_len) { uint16_t enc_len = 0; gtpv2c_buffer_t buf = {0}; enc_len += encode_gtpv2c_header_t(&val->header, &buf); if (val->imsi.header.len) enc_len += encode_imsi_ie_t(&(val->imsi), &buf); if (val->msisdn.header.len) enc_len += encode_msisdn_ie_t(&(val->msisdn), &buf); if (val->mei.header.len) enc_len += encode_mei_ie_t(&(val->mei), &buf); if (val->uli.header.len) enc_len += encode_uli_ie_t(&(val->uli), &buf); if (val->serving_nw.header.len) enc_len += encode_serving_network_ie_t(&(val->serving_nw), &buf); if (val->rat_type.header.len) enc_len += encode_rat_type_ie_t(&(val->rat_type), &buf); if (val->indication.header.len) enc_len += encode_indication_ie_t(&(val->indication), &buf); if (val->sender_ftied.header.len) enc_len += encode_ftied_ie_t(&(val->sender_ftied), &buf); if (val->s5s8pgw_pmip.header.len) enc_len += encode_ftied_ie_t(&(val->s5s8pgw_pmip), &buf); if (val->apn.header.len) enc_len += encode_apn_ie_t(&(val->apn), &buf); if (val->seletion_mode.header.len) enc_len += encode_selection_mode_ie_t(&(val->seletion_mode), &buf); if (val->charging_characteristics.header.len) enc_len += encode_charging_char_ie_t(&(val->charging_characteristics), &buf); if (val->pdn_type.header.len) enc_len += encode_pdn_type_ie_t(&(val->pdn_type), &buf); if (val->paa.header.len) enc_len += encode_paa_ie_t(&(val->paa), &buf); if (val->apn_restriction.header.len) enc_len += encode_apn_restriction_ie_t(&(val->apn_restriction), &buf); if (val->ambr.header.len) enc_len += encode_ambr_ie_t(&(val->ambr), &buf); if (val->bearer_context.header.len) enc_len += encode_bearer_context_to_be_created_ie_t(&(val->bearer_context), &buf); if (val->recovery.header.len) enc_len += encode_recovery_ie_t(&(val->recovery), &buf); if (val->ue_timezone.header.len) enc_len += encode_ue_timezone_ie_t(&(val->ue_timezone), &buf); *msg_len = enc_len; memcpy(msg, buf.val, buf.len); return enc_len; } /** * Encodes create session response to buffer. * @param val * create session response * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ int encode_create_session_response_t(create_session_response_t *val, uint8_t *msg, uint16_t *msg_len) { uint16_t enc_len = 0; gtpv2c_buffer_t buf = {0}; enc_len += encode_gtpv2c_header_t(&(val->header), &buf); if (val->cause.header.len) enc_len += encode_cause_ie_t(&(val->cause), &buf); if (val->s11_ftied.header.len) enc_len += encode_ftied_ie_t(&(val->s11_ftied), &buf); if (val->pgws5s8_pmip.header.len) enc_len += encode_ftied_ie_t(&(val->pgws5s8_pmip), &buf); if (val->paa.header.len) enc_len += encode_paa_ie_t(&(val->paa), &buf); if (val->apn_restriction.header.len) enc_len += encode_apn_restriction_ie_t(&(val->apn_restriction), &buf); if (val->ambr.header.len) enc_len += encode_ambr_ie_t(&(val->ambr), &buf); if (val->pco.header.len) enc_len += encode_pco_ie_t(&(val->pco), &buf); if (val->bearer_context.header.len) enc_len += encode_bearer_context_created_ie_t(&(val->bearer_context), &buf); *msg_len = enc_len; memcpy(msg, buf.val, buf.len); return enc_len; } /** * Encodes modify bearer request to buffer. * @param val * modify bearer request * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ int encode_modify_bearer_request_t(modify_bearer_request_t *val, uint8_t *msg, uint16_t *msg_len) { uint16_t enc_len = 0; gtpv2c_buffer_t buf = {0}; enc_len += encode_gtpv2c_header_t(&(val->header), &buf); if (val->indication.header.len) enc_len += encode_indication_ie_t(&(val->indication), &buf); if (val->s11_mme_fteid.header.len) enc_len += encode_ftied_ie_t(&(val->s11_mme_fteid), &buf); if (val->bearer_context.header.len) enc_len += encode_bearer_context_to_be_modified_ie_t( &(val->bearer_context), &buf); *msg_len = enc_len; memcpy(msg, buf.val, buf.len); return enc_len; } /** * Encodes modify bearer response to buffer. * @param val * modify bearer response * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ int encode_modify_bearer_response_t(modify_bearer_response_t *val, uint8_t *msg, uint16_t *msg_len) { uint16_t enc_len = 0; gtpv2c_buffer_t buf = {0}; enc_len += encode_gtpv2c_header_t(&(val->header), &buf); if (val->cause.header.len) enc_len += encode_cause_ie_t(&(val->cause), &buf); if (val->bearer_context.header.len) enc_len += encode_bearer_context_modified_ie_t(&(val->bearer_context), &buf); *msg_len = enc_len; memcpy(msg, buf.val, buf.len); return enc_len; } /** * Encodes delete session request to buffer. * @param val * delete session request * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ int encode_delete_session_request_t(delete_session_request_t *val, uint8_t *msg, uint16_t *msg_len) { uint16_t enc_len = 0; gtpv2c_buffer_t buf = {0}; enc_len += encode_gtpv2c_header_t(&(val->header), &buf); if (val->linked_ebi.header.len) enc_len += encode_eps_bearer_id_ie_t(&(val->linked_ebi), &buf); if (val->indication_flags.header.len) enc_len += encode_indication_ie_t(&(val->indication_flags), &buf); *msg_len = enc_len; memcpy(msg, buf.val, buf.len); return enc_len; } /** * Encodes delete session response to buffer. * @param val * delete session response * @param buf * buffer to store encoded values. * @return * number of encoded bytes. */ int encode_delete_session_response_t(delete_session_response_t *val, uint8_t *msg, uint16_t *msg_len) { uint16_t enc_len = 0; gtpv2c_buffer_t buf = {0}; enc_len += encode_gtpv2c_header_t(&(val->header), &buf); if (val->cause.header.len) enc_len += encode_cause_ie_t(&(val->cause), &buf); *msg_len = enc_len; memcpy(msg, buf.val, buf.len); return enc_len; }
C
#define uint unsigned int struct node { struct node * rev; struct node * fwd; //only allow for int data //TODO: use generics? int value; }; typedef struct node Node; /* node operations */ void initNode (Node * p) { p->fwd = NULL; p->value = 0xDEADBEEF; p->rev = NULL; } void initNodeWithValue (Node * p, int v) { initNode(p); p->value = v; } Node * newNode () { Node * ret = malloc(sizeof(Node)); initNode(ret); return ret; } void destroyNode (Node * nodePtr) { Node * prev = nodePtr->rev; Node * next = nodePtr->fwd; //if this is not the first node in the list if (prev != NULL) { prev->fwd = next; } //if this is not the last node in the list if (next != NULL) { next->rev = prev; } free(nodePtr); return; }
C
#include<iostream> using namespace std; //Function to reverse the given array void reverseArray(int a[],int n){ int l=0; int r=n-1; while(l<r){ int temp=a[l]; a[l]=a[r]; a[r]=temp; l++; r--; } } //Function to print the elements of array void printArray(int a[],int n){ for(int i=0;i<n;i++){ cout<<a[i]<<"\t"; } } int main() { int a[]={10,5,36,85}; int n=sizeof(a)/sizeof(a[0]); cout<<"Input Array:"<<endl; printArray(a,n); reverseArray(a,n); cout<<"\nAfter reversal:"<<endl; printArray(a,n); return 0; }
C
#include "types.h" #include "user.h" #include "x86.h" #define PGSIZE 4096 int thread_create(void (*start_routine)(void*), void* arg) { void *stack = malloc(2 * PGSIZE); if ((uint)stack % PGSIZE != 0) stack += PGSIZE - (uint)stack % PGSIZE; return clone(start_routine, arg, stack); } int thread_join(int pid) { int ustack; if ((ustack = getstack(pid)) < 0) return -1; //find ustack, see definition in proc.c free((void*)ustack); return join(pid); } void lock_acquire(lock_t* lock) { while(xchg(lock, 1) != 0) ; } void lock_release(lock_t* lock) { xchg(lock, 0); } void lock_init(lock_t* lock) { *lock = 0; }
C
#include "header.h" void edge(char* address) { FILE* inputFile = NULL; inputFile = fopen(address, "rb"); fread(&bmpFile, sizeof(BITMAPFILEHEADER), 1, inputFile); fread(&bmpInfo, sizeof(BITMAPINFOHEADER), 1, inputFile); int width = bmpInfo.biWidth; int height = bmpInfo.biHeight; int size = bmpInfo.biSizeImage; // height * width * 3 (R,G,B) !!! int bitCnt = bmpInfo.biBitCount; int stride = (((bitCnt / 8) * width) + 3) / 4 * 4; // (width * 3) >> ȼ R,G,B 3 ֱ 3 ø unsigned char* inputImg = NULL; inputImg = (unsigned char*)calloc(size, sizeof(unsigned char)); fread(inputImg, sizeof(unsigned char), size, inputFile); unsigned char* outputImg = NULL, *outputImg2 = NULL, *outputImg3 = NULL; outputImg = (unsigned char*)calloc(size, sizeof(unsigned char)); outputImg2 = (unsigned char*)calloc(size, sizeof(unsigned char)); outputImg3 = (unsigned char*)calloc(size, sizeof(unsigned char)); // Y 迭 R,G,B ƴ϶ Y ϳ ϱ size / 3. // >>>> inputImg, outputImg ũ Y ũⰡ ٸ !!!!!!!!!!!!!! <<<< unsigned char* Y = NULL, * Y2 = NULL; Y = (unsigned char*)calloc(size / 3, sizeof(unsigned char)); Y2 = (unsigned char*)calloc(size / 3, sizeof(unsigned char)); for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { // Luminance input ޾ұ R, G, B Y . ƹų Y迭 . Y[j * width + i] = inputImg[j * stride + 3 * i + 0]; } } // padding width Y width ̴ ٸ! int psize = 1; int pheight = height + (2 * psize); int pwidth = width + (2 * psize); unsigned char* padding = NULL; // Ʒ psizeĭ е padding = (unsigned char*)calloc(pheight * pwidth, sizeof(unsigned char)); // padding Ʒ ä for (int i = 0; i < width; i++) { padding[i + psize] = Y[i]; padding[((pheight - 1) * pwidth) + (i + psize)] = Y[(height - 1) * width + i]; } // padding 翷 ä for (int j = 0; j < height; j++) { padding[(j + psize) * pwidth] = Y[j * width]; padding[(j + psize) * pwidth + (pwidth - 1)] = Y[j * width + (width - 1)]; } for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { padding[(j + psize) * pwidth + (i + psize)] = Y[j * width + i]; } } int pi, pj; double value; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { pj = j + psize; pi = i + psize; value = (padding[pj * pwidth + (pi + 1)] - padding[pj * pwidth + (pi - 1)]) / 2; value > 255 ? (value = 255) : (value < 0 ? (value = 0) : value); Y[j * width + i] = (unsigned char)value; value = (padding[(pj + 1) * pwidth + pi] - padding[(pj - 1) * pwidth + pi]) / 2; value > 255 ? (value = 255) : (value < 0 ? (value = 0) : value); Y2[j * width + i] = (unsigned char)value; } } for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { outputImg[j * stride + i * 3 + 0] = Y[j * width + i]; outputImg[j * stride + i * 3 + 1] = Y[j * width + i]; outputImg[j * stride + i * 3 + 2] = Y[j * width + i]; } } for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { outputImg2[j * stride + i * 3 + 0] = Y2[j * width + i]; outputImg2[j * stride + i * 3 + 1] = Y2[j * width + i]; outputImg2[j * stride + i * 3 + 2] = Y2[j * width + i]; } } int gx, gy; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { gx = Y[j * width + i]; gy = Y2[j * width + i]; value = sqrt(gx * gx + gy * gy); value > 255 ? (value = 255) : (value < 0 ? (value = 0) : value); outputImg3[j * stride + i * 3 + 0] = (unsigned char)value; outputImg3[j * stride + i * 3 + 1] = (unsigned char)value; outputImg3[j * stride + i * 3 + 2] = (unsigned char)value; } } FILE* outputFile = fopen("./image/Output_Gx.bmp", "wb"); fwrite(&bmpFile, sizeof(BITMAPFILEHEADER), 1, outputFile); fwrite(&bmpInfo, sizeof(BITMAPINFOHEADER), 1, outputFile); fwrite(outputImg, sizeof(unsigned char), size, outputFile); outputFile = fopen("./image/Output_Gy.bmp", "wb"); fwrite(&bmpFile, sizeof(BITMAPFILEHEADER), 1, outputFile); fwrite(&bmpInfo, sizeof(BITMAPINFOHEADER), 1, outputFile); fwrite(outputImg2, sizeof(unsigned char), size, outputFile); outputFile = fopen("./image/Output_Edge.bmp", "wb"); fwrite(&bmpFile, sizeof(BITMAPFILEHEADER), 1, outputFile); fwrite(&bmpInfo, sizeof(BITMAPINFOHEADER), 1, outputFile); fwrite(outputImg3, sizeof(unsigned char), size, outputFile); free(outputImg); free(outputImg2); free(outputImg3); fclose(outputFile); free(inputImg); fclose(inputFile); free(Y); free(Y2); free(padding); } void sobel_edge(char* address) { FILE* inputFile = NULL; inputFile = fopen(address, "rb"); fread(&bmpFile, sizeof(BITMAPFILEHEADER), 1, inputFile); fread(&bmpInfo, sizeof(BITMAPINFOHEADER), 1, inputFile); int width = bmpInfo.biWidth; int height = bmpInfo.biHeight; int size = bmpInfo.biSizeImage; // height * width * 3 (R,G,B) !!! int bitCnt = bmpInfo.biBitCount; int stride = (((bitCnt / 8) * width) + 3) / 4 * 4; // (width * 3) >> ȼ R,G,B 3 ֱ 3 ø unsigned char* inputImg = NULL; inputImg = (unsigned char*)calloc(size, sizeof(unsigned char)); fread(inputImg, sizeof(unsigned char), size, inputFile); unsigned char* outputImg = NULL, * outputImg2 = NULL, * outputImg3 = NULL; outputImg = (unsigned char*)calloc(size, sizeof(unsigned char)); outputImg2 = (unsigned char*)calloc(size, sizeof(unsigned char)); outputImg3 = (unsigned char*)calloc(size, sizeof(unsigned char)); // Y 迭 R,G,B ƴ϶ Y ϳ ϱ size / 3. // >>>> inputImg, outputImg ũ Y ũⰡ ٸ !!!!!!!!!!!!!! <<<< unsigned char* Y = NULL, * Y2 = NULL; Y = (unsigned char*)calloc(size / 3, sizeof(unsigned char)); Y2 = (unsigned char*)calloc(size / 3, sizeof(unsigned char)); for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { // Luminance input ޾ұ R, G, B Y . ƹų Y迭 . Y[j * width + i] = inputImg[j * stride + 3 * i + 0]; } } // padding width Y width ̴ ٸ! int psize = 1; int pheight = height + (2 * psize); int pwidth = width + (2 * psize); unsigned char* padding = NULL; // Ʒ psizeĭ е padding = (unsigned char*)calloc(pheight * pwidth, sizeof(unsigned char)); // padding Ʒ ä for (int i = 0; i < width; i++) { padding[i + psize] = Y[i]; padding[((pheight - 1) * pwidth) + (i + psize)] = Y[(height - 1) * width + i]; } // padding 翷 ä for (int j = 0; j < height; j++) { padding[(j + psize) * pwidth] = Y[j * width]; padding[(j + psize) * pwidth + (pwidth - 1)] = Y[j * width + (width - 1)]; } for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { padding[(j + psize) * pwidth + (i + psize)] = Y[j * width + i]; } } // *************************************************************** int filter_x[3][3] = { {-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1} }; int filter_y[3][3] = { {-1, -2, -1}, {0, 0, 0}, {1, 2, 1} }; int pi, pj; double value = 0; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { pi = psize + i; pj = psize + j; value = 0; for (int k = 0; k < 3; k++) { for (int c = 0; c < 3; c++) { value += (filter_x[k][c] * (double)padding[(pj - 1 + k) * pwidth + (pi - 1 + c)]); } } value > 255 ? (value = 255) : (value < 0 ? (value = 0) : value); Y[j * width + i] = (unsigned char)value; value = 0; for (int k = 0; k < 3; k++) { for (int c = 0; c < 3; c++) { value += (filter_y[k][c] * (double)padding[(pj - 1 + k) * pwidth + (pi - 1 + c)]); } } value > 255 ? (value = 255) : (value < 0 ? (value = 0) : value); Y2[j * width + i] = (unsigned char)value; } } for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { outputImg[j * stride + i * 3 + 0] = Y[j * width + i]; outputImg[j * stride + i * 3 + 1] = Y[j * width + i]; outputImg[j * stride + i * 3 + 2] = Y[j * width + i]; } } for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { outputImg2[j * stride + i * 3 + 0] = Y2[j * width + i]; outputImg2[j * stride + i * 3 + 1] = Y2[j * width + i]; outputImg2[j * stride + i * 3 + 2] = Y2[j * width + i]; } } double gx, gy; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { gx = (double)Y[j * width + i]; gy = (double)Y2[j * width + i]; value = sqrt(pow(gx, 2) + pow(gy, 2)); value > 255 ? (value = 255) : (value < 0 ? (value = 0) : value); outputImg3[j * stride + i * 3 + 0] = (unsigned char)value; outputImg3[j * stride + i * 3 + 1] = (unsigned char)value; outputImg3[j * stride + i * 3 + 2] = (unsigned char)value; } } FILE* outputFile = fopen("./image/Output_sobel_Gx.bmp", "wb"); fwrite(&bmpFile, sizeof(BITMAPFILEHEADER), 1, outputFile); fwrite(&bmpInfo, sizeof(BITMAPINFOHEADER), 1, outputFile); fwrite(outputImg, sizeof(unsigned char), size, outputFile); outputFile = fopen("./image/Output_sobel_Gy.bmp", "wb"); fwrite(&bmpFile, sizeof(BITMAPFILEHEADER), 1, outputFile); fwrite(&bmpInfo, sizeof(BITMAPINFOHEADER), 1, outputFile); fwrite(outputImg2, sizeof(unsigned char), size, outputFile); outputFile = fopen("./image/Output_sobel_Edge.bmp", "wb"); fwrite(&bmpFile, sizeof(BITMAPFILEHEADER), 1, outputFile); fwrite(&bmpInfo, sizeof(BITMAPINFOHEADER), 1, outputFile); fwrite(outputImg3, sizeof(unsigned char), size, outputFile); free(outputImg); free(outputImg2); free(outputImg3); fclose(outputFile); free(inputImg); fclose(inputFile); free(Y); free(Y2); free(padding); } void prewitt_edge(char* address) { FILE* inputFile = NULL; inputFile = fopen(address, "rb"); fread(&bmpFile, sizeof(BITMAPFILEHEADER), 1, inputFile); fread(&bmpInfo, sizeof(BITMAPINFOHEADER), 1, inputFile); int width = bmpInfo.biWidth; int height = bmpInfo.biHeight; int size = bmpInfo.biSizeImage; // height * width * 3 (R,G,B) !!! int bitCnt = bmpInfo.biBitCount; int stride = (((bitCnt / 8) * width) + 3) / 4 * 4; // (width * 3) >> ȼ R,G,B 3 ֱ 3 ø unsigned char* inputImg = NULL; inputImg = (unsigned char*)calloc(size, sizeof(unsigned char)); fread(inputImg, sizeof(unsigned char), size, inputFile); unsigned char* outputImg = NULL; outputImg = (unsigned char*)calloc(size, sizeof(unsigned char)); // Y 迭 R,G,B ƴ϶ Y ϳ ϱ size / 3. // >>>> inputImg, outputImg ũ Y ũⰡ ٸ !!!!!!!!!!!!!! <<<< unsigned char* Y = NULL, * Y2 = NULL; Y = (unsigned char*)calloc(size / 3, sizeof(unsigned char)); Y2 = (unsigned char*)calloc(size / 3, sizeof(unsigned char)); for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { // Luminance input ޾ұ R, G, B Y . ƹų Y迭 . Y[j * width + i] = inputImg[j * stride + 3 * i + 0]; } } // padding width Y width ̴ ٸ! int psize = 1; int pheight = height + (2 * psize); int pwidth = width + (2 * psize); unsigned char* padding = NULL; // Ʒ psizeĭ е padding = (unsigned char*)calloc(pheight * pwidth, sizeof(unsigned char)); // padding Ʒ ä for (int i = 0; i < width; i++) { padding[i + psize] = Y[i]; padding[((pheight - 1) * pwidth) + (i + psize)] = Y[(height - 1) * width + i]; } // padding 翷 ä for (int j = 0; j < height; j++) { padding[(j + psize) * pwidth] = Y[j * width]; padding[(j + psize) * pwidth + (pwidth - 1)] = Y[j * width + (width - 1)]; } for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { padding[(j + psize) * pwidth + (i + psize)] = Y[j * width + i]; } } // *************************************************************** int filter_x[3][3] = { {-1, 0, 1}, {-1, 0, 1}, {-1, 0, 1} }; int filter_y[3][3] = { {-1, -1, -1}, {0, 0, 0}, {1, 1, 1} }; int pi, pj; double value = 0; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { pi = psize + i; pj = psize + j; value = 0; for (int k = 0; k < 3; k++) { for (int c = 0; c < 3; c++) { value += (filter_x[k][c] * (double)padding[(pj - 1 + k) * pwidth + (pi - 1 + c)]); } } value > 255 ? (value = 255) : (value < 0 ? (value = 0) : value); Y[j * width + i] = (unsigned char)value; value = 0; for (int k = 0; k < 3; k++) { for (int c = 0; c < 3; c++) { value += (filter_y[k][c] * (double)padding[(pj - 1 + k) * pwidth + (pi - 1 + c)]); } } value > 255 ? (value = 255) : (value < 0 ? (value = 0) : value); Y2[j * width + i] = (unsigned char)value; } } double gx, gy; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { gx = (double)Y[j * width + i]; gy = (double)Y2[j * width + i]; value = sqrt(pow(gx, 2) + pow(gy, 2)); value > 255 ? (value = 255) : (value < 0 ? (value = 0) : value); outputImg[j * stride + i * 3 + 0] = (unsigned char)value; outputImg[j * stride + i * 3 + 1] = (unsigned char)value; outputImg[j * stride + i * 3 + 2] = (unsigned char)value; } } FILE* outputFile = fopen("./image/Output_prewitt_Gx.bmp", "wb"); fwrite(&bmpFile, sizeof(BITMAPFILEHEADER), 1, outputFile); fwrite(&bmpInfo, sizeof(BITMAPINFOHEADER), 1, outputFile); fwrite(outputImg, sizeof(unsigned char), size, outputFile); free(outputImg); fclose(outputFile); free(inputImg); fclose(inputFile); free(Y); free(Y2); free(padding); } void edge_thresholding(char* address, int thr) { FILE* inputFile = NULL; inputFile = fopen(address, "rb"); fread(&bmpFile, sizeof(BITMAPFILEHEADER), 1, inputFile); fread(&bmpInfo, sizeof(BITMAPINFOHEADER), 1, inputFile); int width = bmpInfo.biWidth; int height = bmpInfo.biHeight; int size = bmpInfo.biSizeImage; // height * width * 3 (R,G,B) !!! int bitCnt = bmpInfo.biBitCount; int stride = (((bitCnt / 8) * width) + 3) / 4 * 4; // (width * 3) unsigned char* inputImg = NULL; inputImg = (unsigned char*)calloc(size, sizeof(unsigned char)); fread(inputImg, sizeof(unsigned char), size, inputFile); unsigned char* outputImg = NULL; outputImg = (unsigned char*)calloc(size, sizeof(unsigned char)); unsigned char* Y = NULL; Y = (unsigned char*)calloc(size / 3, sizeof(unsigned char)); for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { Y[j * width + i] = inputImg[j * stride + 3 * i + 0]; } } int value; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { if ((int)Y[j * width + i] < thr) { value = 0; } else { value = Y[j * width + i]; } outputImg[j * stride + 3 * i + 0] = (unsigned char)value; outputImg[j * stride + 3 * i + 1] = (unsigned char)value; outputImg[j * stride + 3 * i + 2] = (unsigned char)value; } } FILE* outputFile = fopen("./image/Output_Edge_thresholding.bmp", "wb"); fwrite(&bmpFile, sizeof(BITMAPFILEHEADER), 1, outputFile); fwrite(&bmpInfo, sizeof(BITMAPINFOHEADER), 1, outputFile); fwrite(outputImg, sizeof(unsigned char), size, outputFile); free(outputImg); fclose(outputFile); free(inputImg); fclose(inputFile); free(Y); }
C
#include "bit-array.h" #include "hamming-code.h" #include "hamming_impl.h" size_t hamming_decode(bits_t *dst, bits_t *src) { size_t uncorrectable = 0; bit a, b, c, d, x, y, z, p; while (bitarray_size(src) >= 8) { a = bitarray_next_front(src); b = bitarray_next_front(src); c = bitarray_next_front(src); d = bitarray_next_front(src); x = bitarray_next_front(src); y = bitarray_next_front(src); z = bitarray_next_front(src); p = bitarray_next_front(src); uncorrectable += hamming84correct(&a, &b, &c, &d, &x, &y, &z, &p); bitarray_push_back(dst, a); bitarray_push_back(dst, b); bitarray_push_back(dst, c); bitarray_push_back(dst, d); } return uncorrectable; }
C
#include <stdarg.h> #include <stdio.h> #include "variadic_functions.h" /** * print_strings - prints strings followed by new line * @separator: string between strings * @n: number of strings passed to the function */ void print_strings(const char *separator, const unsigned int n, ...) { va_list vlist; unsigned int i; char *str; va_start(vlist, n); for (i = 0; i < n; i++) { str = va_arg(vlist, char*); if (str) { printf("%s", str); if (i != (n - 1) && separator) printf("%s", separator); } else { printf("(nil)"); if (i != (n - 1) && separator) printf("%s", separator); } } va_end(vlist); printf("\n"); }
C
#include "header.h" //================================================ // Name: countLessThan6Occurances // Input: int // Output: int // Author: Ganesh Narayan Jaiwal // Date: 4 Aug 2020 // Description: Count occurances of digits less that 6 //================================================ int countLessThan6Occurances(int no) { int cnt = 0; if (no < 0) { no = -no; } while (no > 0) { if (no % 10 < 6) { cnt++; } no /= 10; } return cnt; }
C
#include<stdio.h> #include<math.h> struct point { float x; float y; }p2,p1; double distance(struct point p3,struct point p4) { return sqrt(pow((p3.x-p4.x),2)+pow((p3.y-p4.y),2)); } int main() { double i; printf("enter the x co-ordinate and y co-ordinate"); scanf("%f%f",&p1.x,&p1.y); printf("enter the x co-ordinate and y co-ordinate"); scanf("%f%f",&p2.x,&p2.y); i=distance(p1,p2); printf("\ndistance is %f\n",i); return 0; }
C
/* Copyright (c) 2005 Russ Cox, MIT; see COPYRIGHT */ #include "taskimpl.h" #include <fcntl.h> #include <stdio.h> Task *taskrunning; Context taskschedcontext; static void taskstart(uint y, uint x) { Task *t; ulong z; z = x<<16; /* hide undefined 32-bit shift from 32-bit compilers */ z <<= 16; z |= y; t = (Task*)z; t->startfn(t->startarg); } Task* taskalloc(void (*fn)(void*), void *arg, uint stack) { Task *t; sigset_t zero; uint x, y; ulong z; /* allocate the task and stack together */ t = malloc(sizeof *t+stack); if(t == nil){ fprint(2, "taskalloc malloc: %r\n"); abort(); } memset(t, 0, sizeof *t); t->stk = (uchar*)(t+1); t->stksize = stack; t->startfn = fn; t->startarg = arg; /* do a reasonable initialization */ memset(&t->context.uc, 0, sizeof t->context.uc); sigemptyset(&zero); sigprocmask(SIG_BLOCK, &zero, &t->context.uc.uc_sigmask); /* must initialize with current context */ if(getcontext(&t->context.uc) < 0){ fprint(2, "getcontext: %r\n"); abort(); } /* call makecontext to do the real work. */ /* leave a few words open on both ends */ t->context.uc.uc_stack.ss_sp = t->stk+8; t->context.uc.uc_stack.ss_size = t->stksize-64; #if defined(__sun__) && !defined(__MAKECONTEXT_V2_SOURCE) /* sigh */ #warning "doing sun thing" /* can avoid this with __MAKECONTEXT_V2_SOURCE but only on SunOS 5.9 */ t->context.uc.uc_stack.ss_sp = (char*)t->context.uc.uc_stack.ss_sp +t->context.uc.uc_stack.ss_size; #endif /* * All this magic is because you have to pass makecontext a * function that takes some number of word-sized variables, * and on 64-bit machines pointers are bigger than words. */ //print("make %p\n", t); z = (ulong)t; y = z; z >>= 16; /* hide undefined 32-bit shift from 32-bit compilers */ x = z>>16; makecontext(&t->context.uc, (void(*)())taskstart, 2, y, x); return t; } void contextswitch(Task *from, Task *to) { if(swapcontext(&from->context.uc, &to->context.uc) < 0){ fprint(2, "swapcontext failed: %r\n"); assert(0); } } void needstack(int n) { Task *t; t = taskrunning; if((char*)&t <= (char*)t->stk || (char*)&t - (char*)t->stk < 256+n){ fprint(2, "task stack overflow: &t=%p tstk=%p n=%d\n", &t, t->stk, 256+n); abort(); } }
C
#include <stdio.h> int fib(int n) { //printf("%s\n", __FUNCTION__); if(n < 1) return 0; if( 1 == n || 2 == n) return 1; return fib(n - 1) + fib(n - 2); } int fib_loop1(int n) { int f1, f2; f1 = f2 = 1; for (int i = 3; i <= n ; ++i) { f2 = f2 + f1; f1 = f2 - f1; // Get old value of f2. //printf("%s\n", __FUNCTION__); } return f2; } int fib_loop2(int n) { return 0; } int main() { int n; scanf("%d", &n); printf("fib: %d\n", fib(n)); printf("fib_loop1: %d\n", fib_loop1(n)); printf("fib_loop2: %d\n", fib_loop2(n)); return 0; }
C
/******************************************************************************* // main.c *******************************************************************************/ /******************************************************************************* // Includes *******************************************************************************/ // Module Includes #include "main.h" // Platform Includes #include "Lunar_Main.h" // Other Includes #include <stdio.h> #include <stdlib.h> /******************************************************************************* // Private Constant Definitions *******************************************************************************/ /******************************************************************************* // Private Type Declarations *******************************************************************************/ /******************************************************************************* // Private Variable Definitions *******************************************************************************/ // Variable used in the Hard Fault handler to allow a convenient place for // placing a breakpoint static volatile unsigned int _Continue = 0U; /******************************************************************************* // Private Function Declarations *******************************************************************************/ /******************************************************************************* // Private Function Implementations *******************************************************************************/ /******************************************************************************* // Public Function Implementations *******************************************************************************/ // C entry point int main(void) { // The Core Main module provides a single entry point for starting up the system // It will initialize all configured modules and start the system scheduler // *** NOTE THIS WILL NOT RETURN *** Lunar_Main_Execute(); // Standard C exit code return(EXIT_SUCCESS); } /******************************************************************************* // Interrupt Handlers *******************************************************************************/ // IRQ handler for Hard Fault void HardFault_Handler(void) { while (_Continue == 0U) { // Loop forever } }
C
// // fileProcessingFuntion.c // newC // // Created by yeawonKim on 2021/09/07. // Copyright © 2021 yeawonKim. All rights reserved. // #include <stdio.h> int file_copy(char *oldname, char *newname); void main() { char source[80], destination[80]; printf("\n Enter source file : "); gets(source); printf("\n Enter destination file : "); gets(destination); if (file_copy(source, destination) == 0) puts("\n copy operaion succesful"); else fprintf(stderr, "\n error during copy operation"); } int file_copy(char *oldname, char *newname){ FILE *fold, *fnew; int c; if ((fnew = fopen(newname, "wb")) == NULL) { return(-1); } if ((fold = fopen(oldname, "rb")) == NULL) { return(-1); } while (1) { c = fgetc(fold); if (!feof(fold)) fputc(c, fnew); else break; } fclose(fnew); fclose(fold); return(0); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cochapel <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/01/16 08:22:07 by cochapel #+# #+# */ /* Updated: 2020/02/13 15:53:23 by cochapel ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static char *ft_strjoin_gnl(char *s1, char *s2) { char *tab; int i; int j; i = 0; j = 0; while (s1 && s1[i] != 0) ++i; while (s2 && s2[j] != 0 && s2[j] != '\n') ++j; if (!(tab = malloc(i + j + 1))) return (NULL); i = 0; j = 0; while (s1 != NULL && s1[j] != 0) tab[i++] = s1[j++]; j = 0; while (s2 != NULL && s2[j] != 0 && s2[j] != '\n') tab[i++] = s2[j++]; tab[i] = 0; free(s1); return (tab); } int get_next_line(int fd, char **line) { static char buf[FOPEN_MAX][BUFFER_SIZE + 1]; int ret; int i; if (line == NULL || fd < 0 || BUFFER_SIZE == 0 || fd > FOPEN_MAX) return (-1); if ((line[0] = ft_strjoin_gnl(NULL, buf[fd])) == NULL) return (-1); ret = 1; while (ft_strchr_int(buf[fd], '\n') == -1 && ret != 0) { ret = read(fd, buf[fd], BUFFER_SIZE); if (ret == -1) return (-1); buf[fd][ret] = 0; if (!(line[0] = ft_strjoin_gnl(line[0], buf[fd]))) return (-1); } ret = ft_strchr_int(buf[fd], '\n') + 1; if ((i = 0) == 0 && buf[fd][0] == 0) return (0); while (buf[fd][ret] != 0 && ret != 0) buf[fd][i++] = buf[fd][ret++]; buf[fd][i] = 0; return (1); }
C
#include <stdio.h> #include "cfile.h" int sum(int a,int b) { int c=a+b; printf(" helllpppkfvjo\n"); printf("%d %d",a,b); printf("sum = %d",c); return 0; }
C
/* * File: newmain3.c * Author: RENAN CARDOSO * * Created on 10 de Junho de 2019, 23:02 */ #define _XTAL_FREQ 4000000 #include <xc.h> void decrease_10m(void); void init_count(void); void alarm_activate(void); void delay_1min(void); void decrement_disp(void); int msb = 6; // Bit mais significativo do contador [6 .. 0] int lsb = 0; // Bit menos significativo do contador [9 .. 0] void main(void) { TRISD = 0x03; PORTD = 0x00; TRISB = 0x00; PORTB = 0x60; // Representa o 60 (decimal) exibido no display while(1) { // Caso o boto em RD0 for acionado, decrementar 10 no display if (PORTDbits.RD0) { decrease_10m(); while (PORTDbits.RD0) __delay_ms(100); // Dispositivo para assegurar apenas um 'push' } // Caso o boto em RD0 for acionado, iniciar a contagem if (PORTDbits.RD1) init_count(); } return; } void decrease_10m(void) { msb--; if (!msb) msb = 6; // Quando no display estiver em 1 e o boto for apertado PORTB = (msb << 4) | lsb; // Atualiza display } void init_count(void) { for (int min = msb * 10; min > 0 ; min--) { // Executa a quantidade de minutos selecionado pelo usurio decrement_disp(); // Decrementa e atualiza o valor no display delay_1min(); } alarm_activate(); PORTB = 0x60; // Aps o acionamento do alarme, retorna ao valor inicial //Fim do programa } // Core do programa // Aqui calculado o valor do bit mais e menos significativo para ser inserido no display void decrement_disp(){ // Lgica Decimal if (lsb) lsb--; else { lsb = 9; msb--; } PORTB = (msb << 4) | lsb; // Insere no display } void alarm_activate(){ PORTDbits.RD2 = 1; __delay_ms(5000); PORTDbits.RD2 = 0; } void delay_1min(){ for (int sec = 60 ; sec > 0 ; sec--) { __delay_ms(10); PORTDbits.RD3 ^= 1; // O pino 3 do PORTD existe um led para indicar os segundos corridos } }
C
#include "my_dll.h" #include <stdio.h> #include <stdlib.h> // Creates a DLL // Returns a pointer to a newly created DLL. // The DLL should be initialized with data on the heap. // (Think about what the means in terms of memory allocation) // The DLLs fields should also be initialized to default values. dll_t* create_dll() { dll_t* myDLinkedList = malloc(sizeof(dll_t)); myDLinkedList->count = 0; myDLinkedList->head = NULL; myDLinkedList->tail = NULL; return myDLinkedList; } // DLL Empty // Check if the DLL is empty // Returns 1 if true (The DLL is completely empty) // Returns 0 if false (the DLL has at least one element enqueued) int dll_empty(dll_t* l) { // null list if (l == NULL) { return -1; // at least one element } else if (l->count > 0) { return 0; // empty list } else { return 1; } } // push a new item to the front of the DLL ( before the first node in the list). // Returns a -1 if the operation fails ( and if the DLL is NULL), otherwise returns 1 on success. // (i.e. the memory allocation for a new node failed). int dll_push_front(dll_t* l, int item) { // null list if (l == NULL) { return -1; } else { node_t* node = malloc(sizeof(node_t)); node->data = item; node->next = NULL; node->previous = NULL; //check if memory allocation failed if (node == NULL) { return -1; } // first node? if (dll_empty(l)) { l->head = node; l->tail = node; } else { // update current head's prev to new node node_t* currentHead = l->head; currentHead->previous = node; node->next = currentHead; // update new head to new node l->head = node; } l->count++; return 0; } } // push a new item to the end of the DLL (after the last node in the list). // Returns a -1 if the operation failsm (and if the DLL is NULL), otherwise returns 1 on success. // (i.e. the memory allocation for a new node failed). int dll_push_back(dll_t* l, int item) { // null list if (l == NULL) { return -1; } else { node_t* node = malloc(sizeof(node_t)); node->data = item; node->next = NULL; node->previous = NULL; //check if memory allocation failed if (node == NULL) { return -1; } // first node? if (dll_empty(l)) { l->head = node; l->tail = node; } else { // update current tails's next to new node node_t* currentTail = l->tail; currentTail->next = node; node->previous = currentTail; // update new tail to new node l->tail = node; } l->count++; return 0; } } // Returns the first item in the DLL and also removes it from the list. // Returns a -1 if the operation fails (and if the DLL is NULL). Assume no negative numbers in the list. int dll_pop_front(dll_t* t) { // null list if (t == NULL || dll_empty(t)) { return -1; } else { node_t* currentHead = t->head; int data = currentHead->data; // this is only node in list if (t->count == 1) { t->head = NULL; t->tail = NULL; } else { // get the new head node_t* newHead = currentHead->next; // update prev of new head newHead->previous = NULL; // set head to new head t->head = newHead; } t->count--; free(currentHead); return data; } } // Returns the last item in the DLL, and also removes it from the list. // Returns a -1 if the operation fails (and if the DLL is NULL). Assume no negative numbers in the list. int dll_pop_back(dll_t* t) { // null list if (t == NULL || dll_empty(t)) { return -1; } else { node_t* currentTail = t->tail; int data = currentTail->data; // this is only node in list if (t->count == 1) { t->head = NULL; t->tail = NULL; } else { // get the new tail node_t* newTail = currentTail->previous; // update next of new tail newTail->next = NULL; // set tail to new tail t->tail = newTail; } t->count--; free(currentTail); return data; } } // Inserts a new node before the node at the specified position. // Returns a -1 if the operation fails (and if the DLL is NULL), otherwise returns 1 on success. // (i.e. the memory allocation for a new node failed or trying to insert at a negative position or at // a position past the size of the DLL ). Think testcases here. int dll_insert(dll_t* l, int pos, int item) { // null test and edge cases if (l == NULL || (pos < 0 || pos >= l->count)) { return -1; } else if (pos == 0) { // front dll_push_front(l, item); } else if (pos == l->count - 1) { // back dll_push_back(l, item); } else { node_t* head = l->head; int i = 0; // get target while (i != pos) { head = head->next; i++; } // create new node node_t* node = malloc(sizeof(node_t)); node->data = item; // update pointers for back nodes node_t* next = head->next; node->next = next; next->previous = node; // update pointers for front nodes head->next = node; node->previous = head; l->count++; return 0; } } // Returns the item at position pos starting at 0 ( 0 being the first item ) // Returns a -1 if the operation fails (and if the DLL is NULL). Assume no negative numbers are in the list. // (i.e. trying to get at a negative position or at a position past the size of the DLL ). // Think testcases here. int dll_get(dll_t* l, int pos) { // null test and edge cases if (l == NULL || dll_empty(l) || (pos < 0 || pos >= l->count)) { return -1; } else { node_t* head = l->head; int i = 0; // get target while (i != pos) { head = head->next; i++; } int data = head->data; return data; } } // Removes the item at position pos starting at 0 ( 0 being the first item ) // Returns a -1 if the operation fails (and if the DLL is NULL). // (i.e. trying to remove at a negative position or at a position past the size of the DLL ). // Think testcases here. int dll_remove(dll_t* l, int pos) { // null test and edge cases if (l == NULL || (pos < 0 || pos >= l->count)) { return -1; } else if (pos == 0) { return dll_pop_front(l); } else if (pos == l->count-1) { return dll_pop_back(l); } else { node_t* head = l->head; int i = 0; // get target while (i != pos) { head = head->next; i++; } int data = head->data; node_t* next = head->next; node_t* prev = head->previous; if (next == NULL) { prev->next = NULL; } else { next->previous = prev; prev->next = next; } l->count--; free(head); return data; } } // DLL Size // Queries the current size of a DLL // A DLL that has not been previously created will crash the program. // Returns -1 if the DLL is NULL. int dll_size(dll_t* t) { // null check if (t == NULL) { return -1; } else { return t->count; } } // Free DLL // Removes a DLL and ALL of its elements from memory. // This should be called before the proram terminates. void free_dll(dll_t* t) { // null check if (t == NULL) { return; } else { node_t* tempNode = NULL; // cleanup all nodes first while (t->head != NULL) { tempNode = t->head; t->head = t->head->next; free(tempNode); } // finally clean up data structure free(t); } } // Print out all the elements in the list in forwards direction void forward_print(dll_t* t) { if (t == NULL) { printf("LIST IS NULL\n"); return; } node_t* head = t->head; printf("Printing from head to tail.\n"); while (head != NULL) { printf("%d ", head->data); head = head->next; } printf("\n"); printf("DONE\n"); } // Print out all the elements in the list in backwards direction void backward_print(dll_t* t) { if (t == NULL) { printf("LIST IS NULL\n"); return; } node_t* tail = t->tail; printf("Printing from tail to head.\n"); while (tail != NULL) { printf("%d ", tail->data); tail = tail->previous; } printf("\n"); printf("DONE\n"); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> void quick_sort(int tab[],int deb,int fin) { const int pivot = tab[deb]; int pos=deb; int i; if (deb>=fin) return; for (i=deb; i<fin ; i++) { if (tab[i]<pivot) { tab[pos]=tab[i]; pos++; tab[i]=tab[pos]; tab[pos]=pivot; } } tri_tab_recursif(tab,deb,pos); tri_tab_recursif(tab,pos+1,fin); } void search(int n, struct inhabitant *a){ char prenomsearch[MAX_STR_SIZE]; char nomsearch[MAX_STR_SIZE]; printf("Prenom et nom a chercher : \n"); scanf("%s%s", prenomsearch, nomsearch); for (int i=0; i<n; i++) { if (strcmp(a[i].prenom, prenomsearch)==0 && strcmp(a[i].nom, nomsearch)==0) { printf("%d, %s, %s, %d\n", a[i].distance, a[i].prenom,a[i].nom, a[i].zip); } } printf("Fin de la recherche"); }
C
//Escribir un programa que consulte y muestre en pantalla el estado del cerrojo sobre un fichero usando lockf(3). El programa mostrará el estado del cerrojo (bloqueado o desbloqueado). Además: #include <unistd.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int lockf(int fd, int cmd, off_t len); int main(int argc, char **argv) { if (argc < 2){ printf("Error: No se ha especificado la ruta del archivo. Introducir de nuevo"); return -1; } int fd = open(argv[1], O_CREAT | O_RDWR); int cmd = F_TLOCK; off_t len; int cerr = lockf(fd, cmd, len); if(cerr == -1){ printf("La región está bloqueada"); } return 0; }
C
/* ** EPITECH PROJECT, 2018 ** n4s ** File description: ** ia.c */ #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include "get_info.h" #include "commands.h" void init_info(info_t *info) { info->n_left = 0; info->left = 0; info->n_right = 0; info->right = 0; info->middle = 0; } int check_ret(int ret, int *end) { if (ret == 1) { write(1, "STOP_SIMULATION\n", 16); *end = 1; return (0); } return (1); } int car_movment(info_t info, char **stock, int *end) { int ret = 0; car_speed(info.middle); ret = check_err_parcing(&stock); if (stock != NULL) free_stock(stock); if (check_ret(ret, end) == 0) return (0); right_and_left_dir(&info); ret = check_err_parcing(&stock); if (stock != NULL) free_stock(stock); if (check_ret(ret, end) == 0) return (0); return (1); } int ia(int *end, char **stock) { int ret = 0; info_t info; init_info(&info); write(1, "GET_INFO_LIDAR\n", 15); ret = check_err_parcing(&stock); parcing_captor(&info, stock); if (ret == 84) { *end = 1; free_stock(stock); return (0); } if (check_ret(ret, end) == 0) { free_stock(stock); return (0); } else { if (car_movment(info, stock, end) == 0) { free_stock(stock); return (0); } } if (stock != NULL) free_stock(stock); return (0); }
C
#include "monty.h" /** * execute - executes function * @opcode: The opcode * @line_number: The line number the opcode is found */ void execute(char *opcode, unsigned int line_number) { unsigned int i; instruction_t opcodes[] = { {"pall", pall}, {"pint", pint}, {"nop", nop}, {"pop", pop}, {"swap", swap}, {"add", add}, {"sub", sub}, {"div", op_div}, {"mul", mul}, {"mod", mod}, {NULL, NULL} }; for (i = 0; opcodes[i].opcode; ++i) { if (strcmp(opcodes[i].opcode, opcode) == 0) { opcodes[i].f(&global.head, line_number); return; } } dprintf(STDERR_FILENO, "L%u: unknown instruction %s\n", line_number, opcode); free_list(); exit(EXIT_FAILURE); }
C
/* * Copyright(C) 2007 Neuros Technology International LLC. * <www.neurostechnology.com> * * * 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, version 2 of the License. * * This program is distributed in the hope that, in addition to its * original purpose to support Neuros hardware, it will be useful * otherwise, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * **************************************************************************** * * Generic IPC routines. * * REVISION: * * 3) Signal caught while sem blocking is not fatal.------- 2007-05-30 MG * 2) Complete rewrite to avoid use of shmem and simplify.- 2007-05-25 nerochiaro * 1) Initial creation. ----------------------------------- 2007-04-29 MG * */ #include <fcntl.h> #include <sys/stat.h> #include <errno.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> //#define OSD_DBG_MSG #include "nc-err.h" #include "ipc-helper.h" #if defined(__GNU_LIBRARY__) && !defined(_SEM_SEMUN_UNDEFINED) /* union semun is defined by including <sys/sem.h> */ #else /* according to X/OPEN we have to define it ourselves */ union semun { int val; /* value for SETVAL */ struct semid_ds *buf; /* buffer for IPC_STAT, IPC_SET */ unsigned short *array; /* array for GETALL, SETALL */ /* Linux specific part: */ struct seminfo *__buf; /* buffer for IPC_INFO */ }; #endif /** * Creates or retrieves a single semaphore with specified @path + @id . * If the semaphore didn't already exist, it is initialized to the specified @initial value. * * Note that applications should coordinate between themselves how to use the same @path + @id * to access the same semaphore, this is not part of the semaphores API. * * Warning: this operation is not atomic. It's a two- or three- step operation and if the thread * is scheduled out between operations the semaphore can be found in an inconsistent state by other * threads. * * @param path * Path to an existing file that is used to generate an unique key for the semaphore. * @param id * A single non-zero value also used to generate the key (note: it's an int but the value should fit in a char). * @param initial * Initial value of the semaphore if not existing. Must be zero or more. * @param sem * Upon return this will contain the semaphore handle if successful, 0 otherwise. * @return * 0 if semaphore didn't exist and it was created and initialized. * 1 if the semaphore existed and it was just opened. * -1 for general failure. */ int CoolSemCreate(const char * path, int id, int initial, int *sem) { /* Implementation details: Note that this function assumes that if path doesn not exist, then the semaphore needs to be created and initialized. But if path already exist, it doesn't mean the semaphore exists too. We will first try to see if the semaphore already exists, and if not we create and initialize it. Otherwise we will just open the existing one without changing the resource value. Also note that we operate on 1 single semaphore for each semid (which is actually a semaphore set, but we use just the first one). */ key_t key; union semun arg; // gets the sem key from the file+id, the file may not exist. if ((key = ftok(path, id)) == -1) { if (fopen(path, "w") == NULL) { FATALLOG("Semaphore id file cannot be created.\n"); *sem = 0; return -1; } } // We check if the semaphore already exists (will return -1 if it does) and // if it doesn't exist this operation creates it immediately. if ((*sem = semget(key, 1, 0666 | IPC_CREAT | IPC_EXCL)) == -1) { if (errno == EEXIST) { //The sem exists already, so we just open it and don't do any initialization. if ((*sem = semget(key, 1, 0666 )) == -1) { FATALLOG("Opening of existing semaphore failed.\n"); *sem = 0; return -1; } else { DBGLOG("Semaphore already existing, it was just opened [ID: %d]\n", *sem); return 1; } } else { FATALLOG("Semaphore check/creation failed.\n"); *sem = 0; return -1; } } else { DBGLOG("The semaphore is [ID: %d]\n", *sem); //We just created a new semaphore which is not initialized. We initialize it here. //Due to the inherent limitation of SystemV semaphores, this has to be done in //this separate step, thus potentially allowing for some race condition issues. //There is nothing that can be done about it, but it's at least good to know it. arg.val = initial; if (semctl(*sem, 0, SETVAL, arg) == -1) { FATALLOG("Initialization of semaphore failed (semctl SETVAL)\n"); //This is a last ditch attempt at cleanup. We can't do nothing even if it fails, so //we don't even check the result code. semctl(*sem, 0, IPC_RMID, arg); *sem = 0; return -1; } } DBGLOG("Semaphore created and initialized [ID: %d]\n", *sem); return 0; } /** * Retrieves a single semaphore with specified @path + @id, only if exists. * * Note that applications should coordinate between themselves how to use * the same @path + @id to access the same semaphores, this is not part of the semaphores API * * This operation is atomic with respect to the sem acquisition (technically it's a two-step * operation but even if the @path or the sem is deleted between operations, the result would * be the same as if the same as if the operation was actually atomic). * * @param path * Path to an existing file that is used to generate an unique key for the semaphore. * @param id * A single non-zero char value (but not necessarily ASCII), also used to generate the key. * @param sem * Upon return this will contain the semaphore handle if successful, 0 otherwise. * @return * 0 if successful, 1 if semaphore doesn't exist or -1 if there were errors. */ int CoolSemGet(const char * path, int id, int *sem) { key_t key; DBGLOG("Retrieving existing semaphore [path: %s, id: %c]\n", path, id); // gets the sem key from the file+id, the file may not exist. if ((key = ftok(path, id)) == -1) { //if the file doesn't exist, the semaphore for us doesn't exist also. DBGLOG("Semaphore doesn't exist (missing file)\n"); *sem = 0; return 1; } // We check if the semaphore already exists (will return -1 if it does) and // if it doesn't exist this operation will not create it. if ((*sem = semget(key, 1, 0666)) == -1) { if (errno == ENOENT) { DBGLOG("Semaphore doesn't exist.\n"); return 1; } else { FATALLOG("Error while checking semaphore existence.\n"); *sem = 0; return -1; } } DBGLOG("Retrieved existing semaphore [ID: %d]\n", *sem); return 0; } /** * Destroy semaphore with given handle. * * This operation is atomic. * * @param sem * Semaphore handle created either by CoolSemCreate* or CoolSemGet * @return * 0 if successful, otherwise -1 * */ int CoolSemDestroy(int sem) { union semun arg; DBGLOG("Destroying semaphore [ID: %d]\n", sem); if (sem) { if (semctl(sem, 0, IPC_RMID, arg) == -1) { FATALLOG("Destruction of semaphore %d failed (semctl IPC_RMID)\n", sem); return -1; } } DBGLOG("Semaphore destroyed [ID: %d]\n", sem); return 0; } /** Sem increment. This operation has the meaning of releasing one unit of the resource. * * This operation is atomic. * * @param sem * Semaphore handle cretaed either by CoolSemCreate* or CoolSemGet * @return * 0 if successful, -1 otherwise. * */ int CoolSemUp(int sem) { struct sembuf sb = {0, 1, 0}; /* set to release resource */ DBGLOG("Releasing resource (UP) on semaphore [ID: %d]\n", sem); if (sem) { if (semop(sem, &sb, 1) == -1) { FATALLOG("Release of resource failed (semop UP 1)\n"); return -1; } } DBGLOG("Resource released on semaphore [ID: %d]\n", sem); return 0; } /** Sem set value. * This operation resets the resource, use with CAUTION as it may break the UP/DOWN * sem operation pair. * * This operation is atomic. * * @param sem * Semaphore handle cretaed either by CoolSemCreate* or CoolSemGet * @param val * Resource value set to the semaphore. * @return * 0 if successful, -1 otherwise. * */ int CoolSemSetValue(int sem, int val) { union semun arg; DBGLOG("Setting resource on semaphore [ID: %d] to [value: %d]\n", sem, val); arg.val = val; if (semctl(sem, 0, SETVAL, arg) == -1) { FATALLOG("Setting resource failed (semctl SETVAL val)\n"); return -1; } DBGLOG("Resource set on semaphore [ID: %d] to [value: %d]\n", sem, val); return 0; } /** Sem get value. * This operation gets the current value of the resource. * * This operation is atomic. * * @param sem * Semaphore handle cretaed either by CoolSemCreate* or CoolSemGet * @param val * Will be filled with value on return, if successful. * @return * 0 if successful, -1 otherwise. * */ int CoolSemGetValue(int sem, int *val) { DBGLOG("Getting resource value on semaphore [ID: %d]\n", sem); *val = semctl(sem, 0, GETVAL, 0); if (*val == -1) { FATALLOG("Getting resource value failed (semctl SETVAL val)\n"); return -1; } DBGLOG("Resource get value on semaphore [ID: %d] has [value: %d]\n", sem, *val); return 0; } /** Sem increment (binary). * This operation shall be called only on semaphores that shall have "binary" semantics. * In other words, semaphores where the resource count can only be 0 or 1. * * This operation has the meaning of releasing one unit of the resource, but with the * important distinction that is can be called any number of times without the resource value * ever raising above the limit of 1. * * Please use this function only when you are sure you really need binary semantics and you * cannot obtain them with norma @CoolSemUp (in most cases you can do that). * * This operation is atomic. * * @param sem * Semaphore handle cretaed either by CoolSemCreate* or CoolSemGet * @return * 0 if successful, -1 otherwise. * */ #if 0 // this has been defined to use CoolSemSetValue API, // function is left here for reference. int CoolSemUpBinary(int sem) { union semun arg; DBGLOG("Releasing resource (UP,binary) on semaphore [ID: %d]\n", sem); arg.val = 1; if (semctl(sem, 0, SETVAL, arg) == -1) { FATALLOG("Release of resource failed (semctl SETVAL 1)\n"); return -1; } DBGLOG("Resource released on semaphore [ID: %d]\n", sem); return 0; } #endif /** Sem decrement. This operation has the meaning of trying to acquire one unit of the resource. * If the resouce count is zero (depleted), this call will block until resource becomes available again. * If you don't want to block, pass 0 to @blocking and the call will return immediately and notify if the * resource was depleted or if it was acquired successfully. * * This operation is atomic. * * @param sem * Semaphore handle created either by @CoolSemCreate or @CoolSemCreateBinary. * @param blocking * 1 to block caller, 0 to indicate non-block operation. * @return * 0 if acquired successfully. * 1 if resource depleted (when non @blocking) or if semaphore destroyed while waiting (when @blocking). * -1 in case of failure. * */ int CoolSemDown(int sem, int blocking) { struct sembuf sb; int ret = -1; DBGLOG("Acquiring resource (DOWN) on semaphore [ID: %d, blocking:%d]\n", sem, blocking); // sb = {0, -1, 0}; /* set to allocate resource */ sb.sem_num = 0; sb.sem_op = -1; sb.sem_flg = (blocking)? 0:IPC_NOWAIT; if (sem) { ret = semop(sem, &sb, 1); if (ret == -1) { switch (errno) { case EAGAIN: DBGLOG("Time limit reached while in DOWN-blocking on it [ID: %d]\n", sem); return 1; case EINTR: DBGLOG("Signal caught while in DOWN-blocking on it [ID: %d]\n", sem); return 1; case EIDRM: DBGLOG("Semaphore was destroyed while in DOWN-blocking on it [ID: %d]\n", sem); return 1; default: FATALLOG("Acquisition of resource failed (semop DOWN 1) [errno: %d]\n", errno); return -1; } } } DBGLOG("Resource acquired on semaphore [ID: %d, blocking:%d]\n", sem, blocking); return 0; } #if 0 //FIXME: semtimedop not as part of ARM Linux?? /** Sem decrement with a timeout value. This operation has the meaning of trying to acquire one unit of the resource. * If the resouce count is zero (depleted), this call will block until resource becomes available again * or the specified timeout value times out. * * This operation is atomic. * * @param sem * Semaphore handle created either by @CoolSemCreate or @CoolSemCreateBinary. * @param ms * time out value in mili-seconds. * @return * 0 if acquired successfully. * 1 if resource depleted (when non @blocking) or if semaphore destroyed while waiting (when @blocking). * -1 in case of failure. * */ int CoolSemTimedDown(int sem, int ms) { struct sembuf sb; int ret = -1; struct timespec tm; unsigned long utm; DBGLOG("Acquiring resource (DOWN) on semaphore [ID: %d, blocking:%d]\n", sem, blocking); // sb = {0, -1, 0}; /* set to allocate resource */ sb.sem_num = 0; sb.sem_op = -1; sb.sem_flg = IPC_NOWAIT; utm = ms%1000000; tm.tv_sec = ms/1000000; tm.tv_nsec = utm*1000000; if (sem) { ret = (tm.tv_sec||tm.tv_nsec)? semtimedop(sem, &sb, 1, &tm):semop(sem, &sb, 1); if (ret == -1) { switch (errno) { case EAGAIN: DBGLOG("Time limit reached while in DOWN-blocking on it [ID: %d]\n", sem); return 1; case EINTR: DBGLOG("Signal caught while in DOWN-blocking on it [ID: %d]\n", sem); return 1; case EIDRM: DBGLOG("Semaphore was destroyed while in DOWN-blocking on it [ID: %d]\n", sem); return 1; default: FATALLOG("Acquisition of resource failed (semop DOWN 1) [errno: %d]\n", errno); return -1; } } } DBGLOG("Resource acquired on semaphore [ID: %d, blocking:%d]\n", sem, blocking); return 0; } #endif
C
#include "stdio.h" #include "string.h" #include "stdlib.h" int main (int argc, char** argv) { char c = 0; char dBug = 0; char enc = 0; char* key; char* inFileName; char* outFileName; size_t size; int counter = 0; FILE* in = stdin; FILE* out = stdout; for (int i = 1; i < argc; i++){ if (strncmp(argv[i], "-D", 2) == 0){ puts(argv[i]); dBug = 1; } if (strncmp(argv[i], "-e", 2) == 0) { enc = -1; size = strlen(argv[i]) - 2; key = malloc(size*sizeof(char)); strncpy(key, &argv[i][2], size); } if (strncmp(argv[i], "+e", 2) == 0) { enc = 1; size = strlen(argv[i]) - 2; key = malloc(size*sizeof(char)); strncpy(key, &argv[i][2], size); } if (strncmp(argv[i], "-i", 2) == 0){ inFileName = malloc((strlen(argv[i]) - 2)*sizeof(char)); strncpy(inFileName, &argv[i][2], strlen(argv[i]) - 2); in = fopen(inFileName, "r"); } if (strncmp(argv[i], "-o", 2) == 0){ outFileName = malloc((strlen(argv[i]) - 2)*sizeof(char)); strncpy(outFileName, &argv[i][2], strlen(argv[i]) - 2); out = fopen(outFileName, "w"); } } while (c != EOF) { c = fgetc(in); if (dBug && c != EOF) fprintf(stderr, "%#04x\t", c); if (enc == 0 && c >= 'A' && c <= 'Z') c = c + 32; else if (enc !=0 && c != EOF) { if ( c == '\n'){ c = (c + enc*(key[(counter++)%size]))%128; fputc(c,out); counter = 0; c = '\n'; } else c = (c + enc*(key[(counter++)%size]))%128; if (c < 0) c = c * (-1); } if (dBug && c != EOF) fprintf(stderr, "%#04x\n", c); fputc(c,out); } printf ("\n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #define STR_LEN 80 // 函数原型 int count_spaces(const char *); int main(void) { char str[STR_LEN + 1] = "fdsa drf tewq gsdafsd"; printf("%d\n", count_spaces(str)); return 0; } // 函数定义 // const常量,只读参数 int count_spaces(const char *s) { int count = 0; // 以空字符'\0'为结束条件 while(*s != '\0') { if(*s == ' ') { count++; } s++; } return count; }
C
#include<stdio.h> #include<stdlib.h> #define Max_String 100 #define Max_Lines 10 //Searches the string for a specified value and returns the position of where it was found int Find(char *s, char *value){ if(! *value) return -1; int index = 0; while(*s && *s != *value) s++, index++; while(*s && *value && *s == *value) s++, value++; if(!*value) return index; return -1; } //////////////////////// Auxiliary functions /////////////////////////// ///////////////////////////////////////////////////// void Concat(char *original, char *add){ while(*original) original++; while(*add){ *original = *add; original++, add++; } *original = '\0'; } char *ncaracters(char caracter, int value){ char *result = malloc(value * sizeof(char*)); for(int i = 0; i < value; i++) result[i] = caracter; result[value] = '\0'; return result; } int is_letter(char c){ return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')); } int is_num(char c){ return (c >= '0' && c <= '9'); } int is_num_or_letter(char c){ return (is_num(c) || is_letter(c)); } int printable(char c){ return (c > 31); } int is_lower(char c){ return (c >= 'a' && c <= 'z'); } int is_upper(char c){ return (c >= 'A' && c <= 'Z'); } int is_function(int (*f)(char), char *s){ while(*s){ if(!f(*s)) return 0; s++; } return 1; } void copy(char *or, char *cop){ while(*cop){ *or = *cop; or++, cop++; } *or = '\0'; } void replace_first(char *or, char *s1, char *s2){ int index = Find(or, s1); if(index >= 0){ int ind = 0; int point; char *copy_or = or; char *new = malloc(sizeof(char*) * Max_String); for(int i = 0; i < index; i++) new[ind] = *copy_or, copy_or++, ind++, point++; while(*s2) new[ind] = *s2, ind++, s2++; while(*s1) s1++, copy_or++, point++; while(*copy_or) new[ind] = *copy_or, ind++, copy_or++, point++; new[ind] = '\0'; copy(or, new); free(new); } } void strip_left(char *orig){ if(Len(orig) > 0){ char *new = malloc(sizeof(char*) * Max_String); char *copy_orig = orig; while(*copy_orig == ' ') copy_orig++; int i = 0; while(*copy_orig) new[i] = *copy_orig, copy_orig++, i++; new[i] = '\0'; copy(orig, new); free(new); } } void strip_rigth(char *orig){ int l = Len(orig); if(l > 0){ int i = 0; char *copy_orig = orig; char *copy_orig2 = orig; char *new = malloc(sizeof(char*) * Max_String); while(*(copy_orig + 1)) copy_orig++; while(*copy_orig == ' ') copy_orig--, i++; for(int j = 0; j < l - i; j++) new[j] = *copy_orig2, copy_orig2++; new[l - i] = '\0'; copy(orig, new); free(new); } } int lines(char *orig){ int i = 0; while(*orig){ if(*orig == '\n') i++; orig++; } return i + 1; } /////////////////////////////////////////////////////////////// //Calculates string's length int Len(char *s){ int i = 0; while(*s) s++, i++; return i; } //Compares two strings int Compare(char *s1, char *s2){ while(*s1 && *s2 && *s1 == *s2) s1++, s2++; return (!*s1 && !*s2); } //Converts the first character to upper case void Capitalize(char *s){ if(*s && *s >= 'a' && *s <= 'z') *s -= 32; } //Converts string into lower case void Casefold(char *s){ while(*s){ if(*s >= 'A' && *s <= 'Z') *s += 32; s++; } } //Returns a centered string void Center(char *s, int length, char caracter){ int lenS = Len(s); if(lenS < length){ int n = ((length / 2) - (lenS / 2)); char *s1 = ncaracters(caracter, length - n - lenS); char *s2 = ncaracters(caracter, n); Concat(s, s2); Concat(s1, s); copy(s, s1); free(s1); free(s2); } } //Returns the number of times a specified value occurs in a string int Count(char *s, char *value){ int count = 0; char *news; char *newvalue; if(! *value) return 0; while(*s){ news = s; newvalue = value; while(*news && *newvalue && *news == *newvalue) news++, newvalue++; if(!*newvalue) count++; s++; } return count; } //Returns true if the string ends with the specified value int Endswith(char *s, char *ending){ if(!*ending) return 1; while(*s && *ending && *s != *ending) s++; while(*s && *ending && *s == *ending) s++, ending++; return (!*ending && !*s); } //Sets the tab size of the string void Expandstabs(char *s, int n){ char news[Max_String * 5]; char *copys = s; int i = 0; while(*copys){ if(*copys != ' '){ news[i] = *copys; i++; for(int j = 0; j < n; j++) news[i + j] = ' '; i += n; } copys++; } news[i] = '\0'; copy(s, news); } //Searches the string for a specified value and returns the position of where it was found int Index(char *s, char *value, int a, int b){ if(! *value) return -1; int index = 0; int j = a; for(int i = 0; i < a; i++) *s++; while(j < b && *s && *s != *value) s++, index++, j++; while(j < b && *s && *value && *s == *value) s++, value++, j++; if(!*value) return index; return -1; } //Returns True if all characters in the string are alphanumeric int Isalnum(char *s){ if(!*s) return 0; return is_function(is_num_or_letter, s); } //Returns True if all characters in the string are in the alphabet int Isalpha(char *s){ if(!*s) return 0; return is_function(is_letter, s); } //Returns True if all characters in the string are decimals int Isdecimal(char *s){ if(!*s) return 0; return is_function(is_num, s); } //Returns True if all characters in the string are printable int Isprintable(char *s){ return is_function(printable, s); } //Returns True if all characters in the string are lower case int Islower(char *s){ return is_function(is_lower, s); } //Returns True if all characters in the string are upper case int Isupper(char *s){ return is_function(is_upper, s); } //Returns True if the string follows the rules of a title int Istitle(char *s){ if(is_upper(*s)){ s++; while(*s && is_lower(*s)) s++; if(! *s) return 1; } return 0; } //Returns a string where a specified value is replaced with a specified value void Replace(char *orig, char *s1, char *s2){ if(!Compare(s1, s2)){ int index = Find(orig, s1); while(index >= 0){ replace_first(orig, s1, s2); index = Find(orig, s1); } } } //Returns a right justified version of the string void Rjust(char *orig, int n, char c){ int l = Len(orig); if(n > l){ char *new = malloc(sizeof(char*) * Max_String); for(int i = 0; i < (n - l); i++) new[i] = c; for(int i = (n - l); i < n; i++) new[i] = orig[i - (n - l)]; new[n] = '\0'; copy(orig, new); free(new); } } //Fills the string with a specified number of 0 values at the beginning void Zfill(char *orig, int n){ return Rjust(orig, n, '0'); } //Converts the first character of each word to upper case void Title(char *orig){ int l = Len(orig); if(l > 0){ if(is_lower(orig[0])) orig[0] -= 32; for(int i = 1; i < l; i++) if(is_lower(orig[i]) && orig[i - 1] == ' ') orig[i] = orig[i] - 32; } } //Swaps cases, lower case becomes upper case and vice versa void Swapcase(char *orig){ while(*orig){ if(is_lower(*orig)) *orig -= 32; else if(is_upper(*orig)) *orig += 32; orig++; } } //Returns true if the string starts with the specified value int Startswith(char *orig, char *start){ while(*orig && *start && *orig == *start) orig++, start++; return (! *start); } //Returns a trimmed version of the string void Strip(char *orig){ strip_left(orig); strip_rigth(orig); } //Splits the string at the specified separator, and returns a list char **Rsplit(char *orig, char sep){ int nb_lines = lines(orig); char **result = malloc(sizeof(char**) * nb_lines); int i = 0; while(i < nb_lines){ result[i] = malloc(sizeof(char*) * Max_String); int j =0; while(*orig && *orig != sep) result[i][j] = *orig, orig++, j++; result[i][j] = '\0'; orig++; i++; } return result; } //Splits the string at line breaks and returns a list char **Splitlines(char *orig){ return Rsplit(orig, '\n'); } //Returns a tuple where the string is parted into three parts char **Rpartition(char *orig, char *part){ int n = Find(orig, part); int l = Len(orig); int l1 = Len(part); char **result = malloc(sizeof(char**) * 3); for(int i = 0; i < 3; i++) result[i] = malloc(sizeof(char*) * Max_String); for(int i = 0; i < n; i++) result[0][i] = orig[i]; result[0][n] = '\0'; copy(result[1], part); for(int i = n + l1; i < l; i++) result[2][i - n - l1] = orig[i]; return result; } //Searches the string for a specified value and returns the last position of where it was found int Rfind(char *orig, char *value){ if(! *value) return -1; int l = Len(orig); int lv = Len(value); int i = l - 1; int j = lv - 1; while(i >= 0){ while(orig[i] != value[j]) i--; if(i >= 0) while(j >= 0 && i >= 0 && orig[i] == value[j]) i--, j--; if(j < 0) return i + 1; } return -1; } char *Join(char **string_array, int len){ char *joined = malloc(sizeof(char*) * Max_String * 10); *joined = '\0'; for(int i = 0; i < len; i++) Concat(joined, string_array[i]); return joined; }
C
# include <stdio.h> # include <stdlib.h> # include <stdarg.h> # include <errno.h> # include <string.h> # include <math.h> enum{ LINESZ = 256, INIT = 2, GROW = 2, NSAMP = 5000 }; typedef struct mat { int nrows; int ncols; int nelem; int max; double *elem; } matrix; char *argv0; char *filename; int lineno; double *xvals; double *yvals; int nalloc; int maxalloc; void fatal(int syserror, int line, char *fmt, ...) { char buf[256]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); fprintf(stderr, "%s: ", argv0); if(line) fprintf(stderr, "%s:%d: ", filename, lineno); fprintf(stderr, "%s", buf); if(syserror) fprintf(stderr, ": %s", strerror(errno)); fprintf(stderr, "\n"); exit(1); } char * emalloc(unsigned int n) { char *p; p = malloc(n); if(p == NULL) fatal(0, 0, "out of memory"); return p; } char * erealloc(void *p, unsigned int n) { p = realloc(p, n); if(p == NULL) fatal(0, 0, "out of memory"); return p; } matrix * matalloc(int nrows, int ncols) { matrix *m; m = (matrix *)emalloc(sizeof(matrix)); m->nrows = nrows; m->ncols = ncols; m->max = m->nelem = nrows*ncols; m->elem = (double *)emalloc(m->max * sizeof(double)); return m; } void matfree(matrix *m) { free(m->elem); free(m); } double * matelem(matrix *m, int i, int j) { return &m->elem[i*m->ncols + j]; } void swap(double *a, double *b) { double tmp; tmp = *a; *a = *b; *b = tmp; } matrix * lupdecomp(matrix *m, matrix *p) { int i, j, k, l, n; double r, a; n = m->nrows; for(i = 0; i < n; i++) *matelem(p, i, 0) = i; for(k = 0; k < n; k++){ r = 0.; for(i = k; i < n; i++) if((a = fabs(*matelem(m, i, k))) > r){ r = a; l = i; } if(r == 0.) return NULL; swap(matelem(p, k, 0), matelem(p, l, 0)); for(i = 0; i < n; i++) swap(matelem(m, k, i), matelem(m, l, i)); for(i = k+1; i < n; i++){ *matelem(m, i, k) /= *matelem(m, k, k); for(j = k+1; j < n; j++) *matelem(m, i, j) -= *matelem(m, i, k) * *matelem(m, k, j); } } return m; } void lupsolve(matrix *m, matrix *p, matrix *x, int k) { # define getlow(m, i, j) ( ((i) == (j)) ? 1 : *matelem(m, i, j) ) # define getupp(m, i, j) *matelem(m, i, j) int i, j, n; matrix *y; double sum; y = matalloc(x->nrows, 1); n = m->nrows; for(i = 0; i < n; i++){ sum = 0.; for(j = 0; j < i; j++) sum += getlow(m, i, j) * *matelem(y, j, 0); *matelem(y, i, 0) = *matelem(m, *matelem(p, i, 0), n+k) - sum; } for(i = n-1; i >= 0; i--){ sum = 0.; for(j = i+1; j < n; j++) sum += getupp(m, i, j) * *matelem(x, j, k); *matelem(x, i, k) = (*matelem(y, i, 0) - sum) / getupp(m, i, i); } matfree(y); } void add(double x, double y) { if(maxalloc == 0){ nalloc = 0; maxalloc = INIT; xvals = (double *)emalloc(maxalloc*sizeof(double)); yvals = (double *)emalloc(maxalloc*sizeof(double)); }else if(nalloc >= maxalloc){ maxalloc *= GROW; xvals = (double *)erealloc(xvals, maxalloc*sizeof(double)); yvals = (double *)erealloc(yvals, maxalloc*sizeof(double)); } if(nalloc > 0 && x <= xvals[nalloc-1]) fatal(0, 1, "repeated or unsorted x values"); xvals[nalloc] = x; yvals[nalloc++] = y; } int readline(FILE *f, char *line, int n) { int i; char c; for(i = 0; i < n-1 && (c = getc(f)) > 0 && c != '\n'; i++) line[i] = c; line[i] = '\0'; return i; } int iswhite(char c) { return c == ' ' || c == '\t'; } int tokens(char *buf, char *elems[], int n) { char *p; int i, sep, inword; inword = i = 0; for(p = buf; *p != '\0'; p++){ sep = iswhite(*p); if(sep && inword){ *p = '\0'; inword = 0; }else if(!sep && !inword){ if(i >= n) fatal(0, 1, "too many columns"); elems[i++] = p; inword = 1; } } return i; } void load(FILE *f) { char line[LINESZ]; char *elems[2]; int n; double x, y; for(lineno = 1; (n = readline(f, line, LINESZ)) > 0; lineno++){ n = tokens(line, elems, 2); if(n == 0) break; if(sscanf(elems[0], "%lg", &x) != 1) fatal(0, 1, "%s: invalid number", elems[0]); if(sscanf(elems[1], "%lg", &y) != 1) fatal(0, 1, "%s: invalid number", elems[1]); add(x, y); } } double nspline(double x, double *b, double *c, double *d) { int low, high, mid; double x1; low = 0; high = nalloc-1; while(low <= high){ mid = (low+high)/2; if(x < xvals[mid]) high = mid-1; else if(x > xvals[mid+1]) low = mid+1; else break; } x1 = x - xvals[mid]; return yvals[mid] + b[mid]*x1 + c[mid]*x1*x1 + d[mid]*x1*x1*x1; } int main(int argc, char *argv[]) { FILE *f; int i, j; double x, dx, *b, *c, *d, *deltax, *deltay; matrix *m, *m0, *p, *mc; argv0 = *argv; maxalloc = 0; if(argc == 1){ filename = "<stdin>"; load(stdin); }else while(*++argv){ filename = *argv; f = fopen(*argv, "r"); if(f == NULL) fatal(1, 0, "%s: unable to read file", *argv); load(f); fclose(f); } b = (double *)emalloc((nalloc-1)*sizeof(double)); c = (double *)emalloc(nalloc*sizeof(double)); d = (double *)emalloc((nalloc-1)*sizeof(double)); deltax = (double *)emalloc((nalloc-1)*sizeof(double)); deltay = (double *)emalloc((nalloc-1)*sizeof(double)); m = matalloc(nalloc, nalloc+1); mc = matalloc(nalloc, 1);; for(i = 0; i < nalloc-1; i++){ deltax[i] = xvals[i+1] - xvals[i]; deltay[i] = yvals[i+1] - yvals[i]; } for(i = 0; i < nalloc; i++) for(j = 0; j < nalloc; j++) if(i == j) *matelem(m, i, j) = (i == 0 || i == nalloc-1) ? 1 : 2*(deltax[i]+deltax[i-1]); else if(i-1 == j) *matelem(m, i, j) = (i == nalloc-1) ? 0 : deltax[j]; else if(i+1 == j) *matelem(m, i, j) = (i == 0) ? 0 : deltax[j-1]; else *matelem(m, i, j) = 0; for(i = 0; i < nalloc; i++) *matelem(m, i, nalloc) = (i == 0 || i == nalloc-1) ? 0 : 3*(deltay[i]/deltax[i] - deltay[i-1]/deltax[i-1]); p = matalloc(nalloc, 1); m0 = lupdecomp(m, p); if(m0 == NULL) fatal(0, 0, "singular matrix"); lupsolve(m, p, mc, 0); for(i = 0; i < nalloc; i++) c[i] = *matelem(mc, i, 0); for(i = 0; i < nalloc-1; i++){ b[i] = deltay[i]/deltax[i] - deltax[i]*(2*c[i] + c[i+1])/3; d[i] = (c[i+1]-c[i])/(3*deltax[i]); } for(i = 0; i < nalloc-1; i++) fprintf(stderr, "%g %g %g\n", b[i], c[i], d[i]); dx = (xvals[nalloc-1] - xvals[0])/NSAMP; x = xvals[0]; for(i = 0; i <= NSAMP; i++){ printf("%g %g\n", x, nspline(x, b, c, d)); x += dx; } matfree(m); matfree(mc); matfree(p); free(deltay); free(deltax); free(d); free(c); free(b); return 0; }
C
#include <stdio.h> #include <string.h> #include <librdkafka/rdkafka.h> int main(int argc, char **argv) { rd_kafka_conf_t *conf; char buf[512]; size_t sz = sizeof(buf); rd_kafka_conf_res_t res; static const char *expected_features = "ssl,sasl_gssapi,lz4,zstd"; char errstr[512]; int i; int failures = 0; printf("librdkafka %s (0x%x, define: 0x%x)\n", rd_kafka_version_str(), rd_kafka_version(), RD_KAFKA_VERSION); if (argc > 1 && !(argc & 1)) { printf("Usage: %s [config.property config-value ..]\n", argv[0]); return 1; } conf = rd_kafka_conf_new(); res = rd_kafka_conf_get(conf, "builtin.features", buf, &sz); if (res != RD_KAFKA_CONF_OK) { printf("ERROR: conf_get failed: %d\n", res); return 1; } printf("builtin.features: %s\n", buf); /* librdkafka allows checking for expected features * by setting the corresponding feature flags in builtin.features, * which will return an error if one or more flags are not enabled. */ if (rd_kafka_conf_set(conf, "builtin.features", expected_features, errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) { printf( "ERROR: expected at least features: %s\n" "got error: %s\n", expected_features, errstr); failures++; } printf("all expected features matched: %s\n", expected_features); /* Apply config from argv key value pairs */ for (i = 1; i + 1 < argc; i += 2) { printf("verifying config %s=%s\n", argv[i], argv[i + 1]); if (rd_kafka_conf_set(conf, argv[i], argv[i + 1], errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) { printf("ERROR: failed to set %s=%s: %s\n", argv[i], argv[i + 1], errstr); failures++; } } rd_kafka_conf_destroy(conf); printf("%d failures\n", failures); return !!failures; }
C
/* ** my_showa_wordtab.c for my_show_wordtab in /home/antonin.rapini/CPool_Day08/task03 ** ** Made by Antonin Rapini ** Login <[email protected]> ** ** Started on Wed Oct 12 21:18:48 2016 Antonin Rapini ** Last update Wed Feb 15 01:41:18 2017 Antonin Rapini */ #include "utils.h" void my_show_wordtab(char **tab) { int index; index = 0; while (tab[index] != 0) { my_putstr(tab[index]); my_putchar('\n'); index = index + 1; } }
C
#include "lib.h" #include <errno.h> #include <stdint.h> #include "sys9.h" char end[]; static char *bloc = { end }; extern int _BRK_(void*); char * brk(char *p) { unsigned long n; n = (uintptr_t)p; n += 3; n &= ~3; if(_BRK_((void*)n) < 0){ errno = ENOMEM; return (char *)-1; } bloc = (char *)n; return 0; } void * sbrk(unsigned long n) { n += 3; n &= ~3; if(_BRK_((void *)(bloc+n)) < 0){ errno = ENOMEM; return (void *)-1; } bloc += n; return (void *)(bloc-n); }
C
#include<stdio.h> //Question 2-3: Write the function htoi(s), which converts a string of //hexadecimal digits (including an optional 0x or 0X) into its equivalent //integer value. The allowable digits are 0 through9, a through f, and A //through F. // // int htoi(char s[]); int main(void){ char s[10] = "ABCD"; int val = htoi(s); //printf("%d %d %d \n",'a','A','0'); printf("decimal: %d\n",val); return 0; } int htoi(char s[]){ int n=0; int i; for(i=0;(s[i]>='0' && s[i]<='9') || (s[i]>='a' && s[i]<='f') || (s[i]>='A' && s[i]<='F') || (s[i]=='x')||(s[i]=='X');++i){ //printf("here 0:%d\n",i); if(s[i]=='0' && i==0){ //printf("here 1\n"); continue; } else if (s[i]=='x' || s[i]=='X'){ //printf("here 2\n"); continue; } else if (s[i]=='\0'){ //printf("here 3\n"); break; } else { //printf("here 4\n"); char subt=0; int x=0; if(s[i] >= 'a'){ subt='a'; x=10; } else if(s[i] >= 'A'){ subt='A'; x=10; } else{ subt='0'; x=0; } n = n*16 + ( s[i] - subt + x); //printf("n:%d\n",n); } } return n; }
C
/* ** EPITECH PROJECT, 2017 ** my_printf ** File description: ** printf */ #include <stdlib.h> #include <stdarg.h> #include "my.h" #include "display_f.h" int contains(char const *str, char c) { int count = 0; for (int i = 0; str[i]; i++) { if (str[i] == c) count++; } return (count); } char *flags_manager(char *str) { char *fl = "#0- +'Il"; char *res = 0; int i = 0; char *flags = "diouxXcsCSpm%b"; for (i = 0; str[i] && (contains(fl, str[i]) || my_char_isnum(str[i])) && !contains(flags, str[i]); i++) {} res = MALLOC(sizeof(char) * (i + 1)); for (i = 0; str[i] && (contains(fl, str[i]) || my_char_isnum(str[i])) && !contains(flags, str[i]); i++) { if (i > 0 && my_char_isnum(str[i - 1]) && !my_char_isnum(str[i])) break; res[i] = str[i]; } res[i] = 0; return (res); } int print(char **str, int (**fctns)(va_list *, char *), va_list *ap) { char *args = 0; static char *flags = "diouxXcsCSpm%b"; args = flags_manager(*str + 1); if (!contains(flags, (*str)[1 + my_strlen(args)])) { my_putchar('%'); FREE(args); return (1); } *str = *str + 1; *str = *str + my_strlen(args); for (int i = 0; flags[i]; i++) { if (**str == flags[i]) { fctns[i](ap, args); FREE(args); return (0); } } } int my_rec(char *str, int count, va_list *ap, int (**fctns)(va_list *, char *)) { static char *flags = "diouxXcsCSpm%b"; static char *fl = "#0- +'Il"; char *args = ""; if (!*str || (str[0] == '%' && !str[1])) return (count); if (*str != '%') { my_putchar(*str); return (my_rec(str + 1, ++count, ap, fctns)); } if (str[1] && !contains(flags, str[1]) && !my_char_isnum(str[1]) && !contains(fl, str[1])) { my_putchar('%'); return (my_rec(str + 1, ++count, ap, fctns)); } count += print(&str, fctns, ap); return (my_rec(str + 1, count, ap, fctns)); } int my_printf(char *str, ...) { va_list ap; int result = 0; int (*fctns[14])(va_list *, char *) = {&d_int, &d_int, &d_oct, &d_u, &d_hexa, &d_bhexa, &d_char, &d_str, &d_cnp, &d_snp, &d_p, &d_mod, &d_mod, &d_bin}; va_start(ap, str); result = my_rec(str, 0, &ap, fctns); va_end(ap); return (result); }
C
#include<stdio.h> #include<stdlib.h> struct node { char data; struct node* left; struct node* right; }; int search(char arr[], int strt, int end, char value); struct node* newNode(char data); struct node* buildTree(char in[], char pre[], int inStrt, int inEnd) { static int preIndex = 0; if(inStrt > inEnd) return NULL; struct node *tNode = newNode(pre[preIndex++]); if(inStrt == inEnd) return tNode; int inIndex = search(in, inStrt, inEnd, tNode->data); tNode->left = buildTree(in, pre, inStrt, inIndex-1); tNode->right = buildTree(in, pre, inIndex+1, inEnd); return tNode; } int search(char arr[], int strt, int end, char value) { int i; for(i = strt; i <= end; i++) { if(arr[i] == value) return i; } } struct node* newNode(char data) { struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node); } void printInorder(struct node* node) { if (node == NULL) return; printInorder(node->left); printf("%c ", node->data); printInorder(node->right); } void merge(int arr[],int l,int m,int r){ int i,j,k; int n1=m-l+1; int n2=r-m; int L[n1],R[n2]; for(i=0;i<n1;i++){ L[i]=arr[l+i]; } for(i=0;i<n2;i++){ R[i]=arr[m+i+1]; } i=0;j=0,k=l; while(i<n1&&j<n2){ if(L[i]<=R[j]){ arr[k]=L[i++]; } else{ arr[k]=R[j++]; } k++; } while(i<n1){ arr[k++]=L[i++]; } while(j<n2){ arr[k++]=R[j++]; } } void mergeSort(int arr[],int l,int r){ if(l<r){ int m=(l+r)/2; mergeSort(arr,l,m); mergeSort(arr,m+1,r); merge(arr,l,m,r); } } int main() { char in[] = {'D', 'B', 'E', 'A', 'F', 'C'}; char pre[] = {'A', 'B', 'D', 'E', 'C', 'F'}; int len = sizeof(in)/sizeof(in[0]); struct node *root = buildTree(in, pre, 0, len - 1); printf("Inorder traversal of the constructed tree is \n"); printInorder(root); getchar(); }
C
/* ** EPITECH PROJECT, 2020 ** NWP_myteams_2019 ** File description: ** parse_command */ #include "server.h" void parse_command_f5(lklist_char_t *nq, lklist_char_t *str, lklist_str_t *array, lklist_char_t *topush) { bool check = false; for (size_t i = 0; i != nq->size(nq); i += 1) { if (nq->at(nq, i) != ' ' && nq->at(nq, i) != '\t') { if (nq->at(nq, i) == '#') topush->push_back(topush, str->at(str, i)); else topush->push_back(topush, nq->at(nq, i)); check = false; } if (nq->at(nq, i) == ' ' || nq->at(nq, i) == '\t') { if (check == false) { array->push_back(array, topush); topush = lklist_char_init(NULL); } check = true; } } array->push_back(array, topush); } lklist_str_t *parse_command_f4(lklist_char_t *nq, lklist_char_t *str) { lklist_str_t *array = lklist_str_init(NULL); lklist_char_t *topush = lklist_char_init(NULL); parse_command_f5(nq, str, array, topush); nq->free(nq); str->free(str); return array; } lklist_str_t *parse_command_f3(lklist_char_t *nq, lklist_char_t *str) { size_t i = 0; size_t j = 0; lklist_char_t *nq_clean = NULL; lklist_char_t *str_clean = NULL; for (; i != nq->size(nq) && (nq->at(nq, i) == ' ' || nq->at(nq, i) == '\t'); i += 1); if (i == nq->size(nq)) return NULL; j = nq->size(nq) - 1; for (; nq->at(nq, j) == ' ' || nq->at(nq, j) == '\t'; j -= 1) { if (j == 0) break; } j += 1; if (i == j) return NULL; nq_clean = catch_str_ij(i, nq, j); str_clean = catch_str_ij(i, str, j); return parse_command_f4(nq_clean, str_clean); } bool parse_command_f2(bool check, lklist_char_t *nquotes) { if (check == false) { nquotes->push_back(nquotes, '#'); check = true; } else if (check == true) { nquotes->push_back(nquotes, '#'); check = false; } return check; } lklist_str_t *parse_command(lklist_char_t *str) { lklist_char_t *nquotes = lklist_char_init(NULL); lklist_str_t *array = NULL; bool check = false; for (size_t i = 0; i != str->size(str); i += 1) { if (str->at(str, i) == '"') check = parse_command_f2(check, nquotes); else if (str->at(str, i) != '"' && check == false) nquotes->push_back(nquotes, str->at(str, i)); else if (str->at(str, i) != '"' && check == true) nquotes->push_back(nquotes, '#'); } array = parse_command_f3(nquotes, str); nquotes->free(nquotes); return array; }
C
#include "holberton.h" #include <stdio.h> #include <stdlib.h> /** * *create_array - function to create an array of char pre initialised * @size: size of the array * @c: character to initialise the array with * Return: pointer to new array */ char *create_array(unsigned int size, char c) { unsigned int i = 0; char *p; if (size <= 0) return (NULL); p = malloc(size * sizeof(c)); if (p == NULL) return (NULL); while (i < size) { p[i] = c; i++; } return (p); }
C
#ifndef __EVENT_CTL_H__ #define __EVENT_CTL_H__ #include <time.h> #include <stdint.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/epoll.h> #ifndef _TIME_H #define _TIME_H struct timespec { __time_t tv_sec; /* Seconds. */ long int tv_nsec; /* Nanoseconds. */ }; struct itimerspec { struct timespec it_interval; struct timespec it_value; }; #endif #ifndef _SYS_EPOLL_H #define _SYS_EPOLL_H typedef union epoll_data { void *ptr; int fd; uint32_t u32; uint64_t u64; }epoll_data_t; struct epoll_event { uint32_t events; /* Epoll events */ epoll_data_t data; /* User data variable */ }; #endif #define EVENT_TYPE_UNUSED 1 #define EVENT_TYPE_TIMER 2 #define EVENT_TYPE_REAR 3 #define EVENT_TYPE_EVENT 4 #define EVENT_TYPE_IMMEDIATE 5 /*ڸ¼ʱֱӵ̳߳أвʹ*/ #define EVENT_TYPE_READY 6 typedef unsigned int event_type; typedef struct { struct hash *hash; }event_hash; /*Link list of event node*/ typedef struct { struct event_node *head; /**/ struct event_node *tail; int length; }event_list; /*Master of the event*/ #define EVENT_HASH_TABLE_SIZE 2048 struct event_timer { int timerfd; /*file description for set timer*/ struct event_node *event; /*pointer to the event node. when event is null, no timer is set.*/ }; struct event_master { int epollfd; /*epoll file description*/ int expected_size; /*the count of monitoring expectly fd description*/ struct epoll_event *events; /*events for returing*/ int maxevents; /*the max size of returing events*/ unsigned long events_alloc; /*the count of the event allocation*/ /* ֮ǰ̳߳صԭepollԴʱú޷ȡԲtimerfdķʽöʱ */ struct event_timer event_timer; /*the structure of event timer*/ event_list timer; /*the link list of the timer event*/ event_list rear; /*the link list of the rear event*/ event_list unuse; /*the link list of the unuse event*/ event_hash event; /*the hash list of the epoll event*/ event_list ready; /*the link list of the ready event*/ }; /*event itself*/ struct event_node { struct event_node *next; /*next pointer of struct event_node*/ struct event_node *prev; /*previous pointer*/ event_type type; /*event type*/ event_type add_type; /*last event type*/ void (*func)(struct event_node *); /*function*/ uint32_t events; /* Epoll events that event happened */ void *arg; /*event argument*/ int fd; /*file description*/ struct epoll_event listen_event;/*file description's listen event*/ struct itimerspec time; /*timeout*/ struct event_master *master;/*pointer to event master*/ }; #define EVENT_ARG(X) ((X)->arg) #define EVENT_FD(X) ((X)->fd) #define EVENT_UNSET_WRITE(X) (((X)->listen_event.events) &= (~EVENT_WRITE)) #define GET_LISTEN_EVENTS(X) ((X)->listen_event.events) #define EVENT_READ EPOLLIN /*ļɶ*/ #define EVENT_WRITE EPOLLOUT /*ļд*/ #define EVENT_RDHUP EPOLLRDHUP /*ʽ׽ֵĶԶ˹رӣִ˰ر*/ #define EVENT_PRI EPOLLPRI /*ļյ˽*/ #define EVENT_ERR EPOLLERR /*¼DZ*/ #define EVENT_HUP EPOLLHUP /*ļ𣬸¼DZ*/ #define EVENT_EDGE_MODE EPOLLET /*ģʽ*/ #define EVENT_FD_IF_READ(EN) ((EN) & EVENT_READ) #define EVENT_FD_IF_WRITE(EN) ((EN) & EVENT_WRITE) #define EVENT_FD_IF_ERROR(EN) (((EN)&EVENT_ERR) || ((EN)&EVENT_HUP)) /* ļ¼ز󣬽ٱӣ ʱͨEPOLL_CTL_MODԸļϵ¼½м */ #define EVENT_ONESHOT EPOLLONESHOT #define EPOLL_TIMER_ADD(master,timer,func,arg,time)\ do{\ if(!timer)\ timer=event_timer_add(master,func,arg,time);\ }while(0) #define EPOLL_TIMER_ADD_MSEC(master,timer,func,arg,time)\ do{\ if(!timer)\ timer=event_timer_add_msec(master,func,arg,time);\ }while(0) #define EPOLL_REAR_ADD(master,timer,func,arg,time)\ do{\ if(!timer)\ timer=event_rear_add(master,func,arg,time);\ }while(0) #define EPOLL_REAR_ADD_MSEC(master,timer,func,arg,time)\ do{\ if(!timer)\ timer=event_rear_add_msec(master,func,arg,time);\ }while(0) #define EVENT_EXECUTE(func,arg)\ do{\ if(func)\ event_immediate_execute(func,arg);\ }while(0) #define EPOLL_EVENT_ADD(master,event,func,arg,ep_events/*Epoll events*/,fd)\ do{\ if(!event)\ event=event_epoll_add(master,func,arg,ep_events,fd);\ }while(0) #if 1 #define EPOLL_EVENT_MOD(master,event,func,arg,ep_events/*Epoll events*/,fd)\ do{\ struct event_node *epoll_event_node_tmp_2 = event_epoll_mod(master,func,arg,ep_events,fd);\ if(event != epoll_event_node_tmp_2)\ abort();\ else\ event = epoll_event_node_tmp_2;\ }while(0) #endif #define EPOLL_CANCEL(event)\ do{\ if(event)\ {\ event_epoll_del(event);\ event=NULL;\ }\ }while(0) #define EPOLL_TIMER_OFF(X) EPOLL_CANCEL(X) #define EPOLL_EVENT_OFF(X) EPOLL_CANCEL(X) /*create master of event*/ struct event_master *event_master_create(int expected_size, int maxevents); /*destroy master*/ void event_master_destroy(struct event_master *m); /*add timer event: seconds*/ struct event_node *event_timer_add(struct event_master *m, void (*func)(struct event_node *), void *arg, long time); /*add timer event: msec*/ struct event_node *event_timer_add_msec(struct event_master *m, void (*func)(struct event_node *), void *arg, long time); /*add timer event: seconds*/ struct event_node *event_rear_add(struct event_master *m, void (*func)(struct event_node *), void *arg, long time); /*add timer event: msec*/ struct event_node *event_rear_add_msec(struct event_master *m, void (*func)(struct event_node *), void *arg, long time); /*add immediate event: cannot cancel*/ void event_immediate_execute(void (*func)(void *), void *arg); /*add file description's event*/ struct event_node *event_epoll_add(struct event_master *m, void (*func)(struct event_node *), void *arg, uint32_t ep_events,/*Epoll events*/ int fd); #if 1 /*modify file description's event*/ struct event_node *event_epoll_mod(struct event_master *m, void (*func)(struct event_node *), void *arg, uint32_t ep_events,/*Epoll events*/ int fd); #endif #define event_epoll_del(ev) event_cancel(ev) /*look up event by file description*/ struct event_node *event_epoll_lookup_by_fd(struct event_master *m, int fd); /*cancel event*/ void event_cancel(struct event_node *event); /*waiting events happen, and process them*/ struct event_node * event_waiting_process(struct event_master *m, struct event_node *fetch); void event_call(struct event_node *ev); #endif
C
#include <stdio.h> /* * Função que recebe n, que é a quantidade de repetições * e retorna a forma recursiva com a quantidade de repetições em n */ int fibbo (int n) { if(n <= 2){ return 1; } else { return fibbo(n - 1) + fibbo(n - 2); } } void main (void) { int a = fibbo(8); printf("%d\n", a); }
C
#include <stdlib.h> #include <string.h> #include "tree.h" #include <stdio.h> int btree_depth(BTree *tree) { int lD; int rD; lD = 0; rD = 0; if(tree) { lD = btree_depth(tree->right); rD= btree_depth(tree->left); if(lD>rD) return lD+1; else return rD+1; } else return -1; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdbool.h> #include <string.h> #include "IntSet.h" #include "nfa.h" NFA newNFA(int numstates){ //allocate NFA NFA nfa = (NFA)malloc(sizeof(struct nfa)); //initialize NFA nfa->CURR_STATES = NULL; nfa->NUM_STATES = numstates; //allocate transition table nfa->TRANSITION_TABLE = (IntSet**)malloc(numstates * sizeof(IntSet*)); for (int i=0; i<numstates; i++){ nfa->TRANSITION_TABLE[i] = (IntSet *)malloc(128 * sizeof(IntSet)); } //initialize transition table for(int i=0; i<numstates; i++){ for(int j=0; j<128; j++){ nfa->TRANSITION_TABLE[i][j] = IntSet_new(); } } //allocate acceptance table nfa->ACCEPT_TABLE = (bool*)malloc(numstates * sizeof(bool)); //initialize acceptance table for(int i=0; i<numstates; i++){ nfa->ACCEPT_TABLE[i] = false; } return nfa; } void freeNFA(NFA nfa){ for (int i = 0; i < nfa->NUM_STATES; i++) { for(int j=0; j<128; j++){ IntSet_free(nfa->TRANSITION_TABLE[i][j]); } free(nfa->TRANSITION_TABLE[i]); } free(nfa->TRANSITION_TABLE); IntSet_free(nfa->CURR_STATES); free(nfa->ACCEPT_TABLE); free(nfa); } void resetNFA(NFA nfa){ if(nfa->CURR_STATES != NULL){ IntSet_free(nfa->CURR_STATES); } nfa->CURR_STATES = IntSet_new(); IntSet_add(nfa->CURR_STATES, 0); } int NFA_size(NFA nfa){ return nfa->NUM_STATES; } char* NFA_get_description(NFA nfa){ return nfa->DESCRIPTION; } void NFA_set_description(NFA nfa, char* str){ nfa->DESCRIPTION = str; } IntSet NFA_get_transitions(NFA nfa, int src, char sym){ int n = sym; return (nfa->TRANSITION_TABLE)[src][n]; } void NFA_add_transition(NFA nfa, int src, char sym, int dst){ int n = sym; if(!IntSet_contains(nfa->TRANSITION_TABLE[src][n], dst)){ IntSet_add(nfa->TRANSITION_TABLE[src][n], dst); } } void NFA_add_transition_str(NFA nfa, int src, char *str, int dst){ for(int i=0; i<strlen(str); i++){ int sym = str[i]; if(!IntSet_contains(nfa->TRANSITION_TABLE[src][sym], dst)){ IntSet_add(nfa->TRANSITION_TABLE[src][sym], dst); } } } void NFA_add_transition_all(NFA nfa, int src, int dst){ for(int j=0; j<128; j++){ if(!IntSet_contains(nfa->TRANSITION_TABLE[src][j], dst)){ IntSet_add(nfa->TRANSITION_TABLE[src][j], dst); } } } void NFA_set_accepting(NFA nfa, int state, bool value){ nfa->ACCEPT_TABLE[state] = value; } bool NFA_get_accepting(NFA nfa, int state){ return nfa->ACCEPT_TABLE[state]; } bool NFA_execute(NFA nfa, char *input){ resetNFA(nfa); IntSet temp; for(int i=0; i<strlen(input); i++){ int sym = input[i]; temp = IntSet_new(); IntSetIterator curr_iterator = IntSet_iterator(nfa->CURR_STATES); while(IntSetIterator_has_next(curr_iterator)){ int cur = IntSetIterator_next(curr_iterator); IntSet_union(temp, NFA_get_transitions(nfa, cur, sym)); } free(curr_iterator); IntSet_free(nfa->CURR_STATES); nfa->CURR_STATES = temp; IntSet_union(nfa->CURR_STATES, temp); } bool accepted = false; IntSetIterator accept_iterator = IntSet_iterator(nfa->CURR_STATES); while(IntSetIterator_has_next(accept_iterator)){ int cur = IntSetIterator_next(accept_iterator); if(nfa->ACCEPT_TABLE[cur]==true){ // printf("%s\n", "ACCEPTED" ); accepted = true; } } // printf("%s\n",accepted?"true":"false"); free(accept_iterator); return accepted; }
C
#include <stdio.h> #include <stdlib.h> #include "master.h" void validate_arguments(int argc, char **argv) { if (argc != 1 && argc != 2) { fprintf(stderr, "Usage: %s [port]\n", argv[0]); exit(EXIT_FAILURE); } if (argc == 2 && !is_port_number_valid(argv[1])) { fprintf(stderr, "Invalid port number\n"); exit(EXIT_FAILURE); } } void initialize_config(config *c, int argc, char **argv) { if (argc == 2) { c->connection_port = atoi(argv[1]); } else { c->connection_port = -1; } c->finish = false; }
C
#include "console.h" #include "os/kernel.h" #include "string.h" #include "vargs.h" // vsprintf 定义在vsprintf.c中 extern int vsprintf(char * buf, const char * fmt, va_list args); void printk(const char *format, ...) { // 避免频繁创建临时变量,内核的栈很宝贵 static char buff[1024]; va_list args; int i; va_start(args, format); i = vsprintf(buff, format, args); va_end(args); buff[i] = '\0'; console_puts(buff,dc_black,dc_white); } void printk_color(disp_color_t back, disp_color_t fore, const char *format, ...) { // 避免频繁创建临时变量,内核的栈很宝贵 static char buff[1024]; va_list args; int i; va_start(args, format); i = vsprintf(buff, format, args); va_end(args); buff[i] = '\0'; console_puts(buff, back, fore); }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> char *load_memory_init(size_t init_elems) { char *load_ptr; if ( (load_ptr = (char *) malloc(init_elems * sizeof(char) ) ) ) { return load_ptr; free(load_ptr); } else { return NULL; exit(1); } } int program_weight_transform(size_t init_program_weight) { if (0 < init_program_weight && init_program_weight <= 9) { if ( (init_program_weight == 1) ) { int loader_num = init_program_weight * 20000 + 9000; return loader_num; } else { int loader_num = init_program_weight * 10000 + 9000; return loader_num; } } else { return 0; } } void pred_loadbar_init(size_t program_weight) { int i, u = 0; int time_counter = program_weight * 10; char *initer_ptr = load_memory_init(time_counter); if (program_weight_transform(program_weight) != 0) { for(i = 0; i < time_counter; i++) { if (i % 10 == 0) { initer_ptr[u] = '.'; ++u; } printf("Initializing loading process: [%s]", initer_ptr); printf("\r"); fflush(stdout); usleep( program_weight_transform(program_weight) ); } printf("Initializing complete, starting detailed parsing:\n"); } else { printf("PROGRAM_WEIGHT_INPUT_ERROR\n"); exit(0); } } void part_process_loadbar(size_t operation_weight) { int k, point = 0; char *part_ptr = load_memory_init(10); for(k = 0; k <= 100; k++) { if (k % 10 == 0) { part_ptr[point] = '.'; ++point; } printf("[%s]%d%%", part_ptr, k); printf("\r"); fflush(stdout); usleep( program_weight_transform(operation_weight) ); } printf("\n"); } void whole_process_loadbar(size_t ldr_program_weight) { int j, g = 0; char *array_ptr = load_memory_init(20); for(j = 0; j <= 100; j++) { if (j % 5 == 0) { array_ptr[g] = '#'; ++g; } printf("%d%%[%s]", j, array_ptr); printf("\r"); fflush(stdout); usleep( program_weight_transform(ldr_program_weight) - 10000 ); } printf("\n"); printf("Loading sucessfully complete!\n"); printf("\n"); }
C
#include <stdio.h> #include <stdlib.h> void mergeSort(int *, int); void mergePass(int *, int *, int, int); void merge(int *, int *, int, int, int); void input_data(int *, int); void output_data(int *, int); int main() { int *a = NULL; int i, n; printf("Input the length of array:\n"); scanf("%d", &n); a = (int *)malloc(sizeof(int) * n); input_data(a, n); printf("before sorting:\n"); output_data(a, n); mergeSort(a, n); printf("after sorting:\n"); output_data(a, n); free(a); return 0; } void mergeSort(int a[], int n) { int *b = NULL; int s = 1; int count = 1; b = (int *)malloc(sizeof(int) * n); while (s < n) { printf("sort %d:\n", count++); mergePass(a, b, s, n); s += s; printf("sort %d:\n", count++); mergePass(b, a, s, n); s += s; } free(b); } void mergePass(int x[], int y[], int s, int n) { int i = 0; int j; while (i < n - 2 * s) { merge(x, y, i, i + s - 1, i + 2 * s -1); i = i + 2 * s; } if (i + s < n) merge(x, y, i, i + s - 1, n - 1); else for (j = i; j <= n - 1; j++) y[j] = x[j]; for (i = 0; i < n; i++) printf("%d ", y[i]); printf("\n"); } void merge(int c[], int d[], int l, int m, int r) { int i, j, k; i = l; j = m + 1; k = l; while ((i <= m) && (j <= r)) if (c[i] <= c[j]) d[k++] = c[i++]; else d[k++] = c[j++]; int q; if (i > m) for (q = j; q <= r; q++) d[k++] = c[q]; else for (q = i; q <= m; q++) d[k++] = c[q]; } void output_data(int *a, int n) { int i; for (i = 0; i < n; i++) printf("%d ", a[i]); printf("\n"); } void input_data(int *a, int n) { int i; i = 0; printf("Now you can input the data:\n"); while (i < n) { printf("a[%d]=", i); scanf("%d", &a[i]); i++; } }
C
#include <stddef.h> #include <stdio.h> #include <string.h> #include "lua.h" #include "lauxlib.h" #ifndef CPRINT_STREAM # define CPRINT_STREAM stdout #endif #ifndef LUA_QL # define LUA_QL(s) "'" s "'" #endif #define w( s, n ) (fwrite( (s), sizeof( char ), (n), CPRINT_STREAM )) #define tab() (putc( '\t', CPRINT_STREAM )) #define nl() (putc( '\n', CPRINT_STREAM ), fflush( CPRINT_STREAM )) /* Try to figure out if we are a posix or windows environment */ #if defined( _WIN32 ) || defined( _WIN64 ) || defined( __WIN32__ ) || \ defined( __TOS_WIN__ ) || defined( __WINDOWS__ ) /* windows */ #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <io.h> static int color_mapping[] = { 0, /* black */ 4, /* red */ 2, /* green */ 6, /* yellow */ 1, /* blue */ 5, /* magenta/purple */ 3, /* cyan/aqua */ 7, /* white */ 0, 0 /* unused */ }; typedef struct { int enabled; HANDLE hConsole; int last_fg; int last_bg; int last_md; } cprint_info; static void cprint_init( cprint_info* info ) { int fd = _fileno( CPRINT_STREAM ); info->last_fg = 7; info->last_bg = 0; info->last_md = 0; info->enabled = _isatty( fd ); info->hConsole = (HANDLE)_get_osfhandle( fd ); if( info->hConsole == INVALID_HANDLE_VALUE ) info->enabled = 0; } static void cprint_doansi( cprint_info* info, char const* esc, size_t n ) { if( info->enabled ) { char const* p = esc; int high, inverse; p += 2; /* skip ESC and [ */ while( *p != 'm' ) { if( *p == '3' && '0' <= p[1] && p[1] <= '9' ) { int fg = p[1] - '0'; if( fg > 7 ) fg = 7; /* default foreground */ info->last_fg = color_mapping[ fg ]; p += 2; } else if( *p == '4' && '0' <= p[1] && p[1] <= '9' ) { int bg = p[1] - '0'; if( bg > 7 ) bg = 0; /* default background */ info->last_bg = color_mapping[ bg ]; p += 2; } else if( *p != ';' ) { switch( *p ) { case '0': if( p == esc+2 ) { info->last_fg = 7; info->last_bg = 0; } info->last_md = 0; break; case '1': info->last_md = 1; break; case '7': info->last_md = 7; break; default: info->last_md = 0; break; } p += 1; } else p += 1; } high = info->last_md == 1; inverse = info->last_md == 7; SetConsoleTextAttribute( info->hConsole, info->last_fg*(1+inverse*15)+high*8 + info->last_bg*(1+(!inverse)*15) ); } } #elif defined( unix ) || defined( __unix ) || defined( __unix__ ) || \ defined( __TOS_AIX__ ) || defined( _SYSTYPE_BSD ) /* some form of unix */ #include <unistd.h> #include <stdlib.h> typedef struct { int enabled; } cprint_info; /* defined in pr_ansi.h */ static int terminal_supported( char const* term ); static void cprint_init( cprint_info* info ) { char const* term = getenv( "TERM" ); info->enabled = term != NULL && terminal_supported( term ) && isatty( fileno( CPRINT_STREAM ) ); } static void cprint_doansi( cprint_info* info, char const* esc, size_t n ) { if( info->enabled ) w( esc, n ); } #else /* unknown/unsupported OS */ typedef struct { int dummy; } cprint_info; static void cprint_init( cprint_info* info ) { info->dummy = 0; } static void cprint_doansi( cprint_info* info, char const* esc, size_t n ) { (void)info; (void)esc; (void)n; } #endif #include "pr_ansi.h" static int cprint( lua_State* L ) { cprint_info* info = lua_touserdata( L, lua_upvalueindex( 1 ) ); int top = lua_gettop( L ); int i = 0; lua_getglobal( L, "tostring" ); for( i = 1; i <= top; ++i ) { size_t n = 0; char const* s = NULL; lua_pushvalue( L, -1 ); lua_pushvalue( L, i ); lua_call( L, 1, 1 ); s = lua_tolstring( L, -1, &n ); if( s == NULL ) return luaL_error( L, LUA_QL("tostring") " must return a string to " LUA_QL("print") ); if( i > 1 ) tab(); write_ansi( info, s, n ); lua_pop( L, 1 ); } nl(); return 0; } #ifndef CPRINT_API # define CPRINT_API #endif CPRINT_API int luaopen_cprint( lua_State* L ) { cprint_info* info = lua_newuserdata( L, sizeof( cprint_info ) ); cprint_init( info ); lua_pushcclosure( L, cprint, 1 ); return 1; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ld.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dwald <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/02/05 13:32:14 by dwald #+# #+# */ /* Updated: 2018/04/20 18:11:09 by dwald ### ########.fr */ /* */ /* ************************************************************************** */ #include "corewar.h" /* ** Take a random argument and a registry. Load the value of the first argument ** in the registry. Changes the carry. */ static int check_error_ld(int param[], t_champion *champ, t_data *data) { bool error; param[0] = champ->argstype[0]; param[1] = champ->argstype[1]; error = false; if ((param[0] > 3 || param[0] < 1) || (param[1] > 3 || param[1] < 1)) error = true; else if ((param[0] != DIR_CODE && param[0] != IND_CODE) || param[1] != REG_CODE) error = true; if (error == true) { if ((data->verbose & 32) == 32) ft_printf("ERROR: Process %i tries to read instruction's parameter \ with no valid argument type\n", champ->number); return (-2); } else return (0); } static void verbose_ld(t_data *data, t_champion *champ, int val) { char color[7]; if ((data->verbose & 4) == 4) { color_champion(champ->number, color); ft_printf("%sPlayer #%i | ld %i (hex %x) -> r%i\n"RESET, color, champ->number, val, (unsigned int)val, champ->args[1]); } return ; } int corewar_ld(t_data *data, t_champion *champ) { int parameter[2]; int val; val = 0; if (data->debug) dump_state("ld", data, champ); if (check_error_ld((int(*))&parameter, champ, data) == -1) return (-1); if (parameter[0] == DIR_CODE) { champ->reg[champ->args[1]] = champ->args[0]; val = champ->args[0]; } else if (parameter[0] == IND_CODE) { val = get_mem_32bits(champ, idx_address(champ->args[0])); champ->reg[champ->args[1]] = val; } champ->carry = (champ->reg[champ->args[1]] == 0) ? 1 : 0; verbose_ld(data, champ, val); return (1); }
C
#include "Auth.h" CLIENT *cl; int main(int argc, char *argv[]) { int *result; int selection; char choice; if (argc < 2) { printf("USAGE: client <SERVER IP>"); return 1; } cl = clnt_create(argv[1], PRINTER, PRINTER_V1, "tcp"); if (cl == NULL) { printf("error: could not connect to server.\n"); return 1; } while(1) { printFilledLines(); printf("Operations:\n"); printf("To Register [r/R] \n"); printf("To Login [l/L] \n"); printFilledLines(); choice = getchar(); switch(tolower(choice)) { case 'r': RegisterUser(); break; case 'l': Login(); break; default: printf("Enter Valid input."); } } return 0; } void RegisterUser() { struct user *l, new; char username[15],password[15]; int *result; char choice; printf("Enter UserName : \n"); scanf("%s", &username); printf("Enter Password : \n"); scanf("%s", &password); strcpy(new.id, username); strcpy(new.password,password); l = &new; if(isUserAvailable(l)== 1) { result = insert_user_1(l, cl); if (result == NULL) { printf("error: RPC failed!\n"); return 1; } else { printf("Registration successful"); printNewLine(); printf("To login [y]. To Exit [n]"); scanf("%s", &choice); switch(tolower(choice)) { case 'y': Login(); break; case 'n': exit(0); break; default: printf("enter y/n"); } } } else { printf("Username already exists. Try a different one \n"); printNewLine(); printNewLine(); RegisterUser(); } } void Login() { struct user *l, new; char username[15],password[15]; int result; printFilledLines(); printf("Login Page"); printNewLine(); printFilledLines(); printNewLine(); printf("Enter User Name : \n"); scanf("%s", &username); printf("Enter Password : \n"); scanf("%s", &password); strcpy(new.id, username); strcpy(new.password,password); l = &new; result = isAutheticatedUser(l); if(result == 1) { printf("welcome %s !", l->id); printNewLine(); printNewLine(); printNewLine(); exit(0); } else if(result == 2) { printf("Welcome admin! Number of registered users are %d",getAllUserCount()); printNewLine(); printNewLine(); printNewLine(); exit(0); } else { printf("Invalid user"); printNewLine(); printNewLine(); printNewLine(); exit(0); } } int isUserAvailable(user *l) { int *result; result = validate_user_1(l, cl); if (result == NULL) { printf("error: RPC failed!\n"); return 1; } return *result; } int isAutheticatedUser(user *l) { int *result = 0; result = authenticate_user_1(l, cl); if (result == NULL) { printf("error: RPC failed!\n"); return 1; } return *result; } int getAllUserCount() { struct user *l; int *result = 0; result = count_user_1(l, cl); if (result == NULL) { printf("error: RPC failed!\n"); return 1; } return *result; } void printFilledLines() { printf("====================================================== \n"); } void printNewLine() { printf("\n"); }
C
#include <stdio.h> int main (int argc, char*argv[]) { // primeira variavel char a; a = 'X'; // variavel que armazena um ENDERECO de char // (char*) char* p; // armazeno o endereco da primeira variavel p = &a; printf("Endereco inicial: %p\n", p); printf("Conteudo no endereco: %c\n", *p); int x = 1; // for, while while (x <= 10000) { p = p + 1; printf("%p : %c\n", p, *p); x = x + 1; } }
C
#include "matrix_test.h" #include <stdbool.h> #include <stdio.h> #include <assert.h> int main() { clock_t start, end; matrix_t first_input_matrix, second_input_matrix, output_matrix; /** CAUTION: mult function calls "create and fill" function for out matrix, * so do not send a fullly created and filled matrix to function. * This will cause memory leaks as new sectors of the heap will be assigned and * previously allocated blocks lost */ /** MULT LARGE: warning, this is O(n^3) so gets verrry slow at large N*/ printf("Testing mult (large)...\n"); assert (test_create_matrix(&first_input_matrix, 500, 5) && "large matrix fill error"); assert (test_create_matrix(&second_input_matrix, 500, 7) && "large matrix fill error"); printf("Line: %d. Starting clock, please wait for execution to finish... \n", __LINE__); start = clock(); assert (test_mult_matrix(&first_input_matrix, &second_input_matrix, &output_matrix) && "large matrix mult error"); end = clock(); double time_taken = (end - start) / (CLOCKS_PER_SEC); printf("Execution time for mult in seconds: %f \n\n", time_taken); assert(test_free_matrix(&first_input_matrix, false) && "free large memory error"); assert(test_free_matrix(&second_input_matrix, false) && "free large memory error"); assert(test_free_matrix(&output_matrix, false) && "free large memory error"); //printf("Line: %d \n", __LINE__); }
C
#include <smartcard_utils_interface/serialize_util.h> /********************************************************************/ /* Implementation using JSON and Base64/HEX */ /********************************************************************/ #include <smartcard_common/global_vars.h> #include <smartcard_external_utilities/base64.h> #include <smartcard_external_utilities/cJSON.h> #include <smartcard_utils_interface/system_funcs.h> #include <error_codes.h> #include <string.h> void save_status(){ save_smartcard_to_json_file(json_file); } // USE JSON FILES void init_smartcard_from_json_file(char * json_file){ // 1. Open smartcard file FILE * f = fopen(json_file, "rb"); if(f==NULL) exit(ERROR_CANT_OPEN_FILE); // 2. Save to array of char fseek(f, 0, SEEK_END); long fsize = ftell(f); fseek(f, 0, SEEK_SET); //same as rewind(f); char * string = (char*)malloc(fsize + 1); if(string==NULL) exit(ERROR_CANT_MALLOC); if(fread(string, 1, fsize, f) < fsize) exit(ERROR_CANT_READ_FILE); string[fsize] = 0; // 3. Close smartcard file fclose(f); // 4. Call serialize_util.h deserialize_smartcart_status deserialize_smartcard_status(string); // 5. Free allocated string free(string); } void save_smartcard_to_json_file(char * json_file){ //TODO secure write : simulate atomic writing // 1. Open smartcard file FILE * f = fopen(json_file, "w+"); if(f==NULL) exit(ERROR_CANT_OPEN_FILE); // 2. Save to array of char char * json_string = serialize_smartcard_status(); if(json_string==NULL) exit(ERROR_CANT_MALLOC); fputs(json_string, f); // 3. Close smartcard file fclose(f); // 4. Free allocated string free(json_string); } // AUX FUNCTIONS FOR JSON SERIALIZATION void serialize_BYTE(cJSON * object, char * name, BYTE value){ char temp_hex_string[3]; sprintf(temp_hex_string, "%02X", value); cJSON_AddStringToObject(object, name, temp_hex_string); } void deserialize_BYTE(cJSON * object, char * name, BYTE * val) { if(cJSON_HasObjectItem(object, name)){ cJSON* temp_object = cJSON_GetObjectItem(object, name); sscanf(temp_object->valuestring, "%2hhx", val); } // if 'name' is not in the JSON, its 'val' is not affected } void serialize_WORD(cJSON * object, char * name, WORD value){ char temp_hex_string[5]; sprintf(temp_hex_string, "%04X", value); cJSON_AddStringToObject(object, name, temp_hex_string); } void deserialize_WORD(cJSON * object, char * name, BYTE * val) { if(cJSON_HasObjectItem(object, name)){ cJSON* temp_object = cJSON_GetObjectItem(object, name); sscanf(temp_object->valuestring, "%4hx", val); } // if 'name' is not in the JSON, its 'val' is not affected } void serialize_BYTE_ARRAY(cJSON * object, char * name, BYTE * value, WORD length) { int temp_base64_len; char * temp_base64 = base64(value, length, &temp_base64_len); // To Base64, the function allocates memory cJSON_AddStringToObject(object, name, temp_base64); // Add base64 string to JSON free(temp_base64); // free the allocated memory in base64() } void deserialize_BYTE_ARRAY(cJSON * object, char * name, BYTE * val, WORD exp_length) { if(cJSON_HasObjectItem(object, name)){ int temp_unbase64_len; cJSON * temp_object = cJSON_GetObjectItem(object, name); char * temp_unbase64 = unbase64(temp_object->valuestring, strlen(temp_object->valuestring), &temp_unbase64_len); if (temp_unbase64_len != exp_length) exit(ERROR_BAD_JSON_VALUE_LENGTH); mem_cpy(val, temp_unbase64, temp_unbase64_len); free(temp_unbase64); } } // INTERFACE IMPLEMENTATION char* serialize_smartcard_status(){ int i; cJSON *root = cJSON_CreateObject(); // BLOB_STORE_ITEM blob_store [MAX_NUMBER_OF_BLOBS] cJSON* blob_store_json_array = cJSON_CreateArray(); for(i=0; i < MAX_NUMBER_OF_BLOBS; ++i){ cJSON * blob_store_item_json = cJSON_CreateObject(); // BYTE buffer[MAX_BLOB_SIZE] serialize_BYTE_ARRAY(blob_store_item_json, "buffer", blob_store[i].buffer, MAX_BLOB_SIZE); cJSON_AddItemToArray(blob_store_json_array, blob_store_item_json); } cJSON_AddItemToObject(root, "blob_store", blob_store_json_array); // BLOB_CATALOG_ITEM blob_catalog [MAX_NUMBER_OF_BLOBS] cJSON* blob_catalog_json_array = cJSON_CreateArray(); for(i=0; i < MAX_NUMBER_OF_BLOBS; ++i){ cJSON * blob_catalog_item_json = cJSON_CreateObject(); //BYTE exists serialize_BYTE(blob_catalog_item_json, "exists", blob_catalog[i].exists); //BYTE uri[MAX_URI_SIZE] serialize_BYTE_ARRAY(blob_catalog_item_json, "uri", blob_catalog[i].uri, MAX_URI_SIZE); //BYTE uri_size; serialize_BYTE(blob_catalog_item_json, "uri_size", blob_catalog[i].uri_size); //WORD buffer_size; serialize_WORD(blob_catalog_item_json, "buffer_size", blob_catalog[i].buffer_size); cJSON_AddItemToArray(blob_catalog_json_array, blob_catalog_item_json); } cJSON_AddItemToObject(root, "blob_catalog", blob_catalog_json_array); // BYTE master_backup_key [MASTER_BACKUP_KEY_SIZE] serialize_BYTE_ARRAY(root, "master_backup_key", master_backup_key, MASTER_BACKUP_KEY_SIZE); // BYTE root_code[ACCESS_CODE_SIZE] serialize_BYTE_ARRAY(root, "root_code", root_code, ACCESS_CODE_SIZE); // BYTE resurrection_key[RESURRECTION_KEY_SIZE] serialize_BYTE_ARRAY(root, "resurrection_key", resurrection_key, RESURRECTION_KEY_SIZE); // BYTE pin_trials serialize_BYTE(root, "pin_trials", pin_trials); // BYTE puk_trials serialize_BYTE(root, "puk_trials", puk_trials); // BYTE device_id[ID_SIZE] serialize_BYTE_ARRAY(root, "device_id", device_id, ID_SIZE); // WORD x_size serialize_WORD(root, "x_size", x_size); // BYTE device_key[MAX_SMALLINT_SIZE] serialize_BYTE_ARRAY(root, "device_key", device_key, MAX_SMALLINT_SIZE); // BYTE puk[PUK_SIZE] serialize_BYTE_ARRAY(root, "puk", puk, PUK_SIZE); // BYTE pin[PIN_SIZE] serialize_BYTE_ARRAY(root, "pin", pin, PIN_SIZE); // BYTE mode serialize_BYTE(root, "mode", mode); // BYTE auth_keys[NUM_AUTH_KEYS][MAX_BIGINT_SIZE] serialize_BYTE_ARRAY(root, "auth_keys", auth_keys, NUM_AUTH_KEYS*MAX_BIGINT_SIZE); // WORD auth_keys_sizes[NUM_AUTH_KEYS] serialize_BYTE_ARRAY(root, "auth_keys_sizes", auth_keys_sizes, NUM_AUTH_KEYS); // BYTE buffer[BUFFER_MAX_SIZE] serialize_BYTE_ARRAY(root, "buffer", buffer, BUFFER_MAX_SIZE); // WORD buffer_size serialize_WORD(root, "buffer_size", buffer_size); // BYTE authData serialize_BYTE(root, "authData", authData); // GROUP groups[NUM_GROUPS] cJSON* groups_json_array = cJSON_CreateArray(); for(i=0; i < NUM_GROUPS; ++i){ cJSON * groups_item_json = cJSON_CreateObject(); // BYTE group_id serialize_BYTE(groups_item_json, "group_id", groups[i].group_id); // BYTE modulus[MAX_BIGINT_SIZE] serialize_BYTE_ARRAY(groups_item_json, "modulus", groups[i].modulus, MAX_BIGINT_SIZE); // WORD modulus_size serialize_WORD(groups_item_json, "modulus_size", groups[i].modulus_size); // BYTE q[MAX_SMALLINT_SIZE] serialize_BYTE_ARRAY(groups_item_json, "q", groups[i].q, MAX_SMALLINT_SIZE); // WORD q_size serialize_WORD(groups_item_json, "q_size", groups[i].q_size); // BYTE f[MAX_BIGINT_SIZE] serialize_BYTE_ARRAY(groups_item_json, "f", groups[i].f, MAX_BIGINT_SIZE); // WORD f_size serialize_WORD(groups_item_json, "f_size", groups[i].f_size); // BYTE g[NUM_GEN][MAX_BIGINT_SIZE] serialize_BYTE_ARRAY(groups_item_json, "g", groups[i].g, NUM_GEN*MAX_BIGINT_SIZE); // WORD g_size[NUM_GEN] serialize_BYTE_ARRAY(groups_item_json, "g_size", groups[i].g_size, NUM_GEN); // BYTE num_generators serialize_BYTE(groups_item_json, "num_generators", groups[i].num_generators); cJSON_AddItemToArray(groups_json_array, groups_item_json); } cJSON_AddItemToObject(root, "groups", groups_json_array); #if NUM_COUNTERS > 0 // COUNTER counters[NUM_COUNTERS] cJSON* counters_json_array = cJSON_CreateArray(); for(i=0; i < NUM_COUNTERS; ++i){ cJSON * counters_item_json = cJSON_CreateObject(); // BYTE counter_id serialize_BYTE(counters_item_json, "counter_id", counters[i].counter_id); // BYTE key_id serialize_BYTE(counters_item_json, "key_id", counters[i].key_id); // BYTE index serialize_BYTE(counters_item_json, "index", counters[i].index); // BYTE threshold serialize_BYTE(counters_item_json, "threshold", counters[i].threshold); // BYTE cursor[CURSOR_SIZE] serialize_BYTE_ARRAY(counters_item_json, "cursor", counters[i].cursor, CURSOR_SIZE); // BYTE exists serialize_BYTE(counters_item_json, "exists", counters[i].exists); cJSON_AddItemToArray(counters_json_array, counters_item_json); } cJSON_AddItemToObject(root, "counters", counters_json_array); #endif // ISSUER issuers[NUM_ISSUERS] cJSON* issuers_json_array = cJSON_CreateArray(); for(i=0; i < NUM_ISSUERS; ++i){ cJSON * issuers_item_json = cJSON_CreateObject(); // BYTE issuer_id serialize_BYTE(issuers_item_json, "issuer_id", issuers[i].issuer_id); // BYTE group_id serialize_BYTE(issuers_item_json, "group_id", issuers[i].group_id); // BYTE gen_id_1 serialize_BYTE(issuers_item_json, "gen_id_1", issuers[i].gen_id_1); // BYTE gen_id_2 serialize_BYTE(issuers_item_json, "gen_id_2", issuers[i].gen_id_2); // BYTE numpres serialize_BYTE(issuers_item_json, "numpres", issuers[i].numpres); // BYTE counter_id serialize_BYTE(issuers_item_json, "counter_id", issuers[i].counter_id); // BYTE exists serialize_BYTE(issuers_item_json, "exists", issuers[i].exists); cJSON_AddItemToArray(issuers_json_array, issuers_item_json); } cJSON_AddItemToObject(root, "issuers", issuers_json_array); // PROVER provers[NUM_PROVERS] cJSON* provers_json_array = cJSON_CreateArray(); for(i=0; i < NUM_PROVERS; ++i){ cJSON * provers_item_json = cJSON_CreateObject(); // BYTE prover_id serialize_BYTE(provers_item_json, "prover_id", provers[i].prover_id); // WORD ksize serialize_WORD(provers_item_json, "ksize", provers[i].ksize); // WORD csize serialize_WORD(provers_item_json, "csize", provers[i].csize); // BYTE kx[MAX_SMALLINT_SIZE] serialize_BYTE_ARRAY(provers_item_json, "kx", provers[i].kx, MAX_SMALLINT_SIZE); // BYTE c[HASH_SIZE] serialize_BYTE_ARRAY(provers_item_json, "c", provers[i].c, HASH_SIZE); // BYTE proofsession[PROOFSESSION_SIZE] serialize_BYTE_ARRAY(provers_item_json, "proofsession", provers[i].proofsession, PROOFSESSION_SIZE); // BYTE proofstatus serialize_BYTE(provers_item_json, "proofstatus", provers[i].proofstatus); // BYTE cred_ids[NUM_CREDS] serialize_BYTE_ARRAY(provers_item_json, "cred_ids", provers[i].cred_ids, NUM_CREDS); // BYTE cred_ids_size serialize_BYTE(provers_item_json, "cred_ids_size", provers[i].cred_ids_size); // BYTE exists serialize_BYTE(provers_item_json, "exists", provers[i].exists); cJSON_AddItemToArray(provers_json_array, provers_item_json); } cJSON_AddItemToObject(root, "provers", provers_json_array); // BYTE current_prover_id serialize_BYTE(root, "current_prover_id", current_prover_id); // CREDENTIAL credentials[NUM_CREDS] cJSON* credentials_json_array = cJSON_CreateArray(); for(i=0; i < NUM_CREDS; ++i){ cJSON * credentials_item_json = cJSON_CreateObject(); // BYTE credential_id serialize_BYTE(credentials_item_json, "credential_id", credentials[i].credential_id); // BYTE issuer_id serialize_BYTE(credentials_item_json, "issuer_id", credentials[i].issuer_id); // BYTE v[MAX_SMALLINT_SIZE] serialize_BYTE_ARRAY(credentials_item_json, "v", credentials[i].v, MAX_SMALLINT_SIZE); // BYTE kv[MAX_SMALLINT_SIZE] serialize_BYTE_ARRAY(credentials_item_json, "kv", credentials[i].kv, MAX_SMALLINT_SIZE); // BYTE status serialize_BYTE(credentials_item_json, "status", credentials[i].status); // BYTE prescount serialize_BYTE(credentials_item_json, "prescount", credentials[i].prescount); // WORD v_size serialize_WORD(credentials_item_json, "v_size", credentials[i].v_size); // WORD kv_size serialize_WORD(credentials_item_json, "kv_size", credentials[i].kv_size); // BYTE exists serialize_BYTE(credentials_item_json, "exists", credentials[i].exists); cJSON_AddItemToArray(credentials_json_array, credentials_item_json); } cJSON_AddItemToObject(root, "credentials", credentials_json_array); // BYTE temp_key[MAX_BIGINT_SIZE] serialize_BYTE_ARRAY(root, "temp_key", temp_key, MAX_BIGINT_SIZE); //// ALL STATIC DATA ADDED char * res = cJSON_Print(root); // char * res = cJSON_PrintUnformatted(root); cJSON_Delete(root); return res; } void deserialize_smartcard_status(unsigned char * ascii) { cJSON * root = cJSON_Parse(ascii); int i; // BLOB_STORE_ITEM blob_store[MAX_NUMBER_OF_BLOBS] if(cJSON_HasObjectItem(root, "blob_store")){ cJSON * blob_store_json = cJSON_GetObjectItem(root, "blob_store"); if ( blob_store_json->type != cJSON_Array || cJSON_GetArraySize(blob_store_json) != MAX_NUMBER_OF_BLOBS ) exit(ERROR_BAD_JSON_ARRAY_LENGTH); for(i=0; i < MAX_NUMBER_OF_BLOBS; ++i){ cJSON * blob_store_item_json = cJSON_GetArrayItem(blob_store_json, i); // BYTE buffer[MAX_BLOB_SIZE] deserialize_BYTE_ARRAY(blob_store_item_json, "buffer", blob_store[i].buffer, MAX_BLOB_SIZE); } } // BLOB_CATALOG_ITEM blob_catalog[MAX_NUMBER_OF_BLOBS] if(cJSON_HasObjectItem(root, "blob_catalog")){ cJSON * blob_catalog_json = cJSON_GetObjectItem(root, "blob_catalog"); if ( blob_catalog_json->type != cJSON_Array || cJSON_GetArraySize(blob_catalog_json) != MAX_NUMBER_OF_BLOBS ) exit(ERROR_BAD_JSON_ARRAY_LENGTH); for(i=0; i < MAX_NUMBER_OF_BLOBS; ++i){ cJSON * blob_catalog_item_json = cJSON_GetArrayItem(blob_catalog_json, i); // BYTE exists deserialize_BYTE(blob_catalog_item_json, "exists", &(blob_catalog[i].exists)); // BYTE uri[MAX_URI_SIZE] deserialize_BYTE_ARRAY(blob_catalog_item_json, "uri", blob_catalog[i].uri, MAX_URI_SIZE); // BYTE uri_size deserialize_BYTE(blob_catalog_item_json, "uri_size", &(blob_catalog[i].uri_size)); // WORD buffer_size deserialize_WORD(blob_catalog_item_json, "buffer_size", &(blob_catalog[i].buffer_size)); } } // BYTE master_backup_key[MASTER_BACKUP_KEY_SIZE] deserialize_BYTE_ARRAY(root, "master_backup_key", master_backup_key, MASTER_BACKUP_KEY_SIZE); // BYTE root_code[ACCESS_CODE_SIZE] deserialize_BYTE_ARRAY(root, "root_code", root_code, ACCESS_CODE_SIZE); // BYTE resurrection_key[RESURRECTION_KEY_SIZE] deserialize_BYTE_ARRAY(root, "resurrection_key", resurrection_key, RESURRECTION_KEY_SIZE); // BYTE pin_trials deserialize_BYTE(root, "pin_trials", &pin_trials); // BYTE puk_trials deserialize_BYTE(root, "puk_trials", &puk_trials); // BYTE device_id[ID_SIZE] deserialize_BYTE_ARRAY(root, "device_id", device_id, ID_SIZE); // WORD x_size deserialize_WORD(root, "x_size", &x_size); // BYTE device_key[MAX_SMALLINT_SIZE] deserialize_BYTE_ARRAY(root, "device_key", device_key, MAX_SMALLINT_SIZE); // BYTE puk[PUK_SIZE] deserialize_BYTE_ARRAY(root, "puk", puk, PUK_SIZE); // BYTE pin[PIN_SIZE] deserialize_BYTE_ARRAY(root, "pin", pin, PIN_SIZE); // BYTE mode deserialize_BYTE(root, "mode", &mode); // BYTE auth_keys[NUM_AUTH_KEYS][MAX_BIGINT_SIZE] deserialize_BYTE_ARRAY(root, "auth_keys", auth_keys, NUM_AUTH_KEYS*MAX_BIGINT_SIZE); // WORD auth_keys_sizes[NUM_AUTH_KEYS] deserialize_BYTE_ARRAY(root, "auth_keys_sizes", auth_keys_sizes, NUM_AUTH_KEYS); // BYTE buffer[BUFFER_MAX_SIZE] deserialize_BYTE_ARRAY(root, "buffer", buffer, BUFFER_MAX_SIZE); // WORD buffer_size deserialize_WORD(root, "buffer_size", &buffer_size); // BYTE authData deserialize_BYTE(root, "authData", &authData); // GROUP groups[NUM_GROUPS] if(cJSON_HasObjectItem(root, "groups")){ cJSON * groups_json = cJSON_GetObjectItem(root, "groups"); if ( groups_json->type != cJSON_Array || cJSON_GetArraySize(groups_json) != NUM_GROUPS ) exit(ERROR_BAD_JSON_ARRAY_LENGTH); for(i=0; i < NUM_GROUPS; ++i){ cJSON * groups_item_json = cJSON_GetArrayItem(groups_json, i); // BYTE group_id deserialize_BYTE(groups_item_json, "group_id", &(groups[i].group_id)); // BYTE modulus[MAX_BIGINT_SIZE] deserialize_BYTE_ARRAY(groups_item_json, "modulus", groups[i].modulus, MAX_BIGINT_SIZE); // WORD modulus_size deserialize_WORD(groups_item_json, "modulus_size", &(groups[i].modulus_size)); // BYTE q[MAX_SMALLINT_SIZE] deserialize_BYTE_ARRAY(groups_item_json, "q", groups[i].q, MAX_SMALLINT_SIZE); // WORD q_size deserialize_WORD(groups_item_json, "q_size", &(groups[i].q_size)); // BYTE f[MAX_BIGINT_SIZE] deserialize_BYTE_ARRAY(groups_item_json, "f", groups[i].f, MAX_BIGINT_SIZE); // WORD f_size deserialize_WORD(groups_item_json, "f_size", &(groups[i].f_size)); // BYTE g[NUM_GEN][MAX_BIGINT_SIZE] deserialize_BYTE_ARRAY(groups_item_json, "g", groups[i].g, NUM_GEN*MAX_BIGINT_SIZE); // WORD g_size[NUM_GEN] deserialize_BYTE_ARRAY(groups_item_json, "g_size", groups[i].g_size, NUM_GEN); // BYTE num_generators deserialize_BYTE(groups_item_json, "num_generators", &(groups[i].num_generators)); } } #if NUM_COUNTERS > 0 // COUNTER counters[NUM_COUNTERS] if(cJSON_HasObjectItem(root, "counters")){ cJSON * counters_json = cJSON_GetObjectItem(root, "counters"); if ( counters_json->type != cJSON_Array || cJSON_GetArraySize(counters_json) != NUM_COUNTERS ) exit(ERROR_BAD_JSON_ARRAY_LENGTH); for(i=0; i < NUM_COUNTERS; ++i){ cJSON * counters_item_json = cJSON_GetArrayItem(counters_json, i); // BYTE counter_id deserialize_BYTE(counters_item_json, "counter_id", &(counters[i].counter_id)); // BYTE key_id deserialize_BYTE(counters_item_json, "key_id", &(counters[i].key_id)); // BYTE index deserialize_BYTE(counters_item_json, "index", &(counters[i].index)); // BYTE threshold deserialize_BYTE(counters_item_json, "threshold", &(counters[i].threshold)); // BYTE cursor[CURSOR_SIZE] deserialize_BYTE_ARRAY(counters_item_json, "cursor", counters[i].cursor, CURSOR_SIZE); // BYTE exists deserialize_BYTE(counters_item_json, "exists", &(counters[i].exists)); } } #endif // ISSUER issuers[NUM_ISSUERS] if(cJSON_HasObjectItem(root, "issuers")){ cJSON * issuers_json = cJSON_GetObjectItem(root, "issuers"); if ( issuers_json->type != cJSON_Array || cJSON_GetArraySize(issuers_json) != NUM_ISSUERS ) exit(ERROR_BAD_JSON_ARRAY_LENGTH); for(i=0; i < NUM_ISSUERS; ++i){ cJSON * issuers_item_json = cJSON_GetArrayItem(issuers_json, i); // BYTE issuer_id deserialize_BYTE(issuers_item_json, "issuer_id", &(issuers[i].issuer_id)); // BYTE group_id deserialize_BYTE(issuers_item_json, "group_id", &(issuers[i].group_id)); // BYTE gen_id_1 deserialize_BYTE(issuers_item_json, "gen_id_1", &(issuers[i].gen_id_1)); // BYTE gen_id_2 deserialize_BYTE(issuers_item_json, "gen_id_2", &(issuers[i].gen_id_2)); // BYTE numpres deserialize_BYTE(issuers_item_json, "numpres", &(issuers[i].numpres)); // BYTE counter_id deserialize_BYTE(issuers_item_json, "counter_id", &(issuers[i].counter_id)); // BYTE exists deserialize_BYTE(issuers_item_json, "exists", &(issuers[i].exists)); } } // PROVER provers[NUM_PROVERS] if(cJSON_HasObjectItem(root, "provers")){ cJSON * provers_json = cJSON_GetObjectItem(root, "provers"); if ( provers_json->type != cJSON_Array || cJSON_GetArraySize(provers_json) != NUM_PROVERS ) exit(ERROR_BAD_JSON_ARRAY_LENGTH); for(i=0; i < NUM_PROVERS; ++i){ cJSON * provers_item_json = cJSON_GetArrayItem(provers_json, i); // BYTE prover_id deserialize_BYTE(provers_item_json, "prover_id", &(provers[i].prover_id)); // WORD ksize deserialize_WORD(provers_item_json, "ksize", &(provers[i].ksize)); // WORD csize deserialize_WORD(provers_item_json, "csize", &(provers[i].csize)); // BYTE kx[MAX_SMALLINT_SIZE] deserialize_BYTE_ARRAY(provers_item_json, "kx", provers[i].kx, MAX_SMALLINT_SIZE); // BYTE c[HASH_SIZE] deserialize_BYTE_ARRAY(provers_item_json, "c", provers[i].c, HASH_SIZE); // BYTE proofsession[PROOFSESSION_SIZE] deserialize_BYTE_ARRAY(provers_item_json, "proofsession", provers[i].proofsession, PROOFSESSION_SIZE); // BYTE proofstatus deserialize_BYTE(provers_item_json, "proofstatus", &(provers[i].proofstatus)); // BYTE cred_ids[NUM_CREDS] deserialize_BYTE_ARRAY(provers_item_json, "cred_ids", provers[i].cred_ids, NUM_CREDS); // BYTE cred_ids_size deserialize_BYTE(provers_item_json, "cred_ids_size", &(provers[i].cred_ids_size)); // BYTE exists deserialize_BYTE(provers_item_json, "exists", &(provers[i].exists)); } } // BYTE current_prover_id deserialize_BYTE(root, "current_prover_id", &current_prover_id); // CREDENTIAL credentials[NUM_CREDS] if(cJSON_HasObjectItem(root, "credentials")){ cJSON * credentials_json = cJSON_GetObjectItem(root, "credentials"); if ( credentials_json->type != cJSON_Array || cJSON_GetArraySize(credentials_json) != NUM_CREDS ) exit(ERROR_BAD_JSON_ARRAY_LENGTH); for(i=0; i < NUM_CREDS; ++i){ cJSON * credentials_item_json = cJSON_GetArrayItem(credentials_json, i); // BYTE credential_id deserialize_BYTE(credentials_item_json, "credential_id", &(credentials[i].credential_id)); // BYTE issuer_id deserialize_BYTE(credentials_item_json, "issuer_id", &(credentials[i].issuer_id)); // BYTE v[MAX_SMALLINT_SIZE] deserialize_BYTE_ARRAY(credentials_item_json, "v", credentials[i].v, MAX_SMALLINT_SIZE); // BYTE kv[MAX_SMALLINT_SIZE] deserialize_BYTE_ARRAY(credentials_item_json, "kv", credentials[i].kv, MAX_SMALLINT_SIZE); // BYTE status deserialize_BYTE(credentials_item_json, "status", &(credentials[i].status)); // BYTE prescount deserialize_BYTE(credentials_item_json, "prescount", &(credentials[i].prescount)); // WORD v_size deserialize_WORD(credentials_item_json, "v_size", &(credentials[i].v_size)); // WORD kv_size deserialize_WORD(credentials_item_json, "kv_size", &(credentials[i].kv_size)); // BYTE exists deserialize_BYTE(credentials_item_json, "exists", &(credentials[i].exists)); } } // BYTE temp_key[MAX_BIGINT_SIZE] deserialize_BYTE_ARRAY(root, "temp_key", temp_key, MAX_BIGINT_SIZE); //// ALL STATIC DATA ADDED cJSON_Delete(root); }
C
#include <stdio.h> void ifAndElse(int n) { if (n < 10) { printf("Oh no!"); } if (n > 10) { printf("Hey!"); } else { printf("Hey!"); } } void ifAndElse2(int n) { if (n < 10) { printf("Oh no!"); } if (n > 10) { printf("Hey!"); } else { printf("Hey!"); } } int main() { ifAndElse(20); ifAndElse2(18); }
C
#include <stdio.h> #include <unistd.h> #include "threadPool.h" #include "osqueue.h" void stupid_task(void *a) { printf("\n\t1 + 1 = 3\n"); } void test_thread_pool_sanity(int numThreads) { ThreadPool *tp = tpCreate(numThreads); int i; for (i = 0; i < numThreads; ++i) { tpInsertTask(tp, stupid_task, NULL); } tpDestroy(tp, 0); } //test my thread pool int main() { // arg is num of threads test_thread_pool_sanity(5); ThreadPool *tp = tpCreate(3); tpDestroy(tp, 0); return 0; }
C
#include<stdio.h> int main() { float fahr,celsius; //declaration int lower, upper,step; lower = 0; /*lower limit */ upper = 300; /* upper limit */ step = 20; /* step size */ fahr = lower; while(fahr <= upper){ celsius = (5.0/9.0) * (fahr-32.0); printf("%3.0f\t%6.1f\n",fahr,celsius); fahr = fahr + step; } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* tester_read.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: user42 <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/04/09 18:30:59 by user42 #+# #+# */ /* Updated: 2021/04/19 19:45:25 by user42 ### ########.fr */ /* */ /* ************************************************************************** */ #include "tester.h" void ft_read_test_full(char *file, int n, int *success, size_t buf_size) { ssize_t ret; char buf[buf_size]; int fd; int err; ssize_t ftret; char ftbuf[buf_size]; int ftfd; int fterr; display_test_name(n); fd = open(file, O_RDONLY); ftfd = open(file, O_RDONLY); display_type_arg("size_t", "BUFFER_SIZE"); printf(" = '%zd';\n", buf_size); display_type_return("char *"); ret = read(fd, buf, buf_size); buf[ret] = '\0'; printf("read : '%s'\n", buf); err = errno; printf("ret = %ld\nerrno = %d\n", ret, err); ftret = ft_read(ftfd, ftbuf, buf_size); ftbuf[ftret] = '\0'; printf("ft_read : '%s'\n", ftbuf); fterr = errno; printf("ftret = %ld\nerrno = %d\n", ftret, fterr); printf("Resultat : "); if (ret != ftret || fterr != err) test_failure(); else *success = *success + test_success(); printf("\n\n"); close(fd); close(ftfd); } void ft_read_test(char *file, int n, int *success, size_t buf_size) { ssize_t ret; char buf[buf_size]; int fd; int err; ssize_t ftret; char ftbuf[buf_size]; int ftfd; int fterr; blue(); printf("Test [%02d] : ", n); reset_color(); fd = open(file, O_RDONLY); ftfd = open(file, O_RDONLY); ret = read(fd, buf, buf_size); err = errno; ftret = ft_read(ftfd, ftbuf, buf_size); fterr = errno; if (ret != ftret || fterr != err) test_failure(); else *success = *success + test_success(); close(fd); close(ftfd); } int ft_read_tester(int output) { int success = 0; ssize_t ret; blue(); printf(" (-------) \n"); printf(" -<( FT_READ )>- \n"); printf(" (-------) \n\n"); reset_color(); if (output == 1) { ft_read_test_full("Tester/test.txt", 1, &success, 0); ft_read_test_full("Tester/test.txt", 2, &success, 2); ft_read_test_full("Tester/test.txt", 3, &success, -10); ft_read_test_full("Tester/test.txt", 4, &success, 256); ft_read_test_full("Tester/test.txt", 5, &success, 600); ft_read_test_full("Tester/test.txt", 6, &success, 255); ft_read_test_full("Tester/blank.txt", 7, &success, 0); ft_read_test_full("Tester/blank.txt", 8, &success, -10); ft_read_test_full("Tester/blank.txt", 9, &success, 2); ft_read_test_full("Tester/blank.txt", 10, &success, 4); ft_read_test_full("Tester/blank.txt", 11, &success, 60); ft_read_test_full("Tester/blank.txt", 12, &success, 255); } else { ft_read_test("Tester/test.txt", 1, &success, 0); ft_read_test("Tester/test.txt", 2, &success, 2); ft_read_test("Tester/test.txt", 3, &success, -10); ft_read_test("Tester/test.txt", 4, &success, 256); ft_read_test("Tester/test.txt", 5, &success, 600); ft_read_test("Tester/test.txt", 6, &success, 255); ft_read_test("Tester/blank.txt", 7, &success, 0); ft_read_test("Tester/blank.txt", 8, &success, -10); ft_read_test("Tester/blank.txt", 9, &success, 2); ft_read_test("Tester/blank.txt", 10, &success, 4); ft_read_test("Tester/blank.txt", 11, &success, 60); ft_read_test("Tester/blank.txt", 12, &success, 255); } if (success == 12) green(); else red(); printf(" -<( %d/12 )>-\n\n", success); reset_color(); return ((success == 12) ? 1 : 0); }
C
/* $Id: tekpot.c,v 1.3 2010/01/31 08:30:19 demon Exp $ */ /* * Copyright (c) 2009 Dimitri Sokolyuk <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct point Point; typedef struct patch Patch; struct point { float x, y, z; } *point, *ppoint, max; struct patch { int p[16]; } *patch, *ppatch; int tekheight = 3072; int tekwidth = 4096; int npoints = 100; void loadpatch(char *filename, int *patches, int *verticles) { int i, k; float x, y, z; int a, b, c, d; FILE *fd; fd = fopen(filename, "r"); if (!fd) err(1, "can't open %s", filename); fscanf(fd, "%i\n", patches); patch = calloc(*patches, sizeof(Patch)); if (!patch) err(1, "can't allocate memory"); ppatch = patch; for (i = 0; i < *patches; i++) { k = 0; fscanf(fd, "%i, %i, %i, %i,", &a, &b, &c, &d); ppatch->p[k++] = --a; ppatch->p[k++] = --b; ppatch->p[k++] = --c; ppatch->p[k++] = --d; fscanf(fd, "%i, %i, %i, %i,", &a, &b, &c, &d); ppatch->p[k++] = --a; ppatch->p[k++] = --b; ppatch->p[k++] = --c; ppatch->p[k++] = --d; fscanf(fd, "%i, %i, %i, %i,", &a, &b, &c, &d); ppatch->p[k++] = --a; ppatch->p[k++] = --b; ppatch->p[k++] = --c; ppatch->p[k++] = --d; fscanf(fd, "%i, %i, %i, %i\n", &a, &b, &c, &d); ppatch->p[k++] = --a; ppatch->p[k++] = --b; ppatch->p[k++] = --c; ppatch->p[k++] = --d; ++ppatch; } fscanf(fd, "%i\n", verticles); point = calloc(*verticles, sizeof(Point)); if (!point) err(1, "can't allocate memory"); ppoint = point; max.x = 0; max.y = 0; max.z = 0; for (i = 0; i < *verticles; i++) { fscanf(fd, "%f, %f, %f\n", &x, &y, &z); ppoint->x = x; if (abs(x) > max.x) max.x = abs(x); ppoint->y = y; if (abs(y) > max.y) max.y = abs(y); ppoint->z = z; if (abs(z) > max.z) max.z = abs(z); ++ppoint; } fclose(fd); } int rnd(float f) { if (f > 0) f += 0.5; else f -= 0.5; return (int)f; } void rotx(Point *p) { p->y = 0.5 * p->y + 0.866 * p->z; p->z = -0.866 * p->y + 0.5 * p->z; } void project(Point *p) { float d = 100 * max.z; float zoom = 1000; rotx(p); p->x *= d/(2*d - p->z); p->y *= d/(2*d - p->z); p->x *= zoom; p->y *= zoom; p->x += tekwidth/2; p->y += tekheight/3; } void vec(Point *a, Point *b, float lambda) { a->x += lambda*(b->x - a->x); a->y += lambda*(b->y - a->y); a->z += lambda*(b->z - a->z); } #if 0 void bernstein(int steps) { int uinc = 1.0/steps; int u = uinc; for (i = 1; i < steps; i++, u += uinc) { u_sqr = u * u; /* u^2 */ tmp = 1.0 - u; /* (1-u) */ tmp_sqr = tmp * tmp; /* (1-u)^2 */ b[0][i] = tmp * tmp_sqr; /* (1-u)^3 */ b[1][i] = 3 * u * tmp_sqr; /* 3u(1-u)^2 */ b[2][i] = 3 * u_sqr * tmp; /* 3u^2(1-u) */ b[2][i] = u * u_sqr; /* u^3 */ } } #endif void bezier(Patch *pp, int steps) { Point p[16]; int i, j, k, step; float s; for (step = 0; step < steps; step++) { for (i = 0; i < 16; i++) { k = pp->p[i]; p[i].x = point[k].x; p[i].y = point[k].y; p[i].z = point[k].z; } s = (float)step/(float)steps; for (i = 15; i > 0; i--) for (j = 0; j < i; j++) vec(&p[j], &p[j + 1], s); project(p); iplot(!!step, rnd(p->x), rnd(p->y)); } } void usage() { extern char *__progname; fprintf(stderr, "usage: %s datafile\n", __progname); exit(1); } int main(int argc, char **argv) { int patches, verticles; int i, j; if (argc != 2) usage(); loadpatch(*++argv, &patches, &verticles); inittek(); page(); for (i = 0; i < patches; i++) bezier(&patch[i], npoints); endtek(); return 0; }
C
int main(void) { int num[1000]; // ???? int n; // ??2?n?? memset(num, 0, sizeof(num)); num[0] = 1; cin >> n; for(int i = 1; i <= n; i++) { for(int j = 0; j < 1000; j++) { num[j] *= 2; // ????2 } for(int j = 0; j < 1000; j++) // ?? { if(num[j] >= 10) { num[j] -= 10; num[j + 1]++; // ????? } } } int x; for(x = 999; num[x] == 0; x--); // ?????? for(; x >= 0; x--) // ???? { cout << num[x]; } cout << endl; return 0; }
C
#include<stdio.h> #include<conio.h> void buscar(char mat[4][20], char npesquisa[20]); main(){ char mat[4][20], npesquisa[20]; int linha=0; for(linha=0; linha<=3; linha++){ printf("Digite o nome[%d] =",linha); gets(mat[linha]); } printf("Digite um nome para pesquisar: "); gets(npesquisa); buscar(mat, npesquisa); getch(); } void buscar(char mat[4][20], char npesquisa[20]){ int linha=0; for(linha=0; linha<=3; linha++){ if(strcmp(mat[linha],npesquisa)==0){ break; } } if(linha!=4){ printf("Encontrado na linha %d\n",linha); }else{ printf("Nao encontrado!\n"); } }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdarg.h> #include <string.h> #include "coreServ.h" #include "../linkedlist.h" #include "../utils.h" #include "../parser.h" #include "../commands.h" char* gameManager(int* idGame, int idCli,linkedlist_t args, linkedlist_t* listGames, int* currentIndex){ //linkedlist_t listCommand = NULL; char* commands = NULL; int choix = 0; printf("List game size %d\n", sizeL(*listGames)); if(*idGame == -1){ if(!isEmptyL(args)){ element* el = popL(&args); choix = (int)el->val; switch(choix){ case GAME_PENDU: outc(&commands, "%s", "Pendu\n"); break; case GAME_MORPION: outc(&commands, "%s", "Morpion\n"); break; case CHOICE_EXIT: outc(&commands, "%s", "Quitter\n"); break; default: outc(&commands, "%s", "Choix incorrect...\n\n"); waitc(&commands, 1); choix = 0; break; } if(choix != 0 && choix != CHOICE_EXIT){ element* el; for(el = *listGames; el != NULL; el = el->next){ game_t* curGame = (game_t*)el->val; printf("Type G : %d\n", curGame->idTypeGame); if(curGame->idTypeGame == choix && curGame->nbPlayer < 2){ *idGame = curGame->id; curGame->nbPlayer++; outc(&commands, "%s", "La partie peut commencer...\n"); waitc(&commands, 15); // On attend pour le moment break; } } if(*idGame == -1){ game_t *nwGameP = malloc(sizeof(game_t)); // Le pointeur à enregistrer dans la liste nwGameP->id = *currentIndex; nwGameP->idTypeGame = choix; nwGameP->nbPlayer = 1; nwGameP->pipeW = 0; nwGameP->pipeR = 0; printf("Type nwGame : %d\n", nwGameP->idTypeGame); *listGames = addHeadL(*listGames, nwGameP, OTHER); *currentIndex += 1; *idGame = nwGameP->id; outc(&commands, "%s", "En attente d'un autre joueur.\n"); waitc(&commands, 5); } } } //////////////////////////////////////////////////////////////////////// //// MENU //// //////////////////////////////////////////////////////////////////////// if(choix == 0){ systemc(&commands, "clear"); outc(&commands, "%s", "=================== MENU ===================\n"); outc(&commands, "%d %s", GAME_PENDU, ". Pendu\n"); outc(&commands, "%d %s", GAME_MORPION, ". Morpion\n"); outc(&commands, "%d %s", CHOICE_EXIT, ". Quitter\n"); inc(&commands, "%d"); } } else{ // Si idGame != -1 Càd si le joueur est déjà dans une partie //////////////////////////////////////////////////////////////////////// //// Parties en cours (ou attente) //// //////////////////////////////////////////////////////////////////////// element* el; game_t curGame; for(el = *listGames; el != NULL; el = el->next){ curGame = *(game_t*)el->val; if(curGame.id == *idGame){ break; } } if(el == NULL){ outc(&commands, "%s", "Erreur : Impossible de trouver la partie.\n"); *idGame = -1; } else{ if(curGame.nbPlayer < 2){ outc(&commands, "%s", "."); // On attend toujours un autre joueur waitc(&commands, 5); } else{ outc(&commands, "%s", "La partie peut commencer...\n"); waitc(&commands, 15); // On attends pour le moment } } } /*commands = listToStringL(listCommand); listCommand = cleanL(listCommand, 1); // Vide la liste*/ return commands; } linkedlist_t getRespCli(char* resp){ linkedlist_t list = NULL; char* str; char* arg = NULL; TypeArg_e resTypeArg; str = strchr(resp, '['); if(str == NULL){ return NULL; } str += 1; while(*str != ']' && *str != ';' && *str != '\0'){ resTypeArg = recupArg(&str, &arg); if(resTypeArg == A_ERROR){ // Argument introuvable break; } else if(resTypeArg == A_STRING){ // Ajoute une Chaine list = addHeadL(list, (void*)arg, STRING); } else if(resTypeArg == A_INT){ // Ajoute un nombre list = addHeadL(list, (void*)atoi(arg), INT); free(arg); } else{ // Ajoute un float float* respFloat = malloc(sizeof(float)); *respFloat = (float)atof(arg); list = addHeadL(list, respFloat, FLOAT); free(arg); } } return list; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> struct Student{ char name[50]; int score[5]; double average, total; }; /* int main() { int i; FILE *fp; struct Student *p; int n; printf("student num : "); scanf("%d",&n); p = (struct student*)malloc(n * sizeof(struct Student)); fp = fopen("/home/socmgr/iuy/0710/students.txt","w"); if(fp == NULL){ printf("Write Error\n"); return 0; } for(i=0; i<n ; i++){ printf("%d student name : ",i+1); scanf("%s",p[i].name); printf("math : "); scanf("%d",&p[i].score[0]); printf("science : "); scanf("%d",&p[i].score[1]); printf("social : "); scanf("%d",&p[i].score[2]); p[i].total = p[i].score[0] + p[i].score[1] + p[i].score[2]; p[i].average = p[i].total / 3; } fprintf(fp,"student num : %d\n",n); for(i=0; i<n ; i++){ fprintf(fp,"%s - math:%d, science:%d, social:%d average:%.2f \n",p[i].name,p[i].score[0],p[i].score[1],p[i].score[2],p[i].average); } fclose(fp); free(p); return 0; } */ int main() { int i=0; FILE *fp; struct Student *p; char words[20]; int n; fp = fopen("/home/socmgr/iuy/0710/students.txt","r"); if(fp == NULL){ printf("Read Error\n"); return 0; } fscanf(fp,"student num : %d",&n); p = (struct student*)malloc(n * sizeof(struct Student)); for(i=0; i<n ; i++){ fscanf(fp," name: %s",p[i].name); fscanf(fp," %s",&words); if(strcmp(words,"math:")==0){ fscanf(fp,"%d",&p[i].score[0]); } else if(strcmp(words,"science:")==0){ fscanf(fp,"%d",&p[i].score[1]); } else if(strcmp(words,"social:")==0){ fscanf(fp,"%d",&p[i].score[2]); } fscanf(fp," %s",&words); if(strcmp(words,"math:")==0){ fscanf(fp,"%d",&p[i].score[0]); } else if(strcmp(words,"science:")==0){ fscanf(fp,"%d",&p[i].score[1]); } else if(strcmp(words,"social:")==0){ fscanf(fp,"%d",&p[i].score[2]); } fscanf(fp," %s",&words); if(strcmp(words,"math:")==0){ fscanf(fp,"%d",&p[i].score[0]); } else if(strcmp(words,"science:")==0){ fscanf(fp,"%d",&p[i].score[1]); } else if(strcmp(words,"social:")==0){ fscanf(fp,"%d",&p[i].score[2]); } fscanf(fp," average: %lf",&p[i].average); printf("name: %s math:%d, science:%d, social:%d average:%.2f \n", p[i].name, p[i].score[0], p[i].score[1], p[i].score[2], p[i].average); } printf("\n"); fclose(fp); free(p); return 0; }
C
/*#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <string.h> #include <arpa/inet.h> */ #include "../include/my.h" int my_strlen(char const *str) { int n = 0; while (*(str + n)) ++n; return (n); } void my_putchar(char c) { write(1, &c, 1); } int my_put_base(unsigned int nb, char *base) { int deep = my_strlen(base); int modulo; if (nb <= deep && nb >= 0 ) my_putchar(base[nb]); if (nb > deep) { modulo = nb % deep; my_put_base(nb / deep, base); my_putchar(base[modulo]); } return (0); } int convert(u_int32_t num) { u_int32_t b0; u_int32_t b1; u_int32_t b2; u_int32_t b3; u_int32_t res; b0 = (num & 0x000000ff) << 24u; b1 = (num & 0x0000ff00) << 8u; b2 = (num & 0x00ff0000) >> 8u; b3 = (num & 0xff000000) >> 24u; res = b0 | b1 | b2 | b3; printf("%u\n", res); my_put_base(res, "0123456789abcdef"); write(1, "\n", 1); return (0); } void bin(unsigned n) { unsigned i; for (i = 1 << 31; i > 0; i = i / 2) (n & i)? printf("1"): printf("0"); printf("\n"); } //print numbers big endian:wq // int boot(char *buf, size_t size) { //256 is size/4; u_int32_t a[256]; u_int32_t b[256]; for (int i = 0; i < 256; ++i) { memcpy(&a[i], buf, 4); a[i] = htonl(a[i]); buf += 4; bin(a[i]); printf("%u\n", a[i]); } //for (int i = 0; i < 256; ++i) { // printf("%u\n", htonl(a[i])); //} return (0); } int main(int ac, char **av) { char *buf; struct stat st; size_t size; int fd; stat("./um.um", &st); size = st.st_size; buf = malloc(sizeof(char) * size + 1); fd = open("./um.um", O_RDONLY); read(fd, buf, size); close(fd); boot(buf, size); return (0); }
C
#include<stdio.h> #include<sys/types.h> #include<sys/wait.h> #include<unistd.h> #include<fcntl.h> #include<time.h> #include<ctype.h> #include<getopt.h> #include<stdlib.h> #include<sys/mman.h> #include"vector.h" #define MAX_SIZE 65100 int get_error(int argc, char* argv[]){ if(argc<4){ printf("The usage: \ ./detect -t [time format] (-c) -l [limit] cmd args\n"); return 1; } return 0; } void print_time(const char* time_format){ char TIME[50]; time_t raw_time; time(&raw_time); struct tm* info=localtime(&raw_time); strftime(TIME, 50, time_format, info); printf("%s\n", TIME); } // time_format, n_proc, exit_code, cmd, args int main(int argc, char* argv[]){ // if(get_error(argc, argv)) return 1; int n_proc=0, exit_code=0, interval=0; char time_format[30], *cmd, *args; int tube[2]; char* old_buf=(char*)mmap(NULL, MAX_SIZE*sizeof(char), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, 0, 0); CHECK_MEMORY(old_buf); cmd=(char*)mmap(NULL, 100*sizeof(char), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, 0, 0); args=(char*)mmap(NULL, 100*sizeof(char), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, 0, 0); old_buf[0]='\0'; time_format[0]='\0'; int opt, cnt=0; while((opt=getopt(argc, argv, "+cl:t:i: "))!=-1){ switch(opt){ case 'c': if(!exit_code){ exit_code=1; // printf("Exit code status: %d\n", exit_code); } break; case 'l': if(!n_proc){ n_proc=atoi(optarg); // printf("Limit: %d\n", n_proc); } break; case 't': if(time_format[0]=='\0'){ strcpy(time_format, optarg); // printf("Time format: %s\n", time_format); } break; case 'i': if(!interval){ interval=atoi(optarg); // printf("Interval: %d\n", interval); } break; default: // printf("Other argument: %s\n", optarg); fprintf(stderr, "Not such an option"); exit(1); break; } // if(n_proc && interval && time_format[0]!='\0') break; } args[0]='\0'; cmd[0]='\0'; for(int i=optind;i<argc;++i){ if(i==optind){ strcpy(cmd, argv[i]); } else{ strcat(strcat(args, argv[i]), ","); } } // printf("Command: %s\t", cmd); // printf("Arguments: %s\n", args); if(n_proc<=0 || interval<=0 || cmd[0]=='\0'){ printf("Not appropriate information has been given!\n"); return 1; } if(time_format[0]!='\0') print_time(time_format); int exit_stat[2]; exit_stat[0]=-1; for(int i=0;i<n_proc;++i){ if(pipe(tube)==-1){ EXCEPT(PIPE, "Process failed!"); exit(1); } pid_t pid=fork(); if(pid<0){ EXCEPT(PIPE, "Couldn't create a process!"); exit(1); } else if(pid==0){ close(tube[0]); if(dup2(tube[1], 1)==-1){ EXCEPT(NFILE, "Duplication failed!"); exit(1); } char* args_[100]; args_[0]=cmd; unsigned beg, in=0, j=1; char tmp[100][100]; for(unsigned t=0;t<100;++t) tmp[t][0]='\0'; for(;j<50;++j){ if(in>=strlen(args)) break; for(beg=in;args[in]!=',';++in) tmp[j-1][in-beg]=args[in]; // tmp[j-1][in]='\0'; args_[j]=tmp[j-1]; ++in; } args_[j]=NULL; // printf("Executing: %s %s %s %s\n", args_[0], args_[1], args_[2], args_[3]); if(execvp(args_[0], args_)<0){ EXCEPT(FATAL, "Execution failed!\n"); } exit(1); } else{ int stat; wait(&stat); close(tube[1]); exit_stat[1]=WEXITSTATUS(stat); char buff[MAX_SIZE]; for(unsigned t=0;t<100;++t) buff[t]='\0'; size_t sz; // while((sz=read(tube[0], buff, MAX_SIZE))>0); read(tube[0], buff, MAX_SIZE); // printf("strlen of current buff : %ld\n", strlen(buff)); if(memcmp(buff, old_buf, MAX_SIZE)/* || exit_stat[0]!=exit_stat[1]*/){ write(1, buff, strlen(buff)); if(exit_code){ char c='0'+exit_stat[1]; write(1, "exit ", 5); //printf("exit %d\n", exit_stat[1]); write(1, &c, 1); write(1, "\n", 1); } memcpy(old_buf, buff, MAX_SIZE); exit_stat[0]=exit_stat[1]; } // if(exit_stat[1]) exit(1); if(i<n_proc-1){ sleep(interval/1000); if(time_format[0]!='\0') print_time(time_format); } } } return 0; }
C
/* filename - main.c version - 1.0 description - ⺻ Լ -------------------------------------------------------------------------------- first created - 2020.02.10 writer - Hugo MG Sung. */ #include <stdio.h> #include <stdlib.h> #include <string.h> // Լ int main(void) { int arr1[3] = { 1,2,3 }; double arr2[3] = { 1.1,2.2,3.3 }; printf("%d %g \n", *arr1, *arr2); *arr1 += 100; *arr2 += 120.5; printf("%d %g \n", arr1[0], arr2[0]); system("pause"); return EXIT_SUCCESS; }
C
#include <ajp.h> #include <sock.h> #include <notify.h> #include <stdint.h> #include <string.h> struct AJP13_T { int sent; int recv; uint8_t ping[5]; uint8_t pong[5]; }; size_t AJP13SIZE = sizeof(struct AJP13_T); AJP13 new_ajp13() { AJP13 this; this = calloc(AJP13SIZE, 1); return this; } BOOLEAN ajp13_ping(AJP13 this, SOCK sock) { int bytes = 0; this->ping[0] = 0x12; this->ping[1] = 0x34; this->ping[2] = 0; this->ping[3] = 1; this->ping[4] = AJP13_CPING; bytes = socket_write(sock, this->ping, 5); if (bytes == 5) { this->sent += 1; return TRUE; } return FALSE; } BOOLEAN ajp13_pong(AJP13 this, SOCK sock) { int bytes = 0; memset(this->pong, 0, sizeof(this->pong)); bytes = socket_read(sock, &this->pong, 5); if (bytes == 5) { if ((this->pong[0] == 'A') && (this->pong[1] == 'B') && (this->pong[2] == 0) && (this->pong[3] == 1) && (this->pong[4] == AJP13_CPONG)) { this->recv += 1; return TRUE; } // we got five bytes but WTF? NOTIFY ( ERROR, "CPONG: data corruption: %02x,%02x,%02x,%02x,%02x", this->pong[0], this->pong[1], this->pong[2], this->pong[3], this->pong[4] ); } NOTIFY(ERROR, "CPONG: unable to read the server response"); return FALSE; } int ajp13_sent(AJP13 this) { return this->sent; } int ajp13_recv(AJP13 this) { return this->recv; }
C
/* i++ ڼ */ /* ++i ȼ */ /* i-- ڼ */ /* --i ȼ */ /* ǰȼӼ iǰ */ #include <stdio.h> void main() { int i = 8; printf("%d\n", ++i); /* i=9*/ printf("%d\n", --i); /* i=9Ļϼ1 8*/ printf("%d\n", i++); /* i=8Ļȴӡ Ϊ9*/ printf("%d\n", i--); /* i=9Ļȴӡ Ϊ8*/ printf("%d\n", -i--); /* i=8ĻϴӡΪ-8 8ڼ1Ϊ7 ټϸ */ /*--ȼ--*/ printf("%d\n", -i++); /* i=-7ĻϴӡΪ7 ڼ1 */ } /* %d */
C
/* ================= printOneQueue ================= This function prints the data in one queue, ten entries to a line. Pre Queue has been filled Post Data deleted and printed. Queue is empty */ void printOneQueue (QUEUE* pQueue) { // Local Definitions int lineCount; int* dataPtr; // Statements lineCount = 0; while (!emptyQueue (pQueue)) { dequeue (pQueue, (void*)&dataPtr); if (lineCount++ >= 10) { lineCount = 1; printf ("\n "); } // if printf("%3d ", *dataPtr); } // while !emptyQueue printf("\n"); return; } // printOne Queue /* Results: Welcome to a demonstration of categorizing data. We generate 25 random numbers and then group them into categories using queues. Categorizing data: 24 7 31 23 26 14 19 8 9 6 43 16 22 0 39 46 22 38 41 23 19 18 14 3 41 End of data categorization Data 0.. 9: 7 8 9 6 0 3 Data 10..19: 14 19 16 19 18 14 Data 20..29: 24 23 26 22 22 23 Data over 29: 31 43 39 46 38 41 41 */
C
#include "kernel/types.h" #include "kernel/stat.h" #include "kernel/fcntl.h" #include "user/user.h" #define PGSIZE 4096 int main(void){ fprintf(1,"sbrk - allocating memory in PGSIZE\n"); uint64 a,b,c; a = (uint64)sbrk(PGSIZE); b = (uint64)sbrk(PGSIZE); c = (uint64)sbrk(PGSIZE); *(int*)a = 1; // writing *(int*)b = *(int*)a; // reading *(int*)c = *(int*)b + 2; // reading fprintf(1,"should print 1,1,3\t%d,%d,%d\n", *(int*)a, *(int*)b, *(int*)c); fprintf(1,"allocating memory with sbrk PASSED\n"); char *m1; int pid; if((pid = fork()) == 0){ fprintf(1,"in child now\n"); m1 = malloc(PGSIZE*5); m1[PGSIZE] = 1; m1[2*PGSIZE] = 'a'; m1[3*PGSIZE] = 't'; fprintf(1,"should print 1 : %d\n",m1[PGSIZE]); fprintf(1,"should print a : %c\n",m1[2*PGSIZE]); fprintf(1,"should print t : %c\n",m1[3*PGSIZE]); fprintf(1,"now forktest from usertests.c (may take some time)\n"); enum{ N = 1000 }; int n, pid; for(n=0; n<N; n++){ pid = fork(); if(pid < 0) break; if(pid == 0) exit(0); } if (n == 0) { fprintf(1,"%s: no fork at all!\n"); exit(1); } if(n == N){ fprintf(1,"%s: fork claimed to work 1000 times!\n"); exit(1); } for(; n > 0; n--){ if(wait(0) < 0){ fprintf(1,"%s: wait stopped early\n"); exit(1); } } if(wait(0) != -1){ fprintf(1,"%s: wait got too many\n"); exit(1); } fprintf(1,"all tests PASSED\n"); fprintf(1,"note: I tested NFUA,LAPA,SCFIFO with printings i left in comments - mostly in vm.c\n"); exit(0); } else { // as in "mem" test in usertests.c int xstatus; wait(&xstatus); if(xstatus == -1){ exit(0); } exit(xstatus); } exit(0); return 0; }