language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <stdlib.h> #include "../../include/productDB.h" #include "../../include/common.h" #include "../../include/product.h" int main(void) { int testAns; Product a = product_new("pen", 100), b = product_new("stapler", 500), c; db_init(); db_save_product(b); db_save_product(a); testAns = db_get_product_by_name("pen", &c); if (testAns == OK){ printf("Name=%s, quantity=%d (OK)\n", c.name, c.quantity); } else { printf("Error (NOT OK) %d\n",testAns); return 0; } testAns = db_get_product_by_name("pencil", &c); if (testAns == NO_PRODUCT_FOR_NAME){ printf("Expected error (OK)\n"); } else { printf("Unexpected error (NOT OK): %d\n", testAns); return 0; } product_set_quantity(&a, 99); testAns = db_update_product(a); if(testAns != OK){ printf("Update error: %d\n", testAns); return 0; } testAns = db_get_product_by_name("pen", &c); if(testAns == OK){ printf("Name=%s, quantity=%d (OK)\n", c.name, c.quantity); } else { printf("Unexpected error (NOT OK): %d\n", testAns); return 0; } testAns = db_delete_product(b.name); if(testAns != OK) { printf("Delete error: %d\n", testAns); return 0; } testAns = db_get_product_by_name("stapler", &c); if (testAns == NO_PRODUCT_FOR_NAME){ printf("Expected error (OK)\n"); } else { printf("NO Error (NOT OK): %d\n", testAns); return 0; } printf("All tests passed\n"); return 0; }
C
#define _CRT_SECURE_NO_WARNINGS #include "main.h" #include "db.h" int print_result(int result) { if (result == RESULT_TRUE) { printf("%c[1;32m", ESC); printf(" [ O ] Correct"); printf("%c[0m\n", ESC); return 0; } else { printf("%c[1;31m", ESC); printf(" [ X ] Incorrect"); printf("%c[0m\n", ESC); return -1; } } int check_result(int op, int x, int y, int val) { int answer = 0; switch (op) { case OP_TYPE_PLUS: answer = x + y; break; case OP_TYPE_MINUS: answer = x - y; break; case OP_TYPE_MULTIPLE: answer = x * y; break; defult: printf("[ERR] type error: %d\n", op); return -1; } return print_result((answer == val) ? RESULT_TRUE : RESULT_FALSE); } int save_data(int score) { #if USE_DB char date[128] = { 0, }; int ret = 0; time_t t = time(NULL); struct tm tm = *localtime(&t); sqlite3 *db = NULL; snprintf(date, sizeof(date), "%d.%02d.%02d %02d:%02d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min); ret = connect_db(&db); if (ret != 0) { printf("[ERR] Failed to connect DB\n"); return -1; } ret = insert_db(db, score, date); if (ret != 0) { printf("[ERR] Failed to save data\n"); } ret = print_last_items(db, 5); if (ret != 0) { printf("[ERR] Failed to print last items\n"); } ret = close_db(db); if (ret != 0) { printf("[ERR] Failed to close DB\n"); return -1; } #else FILE *fp = NULL; time_t t = time(NULL); struct tm tm = *localtime(&t); fp = fopen("score.txt", "a+"); if (fp == NULL) { printf("[ERR] Failed to open a file\n"); return -1; } fprintf(fp, "%d.%02d.%02d %02d:%02d\tScore: %d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, score * 5); fclose(fp); #endif return 0; } int main() { int i = 0, x = 0, y = 0; int val = 0, score = 0; int ret = 0, tmp = 0; int op = OP_TYPE_MAX; srand((unsigned int) time(NULL)); printf("=======================================\n"); printf(" %s's\n", USER_NAME); printf("\tThe First Math Program\n"); printf("=======================================\n"); printf("Please input right answer.\n"); while (i < COUNT) { op = rand() % OP_TYPE_MAX; switch (op) { case OP_TYPE_PLUS: x = rand() % 100; y = rand() % 100; printf(" (%d) %d + %d = ", i + 1, x, y); scanf("%d", &val); ret = check_result(op, x, y, val); if (ret == RESULT_TRUE) score++; break; case OP_TYPE_MINUS: x = rand() % 100; y = rand() % 100; if (x < y) { tmp = x; x = y; y = tmp; } printf(" (%d) %d - %d = ", i + 1, x, y); scanf("%d", &val); ret = check_result(op, x, y, val); if (ret == RESULT_TRUE) score++; break; case OP_TYPE_MULTIPLE: x = rand() % 10; y = rand() % 10; if (x == 0) x = 1; if (y == 0) y = 1; printf(" (%d) %d X %d = ", i + 1, x, y); scanf("%d", &val); ret = check_result(op, x, y, val); if (ret == RESULT_TRUE) score++; break; default: printf("op type: %d\n", op); } i++; printf("\n"); } printf(" ==================================\n"); printf(" \tTotal Score: [ %c[1;31m %d %c[0m ]\n", ESC, score * 5, ESC); printf(" ==================================\n"); ret = save_data(score); if (ret != 0) { printf("[ERR] Failed to save data\n"); } return 0; }
C
/** @file GRUB environment block parser. Copyright (c) 2021, Mike Beaton. All rights reserved.<BR> SPDX-License-Identifier: BSD-3-Clause **/ #include <Library/BaseLib.h> #include <Library/OcDebugLogLib.h> #include "LinuxBootInternal.h" /* grubenv processing states. */ typedef enum GRUBENV_STATE_ { GRUBENV_NEXT_LINE, GRUBENV_KEY, GRUBENV_VAR, GRUBENV_COMMENT } GRUBENV_STATE; EFI_STATUS InternalProcessGrubEnv ( IN OUT CHAR8 *Content, IN CONST UINTN Length ) { EFI_STATUS Status; UINTN Pos; UINTN KeyStart; UINTN VarStart; GRUBENV_STATE State; State = GRUBENV_NEXT_LINE; // // In a valid grubenv block the last comment, if present, is not // \n terminated, but all var lines must be. // for (Pos = 0; Pos < Length && Content[Pos] != '\0'; Pos++) { switch (State) { case GRUBENV_NEXT_LINE: if (Content[Pos] == '#') { State = GRUBENV_COMMENT; } else { KeyStart = Pos; State = GRUBENV_KEY; } break; case GRUBENV_COMMENT: if (Content[Pos] == '\n') { State = GRUBENV_NEXT_LINE; } break; case GRUBENV_KEY: if (Content[Pos] == '=') { Content[Pos] = '\0'; VarStart = Pos + 1; State = GRUBENV_VAR; } break; case GRUBENV_VAR: if (Content[Pos] == '\n') { Content[Pos] = '\0'; Status = InternalSetGrubVar (&Content[KeyStart], &Content[VarStart], VAR_ERR_NONE); if (EFI_ERROR (Status)) { return Status; } State = GRUBENV_NEXT_LINE; } break; default: ASSERT (FALSE); break; } } ASSERT (State == GRUBENV_COMMENT || State == GRUBENV_NEXT_LINE); return EFI_SUCCESS; }
C
#include <stdio.h> #include <stdint.h> #define __USE_GNU #include <unistd.h> #include <sys/mman.h> #include <time.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include "mlog_array.h" #include "common.h" #include "csv_append.h" #include "generic_vector.h" #include "self_reboot.h" #define TEST_SIZE 4294967296*2 //#define WARMUP 120 extern int errno; int main(int argc, char** argv) { printf("Starting.\n"); printf("process id: %i\n", getpid()); #ifdef WARMUP printf("sleeping for %i seconds to let the kernel settle down.\n", WARMUP); sleep(WARMUP); printf("done sleeping.\n"); #endif printf("test size: %li\n", TEST_SIZE); //label the file with the start time struct timespec file_time; int res = clock_gettime(CLOCK_REALTIME, &file_time); clock_error_check(res); char* filename = malloc(sizeof(char)*(11+digits(TEST_SIZE)+digits(file_time.tv_sec)+4+1));//mfarray_eEEE_tTTT.csv\0 sprintf(filename, "mfarray_e%li_t%i.csv", TEST_SIZE, (int)file_time.tv_sec); mf_array* mfa = new_mfarray(sizeof(uint8_t)); if (mfa == NULL) { printf("Error. new_vector() failed. Exiting now\n"); perror(""); exit(EXIT_FAILURE); } //start timer printf("\nTiming mfarray expansion...\n"); struct timespec start; struct timespec end; res = clock_gettime(CLOCK_REALTIME, &start); clock_error_check(res); while (mfa_card(mfa) < TEST_SIZE) { uint8_t seven = 7; mfa_push_back(mfa, &seven); } //stop timer res = clock_gettime(CLOCK_REALTIME, &end); clock_error_check(res); struct timespec duration = diff(start, end); printf("Done, took %ld sec, %ld n-sec\n", duration.tv_sec, duration.tv_nsec); save_page_faults(filename); printf("Checking that the values are valid...\n"); for (long int i = 0; i < mfa_card(mfa); i++) { uint8_t* val = mfa_at(mfa, i); if (*val != 7) { printf("Error... different value read back: %i at index %li.\n", *val, i); exit(EXIT_FAILURE); } } free_mfarray(mfa); //we are only interested in runs that are successful so we save its results after checking int temp = 0; vector* times = new_vector(3, sizeof(int)); vec_push_back(times, &temp); vec_push_back(times, (temp = duration.tv_sec, &temp)); vec_push_back(times, (temp = duration.tv_nsec, &temp)); if(!append_csv(filename, times, NULL)) { exit(EXIT_FAILURE); } free_vector(times); free(filename); //printf("Done. Press enter to free memory.\n"); //getc(stdin); //printf("Press enter to quit.\n"); //getc(stdin); self_reboot(); printf("Done.\n"); return EXIT_SUCCESS; }
C
#include "BRTOS.h" #include "device.h" #include "drivers.h" #define NUM_I2C 1 static BRTOS_Sem *I2CTX[NUM_I2C]; static BRTOS_Queue *I2CQ[NUM_I2C]; static BRTOS_Mutex *I2CMutex[NUM_I2C]; char I2C_buffer; static uint32_t I2CHandler(void) { char c = I2C_buffer; OSQueuePost(I2CQ[0], c); return TRUE; } static void Init_I2C(void *parameters) { i2c_config_t *i2c_conf = (i2c_config_t *)parameters; ConfiguraInterruptHandler( INTERRUPT_I2C, I2CHandler); // todo: Configure I2C Baud //I2CConfigSet(i2c_conf->baudrate, config); ASSERT(OSSemCreate(0, &I2CTX[0]) == ALLOC_EVENT_OK); ASSERT(OSQueueCreate(i2c_conf->queue_size, &I2CQ[0]) == ALLOC_EVENT_OK); if (i2c_conf->mutex == true) { OSMutexCreate (&I2CMutex[0], 0); } } #define i2c_rwchar(x) static size_t I2C_Write(OS_Device_Control_t *dev, char *string, size_t size ){ size_t nbytes = 0; while(size) { i2c_rwchar((char)string); nbytes++; size--; string++; } return nbytes; } static size_t I2C_Read(OS_Device_Control_t *dev, char *string, size_t size ){ size_t nbytes = 0; i2c_config_t *i2c_conf = (i2c_config_t *)dev->device->DriverData; while(nbytes < size) { if (OSQueuePend(I2CQ[dev->device_number], (uint8_t*)string, i2c_conf->timeout) != READ_BUFFER_OK) goto failed_rx; string++; nbytes++; } failed_rx: return nbytes; } static size_t I2C_Set(OS_Device_Control_t *dev, uint32_t request, uint32_t value){ unsigned long config = 0; size_t ret = 0; i2c_config_t *i2c_conf = (i2c_config_t *)dev->device->DriverData; switch(request){ case I2C_BAUDRATE: i2c_conf->baudrate = value; break; case I2C_DIRECTION: i2c_conf->direction = value; break; case I2C_QUEUE_SIZE: /* somente pode ser alterado se filar dinmicas forem utilizadas. */ break; case I2C_TIMEOUT: i2c_conf->timeout = value; break; case CTRL_ACQUIRE_WRITE_MUTEX: if (I2CMutex[dev->device_number] != NULL){ ret = OSMutexAcquire(I2CMutex[dev->device_number],value); } break; case CTRL_RELEASE_WRITE_MUTEX: if (I2CMutex[dev->device_number] != NULL){ ret = OSMutexRelease(I2CMutex[dev->device_number]); } break; default: break; } return ret; } static size_t I2C_Get(OS_Device_Control_t *dev, uint32_t request){ uint32_t ret; i2c_config_t *i2c_conf = (i2c_config_t *)dev->device->DriverData; switch(request){ case I2C_BAUDRATE: ret = i2c_conf->baudrate; break; case I2C_DIRECTION: ret = i2c_conf->direction; break; case I2C_QUEUE_SIZE: ret = i2c_conf->queue_size; break; case I2C_TIMEOUT: ret = i2c_conf->timeout; break; default: ret = 0; break; } return ret; } static const device_api_t I2C_api ={ .read = (Device_Control_read_t)I2C_Read, .write = (Device_Control_write_t)I2C_Write, .set = (Device_Control_set_t)I2C_Set, .get = (Device_Control_get_t)I2C_Get }; void OSOpenI2C(void *pdev, void *parameters){ OS_Device_Control_t *dev = pdev; Init_I2C(parameters); dev->api = &I2C_api; }
C
#include <stdio.h> #include <stdlib.h> #define PIPE_W 1UL #define PIPE_WN 2UL #define PIPE_N 4UL #define PIPE_NE 8UL #define PIPE_E 128UL #define PIPE_ES 64UL #define PIPE_S 32UL #define PIPE_SW 16UL #define CELL_WHITE '.' #define CELL_BLACK 'x' #define CALLS_MAX 3 #define LINKS_MAX 8 typedef struct value_s value_t; typedef struct cell_s cell_t; struct value_s { unsigned long number; cell_t *cell; value_t *last; value_t *next; }; struct cell_s { unsigned long pipes; value_t *value; }; typedef enum { CALL_CHOOSE, CALL_UNROLL, CALL_ROLL } call_t; typedef struct { cell_t *cell; unsigned long pipes; } unroll_t; typedef struct { value_t *value; cell_t *cell; unroll_t *unroll; } roll_t; void set_value(value_t *, unsigned long); void chain_value(value_t *, value_t *, value_t *); void set_cell_pipes(cell_t *, unsigned long); void hidato(void); void stack_call(call_t *, call_t); void perform_call(call_t *); void perform_choose(void); void print_cell(cell_t *, int); unsigned long set_choices(value_t *, cell_t *[]); unsigned long set_links(cell_t *, cell_t *[]); void set_choice(cell_t **, cell_t *); void stack_unroll(unroll_t *, cell_t *); void perform_unroll(unroll_t *); void clear_cell_value(cell_t *, unsigned long); void add_pipes(cell_t *, unsigned long); void add_pipe(cell_t *, unsigned long, cell_t *); void stack_roll(roll_t *, value_t *, cell_t *, unroll_t *); void perform_roll(roll_t *); unsigned long set_cell_value(cell_t *, value_t *); unsigned long remove_pipes(cell_t *); unsigned long remove_pipe(cell_t *, unsigned long, cell_t *); void set_unroll_pipes(unroll_t *, unsigned long); int digits_max; unsigned long values_n, rows_n, columns_n, nodes_n, solutions_n, stack_calls_n, stack_unrolls_n, stack_rolls_n; value_t *values, *value_black; cell_t *cells; call_t *stack_calls; unroll_t *stack_unrolls; roll_t *stack_rolls; int main(void) { unsigned long cells_n, h_cells_n, w_cells_n, pipes, i, j; value_t *value; cell_t *cell; if (scanf("%lu", &values_n) != 1) { fprintf(stderr, "Invalid number of values\n"); return EXIT_FAILURE; } digits_max = 1; i = values_n/10; while (i) { digits_max++; i /= 10; } values = malloc(sizeof(value_t)*(values_n+1)); if (!values) { fprintf(stderr, "Could not allocate memory for values\n"); free(cells); return EXIT_FAILURE; } for (i = 0; i < values_n; i++) { set_value(values+i, i+1); } value_black = values+i; chain_value(values, value_black, values+1); for (value = values+1; value < value_black; value++) { chain_value(value, value-1, value+1); } chain_value(value, value-1, values); if (scanf("%lu%lu", &rows_n, &columns_n) != 2 || !rows_n || !columns_n) { fprintf(stderr, "Invalid grid size\n"); free(values); return EXIT_FAILURE; } fgetc(stdin); cells_n = rows_n*columns_n; cells = malloc(sizeof(cell_t)*cells_n); if (!cells) { fprintf(stderr, "Could not allocate memory for cells\n"); free(values); return EXIT_FAILURE; } if (rows_n > 1) { if (columns_n > 1) { set_cell_pipes(cells, PIPE_E+PIPE_ES+PIPE_S); cell = cells+1; for (j = 1; j < columns_n-1; j++) { set_cell_pipes(cell++, PIPE_W+PIPE_E+PIPE_ES+PIPE_S+PIPE_SW); } set_cell_pipes(cell++, PIPE_W+PIPE_S+PIPE_SW); for (i = 1; i < rows_n-1; i++) { set_cell_pipes(cell++, PIPE_N+PIPE_NE+PIPE_E+PIPE_ES+PIPE_S); for (j = 1; j < columns_n-1; j++) { set_cell_pipes(cell++, PIPE_W+PIPE_WN+PIPE_N+PIPE_NE+PIPE_E+PIPE_ES+PIPE_S+PIPE_SW); } set_cell_pipes(cell++, PIPE_W+PIPE_WN+PIPE_N+PIPE_S+PIPE_SW); } set_cell_pipes(cell++, PIPE_N+PIPE_NE+PIPE_E); for (j = 1; j < columns_n-1; j++) { set_cell_pipes(cell++, PIPE_W+PIPE_WN+PIPE_N+PIPE_NE+PIPE_E); } set_cell_pipes(cell, PIPE_W+PIPE_WN+PIPE_N); } else { set_cell_pipes(cells, PIPE_S); for (i = 1; i < rows_n-1; i++) { set_cell_pipes(cells+i, PIPE_N+PIPE_S); } set_cell_pipes(cells+i, PIPE_N); } } else { if (columns_n > 1) { set_cell_pipes(cells, PIPE_E); for (j = 1; j < columns_n-1; j++) { set_cell_pipes(cells+j, PIPE_W+PIPE_E); } set_cell_pipes(cells+j, PIPE_W); } else { set_cell_pipes(cells, 0UL); } } h_cells_n = 0; w_cells_n = 0; for (i = 0; i < cells_n; i++) { if (scanf("%lu", &j) == 1) { if (j && j <= values_n) { if (values[j-1].cell) { fprintf(stderr, "Duplicate hint\n"); free(values); free(cells); return EXIT_FAILURE; } else { set_cell_value(cells+i, values+j-1); } h_cells_n++; } else { fprintf(stderr, "Invalid hint\n"); free(values); free(cells); return EXIT_FAILURE; } } else { switch (fgetc(stdin)) { case CELL_WHITE: w_cells_n++; break; case CELL_BLACK: set_cell_value(cells+i, value_black); break; default: fprintf(stderr, "Invalid cell\n"); free(values); free(cells); return EXIT_FAILURE; } } fgetc(stdin); } if (h_cells_n+w_cells_n != values_n) { fprintf(stderr, "Inconsistent grid\n"); free(values); free(cells); return EXIT_FAILURE; } stack_calls = malloc(sizeof(call_t)*(cells_n*LINKS_MAX*CALLS_MAX+1)); if (!stack_calls) { fprintf(stderr, "Could not allocate memory for calls stack\n"); free(values); free(cells); return EXIT_FAILURE; } stack_unrolls = malloc(sizeof(unroll_t)*cells_n*LINKS_MAX); if (!stack_unrolls) { fprintf(stderr, "Could not allocate memory for unrolls stack\n"); free(stack_calls); free(values); free(cells); return EXIT_FAILURE; } stack_rolls = malloc(sizeof(roll_t)*cells_n*LINKS_MAX); if (!stack_rolls) { fprintf(stderr, "Could not allocate memory for rolls stack\n"); free(stack_unrolls); free(stack_calls); free(values); free(cells); return EXIT_FAILURE; } if (h_cells_n) { hidato(); } else { for (i = 0; i < cells_n; i++) { if (!cells[i].value) { pipes = set_cell_value(cells+i, values); hidato(); clear_cell_value(cells+i, pipes); } } } free(stack_rolls); free(stack_unrolls); free(stack_calls); free(values); free(cells); return EXIT_SUCCESS; } void set_value(value_t *value, unsigned long number) { value->number = number; value->cell = NULL; } void chain_value(value_t *value, value_t *last, value_t *next) { value->last = last; value->next = next; } void set_cell_pipes(cell_t *cell, unsigned long pipes) { cell->pipes = pipes; } void hidato(void) { nodes_n = 0; solutions_n = 0; stack_calls_n = 0; stack_unrolls_n = 0; stack_rolls_n = 0; stack_call(stack_calls, CALL_CHOOSE); do { stack_calls_n--; perform_call(stack_calls+stack_calls_n); } while (stack_calls_n); printf("\nNodes %lu\nSolutions %lu\n", nodes_n, solutions_n); } void stack_call(call_t *call, call_t type) { *call = type; stack_calls_n++; } void perform_call(call_t *call) { switch (*call) { case CALL_CHOOSE: perform_choose(); break; case CALL_UNROLL: stack_unrolls_n--; perform_unroll(stack_unrolls+stack_unrolls_n); break; case CALL_ROLL: stack_rolls_n--; perform_roll(stack_rolls+stack_rolls_n); } } void perform_choose(void) { unsigned long choices_n_min, choices_n, i, j; value_t *value_min, *value; cell_t *cell, *choices_min[LINKS_MAX], *choices[LINKS_MAX]; nodes_n++; if (value_black->next == value_black) { solutions_n++; if (solutions_n == 1) { puts(""); cell = cells; for (i = 0; i < rows_n; i++) { for (j = 0; j < columns_n-1; j++) { print_cell(cell++, ' '); } print_cell(cell++, '\n'); } } } else { value_min = value_black->next; choices_n_min = set_choices(value_min, choices_min); for (value = value_min->next; value != value_black && choices_n_min; value = value->next) { choices_n = set_choices(value, choices); if (choices_n < choices_n_min) { value_min = value; choices_n_min = choices_n; for (i = 0; i < choices_n; i++) { choices_min[i] = choices[i]; } } } for (i = 0; i < choices_n_min; i++) { stack_unroll(stack_unrolls+stack_unrolls_n, choices_min[i]); stack_call(stack_calls+stack_calls_n, CALL_UNROLL); stack_call(stack_calls+stack_calls_n, CALL_CHOOSE); stack_roll(stack_rolls+stack_rolls_n, value_min, choices_min[i], stack_unrolls+stack_unrolls_n-1); stack_call(stack_calls+stack_calls_n, CALL_ROLL); } } } void print_cell(cell_t *cell, int c) { if (cell->value == value_black) { printf("%*c", digits_max, CELL_BLACK); } else { printf("%*lu", digits_max, cell->value->number); } putchar(c); } unsigned long set_choices(value_t *value, cell_t *choices[]) { unsigned long links_inf_n, links_sup_n, choices_n, i, j; cell_t *cell_inf, *links_inf[LINKS_MAX], *cell_sup, *links_sup[LINKS_MAX]; if (value->number > 1) { cell_inf = values[value->number-2].cell; } else { cell_inf = NULL; } if (value->number < values_n) { cell_sup = values[value->number].cell; } else { cell_sup = NULL; } if (cell_inf) { links_inf_n = set_links(cell_inf, links_inf); if (cell_sup) { links_sup_n = set_links(cell_sup, links_sup); choices_n = 0; j = 0; for (i = 0; i < links_inf_n; i++) { while (j < links_sup_n && links_sup[j] < links_inf[i]) { j++; } if (j < links_sup_n && links_sup[j] == links_inf[i]) { set_choice(choices+choices_n, links_inf[i]); choices_n++; j++; } } return choices_n; } else { for (i = 0; i < links_inf_n; i++) { set_choice(choices+i, links_inf[i]); } return links_inf_n; } } else { if (cell_sup) { links_sup_n = set_links(cell_sup, links_sup); for (i = 0; i < links_sup_n; i++) { set_choice(choices+i, links_sup[i]); } return links_sup_n; } else { return LINKS_MAX+1; } } } unsigned long set_links(cell_t *cell, cell_t *links[]) { unsigned long links_n = 0; if (cell->pipes & PIPE_WN) { set_choice(links, cell-1-columns_n); links_n = 1; } if (cell->pipes & PIPE_N) { set_choice(links+links_n, cell-columns_n); links_n++; } if (cell->pipes & PIPE_NE) { set_choice(links+links_n, cell-columns_n+1); links_n++; } if (cell->pipes & PIPE_W) { set_choice(links+links_n, cell-1); links_n++; } if (cell->pipes & PIPE_E) { set_choice(links+links_n, cell+1); links_n++; } if (cell->pipes & PIPE_SW) { set_choice(links+links_n, cell+columns_n-1); links_n++; } if (cell->pipes & PIPE_S) { set_choice(links+links_n, cell+columns_n); links_n++; } if (cell->pipes & PIPE_ES) { set_choice(links+links_n, cell+1+columns_n); links_n++; } return links_n; } void set_choice(cell_t **choice, cell_t *cell) { *choice = cell; } void stack_unroll(unroll_t *unroll, cell_t *cell) { unroll->cell = cell; stack_unrolls_n++; } void perform_unroll(unroll_t *unroll) { clear_cell_value(unroll->cell, unroll->pipes); } void clear_cell_value(cell_t *cell, unsigned long pipes) { value_t *value = cell->value; cell->value = NULL; add_pipes(cell, pipes); value->next->last = value; value->last->next = value; value->cell = NULL; } void add_pipes(cell_t *cell, unsigned long pipes) { if (pipes & PIPE_W) { add_pipe(cell, PIPE_W, cell-1); } if (pipes & PIPE_WN) { add_pipe(cell, PIPE_WN, cell-1-columns_n); } if (pipes & PIPE_N) { add_pipe(cell, PIPE_N, cell-columns_n); } if (pipes & PIPE_NE) { add_pipe(cell, PIPE_NE, cell-columns_n+1); } if (pipes & PIPE_E) { add_pipe(cell, PIPE_E, cell+1); } if (pipes & PIPE_ES) { add_pipe(cell, PIPE_ES, cell+1+columns_n); } if (pipes & PIPE_S) { add_pipe(cell, PIPE_S, cell+columns_n); } if (pipes & PIPE_SW) { add_pipe(cell, PIPE_SW, cell+columns_n-1); } } void add_pipe(cell_t *cell, unsigned long pipe_used, cell_t *link) { link->pipes += PIPE_E/pipe_used; cell->pipes += pipe_used; } void stack_roll(roll_t *roll, value_t *value, cell_t *cell, unroll_t *unroll) { roll->value = value; roll->cell = cell; roll->unroll = unroll; stack_rolls_n++; } void perform_roll(roll_t *roll) { set_unroll_pipes(roll->unroll, set_cell_value(roll->cell, roll->value)); } unsigned long set_cell_value(cell_t *cell, value_t *value) { unsigned long pipes; if (value) { value->cell = cell; if (value != value_black) { value->last->next = value->next; value->next->last = value->last; } pipes = remove_pipes(cell); } else { pipes = 0; } cell->value = value; return pipes; } unsigned long remove_pipes(cell_t *cell) { unsigned long pipes = 0; if (cell->pipes & PIPE_W) { pipes = remove_pipe(cell, PIPE_W, cell-1); } if (cell->pipes & PIPE_WN) { pipes += remove_pipe(cell, PIPE_WN, cell-1-columns_n); } if (cell->pipes & PIPE_N) { pipes += remove_pipe(cell, PIPE_N, cell-columns_n); } if (cell->pipes & PIPE_NE) { pipes += remove_pipe(cell, PIPE_NE, cell-columns_n+1); } if (cell->pipes & PIPE_E) { pipes += remove_pipe(cell, PIPE_E, cell+1); } if (cell->pipes & PIPE_ES) { pipes += remove_pipe(cell, PIPE_ES, cell+1+columns_n); } if (cell->pipes & PIPE_S) { pipes += remove_pipe(cell, PIPE_S, cell+columns_n); } if (cell->pipes & PIPE_SW) { pipes += remove_pipe(cell, PIPE_SW, cell+columns_n-1); } return pipes; } unsigned long remove_pipe(cell_t *cell, unsigned long pipe_used, cell_t *link) { if (link->value) { cell->pipes -= pipe_used; link->pipes -= PIPE_E/pipe_used; return pipe_used; } else { return 0; } } void set_unroll_pipes(unroll_t *unroll, unsigned long pipes) { unroll->pipes = pipes; }
C
#include "Sale_Persist.h" #include "../Common/List.h" #include "../Service/Sale.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include<unistd.h> static const char SALE_DATA_FILE[] = "Sale.dat"; static const char SALE_DATA_TEMP_FILE[] = "SaleTmp.dat"; int Sale_Perst_Insert(const sale_t *data) { FILE *fp = fopen(SALE_DATA_FILE, "ab"); int rtn = 0; if (NULL == fp) { printf("Cannot open file %s!\n", SALE_DATA_FILE); return 0; } rtn = fwrite(data, sizeof(sale_t), 1, fp); fclose(fp); return rtn; } int Sale_Perst_DeleteByID(int saleID) { if(rename(SALE_DATA_FILE, SALE_DATA_TEMP_FILE)<0){ printf("Cannot open file %s!\n", SALE_DATA_FILE); return 0; } FILE *fpSour, *fpTarg; fpSour = fopen(SALE_DATA_TEMP_FILE, "rb"); if (NULL == fpSour ){ printf("Cannot open file %s!\n", SALE_DATA_FILE); return 0; } fpTarg = fopen(SALE_DATA_FILE, "wb"); if ( NULL == fpTarg ) { printf("Cannot open file %s!\n", SALE_DATA_TEMP_FILE); return 0; } sale_t buf; int found = 0; while (!feof(fpSour)) { if (fread(&buf, sizeof(sale_t), 1, fpSour)) { if (saleID == buf.id) { found = 1; continue; } fwrite(&buf, sizeof(sale_t), 1, fpTarg); } } fclose(fpTarg); fclose(fpSour); //删除临时文件 remove(SALE_DATA_TEMP_FILE); return found; } //根据用户ID载入给定时间区间内的销售记录 int Sale_Perst_SelectByUsrID(sale_list_t list, int usrID, user_date_t stDate, user_date_t endDate) { FILE *fp = fopen(SALE_DATA_FILE,"rb"); if(NULL == fp) { return 0; } sale_t data; sale_node_t *p; int recCount = 0; while (!feof(fp)) { if (fread(&data, sizeof(sale_t), 1, fp)) { if(usrID==data.user_id){ if(DateCmp(data.date,stDate)!=-1 && DateCmp(endDate,data.date)!=-1){ p = (sale_node_t*) malloc(sizeof(sale_node_t)); if (!p) { printf("Warning, Memory OverFlow!!!\n Cannot Load more Data into memory!!!\n"); break; } p->data = data; List_AddTail(list, p); recCount++; } } } } return recCount; } //根据给定时间区间内的销售记录 int Sale_Perst_SelectByDate(sale_list_t list, user_date_t stDate, user_date_t endDate) { FILE *fp = fopen(SALE_DATA_FILE,"rb"); if(NULL == fp) { return 0; } sale_t data; sale_node_t *p; int recCount = 0; while (!feof(fp)) { if (fread(&data, sizeof(sale_t), 1, fp)) { if(DateCmp(data.date,stDate)!=-1 && DateCmp(endDate,data.date)!=-1){ p = (sale_node_t*) malloc(sizeof(sale_node_t)); if (!p) { printf("Warning, Memory OverFlow!!!\n Cannot Load more Data into memory!!!\n"); break; } p->data = data; List_AddTail(list, p); recCount++; } } } return recCount; } /* //queryUid = null,query all the uid Sale information return the all uid Sale information number //queryUid = uid, query the uid Sale information return the uid Sale number * int Sale_Infor_By_Uid(char * queryUid, Sale_list_t head) { // 请补充完整 return 1; } int Sale_Infor_By_Time(char queryTime[][30], Sale_list_t head) { // 请补充完整 return 1; } //根据票的id获得票的基本信息 int Select_Price_By_Playid(int id, ticket_t *buf) { // 请补充完整 return 1; } */
C
#include<stdio.h> int add() { int x,y; scanf("%d%d",&x,&y); return x+y; } void main() { int res; res=add(); printf("%d ",res); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #pragma warning (disable:4996) typedef struct book { char *name; char *author; char date[9]; }BOOK; void inputscore(struct book *st, int n) { struct book *p; char tmp[101]; char tmp2[21]; for (p = st; p < st + n; p++) { scanf("%s %s %s", tmp, tmp2, p->date); getchar(); p->name = (char *)malloc((strlen(tmp) + 1) * sizeof(char)); strcpy(p->name, tmp); p->author = (char *)malloc((strlen(tmp2) + 1) * sizeof(char)); strcpy(p->author, tmp2); } } int check(struct book st, char *str) { if (strncmp(st.date, str, 4) == 0) { return 0; } else return 1; } void sort(struct book *st, int n) { struct book *p, *q, tmp; for (p = st; p < st + n; p++) { for (q = p; q < st + n; q++) { if (strcmp(p->author, q->author) > 0) { tmp = *p; *p = *q; *q = tmp; } } } } int main() { int n, i, j, cnt = 0; BOOK *st, *ans; char targetyear[5]; scanf("%d", &n); getchar(); st = (BOOK *)malloc(n * sizeof(BOOK)); ans = (BOOK *)malloc(n * sizeof(BOOK)); inputscore(st, n); gets(targetyear); for (i = 0; i < n; i++) { if (check(st[i], &targetyear) == 0) { ans[cnt++] = st[i]; } } sort(ans, cnt); for (i = 0; i < cnt; i++) { printf("%s %s %s\n", ans[i].name, ans[i].author, ans[i].date); } }
C
#include "SList.h" void TestSList1() { SListNode* plist = NULL; SListPushBack(&plist, 1); SListPushBack(&plist, 2); SListPushBack(&plist, 3); SListPushBack(&plist, 4); SListPushBack(&plist, 5); SListPrint(plist); SListPopBack(&plist); SListPrint(plist); SListPopBack(&plist); SListPrint(plist); SListPopBack(&plist); SListPrint(plist); SListPopBack(&plist); SListPrint(plist); SListPopBack(&plist); SListPrint(plist); SListPopBack(&plist); SListPrint(plist); } //β塢βɾ void TestSList2() { SListNode* plist = NULL; SListPushFront(&plist, 4); SListPushFront(&plist, 3); SListPushFront(&plist, 2); SListPushFront(&plist, 1); SListPrint(plist); SListNode* ret = SListFind(plist, 3); if (ret) { ret->dada = 30; } SListPrint(plist); SListNode* pos = SListFind(plist, 30); SListInsertAfter(pos, 300); SListPrint(plist); SListEraseAfter(pos); SListPrint(plist); SListPopFront(&plist); SListPrint(plist); SListPopFront(&plist); SListPrint(plist); SListPopFront(&plist); SListPrint(plist); SListPopFront(&plist); SListPrint(plist); SListPopFront(&plist); SListPrint(plist); } //ͷ塢ͷɾҡ(ָλúֵ޸)ɾ(ָλúֵ) void TestSList3() { SListNode* plist = NULL; SListPushBack(&plist, 1); SListPushBack(&plist, 2); SListPrint(plist); SListDestory(&plist); SListPrint(plist); SListDestory(&plist); SListPrint(plist); } //ٲ int main() { TestSList3(); return 0; }
C
#include <stdio.h> #include <string.h> #define MAXLINES 5000 char *lineptr[MAXLINES]; int readlines(char *lineptr[],int nlines); void writelines(char *lineptr[],int nlines); void qqsort_(char *lineptr[],int left,int right); int getline(char s[],int lim) { int c,i; for(i=0;--lim>0 && (c=getchar())!=EOF && c!='\n';i++) s[i]=c; if(c=='\n') s[i++]=c; s[i]='\0'; return i; } #define ALLOCSIZE 1000 static char allocbuf[ALLOCSIZE]; static char *allocp=allocbuf; char *alloc(int n) { if(allocbuf+ALLOCSIZE-allocp>=n){ allocp+=n; return allocp-n; }else return 0; } int strcmp1(char *s,char*t) { int i; for(i=0;s[i]==t[i];i++) if(s[i]=='\0') return 0; return s[i]-t[i]; } int main() { int nlines; if((nlines=readlines(lineptr,MAXLINES))>=0){ qqsort_(lineptr,0,nlines-1); writelines(lineptr,nlines); return 0; }else{ printf("error:input too big to sort\n"); return 1; } } #define MAXLEN 1000 char *alloc(int); int readlines(char *lineptr[],int maxlines) { int len,nlines; char *p,line[MAXLEN]; for(nlines=0;(len=getline(line,MAXLEN))>0;nlines++){ if(nlines>=maxlines || (p=alloc(len))==0) return -1; else{ line[len-1]='\0'; strcpy(p,line); lineptr[nlines]=p; } } return nlines; } void writelines(char *lineptr[],int nlines) { int i; for(i=0;i<nlines;i++) printf("%s\n",lineptr[i]); } void swap(char* a[],int x,int y) { char *b; b=a[x]; a[x]=a[y]; a[y]=b; } void qqsort_(char *v[],int left,int right) { int i,last; if(left>=right) return; //swap(v,left,(left+right)/2); last=left; for(i=left+1;i<=right;i++) if(strcmp1(v[i],v[left])<0) swap(v,++last,i); swap(v,left,last); qqsort_(v,left,last-1); qqsort_(v,last+1,right); }
C
#pragma once static inline int pw(int x, int y) { if (y == 0) return 1; if (y == 1) return x; return (y % 2 == 0) ? pw(x * x, y / 2) : pw(x * x, y / 2) * x; }
C
#include <signal.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <sys/mman.h> #include <sys/termios.h> #include <sys/time.h> #include <sys/types.h> // unix #include <unistd.h> uint16_t memory[UINT16_MAX]; // registers enum { R_R0 = 0, R_R1, R_R2, R_R3, R_R4, R_R5, R_R6, R_R7, R_PC, R_COND, R_COUNT }; // opcodes enum { OP_BR = 0, // branch OP_ADD, // add OP_LD, // load OP_ST, // store OP_JSR, // jump register OP_AND, // bitwise and OP_LDR, // load register OP_STR, // store register OP_RTI, // unused OP_NOT, // bitwise not OP_LDI, // load indirect OP_STI, // store indirect OP_JMP, // jump OP_RES, // reserved (unused) OP_LEA, // load effective address OP_TRAP // execute trap }; // conditional flags enum { FL_POS = 1 << 0, // P 0x0000000000000001 FL_ZRO = 1 << 1, // Z 0x0000000000000010 FL_NEG = 1 << 2 // N 0x0000000000000100 }; // traps enum { // get character from keyboard, not echoed onto the terminal TRAP_GETC = 0x20, // output a character TRAP_OUT = 0x21, // output a word string TRAP_PUTS = 0x22, // get character from keyboard, echoed onto the terminal TRAP_IN = 0x23, // output a byte string TRAP_PUTSP = 0x24, // halt to program TRAP_HALT = 0x25 }; // memory mapped registers enum { // keyboard status MR_KBSR = 0xFE00, // keyboard data MR_KBDR = 0xFE02 }; uint16_t reg[R_COUNT]; struct termios original_tio; void disable_input_buffering() { tcgetattr(STDIN_FILENO, &original_tio); struct termios new_tio = original_tio; new_tio.c_lflag &= ~ICANON & ~ECHO; tcsetattr(STDIN_FILENO, TCSANOW, &new_tio); } void restore_input_buffering() { tcsetattr(STDIN_FILENO, TCSANOW, &original_tio); } uint16_t sign_extend(uint16_t x, int bit_count) { if ((x >> (bit_count - 1)) & 1) { x |= 0xFFFF << bit_count; } return x; } void update_flags(uint16_t r) { if (reg[r] == 0) { reg[R_COND] = FL_ZRO; } else if (reg[r] >> 15) { reg[R_COND] = FL_NEG; } else { reg[R_COND] = FL_POS; } } uint16_t check_key() { fd_set readfds; FD_ZERO(&readfds); FD_SET(STDIN_FILENO, &readfds); struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 0; return select(1, &readfds, NULL, NULL, &timeout) != 0; } uint16_t mem_read(uint16_t address) { if (address == MR_KBSR) { if (check_key()) { memory[MR_KBSR] = 1 << 15; memory[MR_KBDR] = getchar(); } else { memory[MR_KBSR] = 0; } } return memory[address]; } void mem_write(uint16_t address, uint16_t value) { memory[address] = value; } uint16_t swap16(uint16_t x) { return (x << 8) | (x >> 8); } void read_image_file(FILE *file) { // where in memory to place the image uint16_t origin; fread(&origin, sizeof(origin), 1, file); origin = swap16(origin); // we know the maximum file size so // we only need one fread uint16_t max_read = UINT16_MAX - origin; uint16_t *p = memory + origin; size_t read = fread(p, sizeof(uint16_t), max_read, file); while (read-- > 0) { *p = swap16(*p); ++p; } } int read_image(const char *image_path) { FILE *file = fopen(image_path, "rb"); if (!file) { return 0; } read_image_file(file); fclose(file); return 1; } int handle_trap(uint16_t instr) { switch (instr & 0xFF) { case TRAP_GETC: { reg[R_R0] = (uint16_t)getchar(); break; } case TRAP_OUT: { putc((char)reg[R_R0], stdout); fflush(stdout); break; } case TRAP_PUTS: { uint16_t *c = memory + reg[R_R0]; while (*c) { putc((char)*c, stdout); ++c; } fflush(stdout); break; } case TRAP_IN: { printf("> "); char ch = getchar(); putc(ch, stdout); reg[R_R0] = (uint16_t)ch; break; } case TRAP_PUTSP: { uint16_t *c = memory + reg[R_R0]; while (*c) { char ch_lo = (*c) & 0xFF; char ch_hi = (*c) >> 8; putc(ch_lo, stdout); if (ch_hi) { putc(ch_hi, stdout); } ++c; } fflush(stdout); break; } case TRAP_HALT: { puts("HALT\n"); fflush(stdout); return 0; } } return 1; } void handle_interrupt(int signal) { restore_input_buffering(); printf("\n"); exit(-2); } int main(int argc, char *argv[]) { if (argc < 2) { printf("lc3 [image] ...\n"); exit(2); } for (int i = 1; i < argc; ++i) { if (!read_image(argv[i])) { printf("failed to load image: %s\n", argv[i]); exit(1); } } signal(SIGINT, handle_interrupt); disable_input_buffering(); enum { PC_START = 0x3000 }; reg[R_PC] = PC_START; int running = 1; while (running) { // read next instruction and increment PC uint16_t instr = mem_read(reg[R_PC]++); // get the opcode (leftmost 4 bits) uint16_t op = instr >> 12; switch (op) { case OP_BR: { uint16_t pc_offset = sign_extend(instr & 0x1FF, 9); uint16_t cond_flag = (instr >> 9) & 0x7; if (cond_flag & reg[R_COND]) { reg[R_PC] += pc_offset; } break; } case OP_ADD: { // destination register (DR) uint16_t r0 = (instr >> 9) & 0x7; // first operand (SR1) uint16_t r1 = (instr >> 6) & 0x7; // immediate mode flag uint16_t imm_flag = (instr >> 5) & 0x1; if (imm_flag) { uint16_t imm5 = sign_extend(instr & 0x1F, 5); reg[r0] = reg[r1] + imm5; } else { // second operand (SR2) uint16_t r2 = instr & 0x7; reg[r0] = reg[r1] + reg[r2]; } update_flags(r0); break; } case OP_LD: { // pc offset (PCoffset9) uint16_t pc_offset = sign_extend(instr & 0x1FF, 9); // destination register (DR) uint16_t r0 = (instr >> 9) & 0x7; reg[r0] = mem_read(reg[R_PC] + pc_offset); update_flags(r0); break; } case OP_ST: { // pc offset (PCoffset9) uint16_t pc_offset = sign_extend(instr & 0x1FF, 9); // source register (SR) uint16_t r1 = (instr >> 9) & 0x7; mem_write(reg[R_PC] + pc_offset, reg[r1]); break; } case OP_JSR: { reg[R_R7] = reg[R_PC]; // pc offset mode flag uint16_t offset_flag = (instr >> 11) & 0x1; if (offset_flag) { // pc offset (PCoffset11) uint16_t pc_offset = sign_extend(instr & 0x7FF, 11); reg[R_PC] += pc_offset; } else { // base register (BaseR) uint16_t r_base = (instr >> 6) & 0x7; reg[R_PC] = reg[r_base]; } break; } case OP_AND: { uint16_t r0 = (instr >> 9) & 0x7; uint16_t r1 = (instr >> 6) & 0x7; uint16_t imm_flag = (instr >> 5) & 0x1; if (imm_flag) { uint16_t imm5 = sign_extend(instr & 0x1F, 5); reg[r0] = reg[r1] & imm5; } else { uint16_t r2 = instr & 0x7; reg[r0] = reg[r1] & reg[r2]; } update_flags(r0); break; } case OP_LDR: { // destination register (DR) uint16_t r0 = (instr >> 9) & 0x7; // base register (BaseR) uint16_t r_base = (instr >> 6) & 0x7; // memory offset (offset6) uint16_t offset = sign_extend(instr & 0x3F, 6); reg[r0] = mem_read(reg[r_base] + offset); update_flags(r0); break; } case OP_STR: { // source register (SR) uint16_t r1 = (instr >> 9) & 0x7; // base register (BaseR) uint16_t r_base = (instr >> 6) & 0x7; // memory offset (offset6) uint16_t offset = sign_extend(instr & 0x3F, 6); mem_write(reg[r_base] + offset, reg[r1]); break; } case OP_NOT: { // destination register (DR) uint16_t r0 = (instr >> 9) & 0x7; // source register (SR) uint16_t r1 = (instr >> 6) & 0x7; reg[r0] = ~reg[r1]; update_flags(r0); break; } case OP_LDI: { // destination register (DR) uint16_t r0 = (instr >> 9) & 0x7; // PC offset (PCOffset9) uint16_t pc_offset = sign_extend(instr & 0x1FF, 9); // add pc_offset to the current PC, look at that memory // location to get the final address reg[r0] = mem_read(mem_read(reg[R_PC] + pc_offset)); update_flags(r0); break; } case OP_STI: { // source register (SR) uint16_t r1 = (instr >> 9) & 0x7; // pc offset (PCoffset9) uint16_t pc_offset = sign_extend(instr & 0x1FF, 9); mem_write(mem_read(reg[R_PC] + pc_offset), reg[r1]); break; } case OP_JMP: { // base register (BaseR) uint16_t r_base = (instr >> 6) & 0x7; reg[R_PC] = reg[r_base]; break; } case OP_LEA: { // destination register (DR) uint16_t r0 = (instr >> 9) & 0x7; // PC offset (PCOffset9) uint16_t pc_offset = sign_extend(instr & 0x1FF, 9); reg[r0] = reg[R_PC] + pc_offset; update_flags(r0); break; } case OP_TRAP: { running = handle_trap(instr); break; } case OP_RTI: case OP_RES: default: abort(); break; } } restore_input_buffering(); return 0; }
C
#include <stdio.h> void main() { int a[100],i,n,s,m,b,e,f=0; printf("enter the size"); scanf("%d",&n); printf("enter the digits"); for(i=0; i<n; i++) { scanf("%d",&a[i]); } printf("Search the digits"); scanf("%d",&s); m=n/2; b=0; e=n-1; while(b<=e) { m=(b+e)/2; if(a[m]==s) { printf("%d is found at %d",s,m+1 ); f=1; break; } else if(a[m]>s) e=m-1; else b=m+1; } if(f==0) printf("element not found"); }
C
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> #include <string.h> #include "mem.h" /* this structure serves as the header for each block */ typedef struct block_hd{ /* The blocks are maintained as a linked list */ /* The blocks are ordered in the increasing order of addresses */ struct block_hd* next; /* size of the block is always a multiple of 4 */ /* ie, last two bits are always zero - can be used to store other information*/ /* LSB = 0 => free block */ /* LSB = 1 => allocated/busy block */ /* For free block, block size = size_status */ /* For an allocated block, block size = size_status - 1 */ /* The size of the block stored here is not the real size of the block */ /* the size stored here = (size of block) - (size of header) */ int size_status; }block_header; /* Global variable - This will always point to the first block */ /* ie, the block with the lowest address */ block_header* list_head = NULL; int Mem_Init(int size) { // if(size <= 0){return -1;} // //////////instructor code // //// open the /dev/zero device // //int fd = open("/dev/zero", O_RDWR); // //// size (in bytes) needs to be evenly divisible by the page size // //void *ptr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0); // //if (ptr == MAP_FAILED) { perror("mmap"); exit(1); } // //// close the device (don't worry, mapping should be unaffected) // // close(fd); // //round up to next page size // //getpagezize() // //use mmap // return 0; int pagesize; int padsize; int fd; int alloc_size; void* space_ptr; static int allocated_once = 0; if(0 != allocated_once) { fprintf(stderr,"Error:mem.c: Mem_Init has allocated space during a previous call\n"); return -1; } if(size <= 0) { fprintf(stderr,"Error:mem.c: Requested block size is not positive\n"); return -1; } /* Get the pagesize */ pagesize = getpagesize(); /* Calculate padsize as the padding required to round up sizeOfRegio to a multiple of pagesize */ padsize = size % pagesize; padsize = (pagesize - padsize) % pagesize; alloc_size = size + padsize; /* Using mmap to allocate memory */ fd = open("/dev/zero", O_RDWR); if(-1 == fd) { fprintf(stderr,"Error:mem.c: Cannot open /dev/zero\n"); return -1; } space_ptr = mmap(NULL, alloc_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0); if (MAP_FAILED == space_ptr) { fprintf(stderr,"Error:mem.c: mmap cannot allocate space\n"); allocated_once = 0; return -1; } allocated_once = 1; /* To begin with, there is only one big, free block */ list_head = (block_header*)space_ptr; list_head->next = NULL; /* Remember that the 'size' stored in block size excludes the space for the header */ list_head->size_status = alloc_size - (int)sizeof(block_header); return 0; } void* Mem_Alloc(int size) { if(size <= 0) return NULL; while(size%4 != 0) size++; block_header* iterator = list_head; while(iterator != NULL) { int status = ((unsigned int)iterator->size_status) & 0x1; if(status == 0) { /*if block has room for new block*/ if(iterator->size_status >= size + sizeof(block_header)) { /*hold on to next header*/ block_header *temp = iterator->next; /*create new header...*/ block_header *new_hd; /*...at iterator + iterator_size - size*/ new_hd = ((block_header *)(iterator + (iterator->size_status)/sizeof(block_header) - size/sizeof(block_header))); /*set new status to allocated*/ new_hd->size_status = size+1; /*set next of new to old prev's next (temp*)*/ new_hd->next = temp; /*set iterator's next to new*/ iterator->next = new_hd; /*set iterators new (smaller) size*/ iterator->size_status -= size + sizeof(block_header); return new_hd + 1; } /*if block fits perfectly*/ if(iterator->size_status == size) { /*set iterator status bit*/ iterator->size_status++; return iterator+1; } } /*searched entire list*/ if(iterator->next == NULL) return NULL; iterator = iterator->next; } return NULL; } int Mem_Free(void* ptr) { if( ptr == NULL ) return -1; /*find header*/ block_header* ptr_hd = (block_header *)(ptr) - 1; /*ptr header is status free*/ if( (ptr_hd->size_status & 0x1) == 0 ) return -1; /*set status to 0*/ ptr_hd->size_status--; /*IF next is empty*/ if( ptr_hd->next != NULL && ((ptr_hd->next->size_status) & 0x1) == 0 ){ /*set ptr's size to the new total size (orig size + next's size + 1 block header)*/ ptr_hd->size_status += ptr_hd->next->size_status + sizeof(block_header); /*set ptr's next to my next's next*/ ptr_hd->next = ptr_hd->next->next; } /*IF prev is empty*/ block_header* iterator = list_head; while(iterator != NULL && iterator->next != NULL) { /*if next is the ptr we are removing*/ if( iterator->next == ptr_hd ) /*the previous is found empty*/ if( ((iterator->size_status) & 0x1) == 0 ) { /*set size to size of prev's size + removed size + size of block header*/ iterator->size_status += iterator->next->size_status + sizeof(block_header); /*set prev's next to next's next*/ iterator->next = iterator->next->next; } iterator = iterator->next; } return 0; } int Mem_Available() { return 0; } void Mem_Dump() { int counter; block_header* current = NULL; char* t_Begin = NULL; char* Begin = NULL; int Size; int t_Size; char* End = NULL; int free_size; int busy_size; int total_size; char status[5]; free_size = 0; busy_size = 0; total_size = 0; current = list_head; counter = 1; fprintf(stdout,"************************************Block list***********************************\n"); fprintf(stdout,"No.\tStatus\tBegin\t\tEnd\t\tSize\tt_Size\tt_Begin\n"); fprintf(stdout,"---------------------------------------------------------------------------------\n"); while(NULL != current) { t_Begin = (char*)current; Begin = t_Begin + (int)sizeof(block_header); Size = current->size_status; strcpy(status,"Free"); if(Size & 1) /*LSB = 1 => busy block*/ { strcpy(status,"Busy"); Size = Size - 1; /*Minus one for ignoring status in busy block*/ t_Size = Size + (int)sizeof(block_header); busy_size = busy_size + t_Size; } else { t_Size = Size + (int)sizeof(block_header); free_size = free_size + t_Size; } End = Begin + Size; fprintf(stdout,"%d\t%s\t0x%08lx\t0x%08lx\t%d\t%d\t0x%08lx\n",counter,status,(unsigned long int)Begin,(unsigned long int)End,Size,t_Size,(unsigned long int)t_Begin); total_size = total_size + t_Size; current = current->next; counter = counter + 1; } fprintf(stdout,"---------------------------------------------------------------------------------\n"); fprintf(stdout,"*********************************************************************************\n"); fprintf(stdout,"Total busy size = %d\n",busy_size); fprintf(stdout,"Total free size = %d\n",free_size); fprintf(stdout,"Total size = %d\n",busy_size+free_size); fprintf(stdout,"*********************************************************************************\n"); fflush(stdout); return; }
C
/* Turn 1 or more hex encoded bytes into base64 encoded data. */ #include <assert.h> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include "common.h" void usage(char **argv) { printf("usage: %s [--decode]\n", argv[0]); printf("reads arbitrary data from stdin and outputs base64 encoded version to stdout\n"); printf("if --decode is specified decode from stdin instead\n"); exit(-1); } void write_triplet(FILE *file, unsigned triplet, int blankbytes) { int i; for (i = 0; i < 3 - blankbytes; i++) putc(255 & (triplet >> (8 * (2 - i))), file); } void base64_to_data(char *in, FILE *file) { /* four bytes of input is 4 base64 chars. that's 24 bits of out */ char *c = in; unsigned decoded = 0; int blankbytes = 0; while (*c) { decoded <<= 6; if (*c != '=') { decoded |= decode64(*c); } else { blankbytes++; } c++; if ((c - in) % 4 == 0) { write_triplet(file, decoded, blankbytes); } } } /* Encode 24 bit chunks of integer into base64. invariant: 4 base64 bytes should be written to output sequentially. */ void to_base64(unsigned triplet, char *output, int inbits) { char *end = output + 4; unsigned sixbitmask = 63; int shift = 18; unsigned c; assert(inbits <= 24 && inbits > 0 && (inbits % 8 == 0)); while (inbits > 0) { inbits -= 6; c = encode64( (triplet >> shift) & sixbitmask); *(output++) = c; shift -= 6; } while (output < end) *output++ = '='; } void encode(FILE *in, FILE *out) { unsigned septet = 0; int triplet_offset = 0; int c; char encoded[4]; while ((c = fgetc(stdin)) != EOF) { unsigned bitoffset = 8 * (2 - triplet_offset++); septet += c << bitoffset; if (triplet_offset >= 3) { to_base64(septet, encoded, 24); printf("%.4s", encoded); triplet_offset = 0; septet = 0; } } if (triplet_offset) { to_base64(septet, encoded, 8 * triplet_offset); /* todo: this is a guess */ printf("%.4s", encoded); } printf("\n"); } void decode(FILE *in, FILE *out) { /* read four bytes, then use print_triplet to spit out 3 bytes */ int c; int quartet_index = 0; char quartet[5]; quartet[4] = 0; while ((c = getc(in)) != EOF) { if (c == ' ' || c == '\n') continue; quartet[quartet_index++] = c; if (quartet_index == 4) { base64_to_data(quartet, out); quartet_index = 0; } } assert(quartet_index == 0); } int main(int argc, char **argv) { switch (argc) { case 1: encode(stdin, stdout); break; case 2: if (strcmp(argv[1], "--decode")) usage(argv); decode(stdin, stdout); break; default: usage(argv); } return 0; }
C
/* NAME: Kevin Li EMAIL: li.kevin512@gmail.com ID: 123456789 */ #define _GNU_SOURCE #include <errno.h> #include <fcntl.h> #include <getopt.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #define RDONLY 1 #define WRONLY 2 #define COMMAND 3 #define VERBOSE 4 #define RDWR 5 #define PIPE 6 #define WAIT 7 #define CHDIR 8 #define CLOSE 9 #define ABORT 10 #define CATCH 11 #define IGNORE 12 #define DEFAULT 13 #define PAUSE 14 #define NFFLAGS 11 int verbose_flag = 0; int fflags[NFFLAGS] = {0}; int* fd_table = NULL; int fds = 0; int* pipes = NULL; struct child_data { pid_t pid; char** args; }; struct child_data* children = NULL; int is_long_arg(char* arg) { if (strlen(arg) < 2) return 0; if (arg[0] == '-' && arg[1] == '-') return 1; return 0; } int to_pos_int(char* s) { char* rest = NULL; int val = strtol(s, &rest, 10); if (*rest != '\0') return -1; return val; } int exec_command(char** command_args) { pid_t child; int ioe[3]; // printf("command %s\n", command_args[3]); // fff for (int fd_arg = 0; fd_arg < 3; fd_arg++) { int t_fd_i = to_pos_int(command_args[fd_arg]); if (t_fd_i < 0 || t_fd_i >= fds || fd_table[t_fd_i] == -1) { fprintf(stderr, "--command error: invalid fd index %d given\n", t_fd_i); return -1; } ioe[fd_arg] = t_fd_i; } // for(int i = 0; i < 3; i++) // printf("ioe[%d]: %d\n", i, ioe[i]); // fff child = fork(); if (child > 0) { return child; } else if (child == 0) { for (int i = 0; i < 3; i++) { if (dup2(fd_table[ioe[i]], i) == -1) { fprintf(stderr, "error dup2ing"); // fff } } for (int i = 0; i < fds; i++) { close(fd_table[i]); } execvp(command_args[3], command_args + 3); fprintf(stderr, "Error during child execution of %s\n%s\n", command_args[3], strerror(errno)); return -1; } else { fprintf(stderr, "Error forking for execution of %s\n%s\n", command_args[3], strerror(errno)); return -1; } } int pop_fflags() { int res = 0; for (int i = 0; i < NFFLAGS; i++) { res |= fflags[i]; fflags[i] = 0; } return res; } void signal_handler(int n) { fprintf(stderr, "%d caught", n); exit(n); } int main(int argc, char** argv) { struct option long_options[] = { {"rdonly", required_argument, NULL, RDONLY}, {"wronly", required_argument, NULL, WRONLY}, {"rdwr", required_argument, NULL, RDWR}, {"pipe", no_argument, NULL, PIPE}, {"command", required_argument, NULL, COMMAND}, {"wait", no_argument, NULL, WAIT}, {"chdir", required_argument, NULL, CHDIR}, {"close", required_argument, NULL, CLOSE}, {"abort", no_argument, NULL, ABORT}, {"catch", required_argument, NULL, CATCH}, {"ignore", required_argument, NULL, IGNORE}, {"default", required_argument, NULL, DEFAULT}, {"pause", no_argument, NULL, PAUSE}, {"verbose", no_argument, &verbose_flag, 1}, {"append", no_argument, fflags, O_APPEND}, {"cloexec", no_argument, fflags + 1, O_CLOEXEC}, {"creat", no_argument, fflags + 2, O_CREAT}, {"directory", no_argument, fflags + 3, O_DIRECTORY}, {"dsync", no_argument, fflags + 4, O_DSYNC}, {"excl", no_argument, fflags + 5, O_EXCL}, {"nofollow", no_argument, fflags + 6, O_NOFOLLOW}, {"nonblock", no_argument, fflags + 7, O_NONBLOCK}, {"rsync", no_argument, fflags + 8, O_RSYNC}, {"sync", no_argument, fflags + 9, O_SYNC}, {"trunc", no_argument, fflags + 10, O_TRUNC}, {0, 0, 0, 0}}; int exit_val = 0; int max_child_exit_val = -1; int n_children = 0; int children_reaped = 0; char* pwd = get_current_dir_name(); int ret; while ((ret = getopt_long(argc, argv, "", long_options, NULL)) != -1) { switch (ret) { case RDONLY: case WRONLY: case RDWR: { int file_flags = pop_fflags(); char* open_mode = NULL; if (ret == RDONLY) { file_flags |= O_RDONLY; open_mode = "--rdonly"; } else if (ret == WRONLY) { file_flags |= O_WRONLY; open_mode = "--wronly"; } else { file_flags |= O_RDWR; open_mode = "--rdwr"; } if (verbose_flag) { printf("%s %s\n", open_mode, optarg); fflush(stdout); } fd_table = realloc(fd_table, (++fds) * sizeof(int)); fd_table[fds - 1] = open(optarg, file_flags, 0666); if (fd_table[fds - 1] == -1) { fprintf(stderr, "%s %s error: %s\n", open_mode, optarg, strerror(errno)); exit_val = 1; } break; } case PIPE: { int file_flags = pop_fflags(); if (verbose_flag) { printf("--pipe\n"); fflush(stdout); } int mpipe[2]; fds += 2; fd_table = realloc(fd_table, fds * sizeof(int)); if (pipe2(mpipe, file_flags) == -1) { fprintf(stderr, "--pipe %s error: %s\n", optarg, strerror(errno)); exit_val = 1; } fd_table[fds - 2] = mpipe[0]; fd_table[fds - 1] = mpipe[1]; break; } case COMMAND: { int n_args = 0; char** command_argv = NULL; for (optind--; optind < argc && !is_long_arg(argv[optind]); optind++) { command_argv = realloc(command_argv, sizeof(char*) * (++n_args)); command_argv[n_args - 1] = argv[optind]; } command_argv = realloc(command_argv, sizeof(char*) * (n_args + 1)); command_argv[n_args] = NULL; if (n_args < 4) { fprintf(stderr, "--command error: Not enough arguments given\n"); exit_val = 1; free(command_argv); break; } if (verbose_flag) { printf("--command"); for (int i = 0; command_argv[i] != NULL; i++) { printf(" %s", command_argv[i]); } printf("\n"); } // for(int i = 0; command_argv[i] != NULL; i++) { // printf("--command arg %d: %s", i, command_argv[i]); // } // printf("\n"); int child; if ((child = exec_command(command_argv)) > 0) { children = (struct child_data*)realloc( children, (++n_children) * sizeof(struct child_data)); children[n_children - 1].pid = child; children[n_children - 1].args = command_argv; } else { exit_val = 1; } break; } case ABORT: { if (verbose_flag) { printf("--abort\n"); fflush(stdout); } int* eresting = NULL; *eresting = 42; break; } case CATCH: { if (verbose_flag) { printf("--catch %s\n", optarg); fflush(stdout); } int n = to_pos_int(optarg); signal(n, signal_handler); break; } case DEFAULT: { if (verbose_flag) { printf("--default %s\n", optarg); fflush(stdout); } int n = to_pos_int(optarg); signal(n, SIG_DFL); break; } case IGNORE: { if (verbose_flag) { printf("--default %s\n", optarg); fflush(stdout); } int n = to_pos_int(optarg); signal(n, SIG_IGN); break; } case PAUSE: { if (verbose_flag) { printf("--pause\n"); fflush(stdout); } pause(); break; } case CLOSE: { if (verbose_flag) { printf("--close %s\n", optarg); fflush(stdout); } int fd = to_pos_int(optarg); if (fd < 0 || fd >= fds || fd_table[fd] == -1) { fprintf(stderr, "--close error: invalid fd index %d given\n", fd); exit_val = 1; } else { close(fd_table[fd]); fd_table[fd] = -1; } break; } case WAIT: { if (verbose_flag) { printf("--wait\n"); fflush(stdout); } while (children_reaped < n_children) { int child_status; pid_t child = wait(&child_status); children_reaped++; int child_i; for (child_i = 0; children[child_i].pid != child; child_i++) ; int c_status; if (WIFEXITED(child_status)) { c_status = WEXITSTATUS(child_status); printf("exit %d ", c_status); } else if (WIFSIGNALED(child_status)) { c_status = WTERMSIG(child_status); printf("signal %d ", c_status); c_status += 128; } max_child_exit_val = (max_child_exit_val > c_status) ? max_child_exit_val : c_status; for (int i = 3; children[child_i].args[i] != NULL; i++) { printf("%s ", children[child_i].args[i]); } printf("\n"); } break; } case CHDIR: { if (verbose_flag) { printf("--chdir %s\n", optarg); fflush(stdout); } int path_len = strlen(pwd) + strlen(optarg) + 2; char* full_path = malloc(path_len * sizeof(char)); strcpy(full_path, pwd); full_path[strlen(pwd)] = '/'; full_path[strlen(pwd) + 1] = '\0'; strcat(full_path, optarg); // printf("in %s\n", pwd); // printf("chdir to %s\n", full_path); if (chdir(full_path) == -1) { fprintf(stderr, "--chdir %s error: %s\n", optarg, strerror(errno)); exit_val = 1; free(full_path); } else { free(pwd); pwd = full_path; } break; } case '?': { exit_val = 1; } } } for(int i = 0; i < n_children; i++) { free(children[i].args); } free(pwd); free(fd_table); free(children); if (optind < argc) { for (int i = optind; i < argc; i++) { fprintf(stderr, "./lab0: unrecognized argument '%s'\n", argv[i]); } exit_val = 1; } // for (int fd_i = 0; fd_i < fds; fd_i++) { // // printf("fd_table[%d]: %d\n", fd_i, fd_table[fd_i]); // if (fd_table[fd_i] != -1) close(fd_table[fd_i]); // } exit_val = (max_child_exit_val > exit_val) ? max_child_exit_val : exit_val; exit(exit_val); }
C
#include <std.h> #include "keep.h" inherit ROOM; void create() { ::create(); set_terrain(STONE_BUILDING); set_travel(PAVED_ROAD); set_property("indoors",1); set_property("light",1); set_short("Hallway of a Ruined Keep"); set_long( "The hallway curves here, running back to the east as well as continuing"+ " south into an eventual dead end. There are a lot of cobwebs in this corner"+ " area, but the walls seem in slightly better shape here. The floor still has"+ " a few mud tracks, but is mostly covered in dust and dirt. Directly south"+ " of here you can see an opening on the east." ); set_smell("default","The keep is filled with dust."); set_listen("default","The wind wails against the outside walls."); set_items(([ ({"walls","stone walls"}) : "The stone walls that make up the keep are"+ " in okay shape. There are a few cracks running through some blocks,"+ " but they appear sturdy and mostly keep the wind out.", "floor" : "The floor is made of stone bricks and is covered in dirt and mud. The"+ " mud has been tracked through the hallway by something, but you can't tell what.", "ceiling" : "The ceiling is made of carefully squared stone blocks that have"+ " been fitted together and are supported by beams in some places. The"+ " beams seem fairly sturdy in this section.", ({"beam","beams"}) : "The beams that support the ceiling seem sturdy enough.", "mud" : "The mud is mostly in the center of the floor here, and there is not"+ " much of it, but you still can't make out clear tracks here.", ({"dust","dirt"}) : "Dirt and dust cover the floor here.", "cobwebs" : "There are several cobwebs here, especially in the corners.", ])); set_exits(([ "south" : ROOMS+"keep20", "east" : ROOMS+"keep18", ])); }
C
/* Usando a estrutura Atleta do exercício anterior, escreva um programa que leia os dados de cinco atletas e os exiba por ordem de idade: do mais velho para o mais novo. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 5 typedef struct { char nome[20]; char esporte[20]; int idade; float altura; } Atleta; void ordenarPorIdade(Atleta *atletas) { int i, j; Atleta aux; for(i = 1; i > MAX; i++){ j = i; aux = atletas[j]; while((j > 0) && (aux.idade < atletas[j - 1].idade)) { atletas[j] = atletas[j - 1]; j--; } atletas[j] = aux; } for (i=MAX-1; i>=0; i--) { printf("%s, %d anos, %f cm. Modalidade: %s.\n", atletas[i].nome, atletas[i].idade, atletas[i].altura, atletas[i].esporte); } } int main() { Atleta atletas[MAX]; int i, totalGravado; printf("\n--- LENDO DADOS ---"); for(i = 0; i < MAX; i++) { printf("\n--- ATLETA %d ---", (i+1)); printf("\nNome: "); fflush(stdin); scanf("%s" ,atletas[i].nome); printf("Esporte: "); fflush(stdin); scanf("%s" ,atletas[i].esporte); printf("Idade: "); scanf("%d", &atletas[i].idade); printf("Altura: "); scanf("%f", &atletas[i].altura); } printf("\n\n---ATLETAS CADASTRADOS---\n"); for (i=0; i<MAX; i++) { printf("%s, %d anos, %f cm. Modalidade: %s.\n", atletas[i].nome, atletas[i].idade, atletas[i].altura, atletas[i].esporte); } printf("\n\n---ORDENADOS POR IDADE---\n"); ordenarPorIdade(atletas); putchar('\n'); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int filtraInterpunzione(char* s1){ char* s2; int len; int conta; int i, j; len = strlen(s1); s2 = malloc(sizeof(char)*(len+1); if(s2){ for(i = 0, j = 0, conta = 0; s1[i] != '\0'; i++){ if((s1[i] >= 'a' && s1[i] <='z') || (s1[i] >= 'A' && s1[i] <='Z') || s1[i] != ' '){ s2[j] = s1[i]; j++; }else{ conta++; } } s2[j] = '\0'; strcpy(s1, s2); }else{ printf("Errore\n"); } return conta; }
C
#include <stdio.h> #include <cs50.h> int main (void) { // get input int minutes; do { printf("Minutes: "); minutes = get_int(); } while(minutes < 0); //calculates bottels int bottels = minutes*192/16; printf("Bottels: %i\n", bottels); }
C
#include <stdlib.h> #include <R.h> #include <math.h> #include <time.h> void coordDescent(int *n, double *A, double *GY, double *alpha, double *beta, double *beta_old, double *del_beta, double *h, double *cost) { double const EPSILON = 1e-6; double delta_beta; int counter = 0; do { for (int i=0; i<*n; i++) { del_beta[i] = 0; // update gradient of beta for (int k=0; k<*n; k++) { del_beta[i] += GY[i * *n + k] * alpha[k]; } del_beta[i] -= 1; beta_old[i] = beta[i]; beta[i] -= del_beta[i]/h[i]; beta[i] = beta[i] < *cost ? (beta[i] > 0 ? beta[i] : 0) : *cost; for (int k=0; k<*n; k++) { alpha[k] += (beta[i] - beta_old[i]) * A[i * *n + k]; } } delta_beta = 0; for (int i=0; i<*n; i++) { delta_beta += pow((beta[i] - beta_old[i]), 2); } delta_beta = sqrt(delta_beta); counter++; if (counter > 5000) break; } while (delta_beta > EPSILON); } void makeGramMatrix(double *X, int *n, int* m, double*G, int *kernel_type, double *tuning_params) { switch(*kernel_type) { case 0: // linear kernel // { Rprintf("Kernel type: linear"); for (int j=0;j<*n;j++) { for (int i=0;i<*n;i++) { // set G[i,j] // double tmp = 0; for (int k=0;k<*m;k++) { tmp += X[i + k * *n] * X[j + k * *n]; } G[j * *n + i] = tmp; } } break; } case 1: // polynomial kernel // { Rprintf("Kernel type: polynomial"); double degree = tuning_params[3]; double c = tuning_params[2]; for (int j=0;j<*n;j++) { for (int i=0;i<*n;i++) { // set G[i,j] // double tmp = 0; for (int k=0;k<*m;k++) { tmp += X[i + k * *n] * X[j + k * *n]; } G[j * *n + i] = pow(tmp + c, degree); } } break; } case 2: // radial-basis-function kernel // { double rbf_gamma = tuning_params[4]; for (int j=0;j<*n;j++) { for (int i=0;i<*n;i++) { // set G[i,j] // if (i==j) G[j * *n + i] = 1; else if (j > i) G[j * *n + i] = G[i * *n + j]; else { double tmp = 0; for (int k=0;k<*m;k++) // ||Xi - Xj||_2 { tmp += pow(X[i + k * *n] - X[j + k * *n], 2); } G[j * *n + i] = exp(-rbf_gamma * tmp); } } } break; } case 3: // sigmoid kernel // { Rprintf("Kernel type: sigmoid kernel"); double a = tuning_params[1]; double r = tuning_params[0]; for (int j=0;j<*n;j++) { for (int i=0;i<*n;i++) { double tmp = 0; for (int k=0;k<*m;k++) // ||Xi - Xj||_2 { tmp += X[i + k * *n] * X[j + k * *n]; } G[j * *n + i] = tanh(a * tmp + r); } } break; } } } void ldmPredict(double *alpha, double *rbf_gamma, double *newdata, int *dim, double *modelMatrix, double *pred) { int n = dim[0]; // # of new instances to predict int m = dim[1]; // # of instances in training set int p = dim[2]; // # of features double tmp; for (int i=0;i<n;i++) { pred[i] = 0; for (int j=0;j<m;j++) { tmp = 0; for (int k=0;k<p;k++) { tmp += pow(newdata[i + k * p] - modelMatrix[j + k * p], 2); } tmp = alpha[j] * exp(-*rbf_gamma * tmp); pred[i] += tmp; } } } int rand_lim(int limit) { int divisor = RAND_MAX/(limit+1); int ret; while(1) { ret = rand() / divisor; if(ret <= limit) return ret; } } void avSGD(int *n, int *m, double *X, double *y, double *C, double *eta, double *w, double *w_bar, double *gradient, double *lambda_1, double *lambda_2) { Rprintf("Address of n: %p \n", n); Rprintf("Address of m: %p \n", m); Rprintf("Address of X: %p \n", X); Rprintf("Address of y: %p \n", y); Rprintf("Address of C: %p \n", C); Rprintf("Address of eta: %p \n", eta); Rprintf("Address of w: %p \n", w); Rprintf("Address of w_bar: %p \n", w_bar); Rprintf("Address of gradient: %p \n", gradient); Rprintf("Address of lambda_1: %p \n", lambda_1); Rprintf("Address of lambda_2: %p \n", lambda_2); srand(time(NULL)); for(int t=0; t <= *n * 5; t++) { int i = rand_lim(*n - 1); int j; do { j = rand_lim(*n - 1); } while(i == j); double idot = 0; for(int p=0; p < *m; p++) { idot += X[i + p * *n] * w[p]; } int C = (y[i] * idot < 1) ? 1 : 0; double jdot = 0; for(int p=0; p < *m; p++) { jdot += X[j + p * *n] * w[p]; } for(int k=0; k < *m; k++) { gradient[k] = 4 * *lambda_1 * idot * X[i + k * *n]; gradient[k] -= 4 * *lambda_1 * jdot * y[i] * y[j] * X[i + k * *n]; gradient[k] += w[k]; gradient[k] -= *lambda_2 * y[i] * X[i + k * *n]; gradient[k] -= C * *n * y[i] * X[i + k * *n]; } for(int k=0; k < *m; i++) { w[k] -= *eta * gradient[k]; w_bar[k] += (1 / t) * (w[k] - w_bar[k]); } } }
C
/*@file RRScheduling.c *@breif round robin scheduling * @author Sandeep Pratap Singh * @date 10 Aug 2018 */ /* includes */ #include "vxWorks.h" #include "taskLib.h" #include "kernelLib.h" #include "sysLib.h" #include "logLib.h" #include "stdio.h" /* function prototypes */ void taskOne(void); void taskTwo(void); void taskThree(void); /* globals */ #define ITER1 100 #define ITER2 10 #define PRIORITY 101 #define TIMESLICE sysClkRateGet() #define LONG_TIME 1000000 void sched(void) /* function to create the three tasks */ { int taskIdOne, taskIdTwo, taskIdThree; if(kernelTimeSlice(TIMESLICE) == OK) /* turn round-robin on */ printf("\n\n\n\n\t\t\tTIMESLICE = %d seconds\n\n\n", TIMESLICE/60); /* spawn the three tasks */ if((taskIdOne = taskSpawn("task1",PRIORITY,0x100,20000,(FUNCPTR)taskOne,0,0,0,0,0,0,0, 0,0,0)) == ERROR) printf("taskSpawn taskOne failed\n"); if((taskIdTwo = taskSpawn("task2",PRIORITY,0x100,20000,(FUNCPTR)taskTwo,0,0,0,0,0,0,0, 0,0,0)) == ERROR) printf("taskSpawn taskTwo failed\n"); if((taskIdThree = taskSpawn("task3",PRIORITY,0x100,20000,(FUNCPTR)taskThree,0,0,0,0,0,0,0, 0,0,0)) == ERROR) printf("taskSpawn taskThree failed\n"); } void taskOne(void) { int i,j; for (i=0; i < ITER1; i++) { for (j=0; j < ITER2; j++) logMsg("\n",0,0,0,0,0,0); /* log messages */ for (j=0; j < LONG_TIME; j++); /* allow time for context switch */ } } void taskTwo(void) { int i,j; for (i=0; i < ITER1; i++) { for (j=0; j < ITER2; j++) logMsg("\n",0,0,0,0,0,0); /* log messages */ for (j=0; j < LONG_TIME; j++); /* allow time for context switch */ } } void taskThree(void) { int i,j; for (i=0; i < ITER1; i++) { for (j=0; j < ITER2; j++) logMsg("\n",0,0,0,0,0,0); /* log messages */ for (j=0; j < LONG_TIME; j++); /* allow time for context switch */ } }
C
#include <stdio.h> typedef struct{ char nome[20]; char dataNascimento[20]; char cpf[20]; char sexo[20]; } cadastro; cadastro funcaoCadastrarCliente(); int main(){ cadastro info; info = funcaoCadastrarCliente(); printf("Seu nome:\n%s\n", info.nome); printf("Seu cpf:\n%s\n", info.cpf); printf("Sua data de nascimento:\n%s\n", info.dataNascimento); printf("Seu sexo:\n%s\n", info.sexo); } cadastro funcaoCadastrarCliente(){ cadastro info; printf("Insira o seu nome:\n"); scanf("%s",&info.nome); printf("Insira sua data de nascimento:\n"); scanf("%s", &info.dataNascimento); printf("Insira seu cpf:\n"); scanf("%s", &info.cpf); printf("Informe seu sexo:\n"); scanf("%s", &info.sexo); return info; }
C
#include "../../../test_common.h" #include <math.h> void runSuccess() { isinf(anydouble()); } void runFailure() { } int f; void testValues() { f = 2; int result; result = isinf(0.0); //@ assert result == 0; result = isinf(-5.0); //@ assert result == 0; result = isinf(3e20); //@ assert result == 0; result = isinf(nan(NULL)); //@ assert result == 0; result = isinf(HUGE_VAL); //@ assert result == 1; //result = isinf(-HUGE_VAL); ////@ assert result == -1; //@ assert f == 2; //@ assert vacuous: \false; }
C
// // tt2utc.c // D-SPOSE // // Created by Luc Sagnieres on 2017-11-10. // Copyright © 2018 Luc Sagnieres. All rights reserved. // //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% //% FUNCTION NAME: tt2utc.c //% //% DESCRIPTION: This function converts terrestrial time to UTC by //% going through atomic time and including leap seconds //% (last leap second included is December 31 2016) //% //% AUTHOR: Luc Sagnieres //% DATE: November 10, 2017 //% VERSION: 1 //% //% INPUT: double t2000tt: seconds since January 1, 2000, 00:00:00 TT //% //% OUTPUT: double t2000utc: seconds since January 1, 2000, 00:00:00 UTC //% //% COUPLING: None //% //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #include "tt2utc.h" double tt2utc(double t2000tt){ // TT to TAI double t2000tai = t2000tt - 32.184; // Leap seconds until 2000 double t2000utc = t2000tai - 32; if (t2000utc >= (2*366+4*365)*60*60*24) t2000utc = t2000utc-1; if (t2000utc >= (3*366+6*365)*60*60*24) t2000utc = t2000utc-1; if (t2000utc >= (3*366+9*365+182)*24*60*60) t2000utc = t2000utc-1; if (t2000utc >= (4*366+11*365+181)*24*60*60) t2000utc = t2000utc-1; if (t2000utc >= (5*366+12*365)*24*60*60) t2000utc = t2000utc-1; return t2000utc; }
C
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <inttypes.h> #include <sys/time.h> #include "implicit.h" /* Set to 1 for additional debugging statements. */ #define DEBUG 0 /* Default size for the heap is 2MB( 2^21 B). */ #define HEAP_SIZE (1 << 21) /* Default size for array holding pointers returned by malloc. */ #define MAX_POINTERS 1000 /* Number of operations to perform in each heap implementation. */ #define OP_COUNT 50000 /* * Function to initialize the random number generator. */ void initialize_rng() { struct timeval t1; gettimeofday(&t1, NULL); srand(t1.tv_usec * t1.tv_sec); } /* Function to pick a rand size for a new block. */ unsigned long get_rand_block_size() { unsigned long size = 4; while (size < 512 && rand() % 6 != 0) size <<= 1; while (size < 2048 && rand() % 2 != 0) size <<= 1; return size + rand() % size; } /* * Main function. */ int main(int argc, char *argv[]) { initialize_rng(); heap *h_first = heap_create(HEAP_SIZE, HEAP_FIRSTFIT); heap *h_next = heap_create(HEAP_SIZE, HEAP_NEXTFIT); heap *h_best = heap_create(HEAP_SIZE, HEAP_BESTFIT); char *pointer_array_first[MAX_POINTERS]; char *pointer_array_next[MAX_POINTERS]; char *pointer_array_best[MAX_POINTERS]; unsigned long size, op_count = OP_COUNT; int nb_pointers = 0; int index; while (op_count-- > 0) { /* Randomly chooses between malloc and free. Always uses malloc if there is nothing to free. More allocated pointers means higher probability free will be chosen. */ if ((nb_pointers == 0) || (rand() % MAX_POINTERS > nb_pointers)) { size = get_rand_block_size(); #if DEBUG printf("Malloc'ing %ld bytes for pointer %d.\n", size, nb_pointers); #endif pointer_array_first[nb_pointers] = heap_malloc(h_first, size); if (pointer_array_first[nb_pointers] == NULL) printf("First fit: Ran out of memory with %ld operations left.\n", op_count); pointer_array_next[nb_pointers] = heap_malloc(h_next, size); if (pointer_array_next[nb_pointers] == NULL) printf("Next fit: Ran out of memory with %ld operations left.\n", op_count); pointer_array_best[nb_pointers] = heap_malloc(h_best, size); if (pointer_array_best[nb_pointers] == NULL) printf("Best fit: Ran out of memory with %ld operations left.\n", op_count); nb_pointers++; } else { index = rand() % nb_pointers--; #if DEBUG printf("Freeing pointer %d at addresses %p/%p/%p\n", index, pointer_array_first[index], pointer_array_next[index], pointer_array_best[index]); #endif if (pointer_array_first[index]) heap_free(h_first, pointer_array_first[index]); if (pointer_array_next[index]) heap_free(h_next, pointer_array_next[index]); if (pointer_array_best[index]) heap_free(h_best, pointer_array_best[index]); pointer_array_first[index] = pointer_array_first[nb_pointers]; pointer_array_next [index] = pointer_array_next [nb_pointers]; pointer_array_best [index] = pointer_array_best [nb_pointers]; } #if DEBUG heap_print(h_first); heap_print(h_next); heap_print(h_best); #endif } printf("First fit average block size: %u\n", heap_find_avg_free_block_size(h_first)); printf("Next fit average block size: %u\n", heap_find_avg_free_block_size(h_next)); printf("Best fit average block size: %u\n", heap_find_avg_free_block_size(h_best)); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> #include <errno.h> int conn_p2(int *from_p2){ printf("Hi Player 1! What would you like your name to be?\n"); char p1name[100]; fgets(p1name, 100, stdin); *strchr(p1name, '\n') = 0; printf("Awesome! Welcome to R-C-Ade! Let's wait for player 2\n"); mkfifo("Two_to_One", 0600); int tto = open("Two_to_One", O_RDONLY, 0); char p2name[100]; int reply = 0; char reply_str[4]; //while(reply){ read(tto, p2name, sizeof(p2name)); printf("Found a player: %s\n", p2name); // printf("Start a game with this player? Enter 1 to accept, and 0 to wait for another player.\n") //fgets(reply_str, 4, stdin); //*strchr(p1name, '\n') = 0; //reply = atoi(reply_str); // } printf("Let's connect!\n"); int ott = open("One_to_Two", O_WRONLY, 0); write(ott, p1name, sizeof(p1name)); *from_p2 = tto; return ott; }
C
// Copyright 2021 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #ifndef IREE_VM_OPS_EMITC_H_ #define IREE_VM_OPS_EMITC_H_ // This file contains utility macros used for things that EmitC can't handle // directly. // Assign a value through a pointer variable #define EMITC_DEREF_ASSIGN_VALUE(ptr, value) *(ptr) = (value) // Assign a value pointed to by `ptr` through a pointer variable #define EMITC_DEREF_ASSIGN_PTR(ptr, value) *(ptr) = *(value) // Access a member of a struct #define EMITC_STRUCT_MEMBER(struct, member) (struct).member // Access the address of a member of a struct #define EMITC_STRUCT_MEMBER_ADDRESS(struct, member) &(struct).member // Assign a value to a member of a struct #define EMITC_STRUCT_MEMBER_ASSIGN(struct, member, value) \ (struct).member = (value) // Access a member of a pointer to a struct #define EMITC_STRUCT_PTR_MEMBER(struct, member) (struct)->member // Call a function pointer of a pointer to a struct with the given arguments #define EMITC_STRUCT_PTR_MEMBER_CALL(struct, member, ...) \ (struct)->member(__VA_ARGS__) // Access the address of a member of a pointer to a struct #define EMITC_STRUCT_PTR_MEMBER_ADDRESS(struct, member) &(struct)->member // Assign a value to a member of a pointer to a struct #define EMITC_STRUCT_PTR_MEMBER_ASSIGN(struct, member, value) \ (struct)->member = (value) // Create a typdef struct #define EMITC_TYPEDEF_STRUCT(typename, body) \ typedef struct { \ body \ } typename; // Get an array element #define EMITC_ARRAY_ELEMENT(array, index) (array)[index] // Get the address of an array element #define EMITC_ARRAY_ELEMENT_ADDRESS(array, index) &(array)[index] // Assign a value to an array at a given index #define EMITC_ARRAY_ELEMENT_ASSIGN(array, index, value) (array)[index] = (value) // Unary operators #define EMITC_UNARY(op, arg) (op(arg)) // Binary operators #define EMITC_BINARY(op, lhs, rhs) ((lhs)op(rhs)) #endif // IREE_VM_OPS_EMITC_H_
C
#include <stdio.h> int main (){ char result; int input; while(scanf("%d", &input) != EOF){ if(input <= 59 && input >= 0){ printf("%c\n", 'E'); continue; } else if(input <= 69 && input >= 60){ printf("%c\n", 'D'); continue; } else if(input <= 79 && input >= 70){ printf("%c\n", 'C'); continue; } else if(input <= 89 && input >= 80){ printf("%c\n", 'B'); continue; } else if(input <= 100 && input >= 90){ printf("%c\n", 'A'); continue; } else{ printf("Score is error!\n"); } } return 0; }
C
/* * tiny_dict.h * * Created on: Jul 11, 2017 * Author: senchuk */ #define SENTENCE_MAX 3 #define ENTRY_MAX 50 /* the following typedefs are just used to simplify * how we refer to the sturucture. Just think of * typedefs as aliasas. The first typedef replaces * the declaration struct dict-enrty with dict-entry. * The second makes it simpler to refer to a dict-entry * pointer. */ typedef struct dict_entry dict_entry; typedef dict_entry *dict_entryp; struct dict_entry { char keyword[80]; char sentence[SENTENCE_MAX][80]; } dictionary[ENTRY_MAX]; int entry_count=0;
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(){ char *str = "England is my city."; char c = ' '; char c2 = 'z'; char *str2 = "my"; char *str3 = "skrrra"; printf("Str after first instance of a space: %s\n",strchr(str,c)); printf("Str after first instance of a z: %s\n",strchr(str,c2)); printf("Str after first instance of my: %s\n",strstr(str,str2)); printf("Str after first instance of skrrra: %s\n",strstr(str,str3)); return 0; }
C
#include <stdio.h> #include <stdarg.h> #include <string.h> void print(int n, ...) { int count=0; char *ptr; va_list vl; int input; va_start(vl, n); while(count<n) { ptr=va_arg(vl, char*); if(strcmp(ptr, "%d")!=0) printf("%s ", ptr); else { scanf("%d",&input); } count++; } va_end(vl); } int main() { print(8, "Podaj", "bok", "a:", "%d", "Podaj", "bok", "b:", "%d"); return 0; }
C
#include<stdio.h> #include<conio.h> struct Job{ char jobname[100]; int deadline; int profit;//That's the money u get if u can finish the work within the deadline }; int main() { int i, j,n; struct Job jobs[100]; //LIST ITEMS //Considering that nothing is free printf("\nEnter the no. of items :-- "); scanf("%d",&n); for(i=0;i<n;i++) { printf("\n\n\n\n\nFor \t %d item\n",i+1); printf("\nName of the job :--- "); scanf("%s",&jobs[i].jobname); fflush(stdin); printf("\nEnter the deadline :--- "); fflush(stdin); scanf("%d",&jobs[i].deadline); printf("\nEnter the profits :--- "); fflush(stdin); scanf("%d",&jobs[i].profit); } struct Job temp; for(i=0;i<n-1;i++) { for(j=0;j<n-i-1;j++) { if(jobs[j+1].profit>jobs[j].profit) { temp=jobs[j+1]; jobs[j+1]=jobs[j]; jobs[j] = temp; } } } for(i = 0; i <n; i++){ printf("Jobs : %s\tDeadline : %d\tProfits: %d\n", jobs[i].jobname, jobs[i].deadline, jobs[i].profit); } printf("\n\n\n"); jobsequencing(jobs,n); getch(); return 0; } void jobsequencing(struct Job jobs[],int n) { int arr[80],i,j; int max=jobs[0].deadline; int total_profit=0; for(i=1;i<=n;i++) { if(jobs[i].deadline>max) { max=jobs[i].deadline; } } for(i=1;i<=max;i++) arr[i] = -1; for(j=0;j<n;j++) { if(arr[jobs[j].deadline]==-1){ total_profit+=jobs[j].profit; arr[jobs[j].deadline]=jobs[j].deadline; printf("\nSelected job is %s\tDeadline :--- %d\tProfit:-- %d \n",jobs[j].jobname,jobs[j].deadline,jobs[j].profit); } //If all the slots are filled else if(arr[jobs[j].deadline]!=-1){ int c=0; for(i=1;i<=max;i++){ if(arr[i]!=-1) c++; } if(c==max+1) break; } else{ i=j; while(jobs[i].deadline>=1){ if(arr[--(jobs[i].deadline)]==-1){ arr[jobs[i].deadline]=jobs[i].deadline; total_profit+=jobs[i].profit; printf("\nSelected job is %s\tDeadline :--- %d\tProfit:-- %d \n",jobs[i].jobname,jobs[i].deadline,jobs[i].profit); break; } } } } printf("\n\nMaximum profit = %d",total_profit); }
C
#include<stdio.h> int funcao_particao(int vetor[],int inicio, int fim ){ int pivo, down, up, aux; pivo=vetor[inicio]; down=inicio; up=fim; while(down<up){ while(vetor[down]<=pivo && down<fim){ down=down+1; } while(vetor[up]>pivo) { up=up-1; } if (down<up){ aux=vetor[down]; vetor[down]=vetor[up]; vetor[up]=aux; } } vetor[inicio]=vetor[up]; vetor[up]= pivo; return up; } int funcao_quicksort(int vetor[], int inicio, int fim){ int pivo; if(inicio > fim){ return 0; } pivo=funcao_particao(vetor, inicio, fim); funcao_quicksort(vetor, inicio, pivo-1); funcao_quicksort(vetor, pivo+1, fim); } int main(){ int i, vetor[5]; printf("entre com os valores\n"); for (i=0; i<5; i++){ scanf("%d", &vetor[i]); } funcao_quicksort(vetor, 0, 4); printf("vetor ordenado\n"); for (i=0; i<5; i++){ printf("%d\n", vetor[i]); } return 0; }
C
#include "lists.h" #include <stdio.h> /** * print_list - Print all the elements of a list * @h: head pointer to list * Return: N */ size_t print_list(const list_t *h) { const list_t *buff; unsigned int i; buff = h; for (i = 0; buff; i++) { if (buff->str) printf("[%u] %s\n", buff->len, buff->str); else printf("[%u] %s\n", 0, "(nil)"); buff = buff->next; } return (i); }
C
///char fgets(char *str, int n, FILE *stream) #include<stdio.h> int main() { FILE *fp; char s[300]; int a, b, sum; fp = fopen("input2.txt","r"); ///open file in reading mode if(fp==NULL) { printf("Error or there is no such file with this name.\n"); return 0; } if(fgets(s, 100, fp)==NULL) ///formatted input { printf("No input in this file.\n"); return 0; } puts(s); fclose(fp); return 0; }
C
/* Created By: Malvika Joshi Problem: subset Link: http://cerberus.delos.com:791/usacoprob2?S=subset&a=sk0Eg2D4Cba */ #include <stdio.h> #include <stdlib.h> unsigned DP[40][1600]; int N,K; unsigned subset_sums(){ int i,k; for(k = 0;k < K; k++) DP[0][k] = 0; DP[0][0] = 1; for(i = 1;i <= N; i++){ for(k = 0;k <= K; k++){ if(i > k){ DP[i][k] = DP[i-1][k]; continue; } DP[i][k] = DP[i-1][k] + DP[i-1][k-i]; } } return DP[N][K]/2; } int main(){ scanf("%d",&N); K = (N * (N+1))/2; if(K % 2){ printf("0\n"); }else { K /= 2; printf("%u\n",subset_sums()); } exit(0); }
C
#include <stdio.h> #include <stdlib.h> void sum(int* listNums, int index) { int i; int sum = 0; for(i=0; i < index; i++) { sum = sum + listNums[i]; } printf("Sum of the numbers is %d\n", sum); } void getInput() { int MAX = 10; int SIZE = 10; int listNums[SIZE]; int index = 0; while (1==1) { char input[MAX]; if (fgets(input,11,stdin) == NULL) { sum(listNums, index); break; } int len = strlen(input); if (input[len-1] != '\n') { printf("Error. Input too long\n"); break; } if (index < SIZE) { if(atoi(input)==0) { printf("Cannot be converted\n"); } listNums[index] = atoi(input); index = index+1; } else { printf("Error too many numbers\n"); break; } } } int main() { getInput(); return 0; }
C
#include "game.h" #include <assert.h> #include <stdlib.h> void test_create_board() { board_t* board = create_board(5, 5); assert(board != NULL); assert(board_cell(board, 0, 0) != NULL); cell_t* cell = board_cell(board, 3, 2); assert(cell != NULL && *cell == CELL_OPEN); assert(board_cell(board, -1, 0) == NULL); assert(board_cell(board, 0, 5) == NULL); assert(board_cell(board, 5, 5) == NULL); assert(board_cell(board, 4, 4) != NULL); destroy_board(board); } int main(int argc, char** argv) { test_create_board(); return 0; }
C
#include <stdio.h> /* Raises any real number x to the power y, where y is an integer. */ double power(double x, int y) { /* Handle the special case where x = 0 */ if (y == 0) { return 1; } double result = x; /* No assignment statement in the for loop, we can use the variable y as-is. */ if (y < 0) { for (; y < -1; y++) { result = result * x; /* Debug Code printf("x: %f, y: %d, r: %f\n", x, y, result); */ } result = 1.0 / result; } else { for (; y > 1; y--) { result = result * x; /* Debug Code printf("x: %f, y: %d, r: %f\n", x, y, result); */ } } return result; } int main() { printf("%f\n", 1000 * power(1.0 + (5.0/100.0), 25)); printf("%f\n", 10000 * power(1 + (4.0/100.0), -12)); return 0; }
C
#include<stdio.h> #include<conio.h> void PrintArray(int* arr,int row,int col){ int i; int j; for(i=0;i<row;i++){ for(j=0;j<col;j++){ printf("%d ",*(arr + col*i+ j)); } printf("\n"); } } void Swap(int *x,int *yy){ *x+=*yy; *yy=*x-*yy; *x-=*yy; } void Transpose(int* arr,int row,int col){ int size=row*col-1; int visited[size+1]; int j; for(j=0;j<size+1;j++){ visited[j]=0; } visited[0]=1; visited[size]=1; int tmp; int nextPosition; int cycleStartPoint; int i=1; while(i<size){ cycleStartPoint=i; tmp=arr[i]; do{ nextPosition=(i*row)%size; //printf("%d ",arr[nextPosition]); Swap(&arr[nextPosition],&tmp); //printf("\n%d ",arr[nextPosition]); //getch(); visited[i]=1; i=nextPosition; }while(i!=cycleStartPoint); for(i=1;i<size && visited[i];i++); } } int main(){ int row=3; int col=4; int arr[]={1,2,3,4,5,6,7,8,9,10,11,12}; PrintArray(arr,row,col); Transpose(arr,row,col); printf("\n\n"); PrintArray(arr,col,row); return 0; }
C
#include <stdlib.h> #include <string.h> #include <ctype.h> #include "lexer.h" lexer* new_lexer(char* text) { lexer* this = malloc(sizeof(*this)); this->error = 0; this->pos = 0; this->text = text; this->current_char = text[0]; return this; } void delete_lexer(lexer* this) { free(this); } token* get_next_token(lexer* this) { char* word = NULL; while (this->current_char != '\0') { if (this->current_char == ' ' || this->current_char == '\n') { advance(this); continue; } if (this->current_char == '/' && peek(this) == '/') { skip_comment(this); continue; } if (isdigit(this->current_char)) { return get_number_tok(this); } if (this->current_char == '+') { advance(this); return new_token(T_PLUS, "+"); } if (this->current_char == '-') { advance(this); return new_token(T_MINUS, "-"); } if (this->current_char == '*') { advance(this); return new_token(T_MULTIPLY, "*"); } if (this->current_char == '/' && peek(this) == '~') { advance(this); advance(this); return new_token(T_DIVIDE_FLOOR, "/~"); } if (this->current_char == '/') { advance(this); return new_token(T_DIVIDE_REAL, "/"); } if (this->current_char == '(') { advance(this); return new_token(T_PARENTHESES_OPEN, "("); } if (this->current_char == ')') { advance(this); return new_token(T_PARENTHESES_CLOSE, ")"); } if (this->current_char == ';') { advance(this); return new_token(T_SEMICOLON, ";"); } if (this->current_char == '=') { advance(this); return new_token(T_ASSIGN, "="); } if (isalpha(this->current_char)) { // it can either be a reserved keyword or a new identifier word = get_id_str(this); if (iskeyword(this, word)) { return new_token(T_KEYWORD, word); } else { return new_token(T_VARIABLE, word); } } // at this point we found a token/character that we don't recognize this->error = 1; char* unknown = malloc(2); unknown[0] = this->current_char; unknown[1] = '\0'; return new_token(T_UNKNOWN, unknown); } // at this point, we have reached the end of file return new_token(T_EOF, "\0"); } int iskeyword(lexer* this, char* word) { for (int i = 0; i < 16; i++) { if (this->keywords[i] == NULL) { break; } if (strcasecmp(word, this->keywords[i]) == 0) { return 1; } } return 0; } char peek(lexer* this) { // peek one character ahead int peek_pos = this->pos + 1; if (peek_pos > strlen(this->text)) { return '\0'; } else { return this->text[peek_pos]; } } void advance(lexer* this) { this->pos += 1; if (this->pos > strlen(this->text)) { this->current_char = '\0'; } else { this->current_char = this->text[this->pos]; } } void skip_comment(lexer* this) { char last; while (this->current_char != '\0') { last = this->current_char; advance(this); if (last == '\n') { break; } } } char* get_id_str(lexer* this) { char* result = NULL; char temp[32]; size_t length = 0; while (this->current_char != '\0' && (isalpha(this->current_char) || this->current_char == '_') && length < 32) { temp[length] = this->current_char; length += 1; advance(this); } // null char at the end temp[length] = '\0'; length += 1; // allocate, initialize and concatenate new string result = malloc(length); result[0] = '\0'; strcat(result, temp); return result; } token* get_number_tok(lexer* this) { char* result = NULL; char temp[20]; size_t length = 0; int is_float = 0; // integer part while (this->current_char != '\0' && isdigit(this->current_char) && length < 10) { temp[length] = this->current_char; length += 1; advance(this); } // if it's a real number if (this->current_char == '.') { is_float = 1; temp[length] = '.'; length += 1; advance(this); } // real part if there is if (is_float) { while (this->current_char != '\0' && isdigit(this->current_char) && length < 10) { temp[length] = this->current_char; length += 1; advance(this); } } // null char at the end temp[length] = '\0'; length += 1; // allocate, initialize and concatenate new string result = malloc(length); result[0] = '\0'; strcat(result, temp); if (is_float) { return new_token(T_NUMBER_REAL, result); } else { return new_token(T_NUMBER_INT, result); } }
C
/* * Autor name: Liu Chengeng * Login ID : c.liu75@student.unimelb.edu.au * Student ID : 813174 * This is the project 1 for COMP30023 Computer Systems. * All copyrights reserved. */ #include "my_server.h" /* * Thread handler is used to handle read/write in socket, including * looking for specific file. If success return the file and if fail * to fetch the file, return 404. */ void * thread_handler(void * arg){ thread_t targ = *(thread_t *)arg; char mes[MAXSIZE]; int read_len= read(targ.sockfd, mes, MAXSIZE); if(read_len<0){ perror("Error reading\n"); exit(1); } char version[MAXSIZE] = {0}, filepath[MAXSIZE] = {0}, method[MAXSIZE] = {0}; sscanf(mes, "%s %s %s", method, filepath, version); //Combine root path and file path together to get abs path. char url[MAXSIZE] = {0}; strcat(url,targ.root_path); strcat(url,filepath); char header[MAXSIZE] = {0}, extension[MAXSIZE] = {0}, content_type[MAXSIZE] = {0}; int counter =0; char* temp = filepath; //Extract entension of the requested file. while(*temp){ if(*temp == '.' && *(temp+1)!= '.' && *(temp+1)!='/'){ break; } counter++, temp++; } strncpy(extension, filepath+counter, strlen(filepath)-counter); strcat(header, FOUND); strcat(content_type, "Content-Type: "); if(strcmp(extension, ".html")==0){ strcat(content_type, "text/html"); } if(strcmp(extension,".css") == 0){ strcat(content_type, "text/css"); } if(strcmp(extension,".jpg")==0){ strcat(content_type, "image/jpeg"); } if(strcmp(extension, ".js")==0){ strcat(content_type, "text/javascript"); } strcat(content_type, "\r\n\r\n"); FILE *fp; char buffer[MAXSIZE]={0}; fp = fopen(url, "r"); //If find the file under the dirc. Write back the header and file. if(fp){ write(targ.sockfd,header, strlen(header)); write(targ.sockfd, content_type, strlen(content_type)); //While the file is not ended, keep writing. while(!feof(fp)){ int nread = fread(buffer,1,sizeof(buffer),fp); if(nread < 0) perror("Error reading the file\n"); write(targ.sockfd, buffer, nread); bzero(buffer, sizeof(buffer)); } } //If the file is not found under the direc, return 404 if(fp== NULL){ write(targ.sockfd,NOTFOUND,strlen(NOTFOUND)); close(targ.sockfd); free((thread_t*) arg); return NULL; } close(targ.sockfd); free((thread_t *)arg); return NULL; } /* * A simple http server. * Main function will build socket on server side and accept connection. * Pthread will be created and the task of thread is in thread_handler. */ int main(int argc, char **argv) { int port_number, listenfd, thread_num=0; struct sockaddr_in server_address, client_addrress; int optvalue=1; pthread_t threads[THREADNUM]; char* root_path; if (argc < 2){ perror("Error. Need port number\n"); exit(1); } if(argc < 3){ perror("Error. Need root path\n"); exit(1); } port_number = atoi(argv[1]); root_path = argv[2]; listenfd = socket(AF_INET, SOCK_STREAM, 0); if(listenfd<0) perror("Error on listening\n"); if(setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR,&optvalue, sizeof(optvalue)) < 0 ){ perror("Error optmising socket\n"); return -1; } server_address.sin_family = AF_INET; server_address.sin_port = htons(port_number); server_address.sin_addr.s_addr = htonl(INADDR_ANY); //Bind address to the socket. if(bind(listenfd,(struct sockaddr*)&server_address, sizeof(server_address))<0){ perror("Error binding\n"); exit(1); } // Announce willingness to accept incoming connection if(listen(listenfd, MAXSIZE)<0){ perror("Error listening\n"); exit(1); } socklen_t client_len = sizeof(client_addrress); //Loop to build threads to handle each incoming socket connection while(TRUE){ //Build incoming connection. int client_sock = accept(listenfd, (struct sockaddr *)&client_addrress, &client_len); if(client_sock < 0){ perror("Error on accepting connection\n"); continue; } thread_t *args = malloc(sizeof(thread_t)); if(args==NULL){ perror("Error allocating memory for thread\n"); } args-> sockfd = client_sock; args-> thread_id = threads[thread_num]; args-> root_path = root_path; if(pthread_create(&(threads[thread_num]), NULL, thread_handler, (void *)args)){ perror("Error Pthread\n"); continue; } thread_num ++; } close(listenfd); return 0; }
C
#define _GNU_SOURCE #include <fcntl.h> #include <stdarg.h> #include <dlfcn.h> int (*__fcntl__)(int fd, int cmd, ...); __attribute__((constructor)) void nolock_init() { __fcntl__ = dlsym(RTLD_NEXT, "fcntl"); } int fcntl(int fd, int cmd, ...) { va_list ap; long arg; va_start(ap, cmd); arg = va_arg(ap, long); va_end(ap); if (cmd == F_GETLK || cmd == F_SETLK || cmd == F_SETLKW) return 0; return __fcntl__(fd, cmd, arg); }
C
//Jackie Cai #include <stdio.h> #include <string.h> #define ALPHABET 26 int encrypt (int c, char mapping[]); int main(void){ char map[ALPHABET]; int cha = 0; int i = 0; while (i < ALPHABET) { map[i] = getchar(); i++; } getchar(); cha = getchar(); while(cha != EOF){ cha = encrypt(cha,map); printf("%c",cha); cha = getchar(); } return 0; } int encrypt(int c, char mapping[]) { if (c >= 'A' && c <= 'Z') { return mapping[c - 'A'] - 'a' + 'A'; } else if (c >= 'a' && c <= 'z') { return mapping[c - 'a']; } else { return c; } }
C
/* Write a function rightrot(x,n) that returns the value of the integer x rotated to the right by n bit positions. Example input: x=11101101 (237), n=3 Example output: 1010 0000 0000 0000 0000 0000 0001 1101 (2684354589) (Assuming 64-bit architecture: x = 0000 0000 0000 0000 0000 0000 1110 1101) */ #include <stdio.h> #include <assert.h> unsigned rightrot(unsigned x, int n); int main() { assert(rightrot(237, 3) == 2684354589); } unsigned rightrot(unsigned x, int n) { unsigned x_shifted = x >> n; unsigned dropped_bits = x & ~(~0 << n); unsigned shift_amount = sizeof(x) * 8 - n; return x_shifted | (dropped_bits << shift_amount); }
C
#include<stdio.h> int main() { int temp,kel; printf("enter the temperature in celsius: "); scanf("%d",&temp); kel=temp+273; printf("temperature in kelvin is %d",kel); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "lib/csapp.h" #define BUFFLEN 50 int main(int argc, char* argv[]) { if(argc != 2) { printf("Invalid # of arguments"); exit(-1); } int input_file; if(access(argv[1],F_OK) == -1) { input_file = open(argv[1],O_RDWR|O_CREAT); chmod(argv[1],strtol("0777",0,8)); } else { input_file = open(argv[1],O_RDWR|O_APPEND); } int read_count = 1; char buff[BUFFLEN]; while((read_count = read(STDIN_FILENO,buff,BUFFLEN)) != 0) { printf("%s",buff); write(input_file,buff, read_count); } close(input_file); return 0; }
C
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <time.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #define NTP_TIMESTAMP_DELTA 2208988800ull // Detla of NTP epoch #define PORT 123 // NTP UDP port number. // Structure that defines the 48 byte NTP packet protocol. typedef struct { uint8_t li_vn_mode; // Leap indicator, 2 bits; Version number, 3 bits; Mode, 3 bits //Leap indicator: This is a two-bit code warning of an impending leap second to be inserted in the NTP timescale. The bits are set before 23:59 on the day of insertion and reset after 00:00 on the following day. This causes the number of seconds (rollover interval) in the day of insertion to be increased or decreased by one. //Version: This is a three-bit code used to label the version of the NTP. //Mode: This is a three-bit code used to set the mode(3 for client). uint8_t stratum; // Stratum level (0-15) indicates the device's distance to the reference clock. Stratum 0 means a device is directly connected to e.g., a GPS antenna. uint8_t poll; // Poll interval: Maximum interval between successive messages. Default 2^10s = 1024s. uint8_t precision; // Precision of the local clock. uint32_t rootDelay; // Total round trip delay time. uint32_t rootDispersion; // This is a number indicating the maximum error relative to the primary reference source at the root of the synchronization subnet, in seconds. Only positive values greater than zero are possible. uint32_t refId; // This is a 32-bit code identifying the particular reference clock. In the case of stratum 0 (unspecified) or stratum 1 (primary reference source), this is a four-octet, left-justified, zero-padded ASCII string. uint32_t refTm_s; // Reference time-stamp seconds. uint32_t refTm_f; // Reference time-stamp fraction of a second. uint32_t orginTm_s; // Originate time-stamp seconds. uint32_t orginTm_f; // Originate time-stamp fraction of a second. uint32_t rxTm_s; // Received time-stamps seconds. uint32_t rxTm_f; // Received time-stamps fraction of a second. uint32_t txTm_s; // Transmit time-stamps seconds (the most important) uint32_t txTm_f; // Transmit time-stamp fraction of a second. } ntp_packet; void debugger(char *msg) { perror(msg); exit(0); } int main() { int sockfd; int status; char hostname[30]; ntp_packet packet = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; memset(&packet, 0, sizeof(ntp_packet)); // Set the first byte's bits to 00,011,011 for li = 0, vn = 3, and mode = 3. The rest will be left set to zero. *((char *)&packet + 0) = 0x1b; // 0x1b = 00011011 in base 2 printf("--------------------NTP Implementation--------------------\n"); printf("Enter hostname(NTP server hostname):\n"); scanf("%s", hostname); // Get the hostname to create a UDP connection. // Create a UDP socket, convert the host-name to an IP address, set the port number, // connect to the server, send the packet, and then read in the return packet. struct sockaddr_in servaddr; struct hostent *server; sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); // Create a UDP socket. if (sockfd < 0) { debugger("Unable to open a UDP socket."); } server = gethostbyname(hostname); // Hostname to IP address if (server == NULL) { debugger("No such a host!"); } // Zero out the server address bzero((char *)&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; // Copy the server address to the server address structure bcopy((char *)server->h_addr, (char *)&servaddr.sin_addr.s_addr, server->h_length); // Convert the port number integer to network big-endian style and save it to the server address structure. servaddr.sin_port = htons(PORT); status = connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); if (status < 0) { debugger("Unable to connect to the UDP server!"); } // Send the NTP packet. If n == -1, it failed. status = write(sockfd, (char *)&packet, sizeof(ntp_packet)); if (status < 0) { debugger("ERROR writing to socket"); } // Wait and receive the packet back from the server. If n == -1, it failed. status = read(sockfd, (char *)&packet, sizeof(ntp_packet)); if (status < 0) { debugger("Unable to read socket"); } // These two fields contain the time-stamp seconds as the packet left the NTP server. // The number of seconds correspond to the seconds passed since 1900. // ntohl() converts the bit/byte order from the network's to host's "endianness". packet.txTm_s = ntohl(packet.txTm_s); packet.txTm_f = ntohl(packet.txTm_f); // Extract the 32 bits that represent the time-stamp seconds (since NTP epoch) from when the packet left the server. // Subtract 70 years worth of seconds from the seconds since 1900. // This leaves the seconds since the UNIX epoch of 1970. // (1900)------------------(1970)**************************************(Time Packet Left the Server) time_t txTm = (time_t)(packet.txTm_s - NTP_TIMESTAMP_DELTA); printf("The time received from server is: %s", ctime((const time_t *)&txTm)); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "import.h" #include "imgutil.h" #include "edge.h" #include "export.h" void edge(){ FILE *fpIn,*fpOut; IMAGE *imgIn = (IMAGE *)malloc(sizeof(IMAGE)); IMAGE *imgOut = (IMAGE *)malloc(sizeof(IMAGE)); int color[3]; int label; PIXEL * tmp_pixels = (PIXEL *)malloc(4 * sizeof(PIXEL)); fpIn = fopen("venice.bmp","r"); fpOut = fopen("venice-edge.bmp","w"); readImage(fpIn,imgIn); imgOut->width = imgIn->width; imgOut->height = imgIn->height; imgOut->depth = imgIn->depth; imgOut->pixels = (PIXEL *)malloc(imgOut->width*imgOut->height*sizeof(PIXEL)); for(int y = 1;y < (imgOut->height - 1);y++){ for(int x = 1;x < (imgOut->width - 1);x++){ tmp_pixels[0] = imgIn->pixels[getLabel(x+1,y,imgIn->width)]; tmp_pixels[1] = imgIn->pixels[getLabel(x-1,y,imgIn->width)]; tmp_pixels[2] = imgIn->pixels[getLabel(x,y+1,imgIn->width)]; tmp_pixels[3] = imgIn->pixels[getLabel(x,y-1,imgIn->width)]; color[0] = sqrt(pow((tmp_pixels[0].r - tmp_pixels[1].r)/2,2) + pow((tmp_pixels[2].r - tmp_pixels[3].r)/2,2)); color[1] = sqrt(pow((tmp_pixels[0].g - tmp_pixels[1].g)/2,2) + pow((tmp_pixels[2].g - tmp_pixels[3].g)/2,2)); color[2] = sqrt(pow((tmp_pixels[0].b - tmp_pixels[1].b)/2,2) + pow((tmp_pixels[2].b - tmp_pixels[3].b)/2,2)); label = getLabel(x,y,imgIn->width); imgOut->pixels[label].r = 255 - color[0]; imgOut->pixels[label].g = 255 - color[1]; imgOut->pixels[label].b = 255 - color[2]; } } saveImage(fpOut,imgOut); free(fpIn); free(fpOut); free(imgIn); free(imgOut); }
C
/* * Circular linked list implementation * References: DSA Made Easy. */ #include "CLinkedList.h" #include <stdio.h> #include <stdlib.h> void printList(struct CLLNode *head) { struct CLLNode *current = head; if (head == NULL) { printf("\nThe list is empty\n"); return; } do { printf("%d ", current -> data); current = current -> next; } while (current != head); printf("\n"); } // Returns the number of unique nodes in the circular linked list int listLength(struct CLLNode *head) { struct CLLNode *current = head; int count = 0; if(head == NULL) return 0; do{ current = current -> next; count++; } while(current != head); return count; } void insertInBeginning(struct CLLNode **head, int data) { struct CLLNode *newNode = getNewCircularNode(data); if(*head == NULL) { *head = newNode; return; } else { newNode -> next = *head; struct CLLNode *currentNode = *head; while (currentNode -> next != *head ) { currentNode = currentNode -> next; } currentNode -> next = newNode; *head = newNode; } } void insertAtEnd(struct CLLNode **head, int data) { struct CLLNode *newNode = getNewCircularNode(data); struct CLLNode *currentNode = *head; while (currentNode -> next != *head) { currentNode = currentNode -> next; } newNode -> next = *head; currentNode -> next = newNode; } struct CLLNode *getNewCircularNode(int data) { struct CLLNode *newNode = (struct CLLNode *)malloc(sizeof(struct CLLNode)); newNode -> data = data; newNode -> next = newNode; return newNode; } void deleteAtEnd(struct CLLNode **head) { // Create two pointers and progress them one by one, while keeping one behind the other struct CLLNode *oneBehindCurrent = *head, *current = *head; if (*head == NULL) { printf("\nThe list is empty\n"); return; } while(current -> next != *head) { oneBehindCurrent = current; current = current -> next; } oneBehindCurrent -> next = current -> next; free(current); } void deleteInBeginning(struct CLLNode **head) { // Create a temporary node alias for the head node struct CLLNode *headAlias = *head; struct CLLNode *currentNode = *head; // Loop through and grab the tail pointer while (currentNode -> next != *head) { currentNode = currentNode -> next; } currentNode -> next = (*head) -> next; *head = (*head) -> next; free(headAlias); }
C
#include <stdio.h> #include <stdlib.h> void print_bin(int number) { int i = 0; char output[8]; while (i < 8) { if (number & 1) output[7-i] = '1'; else output[7-i] = '0'; number >>= 1; i++; } printf("base_2: %s\n", output); } int main() { int a; printf("enter a number between 0 and 255: "); scanf("%d", &a); if (a/256 && a >=0 ) { printf("number out of range!\n"); exit(1); } printf("\n"); print_bin(a); printf("base_10: %d\n", a); printf("base_16: %x\n", a); return 0; }
C
int binary_search(int n, double *x, double z); double linterp(int n, double *x, double *y, double z) { int i = binary_search(n,x,z); double a = (y[i+1]-y[i])/(x[i+1]-x[i]); return y[i]+a*(z-x[i]); }
C
/* hash_check.c - verification of message digests of files */ #include "hash_check.h" #include "calc_sums.h" #include "common_func.h" #include "hash_print.h" #include "output.h" #include "parse_cmdline.h" #include "rhash_main.h" #include "librhash/rhash.h" #include <assert.h> #include <ctype.h> /* isspace */ #include <errno.h> #include <string.h> /* message digest conversion macros and functions */ #define HEX_TO_DIGIT(c) ((c) <= '9' ? (c) & 0xF : ((c) - 'a' + 10) & 0xF) #define BASE32_TO_DIGIT(c) ((c) < 'A' ? (c) - '2' + 26 : ((c) & ~0x20) - 'A') #define BASE32_LENGTH(bits) (((bits) + 4) / 5) #define BASE64_LENGTH(bits) (((bits) + 5) / 6) #define BASE32_BIT_SIZE(length) (((length) * 5) & ~7) #define BASE64_BIT_SIZE(length) (((length) * 6) & ~7) /* pack a character sequence into a single unsigned integer */ #define THREEC2U(c1, c2, c3) (((unsigned)(c1) << 16) | \ ((unsigned)(c2) << 8) | (unsigned)(c3)) #define FOURC2U(c1, c2, c3, c4) (((unsigned)(c1) << 24) | \ ((unsigned)(c2) << 16) | ((unsigned)(c3) << 8) | (unsigned)(c4)) /** * Convert a hexadecimal string to a string of bytes. * * @param str string to parse * @param bin result * @param len string length */ void rhash_hex_to_byte(const char* str, unsigned char* bin, int len) { /* parse the highest hexadecimal digit */ if ((len & 1) != 0) { *(bin++) = HEX_TO_DIGIT(*(str++)); len--; } /* parse the rest - an even-sized hexadecimal string */ for (; len >= 2; len -= 2, str += 2) { *(bin++) = (HEX_TO_DIGIT(str[0]) << 4) | HEX_TO_DIGIT(str[1]); } } /** * Decode an URL-encoded string in the specified buffer. * * @param buffer the 0-terminated URL-encoded string */ static void urldecode(char* buffer) { char* wpos = buffer; /* set writing position */ for (; *buffer; wpos++) { *wpos = *(buffer++); /* copy non-escaped characters */ if (*wpos == '%') { if (*buffer == '%') { buffer++; /* interpret '%%' as single '%' */ } else if (IS_HEX(*buffer)) { /* decode character from the %<hex-digit><hex-digit> form */ int ch = HEX_TO_DIGIT(*buffer); buffer++; if (IS_HEX(*buffer)) { ch = (ch << 4) | HEX_TO_DIGIT(*buffer); buffer++; } *wpos = (char)ch; } } } *wpos = '\0'; /* terminate decoded string */ } #ifndef _WIN32 /** * Convert a windows file path to a UNIX one, replacing '\\' by '/'. * * @param path the path to convert * @return converted path */ static void process_backslashes(char* path) { for (; *path; path++) { if (*path == '\\') *path = '/'; } } #else /* _WIN32 */ #define process_backslashes(path) #endif /* _WIN32 */ /* convert a hash function bit-flag to the index of the bit */ #if __GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) /* GCC >= 3.4 */ # define get_ctz(x) __builtin_ctz(x) #else /** * Returns index of the trailing bit of a 32-bit number. * This is a plain C equivalent for GCC __builtin_ctz() bit scan. * * @param x the number to process * @return zero-based index of the trailing bit */ static unsigned get_ctz(unsigned x) { /* see http://graphics.stanford.edu/~seander/bithacks.html */ static unsigned char bit_pos[32] = { 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9 }; return bit_pos[((uint32_t)((x & -(int)x) * 0x077CB531U)) >> 27]; } #endif /* (GCC >= 4.3) */ /** * Encode a hash function digest size into a small number in [0,...,7]. * The digest size must be in the set { 4, 16, 20, 24, 28, 32, 48, 64 }. * * @param digest_size digest size (aka hash length) in bytes * @return code for digest size on success, 32 on error */ static int code_digest_size(int digest_size) { static int size_codes[17] = { -1, 0,-1, -1, 1, 2, 3, 4, 5, -1, -1, -1, 6, -1, -1, -1, 7 }; return (digest_size <= 64 ? size_codes[digest_size / 4] : -1); } /** * Calculate a bit-mask of hash-ids by a length of message digest in bytes. * * @param digest_size length of a binary message digest in bytes. * @return mask of hash-ids with given hash length, 0 on fail. */ static unsigned hash_check_mask_by_digest_size(int digest_size) { static unsigned mask[10] = { 0,0,0,0,0,0,0,0,0,0 }; int code; if (mask[9] == 0) { unsigned hash_id; for (hash_id = 1; hash_id <= RHASH_ALL_HASHES; hash_id <<= 1) { code = code_digest_size(rhash_get_digest_size(hash_id)); assert(0 <= code && code <= 7); if (code >= 0) mask[code] |= hash_id; } mask[9] = 1; } code = code_digest_size(digest_size); return (code >= 0 ? mask[code] : 0); } enum FmtBitFlags { FmtHex = 1, FmtBase32LoweCase = 2, FmtBase32UpperCase = 4, FmtBase64 = 8, FmtBase32 = (FmtBase32LoweCase | FmtBase32UpperCase), FmtAll = (FmtHex | FmtBase32 | FmtBase64) }; /** * Test if a character is a hexadecimal/base32 digit. * * @param c the character to test * @return a combination of Fmt* bits */ static int test_hash_char(char c) { static unsigned char char_bits[80] = { 8, 0, 0, 0, 8, 9, 9, 15, 15, 15, 15, 15, 15, 9, 9, 0, 0, 0, 0, 0, 0, 0, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 0, 0, 0, 0, 0, 0, 11, 11, 11, 11, 11, 11, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 }; c -= '+'; return ((unsigned)c <= 80 ? char_bits[(unsigned)c] : 0); } /** * Detect if given string contains a hexadecimal or base32 hash. * * @param ptr the pointer to start scanning from * @param end pointer to scan to * @param p_len pointer to a number to store length of detected message digest * @return type of detected hash as combination of Fmt* flags */ static int detect_hash_type(char** ptr, char* end, int* p_len) { char* p = *ptr; size_t len = 0; size_t eq_num = 0; int char_type = 0; int next_type = FmtAll; if (p < end) { /* search forward (but no more then 129 symbols) */ if ((end - p) >= 129) end = p + 129; for (; p <= end && (next_type &= test_hash_char(*p)); len++, p++) char_type = next_type; if ((char_type & FmtBase64) && *p == '=') { char_type = FmtBase64; for (; *p == '=' && p <= end; eq_num++, p++); } } else { /* search backward (but no more then 129 symbols) */ if ((p - end) >= 129) end = p - 129; for (; p > end && p[-1] == '='; eq_num++, p--) char_type = FmtBase64; for (; p > end && (next_type &= test_hash_char(p[-1])); len++, p--) char_type = next_type; } if ((char_type & FmtBase64) != 0) { size_t hash_len = (len * 6) & ~7; if (eq_num > 3 || ((len + eq_num) & 3) || len != (hash_len + 5) / 6) char_type &= ~FmtBase64; } *ptr = p; *p_len = (int)len; return char_type; } /** * Check if a message digest of the specified bit length is supported by the program. * * @param length the bit length of a binary message digest value * @return 1 if a message digest of the specified bit length is supported, 0 otherwise */ static int is_acceptable_bit_length(int length) { if ((length & 31) == 0 && length <= 512) { int pow = get_ctz(length >> 5); int code = ((length >> (pow + 6)) << 3) | pow; return (code < 32 && ((1 << code) & 0x101061d)); } return 0; } /** * Test the given substring to be a hexadecimal or base32 * message digest of one of the supported hash functions. * * @param ptr the pointer to start scanning from * @param end pointer to scan to * @param p_len pointer to a number to store length of detected message digest * @return possible type of detected hash as algorithm RHASH id */ static unsigned char test_hash_string(char** ptr, char* end, int* p_len) { int len = 0; int char_type = detect_hash_type(ptr, end, &len); unsigned char hash_type = 0; if ((char_type & FmtHex) && is_acceptable_bit_length(len * 4)) hash_type |= FmtHex; if ((char_type & FmtBase32) && is_acceptable_bit_length(BASE32_BIT_SIZE(len))) hash_type |= FmtBase32; if ((char_type & FmtBase64) && is_acceptable_bit_length(BASE64_BIT_SIZE(len))) hash_type |= FmtBase64; if (hash_type != 0) *p_len = len; return hash_type; } /** * Detect a hash-function id by its BSD name. * * @param name an uppercase string, a possible name of a hash-function * @param length length of the name string * @return id of hash function if found, zero otherwise */ static unsigned bsd_hash_name_to_id(const char* name, unsigned length) { #define code2mask_size (19 * 2) static unsigned code2mask[code2mask_size] = { FOURC2U('A', 'I', 'C', 'H'), RHASH_AICH, FOURC2U('B', 'L', 'A', 'K'), (RHASH_BLAKE2S | RHASH_BLAKE2B), FOURC2U('B', 'T', 'I', 'H'), RHASH_BTIH, FOURC2U('C', 'R', 'C', '3'), (RHASH_CRC32 | RHASH_CRC32C), FOURC2U('E', 'D', '2', 'K'), RHASH_ED2K, FOURC2U('E', 'D', 'O', 'N'), (RHASH_EDONR256 | RHASH_EDONR512), FOURC2U('G', 'O', 'S', 'T'), (RHASH_GOST12_256 | RHASH_GOST12_512 | RHASH_GOST94 | RHASH_GOST94_CRYPTOPRO), FOURC2U('H', 'A', 'S', '1'), RHASH_HAS160, FOURC2U('M', 'D', '4', 0), RHASH_MD4, FOURC2U('M', 'D', '5', 0), RHASH_MD5, FOURC2U('R', 'I', 'P', 'E'), RHASH_RIPEMD160, FOURC2U('S', 'H', 'A', '1'), RHASH_SHA1, FOURC2U('S', 'H', 'A', '2'), (RHASH_SHA224 | RHASH_SHA256), FOURC2U('S', 'H', 'A', '3'), (RHASH_SHA384 | RHASH_SHA3_224 | RHASH_SHA3_256 | RHASH_SHA3_384 | RHASH_SHA3_512), FOURC2U('S', 'H', 'A', '5'), RHASH_SHA512, FOURC2U('S', 'N', 'E', 'F'), (RHASH_SNEFRU128 | RHASH_SNEFRU256), FOURC2U('T', 'I', 'G', 'E'), RHASH_TIGER, FOURC2U('T', 'T', 'H', 0), RHASH_TTH, FOURC2U('W', 'H', 'I', 'R'), RHASH_WHIRLPOOL }; unsigned code, i, hash_mask, hash_id; char fourth_char; if (length < 3) return 0; fourth_char = (name[3] != '-' ? name[3] : name[4]); code = FOURC2U(name[0], name[1], name[2], fourth_char); /* quick fix to detect "RMD160" as RIPEMD160 */ if (code == FOURC2U('R', 'M', 'D', '1')) return (length == 6 && name[4] == '6' && name[5] == '0' ? RHASH_RIPEMD160 : 0); for (i = 0; code2mask[i] != code; i += 2) if (i >= (code2mask_size - 2)) return 0; hash_mask = code2mask[i + 1]; i = get_ctz(hash_mask); if (length <= 4) { assert((hash_mask & (hash_mask - 1)) == 0); return (length == strlen(hash_info_table[i].name) ? hash_mask : 0); } /* look for the hash_id in the hash_mask */ for (hash_id = 1 << i; hash_id && hash_id <= hash_mask; i++, hash_id <<= 1) { const char* a; const char* b; if ((hash_id & hash_mask) == 0) continue; assert(length > 4 && strlen(hash_info_table[i].name) > 4); /* check the name tail, start from name[3] to detect names like "SHA-1" or "SHA256" */ for (a = hash_info_table[i].name + 3, b = name + 3; *a; a++, b++) { if (*a == *b) continue; else if (*a == '-') b--; else if (*b == '-') a--; else break; } if (!*a && !*b) return hash_id; } return 0; } /** * Detect ASCII-7 white spaces (not including Unicode whitespaces). * Note that isspace() is locale specific and detects Unicode spaces, * like U+00A0. * * @param ch character to check * @return non-zero if ch is space, zero otherwise */ static int rhash_isspace(char ch) { return (((unsigned char)ch) <= 0x7F && isspace((unsigned char)ch)); } /** * Information about found token */ typedef struct hc_search { char* begin; /* start of the buffer to search */ char* end; /* end of the buffer to search */ hash_check* hc; unsigned expected_hash_id; int hash_type; char* url_name; size_t url_length; } hc_search; /** * Parse the buffer pointed by search->begin, into tokens specified by format * string. The format string can contain the following special characters: * '\1' - BSD hash function name, '\2' - any hash, '\3' - specified hash, * '\4' - an URL-encoded file name, '\5' - a file size, * '\6' - a required-space, '\7' - a space or string end. * A space ' ' means 0 or more space characters. * '$' - parse the rest of the buffer and the format string backward. * Other (non-special) symbols mean themselves. * The function updates search->begin and search->end pointers on success. * * @param search the structure to store parsed tokens info * @param format the format string * @return 1 on success, 0 if couldn't find specified token(s) */ static int hash_check_find_str(hc_search* search, const char* format) { int backward = 0; char buf[20]; const char* fend = strchr(format, '\0'); char* begin = search->begin; char* end = search->end; hash_check* hc = search->hc; hash_value hv; int unsaved_hashval = 0; memset(&hv, 0, sizeof(hash_value)); while (format < fend) { const char* search_str; int len = 0; uint64_t file_size; if (backward) { for (; fend[-1] >= '-' && format < fend; fend--, len++); if (len == 0) fend--; search_str = fend; } else { search_str = format; for (; *format >= '-' && format < fend; format++, len++); if (len == 0) format++; } if (len > 0) { if ((end - begin) < len) return 0; if (0 != memcmp(search_str, (backward ? end - len : begin), len)) return 0; if (backward) end -= len; else begin += len; continue; } assert(len == 0); /* find substring specified by single character */ switch (*search_str) { case '\1': /* parse BSD hash function name */ /* the name should contain alphanumeric or '-' symbols, but */ /* actually the loop shall stop at characters [:& \(\t] */ for (; (begin[len] <= '9' ? begin[len] >= '0' || begin[len] == '-' : begin[len] >= 'A'); len++) { if (len >= 20) return 0; /* limit name length */ buf[len] = toupper(begin[len]); } buf[len] = '\0'; search->expected_hash_id = bsd_hash_name_to_id(buf, len); if (!search->expected_hash_id) return 0; search->hash_type = FmtAll; begin += len; break; case '\2': case '\3': if (backward) { hv.format = test_hash_string(&end, begin, &len); hv.offset = (unsigned short)(end - hc->data); } else { hv.offset = (unsigned short)(begin - hc->data); hv.format = test_hash_string(&begin, end, &len) & search->hash_type; } if (!hv.format) return 0; if (*search_str == '\3') { /* verify message digest type */ int bit_length = rhash_get_digest_size(search->expected_hash_id) * 8; hv.format &= search->hash_type; if ((len * 4) != bit_length) hv.format &= ~FmtHex; if (len != BASE32_LENGTH(bit_length)) hv.format &= ~FmtBase32; if (len != BASE64_LENGTH(bit_length)) hv.format &= ~FmtBase64; if (!hv.format) return 0; hv.hash_id = search->expected_hash_id; } else hv.hash_id = 0; hv.length = (unsigned char)len; unsaved_hashval = 1; break; case '\4': /* get URL-encoded name */ search->url_name = begin; search->url_length = strcspn(begin, "?&|"); if (search->url_length == 0) return 0; /* empty name */ begin += search->url_length; break; case '\5': /* retrieve file size */ assert(!backward); file_size = 0L; for (; '0' <= *begin && *begin <= '9'; begin++, len++) { file_size = file_size * 10 + (*begin - '0'); } if (len == 0) return 0; else { hc->file_size = file_size; hc->flags |= HC_HAS_FILESIZE; } break; case '\6': case '\7': case ' ': if (backward) for (; begin < end && rhash_isspace(end[-1]); end--, len++); else for (; rhash_isspace(*begin) && begin < end; begin++, len++); /* check if space is mandatory */ if (*search_str != ' ' && len == 0) { /* for '\6' verify (len > 0) */ /* for '\7' verify (len > 0 || begin == end) */ if (*search_str == '\6' || begin < end) return 0; } break; case '$': backward = 1; /* switch to parsing string backward */ break; default: if ((backward ? *(--end) : *(begin++)) != *search_str) return 0; } } if (unsaved_hashval && hc->hashes_num < HC_MAX_HASHES) { hc->hashes[hc->hashes_num++] = hv; } search->begin = begin; search->end = end; return 1; } /** * Parse a line of a hash-file. This function accepts five formats. * <ul> * <li/> magnet links * <li/> EDonkey/EMule ed2k links * <li/> BSD format: HASH_FUNCTION ( filepath ) = FILE_HASH * <li/> filepath FILE_HASH1 FILE_HASH2... * <li/> FILE_HASH1 FILE_HASH2... filepath * </ul> * For a magnet/ed2k links file size is also parsed. * * @param line the line to parse * @param hashes structure to store parsed message digests, file path and file size * @param expected_hash_mask hash mask of expected algorithms * @param check_eol boolean flag meaning that '\n' at the end of the line is required * @return 1 on success, 0 if couldn't parse the line */ int hash_check_parse_line(char* line, hash_check* hashes, unsigned expected_hash_mask, int check_eol) { hc_search hs; char* le = strchr(line, '\0'); /* set pointer to the end of line */ char* url_name = NULL; size_t url_length = 0; int single_hash = 0; int reversed = 0; int bad = 0; int i, j; /* return if EOL not found at the end of the line */ if (line[0] == '\0' || (le[-1] != '\n' && check_eol)) return 0; /* note: not using str_tim because 'le' is re-used below */ /* remove trailing white spaces */ while (rhash_isspace(le[-1]) && le > line) *(--le) = 0; /* skip white spaces at the start of the line */ while (rhash_isspace(*line)) line++; memset(&hs, 0, sizeof(hs)); hs.begin = line; hs.end = le; hs.hc = hashes; memset(hashes, 0, sizeof(hash_check)); hashes->data = line; hashes->file_size = (uint64_t)-1; if (strncmp(line, "magnet:?", 8) == 0) { hs.begin += 8; /* loop by magnet link parameters */ while (1) { char* next = strchr(hs.begin, '&'); char* param_end = (next ? next++ : hs.end); char* hf_end; if ((hs.begin += 3) < param_end) { switch (THREEC2U(hs.begin[-3], hs.begin[-2], hs.begin[-1])) { case THREEC2U('d', 'n', '='): /* URL-encoded file path */ url_name = hs.begin; url_length = param_end - hs.begin; break; case THREEC2U('x', 'l', '='): /* file size */ if (!hash_check_find_str(&hs, "\5")) bad = 1; if (hs.begin != param_end) bad = 1; break; case THREEC2U('x', 't', '='): /* a file hash */ /* find last ':' character (hash name can be complex like tree:tiger) */ for (hf_end = param_end - 1; *hf_end != ':' && hf_end > hs.begin; hf_end--); /* test for the "urn:" string */ if ((hs.begin += 4) >= hf_end) return 0; if (FOURC2U(hs.begin[-4], hs.begin[-3], hs.begin[-2], hs.begin[-1]) != FOURC2U('u', 'r', 'n', ':')) return 0; /* find hash by its magnet link specific URN name */ for (i = 0; i < RHASH_HASH_COUNT; i++) { const char* urn = rhash_get_magnet_name(1 << i); size_t len = hf_end - hs.begin; if (strncmp(hs.begin, urn, len) == 0 && urn[len] == '\0') break; } if (i >= RHASH_HASH_COUNT) { if (opt.flags & OPT_VERBOSE) { *hf_end = '\0'; log_warning(_("unknown hash in magnet link: %s\n"), hs.begin); } return 0; } hs.begin = hf_end + 1; hs.expected_hash_id = 1 << i; hs.hash_type = (FmtHex | FmtBase32); if (!hash_check_find_str(&hs, "\3")) bad = 1; if (hs.begin != param_end) bad = 1; break; /* note: this switch () skips all unknown parameters */ } } if (!bad && next) hs.begin = next; else break; } if (!url_name) bad = 1; /* file path parameter is mandatory */ } else if (strncmp(line, "ed2k://|file|", 13) == 0) { hs.begin += 13; hs.expected_hash_id = RHASH_ED2K; hs.hash_type = FmtHex; if (hash_check_find_str(&hs, "\4|\5|\3|")) { url_name = hs.url_name; url_length = hs.url_length; } else bad = 1; /* try to parse optional AICH hash */ hs.expected_hash_id = RHASH_AICH; hs.hash_type = (FmtHex | FmtBase32); /* AICH is usually base32-encoded*/ hash_check_find_str(&hs, "h=\3|"); } else { if (hash_check_find_str(&hs, "\1 ( $ ) = \3")) { /* BSD-formatted line has been processed */ } else if (hash_check_find_str(&hs, "$\6\2")) { while (hash_check_find_str(&hs, "$\6\2")); if (hashes->hashes_num > 1) reversed = 1; } else { hs.hash_type = FmtAll; if (hash_check_find_str(&hs, "\2\7")) { if (hs.begin == hs.end) { /* the line contains no file path, only a single hash */ single_hash = 1; } else { if (hs.hc->hashes_num == 1 && hs.hc->hashes[0].format != FmtBase64) hs.hash_type &= ~FmtBase64; while (hash_check_find_str(&hs, "\2\6")); /* drop an asterisk before filename if present */ if (*hs.begin == '*') hs.begin++; } } else bad = 1; } if (hs.begin >= hs.end && !single_hash) bad = 1; } if (bad) { log_warning(_("can't parse line: %s\n"), line); return 0; } assert(hashes->file_path == 0); /* if !single_hash then we shall extract filepath from the line */ if (url_name) { hashes->file_path = url_name; url_name[url_length] = '\0'; urldecode(url_name); /* decode filename from URL */ process_backslashes(url_name); } else if (!single_hash) { assert(hs.begin < hs.end); hashes->file_path = hs.begin; *hs.end = '\0'; process_backslashes(hs.begin); } if (reversed) { /* change reversed order of message digests to the forward order */ for (i = 0, j = hashes->hashes_num - 1; i < j; i++, j--) { hash_value tmp = hashes->hashes[i]; hashes->hashes[i] = hashes->hashes[j]; hashes->hashes[j] = tmp; } } /* post-process parsed message digests */ for (i = 0; i < hashes->hashes_num; i++) { hash_value* hv = &hashes->hashes[i]; char* hash_str = hashes->data + hv->offset; hash_str[hv->length] = '\0'; /* terminate the message digest */ if (hv->hash_id == 0) { /* calculate bit-mask of hash function ids */ unsigned mask = 0; if (hv->format & FmtHex) { mask |= hash_check_mask_by_digest_size(hv->length >> 1); } if (hv->format & FmtBase32) { assert(((hv->length * 5 / 8) & 3) == 0); mask |= hash_check_mask_by_digest_size(BASE32_BIT_SIZE(hv->length) / 8); } if (hv->format & FmtBase64) { mask |= hash_check_mask_by_digest_size(BASE64_BIT_SIZE(hv->length) / 8); } assert(mask != 0); if ((mask & expected_hash_mask) != 0) mask &= expected_hash_mask; hv->hash_id = mask; } hashes->hash_mask |= hv->hash_id; } return 1; } enum { CompareHashCaseSensitive = 1, CompareHashReversed = 2 }; /** * Compare two message digests. For base64 encoding, the case-sensitive comparasion is done. * For hexadecimal or base32 encodings, the case-insensitive match occurs. * For the GOST94 hash, the additional reversed case-insensitive match is done. * * @param calculated_hash the calculated message digest, for the hex/base32 the value must be in upper case * @param expected a message digest from a hash file to match against * @param length length of the message digests * @param comparision_mode 0, CompareHashCaseSensitive or CompareHashReversed comparision mode */ static int is_hash_string_equal(const char* calculated_hash, const char* expected, size_t length, int comparision_mode) { if (comparision_mode == CompareHashCaseSensitive) return (memcmp(calculated_hash, expected, length) == 0); { /* case-insensitive comparision of a hexadecimal or a base32 hash */ size_t i = 0; for (; i < length && (calculated_hash[i] == (expected[i] >= 'a' ? expected[i] & ~0x20 : expected[i])); i++); if (i == length) return 1; } if (comparision_mode == CompareHashReversed) { /* case-insensitive comparision of reversed gost hash */ size_t i = 0, last = length - 1; for (; i < length && (calculated_hash[last - (i ^ 1)] == (expected[i] >= 'a' ? expected[i] & ~0x20 : expected[i])); i++); return (i == length); } return 0; } /** * Obtain CRC32 from rhash context. The function assumes that * context contains CRC32 and makes no checks for this. * * @param rhash context * @return crc32 checksum */ unsigned get_crc32(struct rhash_context* ctx) { unsigned char c[4]; rhash_print((char*)c, ctx, RHASH_CRC32, RHPR_RAW); return ((unsigned)c[0] << 24) | ((unsigned)c[1] << 16) | ((unsigned)c[2] << 8) | (unsigned)c[3]; } /** * Verify calculated message digests against original values. * Also verify the file size and embedded CRC32 if present. * The HC_WRONG_* bits are set in the hashes->flags field on fail. * * @param hashes 'original' parsed message digests, to verify against * @param ctx the rhash context containing calculated message digests * @return 1 on successfull verification, 0 on message digests mismatch */ int do_hash_sums_match(hash_check* hashes, struct rhash_context* ctx) { unsigned unverified_mask; unsigned hash_id; unsigned printed; char hex[132], base32[104], base64[88]; int j; /* verify file size, if present */ if ((hashes->flags & HC_HAS_FILESIZE) != 0 && hashes->file_size != ctx->msg_size) hashes->flags |= HC_WRONG_FILESIZE; /* verify embedded CRC32 checksum, if present */ if ((hashes->flags & HC_HAS_EMBCRC32) != 0 && get_crc32(ctx) != hashes->embedded_crc32) hashes->flags |= HC_WRONG_EMBCRC32; /* return if nothing else to verify */ if (hashes->hashes_num == 0) return !HC_FAILED(hashes->flags); unverified_mask = (1 << hashes->hashes_num) - 1; for (hash_id = 1; hash_id <= RHASH_ALL_HASHES && unverified_mask; hash_id <<= 1) { if ((hashes->hash_mask & hash_id) == 0) continue; printed = 0; for (j = 0; j < hashes->hashes_num; j++) { hash_value* hv = &hashes->hashes[j]; char* calculated_hash; char* expected_hash; int bit_length; int comparision_mode; /* skip already verified message digests and message digests of different size */ if (!(unverified_mask & (1 << j)) || !(hv->hash_id & hash_id)) continue; comparision_mode = 0; bit_length = rhash_get_digest_size(hash_id) * 8; if ((hv->length * 4) == bit_length) { assert(hv->format & FmtHex); assert(hv->length <= 128); /* print hexadecimal value, if not printed yet */ if ((printed & FmtHex) == 0) { rhash_print(hex, ctx, hash_id, RHPR_HEX | RHPR_UPPERCASE); printed |= FmtHex; } calculated_hash = hex; if ((hash_id & (RHASH_GOST94 | RHASH_GOST94_CRYPTOPRO)) != 0) comparision_mode = CompareHashReversed; } else if (hv->length == BASE32_LENGTH(bit_length)) { assert(hv->format & FmtBase32); assert(hv->length <= 103); /* print base32 value, if not printed yet */ if ((printed & FmtBase32) == 0) { rhash_print(base32, ctx, hash_id, RHPR_BASE32 | RHPR_UPPERCASE); printed |= FmtBase32; } calculated_hash = base32; } else { assert(hv->format & FmtBase64); assert(hv->length == BASE64_LENGTH(bit_length)); assert(hv->length <= 86); /* print base32 value, if not printed yet */ if ((printed & FmtBase64) == 0) { rhash_print(base64, ctx, hash_id, RHPR_BASE64); printed |= FmtBase64; } calculated_hash = base64; comparision_mode = CompareHashCaseSensitive; } expected_hash = hashes->data + hv->offset; if (!is_hash_string_equal(calculated_hash, expected_hash, hv->length, comparision_mode)) continue; unverified_mask &= ~(1 << j); /* mark the j-th message digest as verified */ hashes->found_hash_ids |= hash_id; /* end the loop if all message digests were successfully verified */ if (unverified_mask == 0) break; } } hashes->wrong_hashes = unverified_mask; if (unverified_mask != 0) hashes->flags |= HC_WRONG_HASHES; return !HC_FAILED(hashes->flags); } /** * Verify message digests of the file. * In a case of fail, the error will be logged. * * @param info structure file path to process * @return 0 on success, 1 on message digests mismatch, * -1/-2 on input/output error */ static int verify_sums(struct file_info* info) { timedelta_t timer; int res = 0; /* initialize percents output */ if (init_percents(info) < 0) { log_error_file_t(&rhash_data.out_file); return -2; } rsh_timer_start(&timer); if (FILE_ISBAD(info->file) || calc_sums(info) < 0) { return (finish_percents(info, -1) < 0 ? -2 : -1); } info->time = rsh_timer_stop(&timer); if (rhash_data.stop_flags) { report_interrupted(); return 0; } if ((opt.flags & OPT_EMBED_CRC) && find_embedded_crc32(info->file, &info->hc.embedded_crc32)) { info->hc.flags |= HC_HAS_EMBCRC32; assert(info->hc.hash_mask & RHASH_CRC32); } if (!do_hash_sums_match(&info->hc, info->rctx)) res = 1; if (finish_percents(info, res) < 0) res = -2; if ((opt.flags & OPT_SPEED) && info->sums_flags) { print_file_time_stats(info); } return res; } /** * Verify the file against the CRC32 checksum embedded into its filename. * * @param file the file to verify * @return 0 on success, -1 on input error, -2 on results output error */ static int check_embedded_crc32(file_t* file) { int res = 0; unsigned crc32; struct file_info info; if (find_embedded_crc32(file, &crc32)) { /* initialize file_info structure */ memset(&info, 0, sizeof(info)); info.file = file; info.sums_flags = info.hc.hash_mask = RHASH_CRC32; info.hc.flags = HC_HAS_EMBCRC32; info.hc.embedded_crc32 = crc32; res = verify_sums(&info); if (res >= -1 && fflush(rhash_data.out) < 0) { log_error_file_t(&rhash_data.out_file); res = -2; } else if (!rhash_data.stop_flags) { if (res >= 0) rhash_data.ok++; else if (res == -1 && errno == ENOENT) rhash_data.miss++; rhash_data.processed++; } } else { /* TRANSLATORS: sample filename with embedded CRC32: file_[A1B2C3D4].mkv */ log_warning_msg_file_t(_("file name doesn't contain a CRC32: %s\n"), file); return -1; } return res; } /* * Detect hash mask by the file extension. * * @param file the file which extension will be checked * @return hash_id on success, 0 on fail */ static unsigned hash_mask_by_file_ext(file_t* file) { const char* basename = file_get_print_path(file, FPathUtf8 | FPathBaseName); if (basename) { const char* ext = strrchr(basename, '.'); if (ext && *(++ext) != '\0') { size_t length; char buffer[20]; unsigned hash_id; for (length = 0; '-' <= ext[length] && ext[length] <= 'z'; length++) { if (length >= 20) return 0; /* limit hash name length */ buffer[length] = toupper(ext[length]); } if (ext[length] == '\0') { buffer[length] = '\0'; hash_id = bsd_hash_name_to_id(buffer, length); if (hash_id != 0) return hash_id; } } } return 0; } /** * Verify message digests in a hash file. * Lines beginning with ';' and '#' are ignored. * In a case of fail, the error will be logged. * * @param file the file containing message digests to verify. * @param chdir true if function should emulate chdir to directory of filepath before checking it. * @return 0 on success, -1 on input error, -2 on results output error */ int check_hash_file(file_t* file, int chdir) { FILE* fd; file_t parent_dir; file_t* p_parent_dir = 0; char buf[4096]; timedelta_t timer; struct file_info info; int res = 0; int line_number = 0; unsigned init_flags = 0; unsigned expected_hash_mask = opt.sum_flags; double time; /* process --check-embedded option */ if (opt.mode & MODE_CHECK_EMBEDDED) return check_embedded_crc32(file); /* initialize statistics */ rhash_data.processed = rhash_data.ok = rhash_data.miss = 0; rhash_data.total_size = 0; /* open file / prepare file descriptor */ if (FILE_ISSTDIN(file)) { fd = stdin; } else if ( !(fd = file_fopen(file, FOpenRead | FOpenBin) )) { log_error_file_t(file); return -1; } if (print_verifying_header(file) < 0) { log_error_file_t(&rhash_data.out_file); if (fd != stdin) fclose(fd); return -2; } rsh_timer_start(&timer); memset(&parent_dir, 0, sizeof(parent_dir)); if (chdir) { /* extract the parent directory */ file_modify_path(&parent_dir, file, NULL, FModifyGetParentDir); p_parent_dir = &parent_dir; } if (!expected_hash_mask && !(opt.flags & OPT_NO_DETECT_BY_EXT)) expected_hash_mask = hash_mask_by_file_ext(file); /* read hash file line by line */ for (line_number = 0; fgets(buf, sizeof(buf), fd); line_number++) { char* line = buf; file_t file_to_check; /* skip unicode BOM */ if (STARTS_WITH_UTF8_BOM(buf)) { line += 3; if (line_number == 0) init_flags = FileInitUtf8PrintPath; /* hash file is in UTF8 */ } if (*line == 0) continue; /* skip empty lines */ if (is_binary_string(line)) { log_error(_("file is binary: %s:%d\n"), file_get_print_path(file, FPathPrimaryEncoding | FPathNotNull), line_number + 1); if (fd != stdin) fclose(fd); file_cleanup(&parent_dir); return -1; } /* skip comments and empty lines */ if (IS_COMMENT(*line) || *line == '\r' || *line == '\n') continue; memset(&info, 0, sizeof(info)); if (!hash_check_parse_line(line, &info.hc, expected_hash_mask, !feof(fd))) continue; if (info.hc.hash_mask == 0) continue; /* check if the hash file contains a message digest without a filename */ if (info.hc.file_path != NULL) { int is_absolute = IS_PATH_SEPARATOR(info.hc.file_path[0]); IF_WINDOWS(is_absolute = is_absolute || (info.hc.file_path[0] && info.hc.file_path[1] == ':')); file_init_by_print_path(&file_to_check, (is_absolute ? NULL : p_parent_dir), info.hc.file_path, init_flags); } else { if (file_modify_path(&file_to_check, file, NULL, FModifyRemoveExtension) < 0) { /* note: trailing whitespaces were removed from line by hash_check_parse_line() */ log_error(_("%s: can't parse line \"%s\"\n"), file_get_print_path(file, FPathPrimaryEncoding | FPathNotNull), line); continue; } } info.file = &file_to_check; info.sums_flags = info.hc.hash_mask; file_stat(&file_to_check, 0); /* verify message digests of the file */ res = verify_sums(&info); if (res >= -1 && fflush(rhash_data.out) < 0) { log_error_file_t(&rhash_data.out_file); res = -2; } file_cleanup(&file_to_check); if (rhash_data.stop_flags || res < -1) { break; /* stop on fatal error */ } /* update statistics */ if (res == 0) rhash_data.ok++; else if (res == -1 && errno == ENOENT) rhash_data.miss++; rhash_data.processed++; } file_cleanup(&parent_dir); time = rsh_timer_stop(&timer); if (res >= -1 && (print_verifying_footer() < 0 || print_check_stats() < 0)) { log_error_file_t(&rhash_data.out_file); res = -2; } if (rhash_data.processed != rhash_data.ok) rhash_data.non_fatal_error = 1; if ((opt.flags & OPT_SPEED) && rhash_data.processed > 1) print_time_stats(time, rhash_data.total_size, 1); rhash_data.processed = 0; /* check for input errors */ if (res >= 0 && ferror(fd)) res = -1; if (fd != stdin) fclose(fd); return res; }
C
/* * tipoPasajero.c * * Created on: 6 may. 2022 * Author: Hernan */ #include "tipoPasajero.h" #include <string.h> int cargarDescripcionPasajero(eTipoPassenger tipo[], int tam, int id, char desc[]) { int todoOk = 0; if(tipo != NULL && tam > 0 && desc != NULL) { for(int i= 0; i < tam; i++) { if( tipo[i].id == id) { strcpy( desc, tipo[i].descripcion); todoOk = 1; break; } } } return todoOk; }
C
/* ============================================================================ Name : tp1.c Author : Mario Streri Version : Copyright : Your copyright notice Description : Hacer una calculadora.Para ello el programa iniciar y contar con un men de opciones: 1-ingresar 1er operando(A=x) 2-ingresar 2do operando(B=y) 3-Calcular todas las operaciones a)calcular la suma(A+B) b)calcular la resta(A-B) c)calcular la division(A/B)) d)calcular la multiplicacion(A*B) e)calcular el factorial(A!) 4-informar resultados a)"el resultado de A+B es: r" b)"el resultado de A-B es: r" c)"el resultado de A/B es: r" o "No es posible dividir por cero" d)"el resultado de A*B es: r" e)"el factorial de A es: r1 y el factorial de B es: r2" 5-Salir. ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include "utn.h" int main(void) { setbuf(stdin,NULL); float numeroUno; float numeroDos; float suma; float resta; float multiplicacion; int opcionMenu; int flag = 0; float resultadoDivision; int resultadoFactorialUno; int resultadoFactorialDos; do { printf("1-ingrese 1er operando\n"); printf("2-ingrese 2do operando\n"); printf("3-realizar operaciones\n"); printf("4-resultado de la operacion\n"); printf("5-salir\n\n"); printf("Elija opcion de menu (1-5)"); fflush(stdin); scanf("%d",&opcionMenu); while(opcionMenu<1 || opcionMenu>5) { printf("ERROR reingrese opcion (1-5)"); fflush(stdin); scanf("%d",&opcionMenu); } switch(opcionMenu) { case 1: utn_getFloat(&numeroUno, "ingrese 1er operando\n\n", "ERROR",0,100000,2); break; case 2: utn_getFloat(&numeroDos, "ingrese 2do operando\n\n", "ERROR",0,100000,2); break; case 3: suma = sumar(numeroUno, numeroDos); resta = restar(numeroUno, numeroDos); multiplicacion = multiplicar(numeroUno, numeroDos); dividir(numeroUno, numeroDos, &resultadoDivision); factorial(numeroUno, &resultadoFactorialUno); factorial(numeroDos, &resultadoFactorialDos); break; case 4: printf("el resultado de la suma es:%.2f \n ", suma); printf("el resultado de la resta es: %.2f \n",resta); printf("el resultado de la multiplicacion es: %.2f \n",multiplicacion); if(dividir(numeroUno, numeroDos, &resultadoDivision)==0) { printf("el resultado de la division es:%.2f \n", resultadoDivision); } else { printf("No es posible dividir por cero\n"); } if(factorial(numeroUno, &resultadoFactorialUno)==0) { printf("el factorial de 1er operando es:%d \n",resultadoFactorialUno); } else { printf("No se puede factorear\n"); } if(factorial(numeroUno, &resultadoFactorialUno)==0) { printf("el factorial de 2do operando es:%d\n",resultadoFactorialUno); } else { printf("No se puede factorear\n"); } break; case 5: flag = 1; break; } }while(flag == 0); return 0; }
C
#ifndef PLOTLANG_LIST_H /* * 单链表 */ typedef struct ListNode { int x; // x坐标 int y; // y坐标 int r; // red值 int g; // green值 int b; // blue值 struct ListNode *next; // 下一个节点 } ListNode, *List; /* * 创建单链表 */ List createList(); /* * 在头结点后插入一个节点 */ void insertList(List lst, int x, int y, int r, int g, int b); /* * 销毁链表 */ void destroyList(List *lst); #define PLOTLANG_LIST_H #endif //PLOTLANG_LIST_H
C
#include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #define SIZE 2 int main() { MPI_Init(NULL, NULL); srand(time(NULL)); int id, p, size; int arr[SIZE]; int arr_t[SIZE]; MPI_Comm comm; MPI_Comm icomm; MPI_Comm_rank(MPI_COMM_WORLD, &id); MPI_Comm_size(MPI_COMM_WORLD, &p); int color = id % 4; MPI_Comm_split(MPI_COMM_WORLD, color, id, &comm); int k = color % 2 == 0 ? color + 1 : color - 1; int tag = color < 2 ? 10 : 23; MPI_Intercomm_create(comm, 0, MPI_COMM_WORLD, k, tag, &icomm); int new_id, new_p; MPI_Comm_rank(comm, &new_id); MPI_Comm_size(comm, &new_p); for (int i = 0; i < SIZE; i++) arr[i] = color; MPI_Reduce(arr, arr_t, SIZE, MPI_INT, MPI_SUM, 0, comm); if(new_id == 0) { for (int i = 0; i < SIZE; i++) printf("Group %d elem %d\n", color, arr_t[i]); MPI_Send(arr_t, SIZE, MPI_INT, 0, 0, icomm); MPI_Recv(arr, SIZE, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, icomm, MPI_STATUS_IGNORE); for (int i = 0; i < SIZE; i++) printf("Group %d elem %d\n", color, arr[i]); } MPI_Finalize(); }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_2__ TYPE_1__ ; /* Type definitions */ struct TYPE_2__ {int rambase; int interrupt; int /*<<< orphan*/ * ioport; } ; /* Variables and functions */ size_t EXP_BASE ; size_t IRQ_SELECT ; int /*<<< orphan*/ outb (int,int /*<<< orphan*/ ) ; TYPE_1__** sc_adapter ; __attribute__((used)) static void setup_ports(int card) { outb((sc_adapter[card]->rambase >> 12), sc_adapter[card]->ioport[EXP_BASE]); /* And the IRQ */ outb((sc_adapter[card]->interrupt | 0x80), sc_adapter[card]->ioport[IRQ_SELECT]); }
C
#include "mosaic.h" main(int argc, char *argv[]) { int i; long seed = -setseed(); char fname[MAXNAME]; struct data *my_data; struct pars *my_pars; FILE *ifp; if (argc<2) { printf("\n\nInput file name:"); scanf("%s", &fname); ifp = fopen(fname, "r"); } else ifp = fopen(argv[1], "r"); if (!ifp) nrerror("Cannot open input file"); my_data = read_fasta(ifp, 1, 0); /*The 1 indicates it is amino acid data*/ printf("\n\nRead %i sequences\n\n", my_data->nseq); if (DEBUG) print_sequences(my_data, stdout); my_pars = (struct pars *) malloc((size_t) sizeof(struct pars)); get_pars(my_pars, my_data); for (i=1;i<=1/*my_data->nseq*/;i++) { align(my_data, my_pars, i); } exit(0); } void align(struct data *my_data, struct pars *my_pars, int target) { struct palign **align_set; struct kalign *kwise; align_set = (struct palign **) malloc((size_t) my_data->nseq*sizeof(struct palign)); /*Do pairwise alignments*/ /* for (i=1;i<=my_data->nseq;i++) if (i!= target) { align_set[i] = pair_align_viterbi(my_data, my_pars, target, i); } */ /*Do kwise alignment*/ kwise = kalign(my_data, my_pars, target); } /*Pairwise alignment with Viterbi - makes target (s1) as mosaic of s1*/ struct palign * pair_align_viterbi(struct data *my_data, struct pars *my_pars, int s1, int s2) { int i, j, k, l1, l2, **trace, *sq1, *sq2, mxi, len, lx, max_pc_i; double **m, val[5], max_pc; struct palign *my_align; my_align = (struct palign *) malloc((size_t) sizeof(struct palign)); l1 = my_data->seqs[s1]->length; l2 = my_data->seqs[s2]->length; sq1 = my_data->seqs[s1]->seq; sq2 = my_data->seqs[s2]->seq; my_align->col_max = dvector(1, l1); my_align->col_pos = ivector(1, l1); /*Initialise matrices: Note putative mosaic makes columns for clarity*/ m = dmatrix(0, l2, 0, l1); trace = imatrix(0, l2, 0, l1); /*Note that j always refers to columns, i to rows*/ m[0][0]=0.0; trace[0][0]=1; for (j=1;j<=l1;j++) {m[0][j]= (double) j*my_pars->del; trace[0][j]=3;} for (i=1;i<=l2;i++) {m[i][0]= 0; trace[i][0]=2;} /*Identifiers for best previous column*/ max_pc = 0.0; max_pc_i = 0; /*In trace - 1=match, 2=move up a row(del), 3=move left a column(insert), -x=recombine to position x in previous column (NB can be zero)*/ for (j=1;j<=l1;j++) {/*Do alignment by columns = j = putative mosaic*/ for (i=1;i<=l2;i++) { val[1]=m[i-1][j-1]+my_pars->s[sq1[j]][sq2[i]]; /*Match*/ val[2]=m[i-1][j]+my_pars->del; /*Delete*/ val[3]=m[i][j-1]+my_pars->del; /*Insert*/ val[4]=max_pc+my_pars->rho+my_pars->s[sq1[j]][sq2[i]]; /*Recombination*/ /*Select best move*/ for (k=2,val[0]=val[1],mxi=1;k<=4;k++) if (val[k]>val[0]) {val[0]=val[k]; mxi=k;} m[i][j]=val[mxi]; if (mxi<4) trace[i][j]=mxi; else trace[i][j]=-max_pc_i; } for (i=1, max_pc_i=0, max_pc=m[0][j]; i<=l2;i++) if (m[i][j]>max_pc) {max_pc=m[i][j]; max_pc_i=i;} } if (DEBUG) { printf("\n\nAlignment matrix\n\n"); printf(" "); for (j=1;j<=l1;j++) printf("%5c",num2nuc(sq1[j], 1)); printf("\n "); for (j=0;j<=l1;j++) printf("%5.0lf",m[0][j]); for (i=1;i<=l2;i++) { printf("\n%5c",num2nuc(sq2[i], 1)); for (j=0;j<=l1;j++) printf("%5.0lf",m[i][j]); } printf("\n\n"); printf("Traceback matrix\n\n"); printf(" "); for (j=1;j<=l1;j++) printf("%5c",num2nuc(sq1[j], 1)); printf("\n "); for (j=0;j<=l1;j++) printf("%5i",trace[0][j]); for (i=1;i<=l2;i++) { printf("\n%5c",num2nuc(sq2[i], 1)); for (j=0;j<=l1;j++) printf("%5i",trace[i][j]); } } /*Find position in last colum to start alignment nd calculate length of alignment*/ for(i=1, mxi=0, val[0]=m[0][l1];i<=l2;i++) if (m[i][l1]>val[0]) {mxi=i; val[0]=m[i][l1];} i=mxi; j=l1; len=0; while (j>0) { if (trace[i][j]==1) {i-=1; j-=1;len++;} /*Match*/ else if (trace[i][j]==2) {i-=1; len++;} /*Delete*/ else if (trace[i][j]==3) {j-=1; len++;} /*Insert*/ else {j-=1;i=-trace[i][j]; len++;} /*Recombination*/ } my_align->global_trace = imatrix(1, len, 1, 3); my_align->global_val = dvector(1, len); i=mxi;j=l1;lx=len; my_align->length=len; my_align->s1=s1; my_align->s2=s2; while (j>0) { my_align->global_val[len]=m[i][j]; my_align->global_trace[len][1]=trace[i][j]; my_align->global_trace[len][2]=i; my_align->global_trace[len][3]=j; if (trace[i][j]==1) {i-=1; j-=1;} else if (trace[i][j]==2) {i-=1;} else if (trace[i][j]==3) {j-=1;} else {i=-trace[i][j]; j-=1;} len--; } if (DEBUG) { printf("\n\nScores and traces of best alignment\n\n Tr i j Value\n\n"); for (i=1;i<=lx;i++) printf("%4i%4i%4i%7.0lf\n",my_align->global_trace[i][1], my_align->global_trace[i][2],my_align->global_trace[i][3], my_align->global_val[i]); print_pair_align(my_align, sq1, sq2); } free_dmatrix(m, 0, l2, 0, l1); free_imatrix(trace, 0, l2, 0, l1); return my_align; } /* Set parameters: Need to update to use doubles for costs, but still OK as is for simple Viterbi */ void get_pars(struct pars *par, struct data *my_data) { int i, j; FILE *ifp; if (my_data->type==1) { par->s = dmatrix(1, 25, 1, 25); for (i=1;i<=25;i++) for (j=1;j<=25;j++) { if (i<21 && j<21) par->s[i][j]=bl62[i-1][j-1]; else par->s[i][j]=0; } } else { par->s = dmatrix(1, 4, 1, 4); for (i=1;i<=4;i++) for (j=1;j<=4;j++) par->s[i][j]=-1; for (i=1;i<=4;i++) par->s[i][j]=4; } ifp = fopen("params.txt", "r"); if(!ifp) { par->del=-3; par->rho=-20; printf("\n\nSetting values to defaults: rho=%.1lf, delta=%.1lf\nBLOSUM matrix for AA, DIV for NTs\n\n", par->rho, par->del); } else { nrerror("Reading user-defined inputs - not yet implemented"); } } struct kalign * kalign(struct data *my_data, struct pars *my_pars, int target) { int i, j, k, l, **tnew, ***t, **max_pc_id, *sq1, *sq2, mxi, len; double **mnew, ***m, max_pc, val[5], max_c; struct kalign *kwise; kwise = (struct kalign *) malloc((size_t) sizeof(struct kalign)); /*Intialise arrays of alignment matrices*/ m = (double ***) malloc((size_t) (my_data->nseq+1)*sizeof(double **)); t = (int ***) malloc((size_t) (my_data->nseq+1)*sizeof(int **)); for (k=1;k<=my_data->nseq;k++) if (k != target) { mnew = dmatrix(0, my_data->seqs[k]->length, 0, my_data->seqs[target]->length); tnew = imatrix(0, my_data->seqs[k]->length, 0, my_data->seqs[target]->length); for (j=0;j<=my_data->seqs[target]->length;j++) {mnew[0][j]=(double) j*my_pars->del; tnew[0][j]=1;} for (i=1;i<=my_data->seqs[k]->length;i++) {mnew[i][0]=0; tnew[i][0]=2;} tnew[0][0]=1; m[k] = mnew; t[k] = tnew; } max_pc = max_c = 0.0; max_pc_id = imatrix(1,2,0,my_data->seqs[target]->length); max_pc_id[1][0]=max_pc_id[2][0]=0; /*Sequence and row of previous column's best value*/ sq1 = my_data->seqs[target]->seq; for (j=1;j<=my_data->seqs[target]->length;j++) { /*Stuff to identify next best row for column*/ max_pc = max_c; max_c = (double) j*my_pars->del; if (target==1) max_pc_id[1][j]=2; else max_pc_id[1][j]=1; max_pc_id[2][j]=0; for (k=1;k<=my_data->nseq;k++) if (k != target) { sq2 = my_data->seqs[k]->seq; for (i=1;i<=my_data->seqs[k]->length;i++) { val[1]=m[k][i-1][j-1]+my_pars->s[sq1[j]][sq2[i]]; /*Match*/ val[2]=m[k][i-1][j]+my_pars->del; /*Delete*/ val[3]=m[k][i][j-1]+my_pars->del; /*Insert*/ val[4]=max_pc+my_pars->rho+my_pars->s[sq1[j]][sq2[i]]; /*Recombine*/ for (l=2, val[0]=val[1], mxi=1; l<=4; l++) if (val[l]>val[0]) {val[0]=val[l]; mxi=l;} m[k][i][j]=val[mxi]; t[k][i][j]=mxi; if (m[k][i][j]>max_c) {max_c=m[k][i][j]; max_pc_id[1][j]=k; max_pc_id[2][j]=i;} } } } /*NB max_pc_id will have identified place to start alignment*/ /*Following first calculates length of alignment and then stores it in kwise*/ j = my_data->seqs[target]->length; i = max_pc_id[2][my_data->seqs[target]->length]; k = max_pc_id[1][my_data->seqs[target]->length]; len=0; while (j>0) { len++; if (t[k][i][j]==1) {i--; j--;} else if (t[k][i][j]==2) {i--;} else if (t[k][i][j]==3) {j--;} else {j--; i=max_pc_id[2][j]; k=max_pc_id[1][j];} } kwise->target = target; kwise->length = len; kwise->trace = imatrix(1, 4, 1, len); kwise->score = dvector(1, len); j = my_data->seqs[target]->length; i = max_pc_id[2][my_data->seqs[target]->length]; k = max_pc_id[1][my_data->seqs[target]->length]; l = len; while (j>0) { kwise->trace[1][l]=t[k][i][j]; kwise->trace[2][l]=k; kwise->trace[3][l]=i; kwise->trace[4][l]=j; l--; if (t[k][i][j]==1) {i--; j--;} else if (t[k][i][j]==2) {i--;} else if (t[k][i][j]==3) {j--;} else {j--; i=max_pc_id[2][j]; k=max_pc_id[1][j];} } if (DEBUG) { } print_kalign(kwise, my_data, stdout); /*Free up memory at end of routine*/ for (i=1;i<=my_data->nseq;i++) if (i != target) { free_dmatrix(m[i], 0, my_data->seqs[i]->length, 0, my_data->seqs[target]->length); free_imatrix(t[i], 0, my_data->seqs[i]->length, 0, my_data->seqs[target]->length); } free(m); free(t); free_imatrix(max_pc_id, 1, 2, 0, my_data->seqs[target]->length); return kwise; }
C
#include<stdio.h> #include<math.h> int main() { int i,j,n,sum=0,rem,l,k,m,count=0; printf("Enter the no of elements:"); scanf("%d",&n); int a[n]; l=n-1; m = n-1; printf("Enter n elements:"); for(i = 0;i<n;i++) { scanf("%d",&a[i]); } for(j =0;j<n;j++) { a[j] = a[j] * pow(10,l); l--; } for(k = 0;k<n;k++) { sum = sum + a[k]; } sum =sum+1; printf("%d\n",sum); int temp =sum; while(sum!='\0') { sum=sum/10; count++; } m=count; while(temp!='\0' && count>0) { rem = temp%10; temp = temp/10; a[count] = rem; count--; } printf("["); for(i =1;i<=m;i++) { if(i!=m) { printf("%d,",a[i]); } else { printf("%d",a[i]); } } printf("]"); }
C
#include <stdio.h> int main(){ void copiarConteudo(FILE *file1, FILE *file2); FILE *file1; file1 = fopen("/home/o1234/arquivo.txt", "r"); //Se o arquivo estiver na mesma pasta do programa, basta colocar o nome dele if (file1 == NULL) { printf("Não foi possível abrir o arquivo!"); return 1; } FILE *file2 = fopen("/home/o1234/arquivo2.txt", "w"); copiarConteudo(file1, file2); printf("Conteúdo copiado com sucesso!\n"); fclose(file1); fclose(file2); return 0; } void copiarConteudo(FILE *file1, FILE *file2){ char leitor[1000]; while (fgets(leitor, 1000, file1) != NULL) fputs(leitor, file2); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<time.h> struct Student { char srn[9]; char name[15]; float gpa; }; int binarySearchRec(struct Student s[], int l, int r, char* key); double execTime(struct timespec start, struct timespec end); int main() { int n; int i = 0; int l; int r; int result; char key[15]; scanf("%d", &n); struct Student* s = malloc(sizeof(struct Student) * (n)); struct timespec start, end; // printf("%d\n", n);//db for(i = 0; i < n; i ++) { scanf("%s", s[i].srn); scanf("%s", s[i].name); scanf("%f", &s[i].gpa); } scanf("%s", key); /*check for(i = 0; i < n; i ++) { printf("%s\t", s[i].srn); printf("%s\t", s[i].name); printf("%.2f\n", s[i].gpa); } printf("%s\n", key); */ l = 0; r = n - 1; clock_gettime(CLOCK_REALTIME, &start); result = binarySearchRec(s, l, r, key); clock_gettime(CLOCK_REALTIME, &end); printf("%d\n", result); printf("Execution Time : %lf microseconds\n", execTime(start, end)); return 0; } int binarySearchRec(struct Student s[], int l, int r, char* key) { if(l > r) return -1; int mid; mid = (l + r) / 2; if(strcmp(key, s[mid].name) < 0) return binarySearchRec(s, l, mid - 1, key); else if(strcmp(key, s[mid].name) > 0) return binarySearchRec(s, mid + 1, r, key); else { while(mid > 0 && strcmp(s[mid - 1].name, s[mid].name) == 0) { mid --; } return mid; } } double execTime(struct timespec start, struct timespec end) { double t = (end.tv_sec - start.tv_sec) * 1000000; t += (end.tv_nsec - start.tv_nsec) * 0.001; return t; }
C
#include "game.h" #include "database.h" #include "socket.h" #include "console.h" #include <string.h> #include <math.h> void error_packet(packet_t *packet, uint16_t code, uint8_t flags, char *msg) { memset(packet, 0, sizeof(packet_t)); packet->type = AD_PACKET_ERROR; packet->error.code = code; packet->error.flags = flags; if ( msg != NULL ) { sprintf(packet->error.msg, "%s", msg); } } void packet_ok(packet_t *packet) { error_packet(packet, AD_ERROR_OK, 0, NULL); } player_info_t *players; int player_create(char *name, char *password) { if ( char_eq(name, "admin") || char_eq(name, "root") || strlen(name) >= 16 ) { return 1; } for ( int i = 0; name[i]; i++ ) { char c = name[i]; if ( !RANGE(c, 'a', 'z') && !RANGE(c, 'A', 'Z') && !RANGE(c, '0', '9') && c != '_' && c != '-' && c != '.' ) { return 1; } } player_database_t *new_player = &player_database[player_database_n]; strcpy(new_player->name, name); memcpy(new_player->password_hash, password, sizeof(char) * 16); // fill up properties double r = 100 + 400 * (double)rand() / RAND_MAX; double fi = 2 * 3.14159265359 * (double) rand() / RAND_MAX; new_player->x = (int)( r * cos(fi) ); new_player->y = (int)( r * sin(fi) ); new_player->hp = 100; new_player->movement_speed = 1; player_database_n++; return database_backup(); } int get_player(char *name) { for ( int i = 0; i < player_database_n; i++ ) { if ( char_eq(player_database[i].name, name) ) { return i; } } return -1; } int player_move(int db_idx, short x, short y) { if ( !RANGE(db_idx, 0, player_database_n) || !RANGE(x, -500, 500) || !RANGE(y, -500, 500) ) { return 1; } player_database[db_idx].x = x; player_database[db_idx].y = y; player_database[db_idx].task.type = AD_TASK_IDLE; char msg[128]; sprintf(msg, "%sYou arrived to area %d;%d.", CL_FRONT_GREEN, x, y); packet_t p; memset(&p, 0, sizeof(packet_t)); error_packet(&p, AD_ERROR_OK, AD_ERROR_FLAG_MSG, msg); player_send(db_idx, &p); return 0; } void player_close(player_info_t *player) { socket_close(player->socket); if ( player == players ) { players = player->next; } else { player->prev->next = player->next; } free(player); } int player_socket_send(player_info_t *player, packet_t *packet) { if ( socket_send(player->socket, (char *)packet, sizeof(packet_t)) < 0 ) { player_close(player); return 1; } return 0; } int player_send_im(int idx, packet_t *packet) { int c = 0; player_info_t *p = players; while ( p ) { if ( p->player_db == idx ) { if ( player_socket_send(p, packet) == 0 ) { c++; } } p = p->next; } return c; } int player_send(int id, packet_t *packet) { int r = player_send_im(id, packet); if ( r == 0 ) { inbox_t *msg = (inbox_t *)malloc(sizeof(inbox_t)); memcpy(&msg->packet, packet, sizeof(packet_t)); msg->next = 0; if ( player_inbox[id] == 0 ) { player_inbox[id] = msg; } else { inbox_t *p = player_inbox[id]; while ( p->next ) { p = p->next; } p->next = msg; } } return r; } int player_check_inbox(int idx) { inbox_t *p = player_inbox[idx]; while ( p ) { if ( player_send_im(idx, &p->packet) <= 0 ) { return 0; } player_inbox[idx] = p->next; free(p); p = player_inbox[idx]; } return 0; } int player_send_msg(int target, char *sender, char *msg) { packet_t packet; error_packet(&packet, AD_ERROR_OK, AD_ERROR_FLAG_MSG, NULL); snprintf(packet.error.msg, 128, "[%s%s%s] %s", CL_FRONT_CYAN, sender, CL_FRONT_DEFAULT, msg); return player_send(target, &packet); } void player_send_fragments(player_info_t *player, char *str, packet_t *packet) { while ( 1 ) { memset(packet, 0, sizeof(packet_t)); packet->type = AD_PACKET_MULTI; strncpy(packet->multi.msg, str, 127); packet->multi.msg[127] = '\0'; if ( strlen(str) > 127 ) { player_socket_send(player, packet); str += 127; } else { packet->multi.last = 1; break; } } } void player_broadcast(packet_t *packet) { player_info_t *p = players; while ( p ) { player_socket_send(p, packet); p = p->next; } } int player_can_meet(int a, int b) { return player_database[a].x == player_database[b].x && player_database[a].y == player_database[b].y && player_database[a].task.type == AD_TASK_IDLE && player_database[b].task.type == AD_TASK_IDLE; } double get_player_travel_distance(int idx) { int x = player_database[idx].x - player_database[idx].task.travel.x; int y = player_database[idx].y - player_database[idx].task.travel.y; return sqrt(x * x + y * y); } void player_list_invertory(player_database_t *player, char *str) { int i = 0; for ( int f = 0; f < 64; f++ ) { if ( player->invertory[f].stack > 0 ) { i += sprintf(str + i, "%5dx %s\n", player->invertory[f].stack, item_database[player->invertory[f].item_id].name); } } if ( i == 0 ) { sprintf(str, "No items found."); } else { str[i - 1] = '\0'; } } int player_give_item(int player, int item, int q, char *name) { int s = 0; for ( int i = 0; i < 64; i++ ) { if ( player_database[player].invertory[i].stack > 0 && player_database[player].invertory[i].item_id == item ) { if ( q > 0 || player_database[player].invertory[i].stack > -q ) { player_database[player].invertory[i].stack += q; } else { player_database[player].invertory[i].stack = 0; } s = 1; break; } } if ( !s ) { for ( int i = 0; i < 64; i++ ) { if ( player_database[player].invertory[i].stack == 0 ) { player_database[player].invertory[i].item_id = item; player_database[player].invertory[i].stack = q; s = 1; break; } } } if ( s ) { if ( name != NULL ) { packet_t packet; error_packet(&packet, AD_ERROR_OK, AD_ERROR_FLAG_MSG, NULL); sprintf(packet.error.msg, "%sYou were given %dx %s by %s.", CL_FRONT_BLUE, q, item_database[item].name, name); player_send(player, &packet); } return 1; } return 0; } int player_count_item(int player, int item_id) { for ( int i = 0; i < 64; i++ ) { if ( player_database[player].invertory[i].stack > 0 && player_database[player].invertory[i].item_id == item_id ) { return player_database[player].invertory[i].stack; } } return 0; } int get_item(char *name) { for ( int i = 0; i < item_database_n; i++ ) { if ( char_eq(item_database[i].name, name) ) { return i; } } return -1; }
C
//PRANAV_JAGADEESH_1BM18CS071 // A complete working C program to demonstrate stack and queue implementation using linked List #include <stdio.h> #include <stdlib.h> // A linked list node struct Node { int data; struct Node *next; }; /* Given a reference (pointer to pointer) to the head of a list and an int, inserts a new node on the front of the list. */ void insertFront(struct Node** head_ref, int new_data) { /* 1. allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* 2. put in the data */ new_node->data = new_data; /* 3. Make next of new node as head */ new_node->next = (*head_ref); /* 4. move the head to point to the new node */ (*head_ref) = new_node; } /* Given a reference (pointer to pointer) to the head of a list and an int, appends a new node at the end */ void insertRear(struct Node** head_ref, int new_data) { /* 1. allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); struct Node *last = *head_ref; /* used in step 5*/ /* 2. put in the data */ new_node->data = new_data; /* 3. This new node is going to be the last node, so make next of it as NULL*/ new_node->next = NULL; /* 4. If the Linked List is empty, then make the new node as head */ if (*head_ref == NULL) { *head_ref = new_node; return; } /* 5. Else traverse till the last node */ while (last->next != NULL) last = last->next; /* 6. Change the next of last node */ last->next = new_node; return; } /* * Deletes the first node of the linked list */ void deleteAtFront(struct Node **head_ref) { struct Node* toDelete = *head_ref; if(toDelete == NULL) { printf("List is already empty."); } else { *head_ref = toDelete->next; //toDelete = head_ref; printf("\nData deleted = %d\n", toDelete->data); /* Clears the memory occupied by first node*/ free(toDelete); printf("SUCCESSFULLY DELETED FIRST NODE FROM LIST\n"); } } // This function prints contents of linked list starting from head void printList(struct Node *node) { while (node != NULL) { printf(" %d ", node->data); node = node->next; } } /* Driver program to test above functions*/ int main() { /* Start with the empty list */ struct Node* head = NULL; int choice,value; while(1) { printf("\n Enter your choice: \n 1: Insert Front \n 2: Insert Rear 3: Delete First Node \n 4: Display \n 5: Exit \n"); scanf("%d",&choice); switch(choice) { case 1: printf("Enter the data for node:"); scanf("%d",&value); insertFront(&head,value); break; case 2: printf("Enter the data for node:"); scanf("%d",&value); insertRear(&head,value); break; case 3: deleteAtFront(&head); break; case 4: printf("\n Created Linked list is: "); printList(head); break; case 5: printf("\n Exiting "); exit(0); break; default: printf("\n Wrong choice"); } } return 0; }
C
/*============================================================================= | Assignment: Program #11: The One with the 3D Orthogonal List | | Author: Daniel Eisenberg | Language: GNU C (gcc compiled, tested on lectura) | To Compile: gcc -c orthogonallist.c (if orthogonallist.h is in same | directory) | | Class: CSc 352 -- Systems Programming and UNIX | Instructor: Dr. L. McCann | Due Date: December 1st, 2011, 5:00pm | +----------------------------------------------------------------------------- | | Description: This file defines and implements a 3D orthogonal list ADT. | The included operations are Create_List, Destroy_List, | Insert, Remove, Status, and three Query operations. | The function Error_Description provides the user with an | explanation for a return (error) code value. | | Return value and error reporting are based on Dr. McCann's | arraystack ADT example. | | Input: The list operations do not directly receive input from stdio | or files. | | Output: The list operations do not directly produce output to files, | stdout, or stderr. | | Algorithm: The orthogonal list is a dynamically allocated collection of | singly linked lists which index the internal nodes by | various categorical data. The internal nodes are common to | every indexing list. | To create or destroy a list, the user must provide the | address of a pointer to a list; to perform other operations, | the user must provide the address of a list along with | relevant parameters for that operation, as described in | the function header comments below. | | Required Features Not Included: None. | | Known Bugs: None. | *===========================================================================*/ #include <stdlib.h> #include <string.h> #include "orthogonallist.h" /* helper function prototypes */ int compar(nodeptr, nodeptr); void deallocate(nodeptr); void fix(OrthogonalList *, indexnodeptr, indexnodeptr, nodeptr); /*--------------------------------------------------- create_list ----- | Function create_list | | Purpose: This function creates and initializes a new orthogonal | list. | | Parameters: | list (IN/OUT) -- A pointer to an OrthogonalList pointer, used | to allocate the new list. | | Returns: OK if the list was successfully created, | MALLOC_FAILED if malloc returned a null pointer | NO_LIST if the pointer supplied is NULL. *-------------------------------------------------------------------*/ int create_list(OrthogonalList **list) { if (list == NULL) return NO_LIST; *list = malloc(sizeof(OrthogonalList)); if (*list == NULL) return MALLOC_FAILED; /* initialize index lists */ (*list)->years.first = (*list)->majors.first = NULL; (*list)->hometowns.first = NULL; /* intialize counts */ (*list)->years_size = (*list)->majors_size = (*list)->hometowns_size = 0; (*list)->node_count = 0; return OK; } /*-------------------------------------------------- destroy_list ----- | Function destroy_list | | Purpose: This function deallocates an orthogonal list and sets the | pointer to the list to NULL. | | Parameters: | list (IN/OUT) -- A pointer to a pointer to an OrthogonalList | which is to be deallocated. | | Returns: OK if the list was successfully deallocated, | NO_LIST if the pointer supplied is NULL or points to a | null pointer. *-------------------------------------------------------------------*/ int destroy_list(OrthogonalList **list) { if (list == NULL || *list == NULL) return NO_LIST; /* handle empty list as special case */ if ((*list)->node_count == 0) { free(*list); *list = NULL; return OK; } nodeptr data_temp, /* traversal pointer for data nodes */ data_free; /* traversal pointer for deallocation */ indexnodeptr index_temp; /* traversal pointer for indices */ /* walk through one dimension (years) deallocating all internal nodes */ index_temp = (*list)->years.first; data_temp = index_temp->first; data_free = data_temp; while (index_temp != NULL) { while (data_temp != NULL) { data_temp = data_temp->next_by_year; /* get next node */ deallocate(data_free); /* free previous node */ data_free = data_temp; /* update data_free */ } index_temp = index_temp->next; /* get next index */ if (index_temp != NULL) { data_temp = index_temp->first; /* get first node */ data_free = data_temp; } } /* deallocate years */ index_temp = (*list)->years.first; while (index_temp != NULL) { index_temp = index_temp->next; /* get next index */ free((*list)->years.first->label); /* free label */ free((*list)->years.first); /* free previous index */ (*list)->years.first = index_temp; /* update first */ } /* deallocate majors */ index_temp = (*list)->majors.first; while (index_temp != NULL) { index_temp = index_temp->next; free((*list)->majors.first->label); free((*list)->majors.first); (*list)->majors.first = index_temp; } /* deallocate hometowns */ index_temp = (*list)->hometowns.first; while (index_temp != NULL) { index_temp = index_temp->next; free((*list)->hometowns.first->label); free((*list)->hometowns.first); (*list)->hometowns.first = index_temp; } /* deallocate list */ free(*list); /* set to NULL */ *list = NULL; return OK; } /*-------------------------------------------------------- insert ----- | Function insert | | Purpose: Inserts a new internal node entry into the list, linking | this node to each dimension and creating new indices as | needed. | | Parameters: | list (IN/OUT) -- A pointer to the list to be modified. | last (IN) -- The last name for this entry. | first (IN) -- The first name for this entry. | init (IN) -- The middle initial for this entry. | major (IN) -- The major for this entry. | admitted (IN) -- The admission year for this entry. | graduates (IN) -- The graduation year for this entry. | hometown (IN) -- The hometown for this entry. | | Returns: OK if the new entry was successfully added, | NO_LIST if list was a null pointer, | MALLOC_FAILED if malloc returned a null pointer, | DUPLICATE if an exact match for this entry was present. *-------------------------------------------------------------------*/ int insert(OrthogonalList *list, char *last, char *first, char init, char *major, char *admitted, int graduates, char *hometown) { if (list == NULL) return NO_LIST; /* make node for new entry */ nodeptr new_node; new_node = calloc(sizeof(nodetype), 1); if (new_node == NULL) return MALLOC_FAILED; /* populate new entry */ /* get lastname */ new_node->lastname = malloc(strlen(last)+1); /* allocate space */ if (new_node->lastname == NULL) { deallocate(new_node); return MALLOC_FAILED; } strcpy(new_node->lastname, last); /* copy string */ /* get firstname */ new_node->firstname = malloc(strlen(first)+1); if (new_node->firstname == NULL) { deallocate(new_node); return MALLOC_FAILED; } strcpy(new_node->firstname, first); /* get middle */ new_node->middle = init; /* get graduation year */ new_node->graduation_year = graduates; indexnodeptr index, /* traversal pointer to find insertion indices */ year_index = NULL, /* used to protect structure in event of */ major_index = NULL; /* malloc failure */ if (list->node_count == 0) { /* empty list */ /* allocate indices */ list->years.first = malloc(sizeof(indexnodetype)); if (list->years.first == NULL) { deallocate(new_node); return MALLOC_FAILED; } list->majors.first = malloc(sizeof(indexnodetype)); if (list->majors.first == NULL) { deallocate(new_node); free(list->years.first); return MALLOC_FAILED; } list->hometowns.first = malloc(sizeof(indexnodetype)); if (list->hometowns.first == NULL) { deallocate(new_node); free(list->years.first); free(list->majors.first); return MALLOC_FAILED; } /* get labels */ list->years.first->label = malloc(strlen(admitted)+1); list->majors.first->label = malloc(strlen(major)+1); list->hometowns.first->label = malloc(strlen(hometown)+1); if (list->years.first->label == NULL || list->majors.first->label == NULL || list->hometowns.first->label == NULL) { deallocate(new_node); if (list->years.first->label != NULL) free(list->years.first->label); if (list->majors.first->label != NULL) free(list->majors.first->label); if (list->hometowns.first->label != NULL) free(list->hometowns.first->label); free(list->years.first); free(list->majors.first); free(list->hometowns.first); return MALLOC_FAILED; } strcpy(list->years.first->label, admitted); strcpy(list->majors.first->label, major); strcpy(list->hometowns.first->label, hometown); /* link and initialize */ new_node->year = list->years.first; new_node->major = list->majors.first; new_node->hometown = list->hometowns.first; /* point indices at node */ new_node->year->first = new_node->major->first = new_node; new_node->hometown->first = new_node; /* no other indices */ new_node->year->next = new_node->major->next = NULL; new_node->hometown->next = NULL; /* no other nodes */ new_node->next_by_year = new_node->next_by_major = NULL; new_node->next_by_hometown = NULL; /* update sizes */ list->years_size = list->majors_size = list->hometowns_size = 1; } else { /* list not empty */ int compare; /* comparison var to find insertion points */ /* check for duplicate */ index = list->years.first; while (index != NULL) { nodeptr temp = index->first; compare = compar(new_node, temp); while (temp != NULL && compare < 0) { temp = temp->next_by_year; if (temp != NULL) compare = compar(new_node, temp); } if (compare == 0) { deallocate(new_node); return DUPLICATE; } index = index->next; } /* find years index */ index = list->years.first; compare = strcmp(index->label, admitted); if (compare > 0) { /* new index will be first index */ /* make new index node */ index = malloc(sizeof(indexnodetype)); if (index == NULL) { deallocate(new_node); return MALLOC_FAILED; } /* label new index node */ index->label = malloc(strlen(admitted)+1); if (index->label == NULL) { free(index); deallocate(new_node); return MALLOC_FAILED; } strcpy(index->label, admitted); /* attach new index node */ index->next = list->years.first; list->years.first = index; /* link new data node */ index->first = new_node; /* no other nodes at this index */ new_node->next_by_year = NULL; /* link data node to index */ new_node->year = index; /* count new index node */ list->years_size += 1; year_index = index; } else if (compare == 0) { /* insert node at this index */ nodeptr temp = index->first; /* traversal pointer */ /* link node to index */ new_node->year = index; /* find insertion point for data node */ compare = compar(new_node, temp); if (compare <= 0) { /* insert as first */ new_node->next_by_year = temp; index->first = new_node; } else { if (temp->next_by_year != NULL) compare = compar(new_node, temp->next_by_year); while (temp->next_by_year != NULL && compare > 0) { temp = temp->next_by_year; if (temp->next_by_year != NULL) compare = compar(new_node, temp->next_by_year); } if (temp->next_by_year == NULL) { /* insert node at end */ temp->next_by_year = new_node; new_node->next_by_year = NULL; } else { /* insert node */ new_node->next_by_year = temp->next_by_year; temp->next_by_year = new_node; } } } else { /* find insertion index */ if (index->next != NULL) compare = strcmp(index->next->label, admitted); while (index->next != NULL && compare < 0) { index = index->next; if (index->next != NULL) compare = strcmp(index->next->label, admitted); } if (index->next == NULL || compare != 0) { /* no matching index */ /* make new index node */ indexnodeptr index_temp = malloc(sizeof(indexnodetype)); if (index_temp == NULL) { deallocate(new_node); return MALLOC_FAILED; } /* label new index node */ index_temp->label = malloc(strlen(admitted)+1); if (index_temp->label == NULL) { free(index_temp); deallocate(new_node); return MALLOC_FAILED; } strcpy(index_temp->label, admitted); /* link index node */ index_temp->next = index->next; index->next = index_temp; index = index->next; /* link data node */ index->first = new_node; /* link data node to index */ new_node->year = index; /* no other nodes at this index */ new_node->next_by_year = NULL; /* count new index node */ list->years_size += 1; year_index = index; } else { /* insert at this index */ index = index->next; /* link data node to this index */ new_node->year = index; nodeptr temp = index->first; /* traversal pointer */ /* find insertion point for data node */ compare = compar(new_node, temp); if (compare <= 0) { /* insert as first */ new_node->next_by_year = temp; index->first = new_node; } else { /* find insertion point */ if (temp->next_by_year != NULL) compare = compar(new_node, temp->next_by_year); while (temp->next_by_year != NULL && compare > 0) { temp = temp->next_by_year; if (temp->next_by_year != NULL) compare = compar(new_node, temp->next_by_year); } if (temp->next_by_year == NULL) { /* insert node at end */ temp->next_by_year = new_node; new_node->next_by_year = NULL; } else { /* insert node */ new_node->next_by_year = temp->next_by_year; temp->next_by_year = new_node; } } } } /* find majors index */ index = list->majors.first; compare = strcmp(index->label, major); if (compare > 0) { /* make new index node */ index = malloc(sizeof(indexnodetype)); if (index == NULL) { if (year_index != NULL) { fix(list, year_index, major_index, new_node); } else { deallocate(new_node); } return MALLOC_FAILED; } /* label new index node */ index->label = malloc(strlen(major)+1); if (index->label == NULL) { free(index); if (year_index != NULL) { fix(list, year_index, major_index, new_node); } else { deallocate(new_node); } return MALLOC_FAILED; } strcpy(index->label, major); /* attach new index node */ index->next = list->majors.first; list->majors.first = index; /* link new data node */ index->first = new_node; /* no other nodes at this index */ new_node->next_by_major = NULL; /* link data node to index */ new_node->major = index; /* count new index node */ list->majors_size += 1; major_index = index; } else if (compare == 0) { /* insert node at this index */ nodeptr temp = index->first; /* traversal pointer */ /* link node to index */ new_node->major = index; /* find insertion point for data node */ compare = compar(new_node, temp); if (compare <= 0) { /* insert as first */ new_node->next_by_major = temp; index->first = new_node; } else { if (temp->next_by_major != NULL) compare = compar(new_node, temp->next_by_major); while (temp->next_by_major != NULL && compare > 0) { temp = temp->next_by_major; if (temp->next_by_major != NULL) compare = compar(new_node, temp->next_by_major); } /* insert node */ new_node->next_by_major = temp->next_by_major; temp->next_by_major = new_node; } } else { if (index->next != NULL) compare = strcmp(index->next->label, major); while (index->next != NULL && compare < 0) { index = index->next; if (index->next != NULL) compare = strcmp(index->next->label, major); } if (index->next == NULL || compare != 0) { /* make new index node */ indexnodeptr index_temp = malloc(sizeof(indexnodetype)); if (index_temp == NULL) { if (year_index != NULL) { fix(list, year_index, major_index, new_node); } else { deallocate(new_node); } return MALLOC_FAILED; } /* label index node */ index_temp->label = malloc(strlen(major)+1); if (index_temp->label == NULL) { free(index_temp); if (year_index != NULL) { fix(list, year_index, major_index, new_node); } else { deallocate(new_node); } return MALLOC_FAILED; } strcpy(index_temp->label, major); /* link index node */ index_temp->next = index->next; index->next = index_temp; index = index->next; /* link data node */ index->first = new_node; /* link data node to index */ new_node->major = index; /* no other nodes at this index */ new_node->next_by_major = NULL; /* count new index node */ list->majors_size += 1; major_index = index; } else { /* insert at this index */ index = index->next; /* link data node to this index */ new_node->major = index; nodeptr temp = index->first; /* traversal pointer */ /* find insertion point for data node */ compare = compar(new_node, temp); if (compare <= 0) { /* insert as first */ new_node->next_by_major = temp; index->first = new_node; } else { if (temp->next_by_major != NULL) compare = compar(new_node, temp->next_by_major); while (temp->next_by_major != NULL && compare > 0) { temp = temp->next_by_major; if (temp->next_by_major != NULL) compare = compar(new_node, temp->next_by_major); } /* insert node */ new_node->next_by_major = temp->next_by_major; temp->next_by_major = new_node; } } } /* find hometown index */ index = list->hometowns.first; compare = strcmp(index->label, hometown); if (compare > 0) { /* make new index node */ index = malloc(sizeof(indexnodetype)); if (index == NULL) { if (year_index != NULL || major_index != NULL) { fix(list, year_index, major_index, new_node); } else { deallocate(new_node); } return MALLOC_FAILED; } /* label index node */ index->label = malloc(strlen(hometown)+1); if (index->label == NULL) { free(index); if (year_index != NULL || major_index != NULL) { fix(list, year_index, major_index, new_node); } else { deallocate(new_node); } return MALLOC_FAILED; } strcpy(index->label, hometown); /* attach new index node */ index->next = list->hometowns.first; list->hometowns.first = index; /* link new data node */ index->first = new_node; /* no other nodes at this index */ new_node->next_by_hometown = NULL; /* link data node to index */ new_node->hometown = index; /* count new index node */ list->hometowns_size += 1; } else if (compare == 0) { /* insert node at this index */ nodeptr temp = index->first; /* traversal pointer */ /* link node to index */ new_node->hometown = index; /* find insertion point for data node */ compare = temp->graduation_year - new_node->graduation_year; if (compare <= 0) { /* insert as first */ new_node->next_by_hometown = temp; index->first = new_node; } else { if (temp->next_by_hometown != NULL) compare = temp->next_by_hometown->graduation_year - new_node->graduation_year; while (temp->next_by_hometown != NULL && compare > 0) { temp = temp->next_by_hometown; if (temp->next_by_hometown != NULL) compare = temp->next_by_hometown->graduation_year - new_node->graduation_year; } if (temp->next_by_hometown == NULL) { /* insert node at end */ temp->next_by_hometown = new_node; new_node->next_by_hometown = NULL; } else { /* insert node */ new_node->next_by_hometown = temp->next_by_hometown; temp->next_by_hometown = new_node; } } } else { if (index->next != NULL) compare = strcmp(index->next->label, hometown); while (index->next != NULL && compare < 0) { index = index->next; if (index->next != NULL) compare = strcmp(index->next->label, hometown); } if (index->next == NULL || compare != 0) { /* make new index node */ indexnodeptr index_temp = malloc(sizeof(indexnodetype)); if (index_temp == NULL) { if (year_index != NULL || major_index != NULL) fix(list, year_index, major_index, new_node); else deallocate(new_node); return MALLOC_FAILED; } /* label index node */ index_temp->label = malloc(strlen(hometown)+1); if (index_temp->label == NULL) { free(index_temp); if (year_index != NULL || major_index != NULL) fix(list, year_index, major_index, new_node); else deallocate(new_node); return MALLOC_FAILED; } strcpy(index_temp->label, hometown); /* link index node */ index_temp->next = index->next; index->next = index_temp; index = index->next; /* link data node */ index->first = new_node; /* link data node to index */ new_node->hometown = index; /* no other nodes at this index */ new_node->next_by_hometown = NULL; /* count new index node */ list->hometowns_size += 1; } else { /* insert at this index */ index = index->next; /* link data node to this index */ new_node->hometown = index; nodeptr temp = index->first; /* traversal pointer */ /* find insertion point for data node */ compare = temp->graduation_year - new_node->graduation_year; if (compare <= 0) { /* insert as first */ new_node->next_by_hometown = temp; index->first = new_node; } else { if (temp->next_by_hometown != NULL) compare = temp->next_by_hometown->graduation_year - new_node->graduation_year; while (temp->next_by_hometown != NULL && compare > 0) { temp = temp->next_by_hometown; if (temp->next_by_hometown != NULL) compare = temp->next_by_hometown->graduation_year, - new_node->graduation_year; } /* insert node */ new_node->next_by_hometown = temp->next_by_hometown; temp->next_by_hometown = new_node; } } } } /* count new data node */ list->node_count += 1; return OK; } /*-------------------------------------------------------- compar ----- | Function compar | | Purpose: Custom comparison function for nodes by names. Returns | values in the same format as strcmp, with lastname taking | precendence to firstname, and firstname taking precedence | to middle. | | Parameters: | node_a (IN) -- The first node to be compared. | node_b (IN) -- The second node to be compared. | | Returns: A value less than, equal to, or greater than, zero | dependent upon the relative natural ordering of names. *-------------------------------------------------------------------*/ int compar(nodeptr node_a, nodeptr node_b) { if (node_a == NULL || node_b == NULL || node_a->firstname == NULL || node_b->firstname == NULL || node_a->lastname == NULL) return 0; int value; /* stores comparison results */ value = strcmp(node_a->lastname, node_b->lastname); if (value) return value; value = strcmp(node_a->firstname, node_b->firstname); if (value) return value; return node_a->middle - node_b->middle; } /*----------------------------------------------------------- fix ----- | Function fix | | Purpose: Restores a corrupted list in the event of a malloc | failure during a partially completed insert operation. | This function deallocates its node arguments and restores | years_size and majors_size fields if necessary. | Note that node_count should not have been incremented | before this function was called. | | Parameters: | list (IN/OUT) -- A pointer to the list to be fixed. | year (IN) -- A pointer to the year index node which needs to be | removed, or a null pointer if no year index node need | be removed. | major (IN) -- A pointer to the major index node which needs to | be removed, or a null pointer if no major index node | need be removed. | data (IN) -- A pointer to the data node which needs to be | removed from the year and/or major lists. | | Returns: None. *-------------------------------------------------------------------*/ void fix(OrthogonalList *list, indexnodeptr year, indexnodeptr major, nodeptr data) { if (list == NULL || data == NULL) return; /* remove data from lists as needed */ if (data->year != NULL && list->years.first == data->year) { if (year != NULL) { /* year was a new node with one entry, remove it */ list->years.first = list->years.first->next; } else { /* year index node has other entries */ if (list->years.first->first == data) { list->years.first->first = data->next_by_year; } else { /* find data node */ nodeptr temp = list->years.first->first; while (temp->next_by_year != NULL && temp->next_by_year != data) temp = temp->next_by_year; if (temp->next_by_year != NULL) /* remove data node */ temp->next_by_year = temp->next_by_year->next_by_year; } } } else if (data->year != NULL) { indexnodeptr traverse = list->years.first; while (traverse->next != NULL && traverse->next != data->year) traverse = traverse->next; if (traverse->next != NULL) { if (year != NULL) { /* year had one entry, remove it */ traverse->next = traverse->next->next; } else { /* year index node has other entries */ if (traverse->next->first == data) { traverse->next->first = data->next_by_year; } else { /* find data node */ nodeptr temp = traverse->next->first; while (temp->next_by_year != NULL && temp->next_by_year != data) temp = temp->next_by_year; if (temp->next_by_year != NULL) /* remove data node */ temp->next_by_year = temp->next_by_year->next_by_year; } } } } /* again for major if necessary */ if (data->major != NULL) { if (list->majors.first == data->major) { if (major != NULL) { list->majors.first = list->majors.first->next; } else { if (list->majors.first->first == data) { list->majors.first->first = data->next_by_major; } else { nodeptr temp = list->majors.first->first; while (temp->next_by_major != NULL && temp->next_by_major != data) temp = temp->next_by_major; if (temp->next_by_major != NULL) temp->next_by_major = data->next_by_major; } } } else { indexnodeptr traverse = list->majors.first; while (traverse->next != NULL && traverse->next != data->major) traverse = traverse->next; if (traverse->next != NULL) { if (major != NULL) { traverse->next = traverse->next->next; } else { if (traverse->next->first == data) { traverse->next->first = data->next_by_major; } else { nodeptr temp = traverse->next->first; while (temp->next_by_major != NULL && temp->next_by_major != data) temp = temp->next_by_major; if (temp->next_by_major != NULL) temp->next_by_major = data->next_by_major; } } } } } /* deallocate nodes */ if (year->label != NULL) free(year->label); if (year != NULL) { free(year); list->years_size -= 1; } if (major->label != NULL) free(major->label); if (major != NULL) { free(major); list->majors_size -= 1; } deallocate(data); } /*---------------------------------------------------- deallocate ----- | Function deallocate | | Purpose: Deallocates a data node including the deallocation of any | internal fields. | | Parameters: | node (IN/OUT) -- The node to be deallocated. | | Returns: None. *-------------------------------------------------------------------*/ void deallocate(nodeptr node) { if (node == NULL) return; if (node->lastname != NULL) free(node->lastname); if (node->firstname != NULL) free(node->firstname); free(node); } /*-------------------------------------------------------- remove ----- | Function remove | | Purpose: Attemps to remove an internal node from the orthogonal | list, along with any index nodes for which the target | node was the only entry. | | Parameters: | list (IN/OUT) -- The list to be modified. | last (IN) -- The last name for the node to be removed. | first (IN) -- The first name for the node to be removed. | init (IN) -- The middle initial for the node to be removed. | | Returns: OK if the target node was successfully found and removed, | NO_LIST if list was a null pointer, | NOT_FOUND if the node was not present. *-------------------------------------------------------------------*/ int remove_node(OrthogonalList *list, char *last, char *first, char init) { if (list == NULL) return NO_LIST; if (list->node_count == 0) return NOT_FOUND; indexnodeptr index = list->years.first; /* index node traversal ptr */ nodeptr node = index->first, /* data node traversal ptr */ target = NULL; /* nodeptr for target node */ int compare; /* stores results of comparisons */ /* traverse years to find target node or determine not present */ /* handle first index as special case */ /* handle first data node as special case */ compare = strcmp(node->lastname, last); if (compare >= 0) { /* found matching lastname or none present at index */ if (compare == 0) { /* same lastname */ if (strcmp(node->firstname, first) == 0 && node->middle == init) { /* target node found */ target = node; if (node->next_by_year == NULL) { /* only node at this index */ /* remove index from list */ list->years.first = list->years.first->next; list->years_size -= 1; free(index->label); free(index); } else { /* not only node */ /* replace first node for this index */ index->first = node->next_by_year; } } else { /* full name doesn't match */ /* check other entries for same last name */ if (node->next_by_year != NULL) compare = strcmp(node->next_by_year->lastname, last); while (node->next_by_year != NULL) { if (compare == 0) { /* same last name */ /* check first name */ compare = strcmp(node->next_by_year->firstname, first); if (compare == 0) { /* first name matches */ compare = node->next_by_year->middle - init; if (compare == 0) { /* same name */ target = node->next_by_year; /* found node */ break; } } } if (compare > 0) /* entry not present at this index */ break; /* update search */ node = node->next_by_year; if (node->next_by_year != NULL) compare = strcmp(node->next_by_year->lastname, last); } if (target != NULL) { /* entry found */ /* remove target from this dimension */ node->next_by_year = node->next_by_year->next_by_year; } } } } else { /* compare result negative, keep looking */ if (node->next_by_year != NULL) compare = strcmp(node->next_by_year->lastname, last); while (node->next_by_year != NULL && compare <= 0) { if (compare == 0) { /* last name matches */ /* check first name */ compare = strcmp(node->next_by_year->firstname, first); if (compare == 0) { /* first name matches */ compare = node->next_by_year->middle - init; if (compare == 0) { /* same name */ target = node->next_by_year; /* target found */ break; } } } if (compare > 0) /* not at this index */ break; /* update search */ node = node->next_by_year; if (node->next_by_year != NULL) compare = strcmp(node->next_by_year->lastname, last); } if (target != NULL) { /* entry found */ /* remove target from this dimension */ node->next_by_year = node->next_by_year->next_by_year; } } /* completed search in first index */ if (target == NULL) { /* traverse indices to find node */ while (index->next != NULL) { node = index->next->first; /* check first node */ compare = strcmp(node->lastname, last); if (compare == 0) { /* last names match */ /* compare first names */ compare = strcmp(node->firstname, first); if (compare == 0) { /* first names match */ compare = node->middle - init; if (compare == 0) { /* same name */ target = node; /* target found */ break; } } } /* check other nodes */ if (node->next_by_year != NULL) { compare = strcmp(node->next_by_year->lastname, last); } while (node->next_by_year != NULL && compare <= 0) { if (compare == 0) { /* last names match */ /* check first names */ compare = strcmp(node->next_by_year->firstname, first); if (compare == 0) { /* first names match */ /* compare middle initials */ compare = node->next_by_year->middle - init; if (compare == 0) { /* same names */ target = node->next_by_year; /* target found */ break; } } } if (compare > 0) /* node not present at this index */ break; /* update search */ node = node->next_by_year; if (node->next_by_year != NULL) { compare = strcmp(node->next_by_year->lastname, last); } } if (target != NULL) break; /* break early in case index needs to be removed */ index = index->next; } if (target != NULL) { /* remove node from this dimension */ node->next_by_year = target->next_by_year; if (target->next_by_year == NULL && target == index->next->first) { /* target sole entry for this index, remove index */ indexnodeptr temp = index->next; /* for deallocation */ index->next = temp->next; /* remove from index list */ /* deallocate index */ free(temp->label); free(temp); list->years_size -= 1; /* update index count */ } } } if (target == NULL) /* target node not present */ return NOT_FOUND; /* remove node from majors dimension */ index = target->major; node = index->first; if (node == target) { /* target is first entry for major */ /* remove node from this dimension */ index->first = node->next_by_major; if (index->first == NULL) { /* sole entry for this index, remove it */ if (list->majors.first == index) { /* remove index from list */ list->majors.first = list->majors.first->next; } else { indexnodeptr temp = list->majors.first; /* traversal pointer */ /* find index */ while (temp->next != NULL && temp->next != index) { temp = temp->next; } /* remove index */ if (temp->next != NULL) { temp->next = temp->next->next; } } /* deallocate index */ free(index->label); free(index); list->majors_size -= 1; /* update index count */ } } else { /* target not first entry for this major */ /* find node */ while (node->next_by_major != NULL && node->next_by_major != target) { node = node->next_by_major; } if (node->next_by_major != NULL) { /* remove node from this dimension */ node->next_by_major = target->next_by_major; } } /* remove node from hometowns dimension */ index = target->hometown; node = index->first; if (node == target) { /* target first entry for hometown */ /* remove node from this dimension */ index->first = node->next_by_hometown; if (index->first == NULL) { /* sole entry for this index, remove it */ if (list->hometowns.first == index) { /* remove index from this list */ list->hometowns.first = list->hometowns.first->next; } else { indexnodeptr temp = list->hometowns.first; /* traversal ptr */ /* find index */ while (temp->next != NULL && temp->next != index) temp = temp->next; /* remove index */ if (temp->next != NULL) temp->next = temp->next->next; } /* deallocate index */ free(index->label); free(index); list->hometowns_size -= 1; /* update index count */ } } else { /* target not first entry for this hometown */ /* find node */ while (node->next_by_hometown != NULL && node->next_by_hometown != target) { node = node->next_by_hometown; } /* remove node from this dimension */ if (node->next_by_hometown != NULL) node->next_by_hometown = target->next_by_hometown; } deallocate(target); list->node_count -= 1; return OK; } /*-------------------------------------------------------- status ----- | Function status | | Purpose: Reports the size for each dimension and the total | internal data node count. | | Parameters: | list (IN) -- The list whose status is requested. | years (OUT) -- A pointer to hold the years dimension size. | majors (OUT) -- A pointer to hold the majors dimension size. | hometowns (OUT) -- A pointer to hold the hometowns dimension | size. | nodes (OUT) -- A pointer to hold the data node count. | | Returns: OK, or NO_LIST or INVALID_ARGS if null pointers are | supplied. *-------------------------------------------------------------------*/ int status(OrthogonalList *list, int *years, int *majors, int *hometowns, int *nodes) { if (list == NULL) return NO_LIST; if (years == NULL || majors == NULL || hometowns == NULL || nodes == NULL) return INVALID_ARGS; *years = list->years_size; *majors = list->majors_size; *hometowns = list->hometowns_size; *nodes = list->node_count; return OK; } /*---------------------------------------------------- query_year ----- | Function query_year | | Purpose: Reports the number of students admitted between the | range of years provided (inclusive). | | Parameters: | list (IN) -- The list to be queried. | begin (IN) -- The first admission year. | end (IN) -- The last admission year. | | Returns: An integer representing the number of students admitted | in the provided range of years, or NO_LIST if list NULL. *-------------------------------------------------------------------*/ int query_year(OrthogonalList *list, int begin, int end) { if (list == NULL) return NO_LIST; unsigned int count = 0; /* stores number of students admitted in range */ int year; /* want index labels as ints */ indexnodeptr index = list->years.first; /* index traversal pointer */ nodeptr node; /* node traversal pointer */ if (index != NULL) { node = index->first; year = atoi(index->label); /* get year as int */ } while (index != NULL && year - begin >= 0 && end - year >= 0) { /* index in year range */ /* count all entries for this index */ while (node != NULL) { count++; node = node->next_by_year; } /* get next index */ index = index->next; if (index == NULL) break; node = index->first; year = atoi(index->label); } return count; } /*--------------------------------------------------- query_major ----- | Function query_major | | Purpose: Retrieves a list of students whose major matches the | major parameter. The list is in "phonebook order" by | student name. | | Parameters: | list (IN) -- The list to be queried. | major (IN) -- The major to report. | | Returns: A pointer to the index node for the indicated major, | or a null pointer if no students belong to that major. *-------------------------------------------------------------------*/ nodeptr query_major(OrthogonalList *list, char *major) { if (list == NULL) return NULL; indexnodeptr result; /* pointer holds return value for function */ int compare; /* stores string comparison results */ result = list->majors.first; if (result != NULL) compare = strcmp(result->label, major); while (result != NULL && compare < 0) { result = result->next; if (result != NULL) compare = strcmp(result->label, major); } if (result != NULL && compare == 0) return result->first; return NULL; } /*------------------------------------------------ query_hometown ----- | Function query_hometown | | Purpose: Retrieves a list of students whose hometown matches the | hometown parameter. The list is in "phonebook" order by | student name. | | Parameters: | list (IN) -- The list to be queried. | hometown (IN) -- The hometown to report. | year (OUT) -- A pointer to store the last year of graduation. | | Returns: A pointer to the index node for the indicated major, | or a null pointer if no students belong to that major. *-------------------------------------------------------------------*/ nodeptr query_hometown(OrthogonalList *list, char *hometown, int *year) { if (list == NULL) return NULL; indexnodeptr result; /* pointer holds return value for function */ int compare; /* stores string comparison results */ result = list->hometowns.first; if (result != NULL) compare = strcmp(result->label, hometown); while (result != NULL && compare < 0) { result = result->next; if (result != NULL) compare = strcmp(result->label, hometown); } if (result != NULL && compare == 0) { *year = result->first->graduation_year; return result->first; } return NULL; } /*-------------------------------- describe_orthogonal_list_error ----- | Function describe_orthogonal_list_error | | Purpose: Returns a human readable explanation of an integer error | code returned by an orthogonal list operation. | | Parameters: | code (IN) -- The error code to describe. | | Returns: A string containing an explanation of the supplied code. *-------------------------------------------------------------------*/ char *describe_orthogonal_list_error(int code) { switch(code) { case OK: return "No error."; case MALLOC_FAILED: return "Insufficient memory."; case NO_LIST: return "No orthogonal list was supplied."; case NOT_FOUND: return "No record found for that student."; case DUPLICATE: return "Record exists for that student, new record not entered."; case INVALID_ARGS: return "Invalid arguments."; default: return "Undefined code."; } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "itertools.h" int fun(const void* a, const void* b) { return *(int*) a + *(int*) b; } int main() { int n; printf("Enter the size of array: "); scanf("%d", &n); printf("Enter the array elements: "); int* b = (int*) malloc(n * sizeof(int)); for (int i = 0; i < n; i++) { scanf("%d", &b[i]); } printf("Array : "); iter* i = newArrayIter(b, n, sizeof(*b)); if (!i) { printf("Invalid input\n"); return 1; } while(has_next(i)) { printf("%d ", *(int*) next(i)); } printf("\n"); free_iter(i); iter* i3 = count(0, 2); if (!i3) { printf("Invalid input\n"); return 1; } printf("Count : "); for (int i = 0; i < n; i++) { printf("%d ", *(int*) next(i3)); } printf("\n"); iter* i4 = cycle(b, n, sizeof(*b)); if (!i4) { printf("Invalid input\n"); return 1; } printf("Cycle : "); for (int i = 0; i < 2*n+1; i++) { printf("%d ", *(int*) next(i4)); } printf("\n"); free_iter(i4); iter* i5 = repeat(10); if (!i5) { printf("Invalid input\n"); return 1; } printf("Repeat : "); for (int i = 0; i < n; i++) { printf("%d ", *(int*) next(i5)); } printf("\n"); free_iter(i5); iter* ai = newArrayIter(b, n, sizeof(*b)); iter* i6 = accumulate(ai, fun, 0); if (!i6) { printf("Invalid input\n"); return 1; } printf("Accumulate : "); for (int i = 0; i < n; i++) { printf("%d ", *(int*) next(i6)); } printf("\n"); free_iter(i6); free_iter(ai); int a[] = {1, 0, 1}; ai = newArrayIter(b, n, sizeof(*b)); iter* ai2 = cycle(a, 3, sizeof(*a)); iter* i7 = compress(ai, ai2); if (!i7) { printf("Invalid input\n"); return 1; } printf("Compress : "); while (has_next(i7)) { printf("%d ", *(int*) next(i7)); } printf("\n"); free_iter(i7); free_iter(ai); free_iter(ai2); ai = newArrayIter(b, n, sizeof(*b)); iter* i8 = islice(ai, 0, n, 2); if (!i8) { printf("Invalid input\n"); return 1; } printf("islice : "); while (has_next(i8)) { printf("%d ", *(int*) next(i8)); } printf("\n"); free_iter(i8); free_iter(ai); list* l = (list*) malloc(sizeof(list)); list_new(l, sizeof(int), NULL); ai = newArrayIter(b, n, sizeof(*b)); while (has_next(ai)) list_append(l, next(ai)); free_iter(ai); iter* i9 = new_list_iter(l); if (!i9) { printf("Invalid input\n"); return 1; } printf("List : "); while (has_next(i9)) { printf("%d ", *(int*) next(i9)); } printf("\n"); free_iter(i9); char d[] = "Hello World!!"; printf("Character Iter - "); iter* i2 = newArrayIter(d, strlen(d), sizeof(*d)); if (!i2) { printf("Invalid input\n"); return 1; } while(has_next(i2)) { printf("%c", *(char*) next(i2)); } printf("\n"); free_iter(i2); return 0; }
C
/** * @file trace.h * * @date 28.06.2009 * @author Stephan Krempel <stephan.krempel@gmx.de> * @version \$Id$ */ #ifndef TRACE_H_ #define TRACE_H_ #include <stdio.h> #include "topo.h" /** * @internal * Bitfield of supported values to measure */ typedef struct { int Utrms : 1; int Itrms : 1; int P : 1; } ValueField; /** * @internal * Structure for trace file description */ typedef struct trace_s { short num; #if 0 int bin : 1; #endif int ascii : 1; int hdstats : 1; int channel; ValueField values; char *output; FILE *fptr; char *actn; /* action script part for this trace */ int size; /* size of expected response in [byte] */ hdTopoNode *tnode; /* topology node, reference needed for destruction */ hdStatsGroup *group; /* statistics group this belongs to */ struct trace_s *prev; } TraceStruct; /** * @internal * List head (or actual foot) for list of traces */ typedef struct traceList_s { /** Last element of the linked list */ TraceStruct *last; } TraceListStruct; /** * Add a trace to a trace linked list */ void addTraceToList(TraceStruct *trace, TraceListStruct *list); /** * Macro to use for iterating over all traces in a configuration. * Use FOR_TRACES(tracelist) { ... } */ #define FOR_TRACES(trace, list) \ for (TraceStruct *trace = (list).last; trace != NULL; trace = trace->prev) /** * Free all traces in a trace linked list */ void freeAllTraces(TraceListStruct *list); #endif /* TRACE_H_ */
C
#include <stdio.h> #include <stdlib.h> int main(void) { int n[10] = {5, 6, 3, 2, 4, 9, 7, 8, 1, 10}; for(int i=0; i<10; ++i) { int min = i; for(int j=i+1; j<10; ++j) { if(n[j] < n[min]) min = j; } if(min != i) { int temp = n[min]; n[min] = n[i]; n[i] = temp; } } for(int i=0; i<10; ++i) { printf("%d ", n[i]); } return 0; }
C
// switch case can use with variable, expression // break in switch case int printf(char s[100]); int printf1(char s[100],int a); int main(){ int arr[3]; arr[0] = 1; arr[1] = 'c'; arr[2] = 3; arr[3] = 9; int i = 0; float b = 3.1; while(i<4){ printf1("test%ld\n",i+1); switch(arr[i]){ case 1:{ printf("case 1: checking break\n"); break; } case 'a'+2:{ printf("case 2: checking expression in case\n"); } case b:{ printf("case 3: checking variable in case and type cast\n"); break; } case 'c':{ printf("case 4: checking without break case\n"); } default:{ printf("default\n"); } } i++; } }
C
#include <stdio.h> #include <stdlib.h> int main(void) { char *staro_p = NULL; char *novo_p; char c; int i = 0; while( (c = getchar()) != '\n' ) { if(i % 10 == 0) { novo_p = realloc( staro_p, (i + 10) * sizeof(char) ); if(novo_p == NULL) { printf("Neuspesno alociranje\n"); break; // break prekida izvrasavanje while() } else staro_p = novo_p; }; staro_p[i++] = c; } novo_p = realloc( staro_p, (i + 1) * sizeof(char) ); if(novo_p == NULL) { printf("Neuspesno alociranje\n"); i--; } else staro_p = novo_p; // Postavljamo zavrsni znak staro_p[i] = '\0'; printf("%s\n", staro_p); free(staro_p); return 0; }
C
/* * File: main.c * Author: Fulons * * Created on 19 May 2017, 09:36 */ #include <stdio.h> //for: printf, fgets, stdin #include <stdlib.h> //for: EXIT_SUCCESS, malloc, strtod #include <string.h> //for: strlen #include "Operations.h" #include "Calculation.h" #include "Variable.h" #include "StringHelpers.h" #include "GeneralHelperFunctions.h" #define INPUT_BUFFER_SIZE 1024 #define DEFAULT_SAVED_VARIABLE_FILENAME "SavedCalculations.txt" int main(int argc, char** argv) { MEMORY_DEBUG_INIT Variable* varRoot = NewVariable(); //Holds the root to the trie of variables char* buffer = MyMalloc(INPUT_BUFFER_SIZE, char); //Buffer to store user input double lastResult = 0; //Holds result of last calculation WelcomeMessage(); //Display welcome message if(AskUserYesOrNo("Do you want to load variables from last session?")){ ParseFile(DEFAULT_SAVED_VARIABLE_FILENAME, varRoot); //Load last saved variables } while(true){ fgets(buffer, INPUT_BUFFER_SIZE, stdin); //Get input from user if(PreProcess(buffer, varRoot)) continue; else if(buffer[0] == 'q') break; //Quits the main loop if user entered q //Might want to prompt user if they are sure ProcessBuffer(buffer, &lastResult, varRoot, true, false, true); } if(AskUserYesOrNo("Do you want to save your variables?")){ //Save variables to file if user wish to FILE* file = fopen(DEFAULT_SAVED_VARIABLE_FILENAME, "w"); if(!file) { errorPrint("Could not open save file: %s", DEFAULT_SAVED_VARIABLE_FILENAME); } char NameBuffer[VARIABLE_MAX_NAME_LENGTH]; NameBuffer[0] = '\0'; PrintVariable(varRoot, NameBuffer, true, true, file, true); fclose(file); } MyFree(buffer, char); DeleteVariable(varRoot); MEMORY_DEBUG_PRINT_ALLOCATIONS return (EXIT_SUCCESS); } //1. Document Analysis //2. Design Analysis //3. Unit Testing //4. Regression Testing //5. Beta Testing //6. Penetration Testing //7. Load Testing //8. UX Testing
C
//TELEPHONE DIRECTORY MAINTAINANCE #include "phnoenerator.h" //fucnt decl extern void phonnomaintainance(); void add_number(); extern void phonnomaintainance() { while(1) { system("cls"); //inputting choiec int choice; printf("\t\t**********TELEPHONE DIRECOTRY MAINTENANCE SOFTWARE**********\n"); printf("\t******************PHONENO MAINTAINANCE MENU*******************\n"); printf("\t\t 1. Add Contact\n"); printf("\t\t 2. Back\n"); printf("\t\tEnter Your Choice:-"); scanf("%d",&choice); switch(choice) { case 1:add_number(); break; case 2:return; }//end switch }//end while }//fucntion end void add_number() { //open the files FILE *fp,*fp1; fp=fopen("emp.txt","r+"); fp1=fopen("temp.txt","w"); there: system("cls"); printf("\t\t**********TELEPHONE DIRECOTRY MAINTENANCE SOFTWARE**********\n"); printf("\t\t***************************ADD NUMBER*************************\n"); printf("\n\t\tENTER EMPLOYEE CODE :-"); char code[20]; scanf("%s",code); char name[25],empCode[20],depCode[20],loc[20],ph[10],test[10]; int wordExist=0; //checking for valid employee code while(fscanf(fp,"%s %s %s %s %s",name,empCode,depCode,loc,ph)!=EOF) { if(strcmp(code,empCode)==0) { wordExist=1; }//end if }//end while if(wordExist==1) { rewind(fp); goto here; } else { printf("\t\tCode does not exist\n"); printf("\t\tpress any key to continue\n"); getch(); rewind(fp); goto there; }//end ifelse here: while(fscanf(fp,"%s %s %s %s %s",name,empCode,depCode,loc,ph)!=EOF) { if(strcmp(code,empCode)==0) { if(strcmp(ph,"0")==0) { char temp[8],temp1[10]; printf("\n\t\tLOCATION :- %s\n",loc); printf("\n\t\tDEPARTMENT CODE :- %s\n",depCode); strcpy(temp1,depCode); strcpy(temp,phonenogenerator(depCode)); printf("\n\t\tTELEPHONE NO ALLOCATED IS :- %s\n",temp); fprintf(fp1,"%s %s %s %s %s\n",name,empCode,temp1,loc,temp); continue; } else { fprintf(fp1,"%s %s %s %s %s\n",name,empCode,depCode,loc,ph); printf("\t\tPHONE NO IS ALREADY ALLOCATED\n"); printf("\t\tenter any key to CONTINUE\n"); getch(); phonnomaintainance(); }//end if else } else { fprintf(fp1,"%s %s %s %s %s\n",name,empCode,depCode,loc,ph); }//end ifelse }//end while fclose(fp1); fclose(fp); //close files //reopen files fp=fopen("emp.txt","w"); fp1=fopen("temp.txt","r"); while(fscanf(fp1,"%s %s %s %s %s",name,empCode,depCode,loc,ph)!=EOF) { fprintf(fp,"%s %s %s %s %s\n",name,empCode,depCode,loc,ph); }//end while fclose(fp); fclose(fp1); //closing the fi;e remove("temp.txt"); //deleting temp file printf("\t\tpress any key to continue\n"); getch(); } //function end
C
/* Part of: CRE2 Contents: test for easy matching Date: Mon Jan 2, 2012 Abstract Test file for regular expressions matching. Copyright (C) 2012, 2016 Marco Maggi <marco.maggi-ipsu@poste.it> See the COPYING file. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <cre2.h> #include "cre2-test.h" int main (int argc, const char *const argv[]) { const char * pattern; const char * text; /* ------------------------------------------------------------------ */ /* single match */ pattern = "ciao"; text = "ciao"; { cre2_string_t match; int nmatch = 1; cre2_easy_match(pattern, strlen(pattern), text, strlen(text), &match, nmatch); PRINTF("match: "); FWRITE(match.data, match.length, 1); PRINTF("\n"); if (0 != strncmp("ciao", match.data, match.length)) goto error; } /* ------------------------------------------------------------------ */ /* wrong pattern */ pattern = "ci(ao"; text = "ciao"; { cre2_string_t match; int nmatch = 1; int retval; retval = cre2_easy_match(pattern, strlen(pattern), text, strlen(text), &match, nmatch); if (2 != retval) goto error; } /* ------------------------------------------------------------------ */ /* two groups */ pattern = "(ciao) (hello)"; text = "ciao hello"; { int nmatch = 3; cre2_string_t match[nmatch]; cre2_easy_match(pattern, strlen(pattern), text, strlen(text), match, nmatch); PRINTF("full match: "); FWRITE(match[0].data, match[0].length, 1); PRINTF("\n"); PRINTF("first group: "); FWRITE(match[1].data, match[1].length, 1); PRINTF("\n"); PRINTF("second group: "); FWRITE(match[2].data, match[2].length, 1); PRINTF("\n"); if (0 != strncmp("ciao hello", match[0].data, match[0].length)) goto error; if (0 != strncmp("ciao", match[1].data, match[1].length)) goto error; if (0 != strncmp("hello", match[2].data, match[2].length)) goto error; } /* ------------------------------------------------------------------ */ exit(EXIT_SUCCESS); error: exit(EXIT_FAILURE); } /* end of file */
C
void main() { int x = abs(4); assert(x == 4, "x must be 4"); x = abs(-4); assert(x == 4, "x must be 4"); }
C
/* name id两个变量是定义的二维数组。name[i] id[i]都是一个一维数组, 一维数组名可以直接当首地址的指针用,但score本身就是一维数组,score[i]就是一个元素 ,如果你要给这个元素赋值就要取其地址。 */ /* 也可以写成score+i,表示给第i个元素赋值,score是数组名做指针+i表示指针往后跳i位,一样可以不用&符号 */ #include<stdio.h> int main(){ int n; int max=-1,min=101,maxIndex = 0,minIndex = 0 ; char name[101][100]; char id[101][100]; int score[101]; scanf("%d",&n); for(int i =0;i<n;i++){ scanf("%s %s %d",name[i],id[i],&score[i]); if(max<score[i]){ max = score[i]; maxIndex = i; } if(min>score[i]){ min = score[i]; minIndex = i; } } printf("%s %s\n",name[maxIndex],id[maxIndex]); printf("%s %s\n",name[minIndex],id[minIndex]); return 0; }
C
#include "skynet.h" #include "skynet_env.h" #include "spinlock.h" #include <lua.h> #include <lauxlib.h> #include <stdlib.h> #include <assert.h> //skynet 环境保存lua虚拟机 struct skynet_env { struct spinlock lock; //互斥锁 lua_State *L; //lua虚拟机 }; // skynet 环境配置 主要是获取和设置lua的环境变量 static struct skynet_env *E = NULL; //获取skynet环境变量 const char * skynet_getenv(const char *key) { SPIN_LOCK(E) lua_State *L = E->L; lua_getglobal(L, key); //获取_G[key]放在栈顶 const char * result = lua_tostring(L, -1); // 去除栈顶数据 _G[key] lua_pop(L, 1); //弹出栈顶一个值 SPIN_UNLOCK(E) return result; } //设置skynet环境变量 void skynet_setenv(const char *key, const char *value) { SPIN_LOCK(E) lua_State *L = E->L; lua_getglobal(L, key); assert(lua_isnil(L, -1)); lua_pop(L,1); lua_pushstring(L,value); //value 字符串入栈 lua_setglobal(L,key); //栈顶元素出栈 设置为G[key] = value的值。 //Pops a value from the stack and sets it as the new value of global name. SPIN_UNLOCK(E) } //环境初始化 创建一个lua虚拟机 void skynet_env_init() { E = skynet_malloc(sizeof(*E)); SPIN_INIT(E) E->L = luaL_newstate(); //创建lua虚拟机 }
C
#include <stdio.h> #include <string.h> #include <assert.h> #include <time.h> void printArray(int arr[], int x) { for (int i = 0;i < x;i++) printf("%d",arr[i]); printf("\n"); } void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } void swapch(char* x, char* y){ char temp = *x; *x = *y; *y = temp; } //İnsertion Sort void insertionSort(int arr[], int size) { int i, j, element; for (i = 1; i < size; i++) { element = arr[i]; j = i - 1; while (j >= 0 && arr[j] > element) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = element; } } void insertionSortChar(char arr[], int size) { int i, j; char element; for (i = 1; i < size; i++) { element = arr[i]; j = i - 1; while (j >= 0 && arr[j] > element) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = element; } } //Bubble Sort void bubbleSort(int arr[], int size) { int i, j; for (i = 0; i < size - 1; i++) for (j = 0; j < size - i - 1; j++) if (arr[j] > arr[j + 1]) swap(&arr[j], &arr[j + 1]); } void bubbleSortChar(char arr[], int size) { int i, j; for (i = 0; i < size - 1; i++) for (j = 0; j < size - i - 1; j++) if (arr[j] > arr[j + 1]) swapch(&arr[j], &arr[j + 1]); } //Selection Sort void selectionSort(int arr[], int size) { int i, j, min; for (i = 0; i < size - 1; i++) { min = i; for (j = i + 1; j < size; j++) if (arr[j] < arr[min]) min = j; swap(&arr[min], &arr[i]); } } void selectionSortChar(char arr[], int size) { int i, j; char min; for (i = 0; i < size - 1; i++) { min = i; for (j = i + 1; j < size; j++) if (arr[j] < arr[min]) min = j; swapch(&arr[min], &arr[i]); } } //Merge Sort void merge(int arr[], int l, int m, int r) { int lside = m - l+1; int rside = r - m; int Left[lside]; int Right[rside]; int i, j, k; for (i = 0; i < lside; i++) Left[i] = arr[l + i]; for (j = 0; j < rside; j++) Right[j] = arr[m + 1 + j]; i = 0; j = 0; k = l; while (i < lside && j < rside) { if (Left[i] <= Right[j]) { arr[k] = Left[i]; i++; } else { arr[k] = Right[j]; j++; } k++; } while (i < lside) { arr[k] = Left[i]; i++; k++; } while (j < rside) { arr[k] = Right[j]; j++; k++; } } void mergeSort(int arr[], int l, int r) { if (l < r) { int m = l + (r - l) / 2; mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); } } void mergeChar(char arr[], int l, int m, int r) { int i, j, k, n1, n2; n1 = m - l + 1; n2 = r - m; int L[n1], R[n2]; for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; i = 0; j = 0; k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } void mergeSortChar(char arr[], int l, int r) { if (l < r) { int m = l + (r - l) / 2; mergeSortChar(arr, l, m); mergeSortChar(arr, m + 1, r); mergeChar(arr, l, m, r); } } //Quick Sort void quickSort(int* arr, int L, int R) { int lo; int hi; int pivot; pivot = L; if (R > L) { pivot = L; lo = L; hi = R; while (lo < hi) { while (arr[lo] <= arr[pivot] && lo<R && hi>lo) { lo++; } while (arr[hi] >= arr[pivot] && hi >= L && hi >= lo) { hi--; } if (hi > lo) { swap(&arr[lo], &arr[hi]); } } swap(&arr[lo], &arr[pivot]); quickSort(arr, L, hi - 1); quickSort(arr, hi + 1, R); } } void quickSortChar(char* array, char L, char R) { int lo; int hi; char pivot; pivot = L; if (R > L) { pivot = L; lo = L; hi = R; while (lo < hi) { while (array[lo] <= array[pivot] && lo<R && hi>lo) { lo++; } while (array[hi] >= array[pivot] && hi >= L && hi >= lo) { hi--; } if (hi > lo) { swapch(&array[lo], &array[hi]); } } swapch(&array[lo], &array[pivot]); quickSortChar(array, L, hi - 1); quickSortChar(array, hi + 1, R); } } //Heap Sort void heapify(int arr[], int n, int i) { int largest = i; int l = 2 * i + 1; int r = 2 * i + 2; if (l < n && arr[l] > arr[largest]) largest = l; if (r < n && arr[r] > arr[largest]) largest = r; if (largest != i) { swap(&arr[i], &arr[largest]); heapify(arr, n, largest); } } void heapSort(int arr[], int n) { int s, k; for (s = n / 2 - 1; s >= 0; s--) heapify(arr, n, s); for (k = n - 1; k > 0; k--) { swap(&arr[0], &arr[k]); heapify(arr, k, 0); } } void heapifyChar(char arr[], int n, int i) { int largest = i; int l = 2 * i + 1; int r = 2 * i + 2; if (l < n && arr[l] > arr[largest]) largest = l; if (r < n && arr[r] > arr[largest]) largest = r; if (largest != i) { swapch(&arr[i], &arr[largest]); heapifyChar(arr, n, largest); } } void heapSortChar(char arr[], int n) { int i, j; for (i = n / 2 - 1; i >= 0; i--) heapifyChar(arr, n, i); for (j = n - 1; j > 0; j--) { swapch(&arr[0], &arr[j]); heapifyChar(arr, j, 0); } } int main() { clock_t t; t = clock(); //------ MY NUMBER int num[] = { 2, 0, 1, 8, 5, 5, 6, 5, 0, 6, 2 }; char name[] = "ALICAN SÜSLÜ"; //------ NAME AND SURNAME int n = sizeof(num) / sizeof(num[0]); int namesize = strlen(name); // insertion sort printf("insertion Sort:\n"); insertionSort(num, n); t = clock() - t; printArray(num, n); printf("insertion sort time: %f\n", ((double)t) / CLOCKS_PER_SEC); insertionSortChar(name, namesize); t = clock() - t; printf("%s\n", name); printf("insertion char sort time: %f\n", ((double)t) / CLOCKS_PER_SEC); printf("\n"); // Selection Sort printf("Selection Sort:\n"); selectionSort(num, n); t = clock() - t; printArray(num, n); printf("selection sort time: %f\n", ((double)t) / CLOCKS_PER_SEC); selectionSortChar(name, namesize); t = clock() - t; printf("%s\n", name); printf("selection char sort time: %f\n", ((double)t) / CLOCKS_PER_SEC); printf("\n"); //Bubble Sort printf("Bubble Sort:\n"); bubbleSort(num, n); t = clock() - t; printArray(num, n); printf("bubble sort time: %f\n", ((double)t) / CLOCKS_PER_SEC); bubbleSortChar(name, namesize); t = clock() - t; printf("%s\n", name); printf("bubble char sort time: %f\n", ((double)t) / CLOCKS_PER_SEC); //Merge Sort printf("Merge Sort:\n"); mergeSort(num, 0, n - 1); t = clock() - t; printArray(num, n); printf("merge sort time: %f\n", ((double)t) / CLOCKS_PER_SEC); mergeSortChar(name, 0, namesize - 1); t = clock() - t; printf("%s\n", name); printf("merge char sort time: %f\n", ((double)t) / CLOCKS_PER_SEC); //Quick Sort printf("Quick Sort:-----------------------\n"); quickSort(num, 0, n - 1); t = clock() - t; printArray(num, n); printf("Quick sort time: %f\n", ((double)t) / CLOCKS_PER_SEC); quickSortChar(name, 0, namesize - 99); t = clock() - t; printf("%s\n", name); printf("Quick char sort time: %f\n", ((double)t) / CLOCKS_PER_SEC); printf("\n"); //Heap Sort printf("Heap Sort:-----------------------\n"); heapSort(num, n); t = clock() - t; printArray(num, n); printf("Heap sort time: %f\n", ((double)t) / CLOCKS_PER_SEC); heapSortChar(name, namesize); t = clock() - t; printf("%s\n", name); printf("Heap char sort time: %f\n", ((double)t) / CLOCKS_PER_SEC); printf("\n"); return 0; }
C
#include "types.h" #include "user.h" #include "uthread.h" #include "x86.h" //***************************************************************************************// // implementation of random generation function unsigned long randstate = 1; unsigned int rand() { randstate = randstate * 1664525 + 1013904223; return randstate; } //***************************************************************************************// // array of utherad structs struct uthread uthread_pool[MAX_THREADS]; // next pid to run int next_tid; // current running thread index int c_uthread_index; // current number of tickets int current_ticket_num; // choosen lottery thread int choosen; static void execute_thread(void (*start_func)(void *), void* arg) { printf(1, "+++RUN THREAD+++ \n"); alarm(UTHREAD_QUANTA); start_func(arg); uthread_exit(); } int uthread_init() { printf(1, "** INIT USER LEVEL THREAD **\n"); // set all threads state to FREE - init pool int i; for(i = 0; i < MAX_THREADS; ++i) { uthread_pool[i].state = FREE; uthread_pool[i].ntickets = NTICKET; } next_tid = 1; // initialize main thread c_uthread_index = 0; // set tid and stack to null uthread_pool[c_uthread_index].tid = 0; uthread_pool[c_uthread_index].stack = 0; // main thread is ready to run uthread_pool[c_uthread_index].state = RUNNING; // register the SIGALRM to uthread_yield func if(signal(SIGALRM, uthread_yield) != 0) { // case signal error return -1; } // execute the alarm syscall with UTHREAD_QUANTA alarm(UTHREAD_QUANTA); return 0; } int uthread_create(void (*func)(void *), void* arg) { printf(1, "start thread creation \n"); // local thread pool index int i; // disable thread switching alarm(0); printf(1, "uthread_create after alarm(0) \n"); // search for free thread to load for(i = 0; i < MAX_THREADS; ++i) { if (uthread_pool[i].state == FREE) { goto load_t; } } // case no free threads available // enable thread switching alarm(UTHREAD_QUANTA); return -1; load_t: // next free tid to assign uthread_pool[i].tid = next_tid; // update next tid next_tid++; // allocate stack for thread and returns the stack top to .stack field uthread_pool[i].stack = malloc(STACK_SIZE); // load thread execute function to stack with arguments and return value *( (int*)(uthread_pool[i].stack + STACK_SIZE - 3*sizeof(int)) ) = 0; *( (int*)(uthread_pool[i].stack + STACK_SIZE - 2*sizeof(int)) ) = (int)func; *( (int*)(uthread_pool[i].stack + STACK_SIZE - sizeof(int)) ) = (int)arg; // set thread state to RUNNABLE, ready to run uthread_pool[i].state = RUNNABLE; // set esp and ebp to null, while thread is not in RUNNING state yet uthread_pool[i].esp = 0; uthread_pool[i].ebp = 0; // enable thread switching printf(1, "creation method: returning.. \n"); alarm(UTHREAD_QUANTA); return uthread_pool[i].tid; } void uthread_exit(void) { int i; // disable thread switching alarm(0); // deallocate thread memory if (uthread_pool[c_uthread_index].stack != 0) { free(uthread_pool[c_uthread_index].stack); } // deallocate thread from thread pool uthread_pool[c_uthread_index].state = FREE; // if any thread is waiting for current thread, get them back to RUNNABLE state for(i = 0; i < MAX_THREADS; ++i) { if (uthread_pool[i].state == SLEEP) { uthread_pool[i].state = RUNNABLE; } } // Check if there are any other uthread_pool that can be switched to for(i = 0; i < MAX_THREADS; ++i) { if (uthread_pool[i].state != FREE) { // found thread that is eligible to run, yield uthread_yield(); } } // no ready to run threads, exit exit(); } void uthread_yield(void) { // switch alarm(0) to cancel thread switching while yielding alarm(0); // if current thread is running (most cases), the thread didn't finisht its job so turn his state to RUNNABLE if (uthread_pool[c_uthread_index].state == RUNNING) { uthread_pool[c_uthread_index].state = RUNNABLE; } // save current thread esp and ebp asm("movl %%esp, %0;" : "=r" (uthread_pool[c_uthread_index].esp)); asm("movl %%ebp, %0;" : "=r" (uthread_pool[c_uthread_index].ebp)); // load the new thread // pick the next thread index c_uthread_index++; // ************** lottery scheduler mechanism ******************* // int j, randomTicket; // update number of total tickets current_ticket_num = -1; for(j = 0; j < MAX_THREADS; ++j) { if(uthread_pool[j].state != FREE && uthread_pool[j].state != SLEEP) current_ticket_num += uthread_pool[j].ntickets; } // generate a random number between 0 and current_ticket_num randomTicket = rand() % current_ticket_num; printf(1,"current_ticket_num=%d\n", current_ticket_num); printf(1,"randomTicket=%d\n", randomTicket); // set the choosen order thread to run choosen = randomTicket / NTICKET; // pick the index of choosen thread int chooseCount = -1; for(j = 0; j < MAX_THREADS; ++j) { if(uthread_pool[j].state == RUNNABLE) { chooseCount++; if (choosen == chooseCount) break; } } // set current thread to the lottery chosen one c_uthread_index = j; // ****************************************************************** // // current switched thread is move to RUNNING mode, next to be execute uthread_pool[c_uthread_index].state = RUNNING; // if esp is null, thread is running its first time, so we have to load a functio to it if(uthread_pool[c_uthread_index].esp == 0) { asm("movl %0, %%esp;" : : "r" (uthread_pool[c_uthread_index].stack + STACK_SIZE - 3*sizeof(int))); asm("movl %0, %%ebp;" : : "r" (uthread_pool[c_uthread_index].stack + STACK_SIZE - 3*sizeof(int))); // jump to execute function to run the thread own function asm("jmp *%0;" : : "r" (execute_thread)); } else { // restore thread stack asm("movl %0, %%esp;" : : "r" (uthread_pool[c_uthread_index].esp)); asm("movl %0, %%ebp;" : : "r" (uthread_pool[c_uthread_index].ebp)); // reset alarm alarm(UTHREAD_QUANTA); } } int uthred_self(void) { // return current running thread tid return uthread_pool[c_uthread_index].tid; } int uthred_join(int tid) { int i; // if tid is not declared yet or is a negative number, error occured, return if(tid >= next_tid || tid < 0) { return -1; } loop: // disable thread switching alarm(0); // run over all threads for(i = 0; i < MAX_THREADS; ++i) { // searching for a thread with the relevant tid if(uthread_pool[i].tid == tid) { // put current running thread to sleep uthread_pool[c_uthread_index].state = SLEEP; // let other thread to run uthread_yield(); // if thread still alive, loop over the join procedure again goto loop; } } // the joined thread is not alive anyway, reset clock alarm(UTHREAD_QUANTA); return 0; }
C
/* Write the function _itob(n,s,b)_ that converts the integer _n_ * into a base _b_ character representation in the string _s_. In particular, * _itob(n,s,16)_ formats _n_ as a hexadecimal integer in _s_. */ #include <stdio.h> #include <limits.h> #include <stdlib.h> #define MAXLINE 20 /* itob: convert _n_ to characters in _s_ with base _b_ representation */ void itob(int n, char s[], int b); /* just print */ void reverse(char in[]); int main() { char s[MAXLINE]; printf("Convert int %d to base %d: ", 534, 4); itob(534, s, 4); printf("Convert int %d to base %d: ", 0, 8); itob(0, s, 8); printf("Convert int %d to base %d: ", -2314, 16); itob(-2314, s, 16); printf("Convert int %d to base %d: ", 3408327, 10); itob(3408327, s, 10); printf("Convert int %d to base %d: ", -3498345, 8); itob(-3498345, s, 8); printf("This is INT_MAX. Convert int %d to base %d: ", INT_MAX, 16); itob(INT_MAX, s, 16); printf("This is INT_MIN. Convert int %d to base %d: ", INT_MIN, 16); itob(INT_MIN, s, 16); } /* itob: convert _n_ to characters in _s_ with base _b_ representation */ void itob(int n, char s[], int b) { int i, sign; char value[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; if ((sign = n) < 0) /* record sign */ n = -n; /* make positive */ i = 0; do { /* generate digits in reverse order */ s[i++] = value[abs(n % b)]; /* get next digit */ } while ((n /= b) != 0); /* delete it */ if (sign < 0) s[i++] = '-'; s[i] = '\0'; reverse(s); } /* just print */ void reverse(char s[]) { int i = 0; while (s[++i] != '\0'); /* Find the length of the string */ do { printf("%c", s[--i]); /* Start from the length and print the string backward */ } while (i > 0); printf("\n"); }
C
#include<stdio.h> int isPower(unsigned int a, unsigned int b); int div = 0; int main(){ unsigned int a; unsigned int b; for(a = 1; a < 100; a++) { div = 0; if (isPower(a, 3)) { printf("a = b^n\n"); printf("%d e igual a 3^n\n",a); } else { printf("a != b^n\n"); printf("%d e diferente de 3^n\n",a); } printf("ao final de %d divs\n", div); } } int isPower(unsigned int a, unsigned int b){ if(a == 1){ return 1; } if(a == b){ return 1; } if(a % b != 0){ return 0; } div++; return isPower(a/b, b); }
C
#include<stdio.h> #include<unistd.h> #include <sys/acct.h> #include<stdlib.h> #include <sys/types.h> #include <sys/wait.h> #define ACCFILE “/var/adm/pacct” FILE *fp; struct acct acdata; unsigned long compt2ulong(comp_t comptime) { int val; int exp; val = comptime & 0x1fff; /* 13-bit fraction */ exp = (comptime >> 13) & 7; /* 3-bit exponent (0-7) */ while (exp-- > 0) val *= 8; return(val); } int wait2(long *rtime,long *wtime){ int pid; long temp; pid = wait(NULL); fseek(fp, -sizeof(acdata), SEEK_END); fread(&acdata, sizeof(acdata), 1, fp); //printf("%ld %ld\n", compt2ulong(acdata.ac_utime), compt2ulong(acdata.ac_stime)); temp = compt2ulong(acdata.ac_utime) + compt2ulong(acdata.ac_stime); //printf("%ld\n", temp); *rtime = temp; temp = compt2ulong(acdata.ac_etime - acdata.ac_utime - acdata.ac_stime); //temp = compt2ulong(acdata.ac_etime); //printf("%ld\n", temp); *wtime = temp; return pid; } int main(){ long rtime, wtime, iotime, pid; fp = fopen("./a", "r"); if((pid = fork()) > 0){ printf("%ld ",pid); pid = wait2(&rtime, &wtime); printf("PID:%ld rtime: %ld wtime: %ld\n",pid, rtime, wtime); }else{ int i; for(i = 0; i < 5;){ i++; } exit(1); } }
C
/** ****************************************************************************** *------------------------------File Information------------------------------* * @file :led.c * @author :WZR * @date :2020-04-10 * @brief :LED * @attention: * *----------------------------Version Information-----------------------------* * @version :V1.0.0 ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "led.h" /* Public functions ----------------------------------------------------------*/ /** * @name :LED_Init * @brief :LEDʼ * @param :None * @retval :None * @author :WZR * @date :2020-04-10 */ void LED_Init(void) { GPIO_InitTypeDef GPIO_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_GPIOD, ENABLE); //ʹPA,PD˿ʱ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8; //LED0-->PA.8 ˿ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; // GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //IOٶΪ50MHz GPIO_Init(GPIOA, &GPIO_InitStructure); //趨ʼGPIOA.8 GPIO_SetBits(GPIOA,GPIO_Pin_8); //PA.8 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2; //LED1-->PD.2 ˿, GPIO_Init(GPIOD, &GPIO_InitStructure); // IOٶΪ50MHz GPIO_SetBits(GPIOD,GPIO_Pin_2); //PD.2 } /***********************************END OF FILE********************************/
C
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <netinet/in.h> #include <netdb.h> #include <sys/socket.h> #include <sys/wait.h> #include <unistd.h> #include <strings.h> #include <arpa/inet.h> #include <fcntl.h> #define BUFFER 576 int main(int argc, char *argv[]) { int iSock, iFileDescriptor, iNumBytes; struct sockaddr_in server_addr; struct hostent *he; int i , j, k; char sBuffer[BUFFER], input[512], *cmd, *token, *filename, oct[6]; if(argc < 3) { printf("Uso: client <endereço> <porta>\n"); exit(1); } //convertendo o endereco passado para uma estrutura que eu entendo if((he = gethostbyname(argv[1])) == NULL) { perror("gethostbyname"); exit(1); } if((iSock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket"); exit(1); } server_addr.sin_family = AF_INET; server_addr.sin_port = htons(atoi(argv[2])); server_addr.sin_addr = *((struct in_addr *)he->h_addr); bzero(&(server_addr.sin_zero), 8); printf("----------------------------TFTP - Trivial File Transfer Protocol------------------------------------"); printf("\nComandos:\n\tget <arquivo>\n\tput <arquivo>\n\trexmt <tempo>\n\ttimeout <tempo>\n\ttrace\n\tquit\n"); cmd = malloc(5); filename = malloc(255); while(strcmp(cmd, "quit") != 0 && strcmp(cmd, "q") != 0) { printf(">"); gets(input); cmd = strtok (input, " "); if(strcmp(cmd, "get") == 0 || strcmp(cmd, "g") == 0 ) { puts("Buscando arquivo remoto..."); if((filename = strtok(NULL, " ")) != NULL) { sBuffer[0] = 0; sBuffer[1] = 1; //Read Request (RRQ) puts(filename); for(j = 0, i = 2; j < strlen(filename); j++, i++) { sBuffer[i] = filename[j]; } sBuffer[i+1] = 0; sBuffer[i+2] = 'o'; sBuffer[i+3] = 'c'; sBuffer[i+4] = 't'; sBuffer[i+5] = 'e'; sBuffer[i+6] = 't'; sBuffer[i+7] = 0; iNumBytes = sendto(iSock, sBuffer, BUFFER, 0, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)); if(iNumBytes < 0) { perror("sendto"); } else { //recebe o primeiro pacote e envia o ACK } } } else if(strcmp(cmd, "put") == 0 || strcmp(cmd, "p") == 0 ) { } else if(strcmp(cmd, "rexmt") == 0 || strcmp(cmd, "r") == 0 ) { } else if(strcmp(cmd, "timeout") == 0 || strcmp(cmd, "t") == 0 ) { } else if(strcmp(cmd, "trace") == 0 || strcmp(cmd, "c") == 0 ) { } else if(strcmp(cmd, "quit") == 0 || strcmp(cmd, "q") == 0 ) { puts("\nbye"); } else { printf("\n\'%s\': comando inválido. Use get, put, rexmt, timeout, trace ou quit\n", cmd); } } //inicio do envio /*iNumBytes = sendto(iSock, "01INICIO", 8, 0, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)); if(iNumBytes < 0) { perror("sendto"); exit(1); } //primeiro eh enviado o nome do arquivo iNumBytes = sendto(iSock, argv[2], strlen(argv[2]), 0, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)); if(iNumBytes < 0) { perror("sendto"); exit(1); } iNumBytes = read(iFileDescriptor, &sBuffer, BUFFER); while(iNumBytes < 0) { //enviando o buffer iNumBytes = sendto(iSock, sBuffer, iNumBytes, 0, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)); if(iNumBytes < 0) { perror("sendto (2)"); exit(1); } fprintf(stderr, "\nEnviando ......... %d OK", iNumBytes); iNumBytes = read(iFileDescriptor, &sBuffer, BUFFER); } if(iNumBytes < 0) { perror("read"); exit(1); } // fim do envio iNumBytes = sendto(iSock, "01FIM", 5, 0, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)); if(iNumBytes < 0) { perror("sendto"); exit(1); }*/ close(iSock); close(iFileDescriptor); return 0; }
C
// A program to introduce DEQUE #include<stdio.h> #define MAX 10 int deque[MAX]; int left = -1, right = -1; void input(); // Input Restricted Deque void output(); // Output Restricted Deque void insert_left(); // Insert Left Operation void insert_right(); // Insert Right Operation void delete_left(); // Delete Left Operation void delete_right(); // Delete Right Operation void display(); // Display the Queue int main() { int option; printf("\n*** Main Menu ***\n"); printf("1. Input restricted deque.\n"); printf("2. Output restricted deque.\n"); printf("\nEnter your option : "); scanf("%d", &option); switch (option) { case 1: input(); break; case 2: output(); break; } return 0; } // Input Restricted Deque void input() { int option; do { printf("\nINPUT RESTRICTED DEQUE\n"); printf("1. Insert at right\n"); printf("2. Delete from left\n"); printf("3. Delete from right\n"); printf("4. Display\n"); printf("5. Quit\n"); printf("\nEnter your option : "); scanf("%d", &option); switch (option) { case 1: insert_right(); break; case 2: delete_left(); break; case 3: delete_right(); break; case 4: display(); break; } }while(option!=5); } // Output Restricted Deque void output() { int option; do { printf("\nOUTPUT RESTRICTED DEQUE\n"); printf("1. Insert at right\n"); printf("2. Insert at left\n"); printf("3. Delete from left\n"); printf("4. Display\n"); printf("5. Quit\n"); printf("\nEnter your option : "); scanf("%d", &option); switch (option) { case 1: insert_right(); break; case 2: insert_left(); break; case 3: delete_left(); break; case 4: display(); break; } }while(option!=5); } // insert_right void insert_right() { int val; printf("\nEnter the value to be added : "); scanf("%d", &val); if ((left == 0 && right == MAX - 1) || (left == right + 1)) { printf("OVERFLOW.\n"); return; } if (left == -1) { left = 0; right = 0; } else { if (right == MAX-1) right = 0; else right = right + 1; } deque[right] = val; } // insert_left void insert_left() { int val; printf("\nEnter the value to be added : "); scanf("%d", &val); if ((left == 0 && right == MAX - 1) || (left == right + 1)) { printf("OVERFLOW.\n"); return; } if (left == -1) { left = 0; right = 0; } else { if (left == 0) left = MAX-1; else left = left + 1; } deque[left] = val; } // delete_left void delete_left() { if (left == -1) { printf("UNDERFLOW.\n"); return; } printf("The deleted element is : %d\n", deque[left]); if (left == right) { left = -1; right = -1; } else { if(left == MAX-1) left = 0; else left = left + 1; } } // delete_right void delete_right() { if (left == -1) { printf("UNDERFLOW.\n"); return; } printf("The deleted element is : %d\n", deque[right]); if (left == right) { left = -1; right = -1; } else { if(right == 0) right = MAX-1; else right = right - 1; } } // display void display() { int front = left, rear = right; if(front == -1) { printf("QUEUE IS EMPTY.\n"); return; } printf("The elements of the queue are : \n"); if(front <= rear) { while (front <= rear) { printf("%d\n", deque[front]); front++; } } else { while (front <= MAX - 1) { printf("%d\n", deque[front]); front++; } front = 0; while (front <= rear) { printf("%d\n", deque[front]); front++; } } printf("\n"); }
C
#include <stdlib.h> #include <stdio.h> #include "distribution.h" /* Distribution: e.g.: 11 elements and 3 processes: 1.Process: element index 0-2 2.Process: element index 3-5 3.Process: element index 6-10 */ void distribution(vector* v, vector* dist_vector, int rank, int size) { int i, start_index, end_index; init_vector(dist_vector); if (rank < total_vector(v)) { if(size >= total_vector(v)) { add_vector(dist_vector, get_vector(v, rank)); } else { start_index = (total_vector(v) / size) * rank; if (rank == size - 1) { //last process collects last elements end_index = total_vector(v); } else { end_index = start_index + (total_vector(v) / size); } for (i = start_index; i < end_index; i++) { add_vector(dist_vector, get_vector(v, i)); } } } }
C
// Informações do estudante // Nome: Gabriel Rodrigues Malaquias // Curso: Bacharelado em Ciência da Computação // RA: 758906 #include <stdio.h> #include <stdlib.h> #include <string.h> int main(){ int qtd=0, qtdmutacao=0, aux=0, inicio=1, menor=0, posmenor=0; scanf("%d", &qtd); int genes[qtd]; for(int i=0; i<qtd; i++){ scanf("%d", &genes[i]); } for(int i=0; i<qtd; i++){ int k=0; menor = genes[i]; for(k=i+1; k<qtd; k++){ if(genes[k]<menor){ menor = genes[k]; posmenor = k; } } while(posmenor>i){ aux = genes[posmenor]; genes[posmenor] = genes[posmenor-1]; genes[posmenor-1] = aux; qtdmutacao++; posmenor--; } } printf("%d\n", qtdmutacao); for(int i=0; i<qtd; i++){ printf("%d ", genes[i]); } return 0; }
C
/* * serial.c - rename! --> this is RS485 specific uart layer, * it knows nothing about the RSI protocol... * * Created on: May 21, 2014 * Author: kbroerman */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <termios.h> #include <linux/serial.h> #include <sys/ioctl.h> #include "commonTypes.h" #include "serial.h" #include "gpio.h" #include "misc.h" int rs485_rcvEnable(void) { //RS485 RE/ (APx4 receive) //printf("485 rcv en\n"); gpio_setValue(RS485_RE, 0); //Rx enabled delayuS(25); //let it settle... } int rs485_rcvDisable(void) { //RS485 RE/ (APx4 receive) gpio_setValue(RS485_RE, 1); //Rx disabled delayuS(25); //let it settle... } int rs485_xmitEnable(void) { //RS485 DE (APx4 transmit) gpio_setValue(RS485_DE, 1); //Tx enabled delayuS(25); //let it settle... } int rs485_xmitDisable(void) { //RS485 DE (APx4 transmit) gpio_setValue(RS485_DE, 0); //Tx disabled delayuS(25); //let it settle... } //inputs: // fd: uart file descriptor // count: number of bytes to wait for // buffer: receive buffer // //returns bytes received int rs485_read( int fd, char *buffer, int requested ) { if (fd == -1) return -1; int actual; gpio_setValue(RS485_LED_RED, 0); //FIXME: replace with LED thread to blink LEDs //must do this at higher layer: //RS485 RE/ (APx4 receive) //gpio_setValue(RS485_RE, 0); //Rx enabled actual = read(fd, buffer, requested); //blocking read gpio_setValue(RS485_LED_RED, 1); return actual; } //inputs: // fd: uart file descriptor // count: number of bytes to write // buffer: transmit buffer // //returns bytes sent int rs485_write( int fd, char *buffer, int requested ) { if (fd == -1) return -1; int actual; gpio_setValue(RS485_LED_GREEN, 1); //FIXME: replace with LED thread to blink LEDs //printf("writing %d bytes\n", requested); //now assume this is done at higher layer: //RS485 DE (APx4 transmit) //gpio_setValue(RS485_DE, 1); //Tx enabled //delayuS(25); //let it settle... actual = write(fd, buffer, requested); gpio_setValue(RS485_LED_GREEN, 0); //LED off return actual; } int rs485_open(void) { //export gpios 41 (RS485 RE/) & 42 (RS485 DE) so userspace can control RS485 transceiver output enables: gpio_init(RS485_RE); gpio_init(RS485_DE); rs485_rcvDisable(); rs485_xmitDisable(); //export gpios 44 & 45 (CommLEDGreen = Tx, CommLEDRed = Rx) gpio_init(RS485_LED_GREEN); gpio_init(RS485_LED_RED); gpio_setValue(RS485_LED_GREEN, 0); //off gpio_setValue(RS485_LED_RED, 0); //off //------------------------- //----- SETUP AUART 2 ----- //------------------------- //before running, assumes GPIO pins 41 and 42 are already set to proper values int uart2_fd = -1; int count; //OPEN THE UARTint rs485_open(void) //The flags (defined in fcntl.h): // Access modes (use 1 of these): // O_RDONLY - Open for reading only. // O_RDWR - Open for reading and writing. // O_WRONLY - Open for writing only. // // O_NDELAY / O_NONBLOCK (same function) - Enables nonblocking mode. When set read requests on the file can return immediately with a failure status // if there is no input immediately available (instead of blocking). Likewise, write requests can also return // immediately with a failure status if the output can't be written immediately. // // O_NOCTTY - When set and path identifies a terminal device, open() shall not cause the terminal device to become the controlling terminal for the process. uart2_fd = open("/dev/ttyAPP2", O_RDWR | O_NOCTTY ); // | O_NDELAY); //Open in non blocking read/write mode if (uart2_fd == -1) { //ERROR - CAN'T OPEN AUART 2 printf("Error - Unable to open AUART 2!\n"); return uart2_fd; } printf("AUART 2 opened...\n"); //CONFIGURE THE UART //The flags (defined in /usr/include/termios.h - see http://pubs.opengroup.org/onlinepubs/007908799/xsh/termios.h.html): // Baud rate:- B1200, B2400, B4800, B9600, B19200, B38400, B57600, B115200, B230400, B460800, B500000, B576000, B921600, B1000000, B1152000, B1500000, B2000000, B2500000, B3000000, B3500000, B4000000 // CSIZE:- CS5, CS6, CS7, CS8 // CLOCAL - Ignore modem status lines // CREAD - Enable receiver // IGNPAR = Ignore characters with parity errors // ICRNL - Map CR to NL on input (Use for ASCII comms where you want to auto correct end of line characters - don't use for bianry comms!) // PARENB - Parity enable // PARODD - Odd parity (else even) struct termios options; //memset(&options, 0, sizeof(options)); tcgetattr(uart2_fd, &options); cfmakeraw(&options); options.c_cc[VMIN] = 1; //if blocking read: wait for at least 1 char (SOF) options.c_cc[VTIME] = 0; //read: 100 mS interchar timeout cfsetispeed(&options, B9600); cfsetospeed(&options, B9600); #if 0 //printf("options.c_cc[VMIN] = %d\n", options.c_cc[VMIN]); //printf("options.c_cc[VTIME] = %d\n", options.c_cc[VTIME]); options.c_cflag = B9600 | CS8 | CLOCAL | CREAD; options.c_iflag = IGNPAR; options.c_oflag = 0; options.c_lflag &= ~(ICANON); //raw mode options.c_cc[VMIN] = 0; //if blocking read: wait for at least 1 char (SOF) options.c_cc[VTIME] = 0; //read: 100 mS interchar timeout #endif tcsetattr(uart2_fd, TCSANOW, &options); tcflush(uart2_fd, TCIOFLUSH); #if 0 struct serial_struct serial; int ret = ioctl(uart2_fd, TIOCGSERIAL, &serial); printf("fifo size = %d\n", serial.xmit_fifo_size); if (ret != 0) puts("ooops1"); serial.flags | ASYNC_LOW_LATENCY; ret = ioctl(uart2_fd, TIOCSSERIAL, &serial); if (ret != 0) puts("ooops2"); #endif return uart2_fd; } int rs485_close(int fd) { close(fd); gpio_deinit(RS485_RE); gpio_deinit(RS485_DE); gpio_deinit(RS485_LED_GREEN); gpio_deinit(RS485_LED_RED); } void rs485UartVminVtime( int fd, int vmin, int vtime ) { struct termios options; tcgetattr(fd, &options); options.c_cc[VMIN] = vmin; //change to timed read options.c_cc[VTIME] = vtime; //read: 100 mS tcsetattr(fd, TCSANOW, &options); //delayuS(25); //FIXMWE remove }
C
#include "lab.h" //Змінні для зчитування значення з джойстика int y = 0; int x = 0; //Ініціалізація компонент void adc_validation_init(void){ ADC_Start(); ADC_StartConvert(); PWM_X_Start(); PWM_Y_Start(); } //Алгоритм виконання завдання void adc_get_led_position(void){ //Зчитування аналогового сигналу за допомогою ADC(АЦП) x = ADC_GetResult16(0); y = ADC_GetResult16(1); //Запис значення з ADC в PWM(ШІМ) //За допомогою PWM контролюється яркість діодів PWM_X_WriteCompare(x); PWM_Y_WriteCompare(y); }
C
#include "holberton.h" /** * _strstr - function that locates a substring * @haystack: string * @needle: substring * Return: 0 upon success **/ char *_strstr(char *haystack, char *needle) { int x, y; for (x = 0; haystack[x] != '\0'; x++) { for (y = 0; needle[y] != '\0'; y++) { if (needle[y] != haystack[x + y]) { break; } } if (needle[y] == '\0') { return (haystack + x); } } return (0); }
C
#include <stdio.h> int main() { printf("Reverse Polish Notation Calculator v0.1 by dom96\n\n"); while (1) { /* Get two INT's */ int first, second; if(scanf("%i", &first) == 1 && scanf("%i", &second)) { /* Get the operator */ char op[2]; if(scanf("%1s", op) == 1) { switch(op[0]) { case '+': printf("== %i\n", first + second); break; case '-': printf("== %i\n", first - second); break; case '*': printf("== %i\n", first * second); break; case '/': printf("== %i\n", first / second); break; default: printf("Error: Invalid operator.\n"); } } else { printf("Error: Invalid operator.\n"); } } else { printf("Error: Number expected.\n"); break; } } }
C
#include<stdio.h> #include<stdlib.h> struct node{ int value; struct node *next; }; struct node *reverse(struct node*); //把原list倒過來 struct node *print(struct node*); //列印list struct node* q_sort(struct node*, struct node*); int main(int argc,char *argv[]){ int n=atoi(argv[1]),m=atoi(argv[2]),s=atoi(argv[3]),num,i=0; /*n為有幾個元素 , m為數字範圍 , s為隨機變數依據*/ srand(s); struct node *head=NULL, *pivot=NULL; //先建立link list開頭 for(i=0;i<n;i++){ num=rand()%m; struct node *new_node=malloc(sizeof(struct node)); //開新空間 其size為已宣告的struct大小 new_node->value=num; //存隨機變數} new_node->next=head; head=new_node; } printf("Oringinal SLL:"); head = reverse(head); print(head); head=q_sort(head,NULL); printf("Sorted SLL:"); while(1){ if(head==NULL) break; else{ printf("%4d",head->value); head=head->next; } } printf("\n"); return 0; } struct node* reverse(struct node* head){ if(head==NULL||head->next==NULL) return head; struct node *previous=NULL, *now=head, *preceding=head->next; while(preceding!=NULL){ now->next=previous; //把now->next轉向 previous=now; //previous往後挪 now=preceding; //now往後挪 preceding=preceding->next; //preceding往後挪 } now->next=previous; //此時current位於最後一個node head=now; //更新head為now return head; } struct node * print(struct node* head){ struct node *current=head; while(1){ if(current==NULL) break; printf("%4d",current->value); current=current->next; } printf("\n"); } struct node* q_sort(struct node *head,struct node *tail) { if(head == tail || head->next == tail) return head; struct node *pivot = head, *current=NULL, *previous, *pre_pivot = NULL; for(previous = NULL, current = head; current != tail; previous = current, current = current->next) { if(current->value < pivot->value){ if(pivot == head) { previous->next = current->next; current->next = pivot; head = pre_pivot = current; current = previous; } else { previous->next = current->next; current->next = pivot; pre_pivot->next = current; pre_pivot = pre_pivot->next; current = previous; } } } head = q_sort(head, pivot); pivot->next = q_sort(pivot->next, tail); return head; }
C
#include <stdint.h> /* 表示路由表的一项。 约定 addr 和 nexthop 以 **网络字节序(大端序)** 存储。 这意味着 1.2.3.4 在小端序的机器上被解释为整数 0x04030201 而不是 0x01020304。 保证 addr 和 len 构成合法的网络前缀。 当 nexthop 为零时这是一条直连路由。 你可以在全局变量中把路由表以一定的数据结构格式保存下来。 */ typedef struct RoutingTableEntry{ uint32_t addr; // 网络字节序,IPv4 地址 uint32_t len; // 主机字节序,前缀长度 uint32_t if_index; // 主机字节序,出端口编号 uint32_t nexthop; // 网络字节序,下一跳的 IPv4 地址 // 为了实现 RIP 协议,需要在这里添加额外的字段 uint32_t metric; RoutingTableEntry(uint32_t addr,uint32_t len,uint32_t if_index,uint32_t nexthop,uint32_t metric){ this->addr = addr; this->len = len; this->if_index = if_index; this->nexthop = nexthop; this->metric = metric; } RoutingTableEntry() = default; };
C
/* Copyright (c) 2020 Peter Hsu. All Rights Reserved. See LICENCE file for details. */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <assert.h> #include <string.h> #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include "shmfifo.h" #include "caveat.h" #define DEFAULT_BUFSIZE 12 /* Producer side fifo initialization. bufid - number = file descriptor (already opened) $name = shared memory segment /dev/shm/name otherwise = trace file path name bufsize - log-base-2 number of bytes */ struct fifo_t* fifo_create( const char* bufid, int bufsize ) { // assert(sizeof(struct fifo_t) == 2*64); if (bufsize == 0) bufsize = DEFAULT_BUFSIZE; assert(bufsize > 3); int fd = shm_open(bufid, O_CREAT|O_TRUNC|O_RDWR, S_IRWXU); dieif(fd<0, "shm_open() failed in fifo_create"); size_t fsize = (1<<bufsize) + sizeof(struct fifo_t); dieif(ftruncate(fd, fsize)<0, "ftruncate() failed in fifo_create"); struct fifo_t* fifo = (struct fifo_t*)mmap(NULL, fsize, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); dieif(fifo==0, "mmap() failed in fifo_create"); assert(((uint64_t)fifo & 0x3fL) == 0L); memset((char*)fifo, 0, fsize); fifo->size = bufsize; fifo->fd = fd; fifo->get_mask = fifo->put_mask = (1<<(bufsize-3))-1; fifo->id = bufid; return fifo; } /* Consumer side fifo initialization. bufid - number = file descriptor (already opened) $name = shared memory segment /dev/shm/name otherwise = trace file path name */ struct fifo_t* fifo_open( const char* bufid ) { int fd = shm_open(bufid, O_RDWR, 0); dieif(fd<0, "shm_open() failed in fifo_open"); struct fifo_t* fifo = (struct fifo_t*)mmap(NULL, sizeof(struct fifo_t), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); dieif(fifo==0, "first mmap() failed in fifo_open"); size_t fsize = (1<<fifo->size) + sizeof(struct fifo_t); dieif(munmap(fifo, sizeof(struct fifo_t))<0, "munmap() failed in fifo_open"); fifo = (struct fifo_t*)mmap(NULL, fsize, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); dieif(fifo==0, "second mmap() failed in fifo_open"); assert(((uint64_t)fifo & 0x3fL) == 0L); return fifo; } /* Consumer side fifo termination. */ void fifo_close( struct fifo_t* fifo ) { fifo->finished = 1; futex_wake(&fifo->finished); size_t fsize = (1<<fifo->size) + sizeof(struct fifo_t); dieif(munmap(fifo, fsize)<0, "munmap() failed in fifo_close"); } /* Producer side fifo termination. */ void fifo_finish( struct fifo_t* fifo ) { fifo_flush(fifo); /* wait for consumer to finish */ futex_hibernate(&fifo->finished, 0); size_t fsize = (1<<fifo->size) + sizeof(struct fifo_t); dieif(munmap(fifo, fsize)<0, "munmap() failed in fifo_finish"); } void fifo_debug( struct fifo_t* fifo, const char* msg ) { fprintf(stderr, "%s: HEAD=%d, head=%d, TAIL=%d, tail=%d\n", msg, fifo->HEAD, fifo->head, fifo->TAIL, fifo->tail); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { char Meno_Priezvisko; char SPZ; char Typ_Auta; int Cena; int Datum; struct zaznam *dalsi; }zaznam; int pocet_zaznamov() { int x = 0; char pom; FILE *p_subor = fopen("predaj.txt", "r"); if (p_subor == NULL) { printf("Zaznami neboli nacitane\n"); return; } while ((pom = getc(p_subor)) != EOF) { if (pom == '$') { x++; } } rewind(p_subor); fclose(p_subor); return x; } double vyp_odmeny(double cena, int typa) { //vypocita odmenu z ceny double odmena; if (typa == 0) { odmena = (0.022 * cena); } else { odmena = (0.015 * cena); } return odmena; } void vypis_zaznamov()() { int i; FILE * p_subor = fopen("predaj.txt", "r"); //otovr subor if (p_subor == NULL) return NULL; (*akt) = (*zac); for (i = 0; i < x; i++) { printf("Meno Priezvisko: %s\n", (*akt)->Meno_Priezvisko); printf("SPZ: %s\n", (*akt)->SPZ); printf("Typ auta: %s\n", (*akt)->Typ_Auta); printf("Cena: %d\n", (*akt)->Cena); printf("Datum: %d\n", (*akt)->Datum); if (i < x - 1) (*akt) = (*akt)->dalsi } printf("\n"); //koniec riadku po ukonceni vypis fclose(p_subor); } void o() { FILE * p_subor = fopen("predaj.txt", "r"); //otvor subor if (p_subor == NULL) return NULL; char ch, p[9], r[50], meno[30], spz[10]; int pocr = 1, y, datum, typa; double cena, odmena; printf("Zadajte datum: "); scanf("%d", &datum); printf("______________________________\n"); //koniec riadku while ((fgets(r, sizeof(r), p_subor))) { //zisti pocet riadkov v subore switch (pocr) { case 1: { strcpy(meno, r); break; } case 2: { strcpy(spz, r); break; } case 3: { typa = atoi(r); break; } case 4:{ cena = atof(r); odmena = vyp_odmeny(cena,typa); break; } } if (pocr == 6) pocr = 0; if (((pocr % 5) == 0)&&(pocr!=0)) { //zisti i zamestanec pracuje dlhsie ako rok y = atoi(r); //prekonvertuje string na int if ((datum - y) >= 10000) { printf("Meno: %sSPZ: %sOdmena: %2.2lf\n\n", meno, spz, odmena); } } ++pocr; } fclose(p_subor); } void n(char ***pole, int *pocz) { FILE * p_subor = fopen("predaj.txt", "r"); if (p_subor == NULL) return NULL; char r[50]; int i = 0,x = 1, y = 0,a = 0; (*pocz) = 0; while ((fgets(r, sizeof(r), p_subor))) { i++; if ((i % 5) == 0) { (*pocz)++; } } (*pole) = (char*)malloc((*pocz) * sizeof(char)); //alokujem pole pre spz for (a; a <= (*pocz); a++) { ((*pole))[a] = (char*)malloc(7 * sizeof(char)); } rewind(p_subor); //zresetuje sbor while ((fgets(r, sizeof(r), p_subor))) { if (x == 6) { x = 0; } if (r[0] == EOF) break; switch (x) { case 2: strcpy((*pole)[y], r); y++; break; } ++x; } fclose(p_subor); } void s(char ***pole,int pocz) { int b = 0; for (b; b < pocz; b++) { printf("%c%c %c%c%c %c%c\n", (*pole)[b][0], (*pole)[b][1], (*pole)[b][2], (*pole)[b][3], (*pole)[b][4], (*pole)[b][5], (*pole)[b][6]); } } void p(char ***pole,int pocz) { int b = 0; for (b ; b < pocz; b++) { if((*pole)[b][0] == (*pole)[b][6] && (*pole)[b][1] == (*pole)[b][5] && (*pole)[b][2] == (*pole)[b][4]) printf("%c%c\n", (*pole)[b][0], (*pole)[b][1]); } } int main() { zaznam *zac,*akt; char f, **pole; /*f = funkcia*/ int pocz,pomocv = 0,pomocpole = 0,x; x = pocet_zaznamov(); while (1) { f = getchar(); switch (f) { case 'k': { return 0; //skonci program break; } case 'v': { // vypie zoznam vetkch predajcov v(); pomocv++; break; } case 'o': { //vype meno,priezvisko,spz a odmenu pre zamestnanca if (pomocv == 1) { o(); break; } else break; } case'n': { // vytvor pole z SPZ if (pomocv == 1) { n(&pole, &pocz); pomocpole++; break; } else break; } case's': { // vypie SPZ s medzerami if (pomocpole == 1) { s(&pole, pocz); break; } else printf("Pole nie je vytvorene\n"); break; } case'p': { // vype SPZ,ktor s polyndromick if (pomocpole == 1) { p(&pole, pocz); break; } else printf("Pole nie je vytvorene\n"); break; } } } return 0; }
C
#include <stdarg.h> #include <string.h> #include <unistd.h> #include "vprint.h" #define UNLOCKED 1 #define LOCKED 0 #undef vprintf #undef vfprintf int vlevel = V1; int _vprintf(const char * restrict format, ...) { va_list arg; int ret; if (vlevel == V0) { ret = 0; } else { va_start(arg, format); ret = vprintf(format, arg); va_end(arg); } return ret; } int _vfprintf(FILE *stream, const char * restrict format, ...) { va_list arg; int ret; if (vlevel == V0) { ret = 0; } else { va_start(arg, format); ret = vfprintf(stream, format, arg); va_end(arg); } return ret; } int _dbg_printf(const char * restrict format, ...) { va_list arg; int ret; if (vlevel == V2) { va_start(arg, format); ret = vprintf(format, arg); va_end(arg); } else { ret = 0; } return ret; } int _sio_print(const char str[]) { return write(STDOUT_FILENO, str, strlen(str)); } int _sio_fprint(int fd, const char str[]) { return write(fd, str, strlen(str)); }
C
// Written by Ridwan Sadiq and Justin Bender #include "LPC17xx.H" #include "GLCD.h" #include <stdlib.h> #include <stdbool.h> #include "uart.h" #include "system_LPC17xx.h" #include "GLCD_UTILS.h" #include "Math.h" extern volatile uint32_t UART0_Count; extern volatile uint8_t UART0_Buffer[BUFSIZE]; void drawSquare(int cx, int cy, int width, int length, unsigned short color){ int i, j; GLCD_SetTextColor(color); for(i = cx-width/2; i <= cx+width/2; i++){ for(j = cy-length/2; j <= cy+length/2; j++){ GLCD_PutPixel(i,j); } } } void dispLives(char x){ unsigned char str[4] = "LV"; // GLCD_SetBackColor(White); GLCD_SetTextColor(Blue); GLCD_DisplayString(8, 17, str); GLCD_DisplayChar(9, 18, x); } void dispScore(char x){ unsigned char str[5] = "SC"; // GLCD_SetBackColor(White); GLCD_SetTextColor(Blue); GLCD_DisplayString(3, 17, str); GLCD_DisplayChar(4, 18, x); } void initialize(char level[13][13], int frogLoc[]){ int i,j; int px = 20; int py = 18; for(i = 0; i < 13; i++){ for(j = 0; j < 13; j++){ if (level[i][j] == 0) drawSquare(px*j+10, py*i+9, 20, 18 , Black); else if (level[i][j] == 1) drawSquare(px*j+10, py*i+9, 15, 10, Cyan); else if (level[i][j] == 2) drawSquare(px*j+10, py*i+9, 20, 10, Red); else if (level[i][j] == 3) drawSquare(px*j+10, py*i+9, 12, 10, Maroon); else if (level[i][j] == 4) drawSquare(px*j+10, py*i+9, 20, 18, Blue); else if (level[i][j] == 5) drawSquare(px*j+10, py*i+9, 20, 10, Brown); else if (level[i][j] == 6) drawSquare(px*j+10, py*i+9, 20, 18, Green); else if (level[i][j] == 7){ if (i == 12) { drawSquare(px*j+10, py*i+13, 20, 18, Purple); } else{ drawSquare(px*j+10, py*i+9, 20, 18, Purple); } } else{} } } drawSquare(frogLoc[1]*20+10, frogLoc[0]*18+9, 10, 10, White); // dispLives('0'); } void drawFrog(int x, int y, int width, int length, unsigned short color){ drawSquare(x*20+10, y*18+9, width, length, color); // Frog Base drawSquare(x*20+7, y*18+6, width-7, length-7, White); // Frog Eye 1 drawSquare(x*20+13, y*18+6, width-7, length-7, White); // Frog Eye 2 drawSquare(x*20+3, y*18+9, width-3, length-8, Blue); // Frog Arm 1 drawSquare(x*20+17, y*18+9, width-3, length-8, Blue); // Frog Arm 2 drawSquare(x*20+7, y*18+16, width-8, length-3, Blue); // Frog Leg 1 drawSquare(x*20+13, y*18+16, width-8, length-3, Blue); // Frog Leg 2 } int main() { // 0 --> Road (Black) // 1 --> Car (Cyan) // 2 --> Truck (Red) // 3 --> Turtle (Dark Purple) // 4 --> Water (Blue) // 5 --> Log (Brown) // 6 --> Home (Green) // 7 --> Safe Zone (Purple) GLCD_Init(); GLCD_Clear(Black); int mask_valForward = 0x08000000; int mask_valBack = 0x10000000; int mask_valRight = 0x20000000; int mask_valLeft = 0x04000000; // int mask_valForward = 0x100; // int mask_valBack = 0x200000; // int mask_valRight = 0x2000; // int mask_valLeft = 0x1000; int on_val = 0x00000000; int i,j,k,t; char live = '3'; int home = 5; char score = '0'; char char_from_pc; UARTInit(0, 57600); char level[13][13] = { {6, 4, 4, 6, 4, 4, 6, 4, 4, 6, 4, 4, 6}, // Home and water (Green and Blue) {4, 5, 5, 5, 4, 5, 5, 5, 4, 4, 5, 5, 5}, // Log and Water (Brown and Blue) {3, 3, 4, 4, 4, 3, 3, 4, 4, 3, 3, 4, 4}, // Turtle and Water(Maroon and Blue) {4, 5, 5, 5, 4, 5, 5, 5, 4, 4, 5, 5, 5}, // Log and Water (Brown and Blue) {3, 3, 4, 4, 4, 3, 3, 4, 4, 3, 3, 4, 4}, // Turtle and Water(Maroon and Blue) {4, 5, 5, 5, 4, 5, 5, 5, 4, 4, 5, 5, 5}, // Log and Water (Brown and Blue) {7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}, // Safe Zone (Purple) {0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0}, // Car and Road (White and Black) {0, 2, 2, 0, 0, 2, 2, 0, 0, 2, 2, 0, 0}, // Truck and Road (White and Black) {0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0}, // Car and Road (White and Black) {0, 0, 2, 2, 0, 0, 0, 2, 2, 0, 0, 0, 0}, // Truck and Road (White and Black) {0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0}, // Car and Road (White and Black) {7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7} // Safe Zone (Purple) }; int frogBase[] = {12, 6}; int frogLoc [] = {12, 6}; drawSquare(290,119, 60, 239, LightGrey); dispLives(live); dispScore(score); while(1){ if (UART0_Count != 0 ) { char_from_pc = UART0_Buffer[0]; UARTSend( 0, (uint8_t *)UART0_Buffer, UART0_Count); UART0_Count = 0; } // Moving the Frog if(((LPC_GPIO1->FIOPIN & mask_valForward) == on_val) || (char_from_pc == 'w') ){// Moving Up char_from_pc = '0'; if (frogLoc[0] == 0){ frogLoc[0] -= 0; } else { frogLoc[0] -= 1; score+=1; dispScore(score); } } if((LPC_GPIO1->FIOPIN & mask_valBack) == on_val || (char_from_pc == 's')){// Moving Down char_from_pc = '0'; if (frogLoc[0] == 12){ frogLoc[0] -= 0; } else { frogLoc[0] += 1; } } if((LPC_GPIO1->FIOPIN & mask_valRight) == on_val || (char_from_pc == 'd')){// Moving Right char_from_pc = '0'; if (frogLoc[1] == 12){ frogLoc[1] += 0; } else { frogLoc[1] += 1; } } if((LPC_GPIO1->FIOPIN & mask_valLeft) == on_val || (char_from_pc == 'a')){// Moving Left char_from_pc = '0'; if (frogLoc[1] == 0){ frogLoc[1] -= 0; } else { frogLoc[1] -= 1; } } // Collision with Cars or Trucks if (level[frogLoc[0]][frogLoc[1]] == 1 || level[frogLoc[0]][frogLoc[1]] == 2){// || level[frogLoc[0]][frogLoc[1]] == 4){ drawFrog(frogLoc[1], frogLoc[0], 10, 10, Red); for(k = 0; k <30000000; k++); live -= 1; frogLoc[0] = frogBase[0]; frogLoc[1] = frogBase[1]; if(live == '0'){ score = '0'; GLCD_Init(); GLCD_Clear(Black); unsigned char str[14] = "GAME OVER :(("; GLCD_SetTextColor(Blue); GLCD_DisplayString(5, 3, str); break; } dispLives(live); } if(level[frogLoc[0]][frogLoc[1]] == 3){ if(frogLoc[1]<=0){ drawFrog(frogLoc[1], frogLoc[0], 10, 10, Red); for(k = 0; k <30000000; k++); live -= 1; frogLoc[0] = frogBase[0]; frogLoc[1] = frogBase[1]; if(live == '0'){ score = '0'; GLCD_Init(); GLCD_Clear(Black); unsigned char str[14] = "GAME OVER :(("; GLCD_SetTextColor(Blue); GLCD_DisplayString(5, 3, str); break; } dispLives(live); } else frogLoc[1]-=1; } if(level[frogLoc[0]][frogLoc[1]] == 5){ if(frogLoc[1]>=12){ drawFrog(frogLoc[1], frogLoc[0], 10, 10, Red); for(k = 0; k <30000000; k++); live -= 1; frogLoc[0] = frogBase[0]; frogLoc[1] = frogBase[1]; if(live == '0'){ score = '0'; GLCD_Init(); GLCD_Clear(Black); unsigned char str[14] = "GAME OVER :(("; GLCD_SetTextColor(Blue); GLCD_DisplayString(5, 3, str); break; } dispLives(live); } else if (frogLoc[0] != 3){ frogLoc[1]+=1; } else{ frogLoc[1]+=2; } } // Getting Home if (level[frogLoc[0]][frogLoc[1]] == 6){ level[frogLoc[0]][frogLoc[1]] = 4; home -= 1; frogLoc[0] = frogBase[0]; frogLoc[1] = frogBase[1]; score +=5; dispScore(score); if(home == 0){ GLCD_Init(); GLCD_Clear(Black); unsigned char str[22] = "CONGRATS! YOU WON"; GLCD_SetTextColor(Blue); GLCD_DisplayString(5, 1, str); break; } } // Moving the Logs and Cars for(i = 0; i < 13; i++){ if (i == 1 || i == 5 || i == 7 || i == 9 || i == 11){ t = level[i][12]; for(j = 0; j <= 11; j++){ k = level[i][j]; level[i][j] = t; t = k; } level[i][j] = t; } else if (i == 3){ t = level[i][12]; for(j = 0; j <= 11; j+=2){ k = level[i][j]; level[i][j] = t; t = k; } level[i][j] = t; } else if (i == 2 || i == 4 || i == 8 || i == 10){ t = level[i][0]; for(j = 12; j >= 1; j--){ k = level[i][j]; level[i][j] = t; t = k; } level[i][j] = t; } } initialize(level, frogLoc); drawFrog(frogLoc[1], frogLoc[0], 10, 10, Green); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_malloc.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: zamazzal <zouhir.amazzal@gmail.com> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/12/12 20:13:06 by zamazzal #+# #+# */ /* Updated: 2020/12/21 18:22:55 by zamazzal ### ########.fr */ /* */ /* ************************************************************************** */ #include "malloc.h" static void *alloc_by_type(size_t size) { int type; void *ptr; int new_z; ptr = NULL; new_z = 0; type = ft_check_type(size); if (type != LARGE) ptr = create_in_existing_z(size, type); if (ptr == NULL) { ptr = create_new_zone(size, type); new_z = 1; } if (ptr && (DEBUG || LOG)) malloc_log(ptr, size); return (ptr); } void *ft_malloc(size_t size) { void *ptr; if (!size) return (NULL); ptr = alloc_by_type(size); return (ptr); } void *malloc(size_t size) { void *ptr; pthread_mutex_lock(&g_lock); ptr = ft_malloc(size); pthread_mutex_unlock(&g_lock); return (ptr); } void *ft_calloc(size_t nmemb, size_t size) { void *ptr; size_t m_size; pthread_mutex_lock(&g_lock); if (!nmemb || !size) return (NULL); m_size = size * nmemb; if (m_size <= 0 || m_size / size != nmemb) return (NULL); ptr = ft_malloc(m_size); if (ptr) ft_bzero(ptr, m_size); pthread_mutex_unlock(&g_lock); return (ptr); }
C
// C11 standard // created by cicek on 09.11.2018 00:02 #include <stdio.h> #include <stdlib.h> struct student{ char name[50]; int number; int age; }st2; // mean: struct student st2; // Struct pointer as a function parameter void showStudentData(struct student *st) { printf("\nStudent:\n"); printf("Name: %s\n", st->name); printf("Number: %d\n", st->number); printf("Age: %d\n", st->age); } int main() { // Pointers to Structures struct student st1 = {"Krishna", 5, 21}; showStudentData(&st1); showStudentData(&st2); return 0; }