language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* * aes.c * ߼ܱ׼Advanced Encryption Standard: AESұ׼뼼оԺNIST * 2001꽨˵ݵļܹ淶 * ǶԳƼӽ㷨㷨֮һһַܱ׼ * ÿܿСΪ128λԿΪ128192256λֻECBCBCCFBOFBּģʽ * * Created on: 2019115 * Author: luozhiyong */ #include <rtthread.h> #ifdef TINY_CRYPT_AES #include <tiny_aes.h> #include <stdlib.h> typedef unsigned char uchar; /** * ECBģʽֳƵ뱾ģʽElectronic codebook * ECB򵥵ĿģʽǰݼܿСAESΪ128λֳɿ飬 * ֮ÿʹͬԿܣͬ * * ECBģʽÿݵļǶ˼ܺͽܶԲм㣬 * ECBģʽȱͬĿᱻܳͬĿ飬ַijЩ²ṩϸݱԡ */ void aes_ecb_encrypt(uchar *private_key, uchar *data, uchar *data_encrypt) { tiny_aes_context ctx; tiny_aes_setkey_enc(&ctx, private_key, 128); tiny_aes_crypt_ecb(&ctx, AES_ENCRYPT, data, data_encrypt); } void aes_ecb_decrypt(uchar *private_key, uchar *data_encrypt, uchar *data_decrypt) { tiny_aes_context ctx; tiny_aes_setkey_dec(&ctx, (uchar *) private_key, 128); tiny_aes_crypt_ecb(&ctx, AES_DECRYPT, data_encrypt, data_decrypt); } /** * aes * CBCģʽֳӣCipher-block chaining * CBCģʽÿܵڼǰǰһȻüܡ * һĿһгʼݿ * * AES_cbc_encryptlength16(128λ)IJֻ0䣬16 * ɼܻܺ³ʼIVCBCģʽECBиߵıԣ * ڶÿݿļǰһݿļԼ޷С * ECBһڼǰҪݽ䣬Ǻʺ϶ݽмܡ */ void aes_cbc_encrypt(uchar *iv, uchar *private_key, uchar *data, uchar *data_encrypt) { tiny_aes_context ctx; tiny_aes_setkey_enc(&ctx, private_key, 256); tiny_aes_crypt_cbc(&ctx, AES_ENCRYPT, rt_strlen((const char *)data), iv, data, data_encrypt); } // aes void aes_cbc_decrypt(uchar *iv, uchar *private_key, uchar len, uchar *data_encrypt, uchar *data_decrypt) { tiny_aes_context ctx; tiny_aes_setkey_dec(&ctx, private_key, 256); tiny_aes_crypt_cbc(&ctx, AES_DECRYPT, len, iv, data_encrypt, data_decrypt); } /** * OFBģʽֳģʽOutput feedback * OFBÿԿKeystreamȻٽԿõ * ÿԿٽԿõģ * ĶԳԼܺͽܵȫһġ * * OFBCFBһdzʺ϶ݵļܣOFBڼܺͽܶǰһݣԼܺͽܶܲС */ void aes_cfb_encrypt(int *iv_off, uchar *iv, uchar *private_key, uchar *data, uchar *data_encrypt) { tiny_aes_context ctx; tiny_aes_setkey_enc(&ctx, private_key, 128); tiny_aes_crypt_cfb128(&ctx, AES_ENCRYPT, rt_strlen((const char *)data), iv_off, iv, data, data_encrypt); } // aes void aes_cfb_decrypt(int *iv_off, uchar *iv, uchar *private_key, uchar len, uchar *data_encrypt, uchar *data_decrypt) { tiny_aes_context ctx; tiny_aes_setkey_dec(&ctx, private_key, 128); tiny_aes_crypt_cfb128(&ctx, AES_DECRYPT, len, iv_off, iv, data_encrypt, data_decrypt);} #define TEST_TINY_AES_IV "0123456789ABCDEF" #define TEST_TINY_AES_KEY "0123456789ABCDEF0123456789ABCDEF" void aes_encrypt_test(uchar *data, uchar *data_encrypt) { uchar iv[16 + 1]; uchar private_key[32 + 1]; // uchar data_encrypt[32]; // uchar data_decrypt[32]; /* encrypt */ rt_memcpy(iv, TEST_TINY_AES_IV, rt_strlen(TEST_TINY_AES_IV)); iv[sizeof(iv) - 1] = '\0'; rt_memcpy(private_key, TEST_TINY_AES_KEY, rt_strlen(TEST_TINY_AES_KEY)); private_key[sizeof(private_key) - 1] = '\0'; rt_memset(data_encrypt, 0x0, sizeof(data_encrypt)); aes_cbc_encrypt(iv, private_key, data, data_encrypt); } void aes_decrypt_test(uchar len, uchar *data_encrypt, uchar *data_decrypt) { uchar iv[16 + 1]; uchar private_key[32 + 1]; rt_memcpy(iv, TEST_TINY_AES_IV, rt_strlen(TEST_TINY_AES_IV)); iv[sizeof(iv) - 1] = '\0'; rt_memcpy(private_key, TEST_TINY_AES_KEY, rt_strlen(TEST_TINY_AES_KEY)); private_key[sizeof(private_key) - 1] = '\0'; //rt_memset(data_decrypt, 0x0, sizeof(data_decrypt)); aes_cbc_decrypt(iv, private_key, len, data_encrypt, data_decrypt); } void aes_test() { unsigned char data[] = "1234567890123456"; unsigned char data_encrypt[32] = {0}; unsigned char data_decrypt[32] = {0}; aes_encrypt_test(data, data_encrypt); uchar len = rt_strlen((const char *)data); aes_decrypt_test(len, data_encrypt, data_decrypt); if(rt_memcmp(data, data_decrypt, len) == 0) { rt_kprintf("AES CBC mode passed!\n"); } else { rt_kprintf("AES CBC mode failed!"); } } #endif
C
/** * @file LEDMat.h * @author Hamilton Lee & Zoltan Csaki * @copyright All rights reserved, 2020 * * This file holds definitions for a fully functional driver for * the Adafruit 8x16 Matrix ADAFRUIT 1.2' LED Matrix. * * URL: https://www.adafruit.com/product/2035 * * DRIVER chip: HT16K33 * * @warning This file is offered AS IS and WITHOUT ANY WARRANTY, without * even the implied warranties of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. */ #include "3140_i2c.h" #include "shared_structs.h" #ifndef __LEDMat__ #define __LEDMat__ /*Buffer for the display data on the matrix*/ /* * displayBubber[i] contains which LEDs are on * in row [i]. i even are the left LED backpack. * i odd are the right LED backpack. 0 is on, * 1 is off. */ static uint8_t displayBuffer[16]; static char hello[16] = {0x00, 0x00, 0x00, 0x00, 0xEA, 0xEA, \ 0xAA, 0xAA, 0xEE, 0xAA, 0x2A, 0xAA, \ 0xEA, 0xEA, 0x00, 0x00}; #define LED_addr 0x70 /*I2C address of our LED matrix*/ #define Start_Osc 0x21 /*Command to start oscillator for LED matrix*/ #define HT16K33_BLINK_CMD 0x80 /*Display OFF no blinking*/ #define HT16K33_BLINK_DISPLAYON 0x01 /*OR with HT16K33_BLINK_CMD for display ON no blinking*/ /*OR with HT16K33_BLINK_CMD and HT16K33_DISPLAY_ON to set the blinking frequency*/ #define HT16K33_BLINK_OFF 0 #define HT16K33_BLINK_2HZ 1 #define HT16K33_BLINK_1HZ 2 #define HT16K33_BLINK_HALFHZ 3 /*Brightness values (OR with HT16K33_CMD_BRIGHTNESS to set brightness)*/ #define HT16K33_CMD_BRIGHTNESS 0xE0 #define LOW_MINUS 0x00 #define LOW 0x02 #define LOW_PLUS 0x04 #define MED_MINUS 0x05 #define MED 0x07 #define MED_PLUS 0x09 #define HIGH_MINUS 0x0B #define HIGH 0x0C #define HIGH_PLUS 0x0E /*WARNING: High brightness draws a lot of current make sure you have sufficient source*/ int MatrixBegin(); /* Function to initialize LED matrix*/ int blinkRate(uint8_t b); /*Sets blinkrate for LED Matrix*/ int setBrightness(uint8_t b);/*Sets the brightness of the LED matrix, as specified by 'b'*/ int clearDisplay(void); /*Clears the entire LED display*/ int allOn(void); /*Turns on ALL LEDs on matrix*/ int updateDisplay(void); /*Draws the current buffer*/ void clearBuffer(void); /*Clears the display buffer*/ void setBuffer(uint8_t val, int index); /*Used to manually set buffer*/ void toBuffer(matCol* matrixCol); /*Writes a linked list of columns into the proper buffer format*/ int startUpSequence(void); /*Start of sequence for program*/ #endif
C
/* ** Copyright 2015, Bart Kampers */ #include "MeasurementTable.h" #include <stdlib.h> #include <string.h> #include <math.h> /* ** Private */ #define ENABLED_MASK 0x01 MeasurementTable measurementTables[MAX_MEASUREMENT_TABLES]; int measurementTableCount = 0; Status InitMeasurementTable(MeasurementTable* measurementTable, const char* name, byte columns, byte rows) { Status status = FindTable(name, &(measurementTable->table)); if (status != OK) { status = CreateTable(name, columns, rows, &(measurementTable->table)); } measurementTable->name = name; return status; } Status CalculateIndex(Measurement* measurement, byte bound, byte* index) { if (bound > 1) { if (measurement != NULL) { float value; Status status = GetMeasurementValue(measurement, &value); if (status == OK) { float range = GetMeasurementRange(measurement); int valueIndex = value / (range / bound); *index = (byte) max(0, min(valueIndex, bound - 1)); } return status; } else { return "NoMeasurementConfigured"; } } else if (bound == 1) { *index = 0; return OK; } else { return "InvalidBound"; } } Status GetActualTableControllerField(MeasurementTable* measurementTable, TableField* field) { Status status = CalculateIndex(measurementTable->columnMeasurement, measurementTable->table.columns, &(measurementTable->columnIndex)); if (status == OK) { status = CalculateIndex(measurementTable->rowMeasurement, measurementTable->table.rows, &(measurementTable->rowIndex)); if (status == OK) { status = GetTableField(measurementTable->name, measurementTable->columnIndex, measurementTable->rowIndex, field); } } return status; } /* ** Interface */ Status CreateMeasurementTable(const char* name, const char* columnMeasurementName, const char* rowMeasurementName, byte columns, byte rows, MeasurementTable** measurementTable) { if (measurementTableCount < MAX_MEASUREMENT_TABLES) { Status status; *measurementTable = &(measurementTables[measurementTableCount]); measurementTableCount++; status = InitMeasurementTable(*measurementTable, name, columns, rows); if (status == OK) { if (columnMeasurementName != NULL) { status = FindMeasurement(columnMeasurementName, &((*measurementTable)->columnMeasurement)); } else { (*measurementTable)->columnMeasurement = NULL; } if (status == OK) { if (rowMeasurementName != NULL) { status = FindMeasurement(rowMeasurementName, &((*measurementTable)->rowMeasurement)); } else { (*measurementTable)->rowMeasurement = NULL; } } } (*measurementTable)->precision = 1.0f; (*measurementTable)->minimum = 1.0f; (*measurementTable)->maximum = 100.0f; (*measurementTable)->decimals = 0; (*measurementTable)->columnIndex = 0; (*measurementTable)->rowIndex = 0; return status; } else { return "OutOfTableControllers"; } } int GetMeasurementTableCount() { return measurementTableCount; } Status GetMeasurementTable(int index, MeasurementTable** table) { if ((0 <= index) && (index < measurementTableCount)) { *table = &(measurementTables[index]); return OK; } else { return "InvalidTableIndex"; } } Status FindMeasurementTable(const char* name, MeasurementTable** table) { int i; for (i = 0; i < measurementTableCount; ++i) { if (strcmp(name, measurementTables[i].name) == 0) { *table = &(measurementTables[i]); return OK; } } return "NoSuchMeasurementTable"; } Status GetActualMeasurementTableField(MeasurementTable* measurementTable, float* fieldValue) { TableField field; Status status = GetActualTableControllerField(measurementTable, &field); if (status == OK) { *fieldValue = field * measurementTable->precision; } return status; } Status GetMeasurementTableField(const MeasurementTable* measurementTable, byte column, byte row, float* fieldValue) { TableField field; Status status = GetTableField(measurementTable->name, column, row, &field); if (status == OK) { *fieldValue = field * measurementTable->precision; } return status; } Status SetMeasurementTableField(const char* name, int column, int row, float value) { MeasurementTable* measurementTable; Status status = FindMeasurementTable(name, &measurementTable); if (status == OK) { int field = roundf(value / measurementTable->precision); status = SetTableField(name, column, row, field); } return status; } Status GetMeasurementTableEnabled(const char* name, bool* enabled) { return GetTableFlags(name, ENABLED_MASK, enabled); } Status SetMeasurementTableEnabled(const char* name, bool enabled) { if (enabled) { return SetTableFlags(name, ENABLED_MASK); } else { return ClearTableFlags(name, ENABLED_MASK); } }
C
/* * * refactor using pigpio * *********************************************************************** */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <limits.h> #include <pigpio.h> #include <unistd.h> #include <time.h> int max_timeout = 15000; //15 sec max interrupt timeout uint32_t previous_tick = 0; //used for preventing early retriggers uint32_t pulse_duty_cycle = 30000; //trigger threshold (30ms, avg length of good pulse) uint32_t min_interval; _Bool logging = 0; //set this to 1 to log to file /* ********************************************************************************* * getTimeStamp (updates a byref buffer to a desired dateformat) ********************************************************************************* */ void getTimeStamp(char* buff, size_t buffersize) { time_t t = time(NULL); strftime(buff, buffersize, "%x %X %Z", localtime(&t)); } /* ********************************************************************************* * myInterrupt (triggered every interval once main loop proceeding) ********************************************************************************* */ void myInterrupt(int gpio, int level, uint32_t tick) { FILE * fptr; uint32_t interval_seen = tick - previous_tick; if (interval_seen < min_interval) // if (((tick < previous_tick + min_interval) && (previous_tick + min_interval <= 4294967295) && previous_tick > 0) || ((previous_tick + min_interval > 4294967295) && (tick < previous_tick + min_interval - 4294967296))) { level = 99; } previous_tick = tick; if (logging) { // open up the file (if we're logging) fptr = fopen("/var/log/gpio-pigtest.log", "a"); } //prepare the timestamp (used if we're logging) char tstampbuf[80]; getTimeStamp(tstampbuf, sizeof tstampbuf); switch(level) { case 0: case 1: min_interval = pulse_duty_cycle; printf ("Interrupt\n"); fflush (stdout); if (logging) { fprintf(fptr,"%s: (Tick: %u) Interrupted (Gap: %i usec)\n", tstampbuf, tick, interval_seen); } break; case 2: min_interval = 0; if (logging) { fprintf(fptr,"%s: (Tick: %u) Timeout (Gap: %i usec)\n", tstampbuf, tick, interval_seen); } break; case 99: min_interval = pulse_duty_cycle - interval_seen; //bit buggy if there are multiple false-triggers if (logging) { fprintf(fptr,"%s: (Tick: %u) False Retrigger Skipped (Gap: %i usec)\n", tstampbuf, tick, interval_seen); } break; default: min_interval = 0; if (logging) { fprintf(fptr,"%s: (Tick: %u) Bad Trigger (Gap: %i usec)\n", tstampbuf, tick, interval_seen); } } if (logging) { fclose(fptr); } } /* ********************************************************************************* * main ********************************************************************************* */ int main (void) { FILE * fptr2; min_interval = pulse_duty_cycle; //start off with min_interval equal to a normal pulse duty cycle char tstampbuf[80]; getTimeStamp(tstampbuf, sizeof tstampbuf); puts(tstampbuf); if (logging) { fptr2 = fopen("/var/log/gpio-pigtest.log", "a"); fprintf(fptr2,"%s: New Run!\n", tstampbuf); } if (gpioInitialise() < 0) { // pigpio initialisation failed. if (logging) { fprintf(fptr2,"%s: Pigpio initialisation failed; Quitting!\n", tstampbuf); fclose(fptr2); return 0; } } else { // pigpio initialised okay. if (logging) { fprintf(fptr2,"%s: Pigpio initialisation OK\n", tstampbuf); fclose(fptr2); } gpioSetISRFunc(18, FALLING_EDGE, max_timeout, myInterrupt); } for (;;) { sleep(UINT_MAX); } gpioTerminate(); return 0; }
C
#include<stdio.h> #include<stdlib.h> struct BST{ int data; struct BST *left; struct BST *right; } *temp= NULL, *root = NULL; typedef struct BST NODE; NODE* create(NODE* root ,int info){ if(root == NULL){ temp = (struct BST *)malloc(sizeof(struct BST)); temp->data = info; temp->left = NULL; temp->right = NULL; return temp; } if(info < (root->data)) root->left = create(root->left,info); if(info > (root->data)) root->right = create(root->right,info); return root; } NODE* search( NODE*root ,int info){ if ( root == NULL) printf("Not Found\n"); else if( info < root->data ) search(root->left, info); else if( info > root->data ) search(root->right, info); else printf("Element found "); return root; } NODE* inorder(NODE*root){ if(root!=NULL){ inorder(root->left); printf("%d",root->data); inorder(root->right); } return root; } NODE* preorder(NODE*root){ if(root!=NULL){ printf("%d",root->data); preorder(root->left); preorder(root->right); } return root; } NODE* postorder(NODE*root){ if(root!=NULL){ postorder(root->left); postorder(root->right); printf("%d",root->data); } return root; } int main() { int info , i , ch, n; do{ printf("\n1.)Insert\n2.)Search\n3.)in\n4.)pre\n5.)post\nEnter choice: "); scanf("%d",&ch); switch(ch){ case 1: printf("How many values : \n"); scanf("%d",&n); for( i = 0 ; i < n ; ++i){ scanf("%d",&info); root=create(root,info); } break; case 2: printf("Enter element to search \n"); scanf("%d",&info); search(root,info); break; case 3:inorder(root); break; case 4:preorder(root); break; case 5:postorder(root); break; } }while(ch!=6); return 0; }
C
/* For each of the following pairs of scanf format strings, * indicate whether or not the two strings are equivalent. * If they're not, show how they can be distinguished. * (a) "%d" versus " %d" * (b) "%d-%d-%d" versus "%d -%d -%d" * (c) "%f" versus "%f " * (d) "%f,%f" versus "%f, %f" */ #include <stdio.h> int main(void) { float a, b, c; float x, y, z; /*scanf("%d", &a);*/ /*printf("a1: %d\n", a);*/ /*scanf(" %d", &b);*/ /*printf("a2: %d\n", b);*/ /*scanf("%d-%d-%d", &a, &b, &c);*/ /*printf("b1: %d, %d, %d\n", a, b, c);*/ /*scanf("%d -%d -%d", &x, &y, &z);*/ /*printf("b2: %d, %d, %d\n", x, y, z);*/ /*scanf("%f", &a);*/ /*printf("c1: %f\n", a);*/ /*scanf("%f ", &b);*/ /*printf("c2: %f\n", b);*/ scanf("%f,%f", &a, &b); printf("d1: %f, %f\n", a, b); scanf("%f, %f", &x, &y); printf("d2: %f, %f\n", x, y); return 0; } /* Answer: * (a) No discernible difference. * (b) The first format string doesn't allow blank characters after * the numbers, but the second does. * (c) The 2nd format string causes scanf to search for an additional * non-blank character after the number. * (d) No difference. */
C
#include <stdlib.h> #include <stdio.h> #include "parsing.h" #include <stdbool.h> #include "except.h" #include "assert.h" #include <inttypes.h> #include "bitpack.h" const int UINT32_SIZE = 32; const int BYTE_SIZE = 8; void parsing_test(FILE *input); FILE* getFile(int argc, char *argv[]); int main(int argc, char *argv[]) { FILE *input = getFile(argc, argv); if (input == NULL) return 0; parsing_test(input); if (input == stdin) fclose(input); } /* from the command line, retrieve the file and return pointer to the file */ FILE* getFile(int argc, char *argv[]) { FILE *input; if (argc == 1) { input = stdin; } else if (argc > 1) { return NULL; } else { input = fopen (argv[1], "rb"); } return input; } void parsing_test(FILE *input) { int c, opcode, rA, rB, rC, opcode_13_rA, opcode_13_value; int shift = UINT32_SIZE; uint64_t word = 0; while ((c = getc(input)) != EOF) { if (shift > 0) { shift = shift - BYTE_SIZE; fprintf(stderr, "shift: %d\n", shift); word = Bitpack_newu(word, BYTE_SIZE, shift, (unsigned)c); } if (shift == 0) { shift = UINT32_SIZE; opcode = get_opcode((uint32_t)word); rA = get_rA((uint32_t)word); rB = get_rB((uint32_t)word); rC = get_rC((uint32_t)word); opcode_13_rA = opcode_13_get_rA((uint32_t)word); opcode_13_value = opcode_13_get_value((uint32_t)word); fprintf(stderr, "word: %d\n", (uint32_t)word); fprintf(stderr, "opcode: %d, rA: %d, rB: %d, rC: %d, ", opcode, rA, rB, rC); fprintf(stderr, "opcode_rA: %d, opcode_value: %d\n", opcode_13_rA, opcode_13_value); } } }
C
/* * UniformMovement.c * * Created on: 01.07.2018 * Author: Dominik * Author: Adam */ #include <stdio.h> #include "UniformMovement.h" Weg s(Geschwindigkeit v, Zeit t, Zeit t0) { return v * (t - t0); } Weg uaS(Geschwindigkeit v, Geschwindigkeit v0, Beschleunigung a) { return (v * v - v0 * v0) / (2 * a); } Geschwindigkeit uaV(Beschleunigung a, Zeit t, Zeit t0, Geschwindigkeit v0) { return a * (t - t0) + v0; }
C
/* Copyright (c) 1992 by AT&T Bell Laboratories. */ /* Advanced C++ Programming Styles and Idioms */ /* James O. Coplien */ /* All rights reserved. */ class Stack { public: Stack() { } ~Stack() { } int pop() { return 1; } void push(int) { } }; class CountedStack { public: CountedStack(): rep(new CountedStackRep) { } int pop() { return rep->rep->pop(); } void push(int i) { rep->rep->push(i); } CountedStack(const CountedStack &c) { rep = c.rep; rep->count++; } CountedStack(const Stack &c) { rep = new CountedStackRep(new Stack(c)); } operator Stack() { return *(rep->rep); } ~CountedStack() { if (--rep->count <= 0) delete rep; } CountedStack &operator=(const CountedStack &c) { c.rep->count++; if (--rep->count <= 0) delete rep; rep = c.rep; return *this; } private: struct CountedStackRep { int count; Stack *rep; CountedStackRep(Stack *s = 0) { rep = s? s: new Stack; count = 1; } } *rep; }; int main() { CountedStack a, b; Stack s, t; a = b; b = s; t = b; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> int arraySum(int *ptr, const int n); int main(void) { int values[120] = {3, 7, -9, 3, 6, -1, 7, 9, 1, -5, 8, 1, 5, 5}; printf("The sum is %i\n", arraySum(values, sizeof(values) / sizeof(int))); return 0; } int arraySum(int *ptr, const int n) { int sum = 0; int *const arrayEnd = ptr + n; for (; ptr < arrayEnd; ++ptr) { sum += *ptr; } return sum; }
C
#include "3-calc.h" /** * get_op_func - manage the option * @s: symbol of operator (string) * * Return: int */ int (*get_op_func(char *s))(int, int) { int pos = 0; op_t ops[] = {{"+", op_add}, {"-", op_sub}, {"*", op_mul}, {"/", op_div}, {"%", op_mod}, {NULL, NULL}}; while (ops[pos].op) { if (!(strcmp(ops[pos].op, s))) { return (ops[pos].f); } pos++; } return (NULL); }
C
/* * @Author: obsidian * @Date: 2016-03-05 15:51:29 * @Last Modified by: obsidian * @Last Modified time: 2016-03-10 14:50:18 */ #include "numstr.h" #include "driver/math/inc/math.h" #include "demo.h" #include "lcd_struct.h" #include "lcd_global.h" void num_init(); void num_input(char key); void num_show(unsigned char pos); void int2str(); void float2str_6(); void float2str_3(); void str2float(); void str2int(); struct Num num = { {0}, 0, 0, -1, 0, num_init, num_input, num_show, int2str, float2str_3, float2str_6, str2int, str2float, }; void num_init() { zero(num.numstr, 10); num.dotpos = -1; num.index = 0; } void num_input(char key) { if(num.index > 10) {return;} if(key == 0xb && lcd.p_status->p_item->is_int == 0) { if(num.dotpos >= 0){return;} num.dotpos = num.index; num.numstr[num.index] = '.'; num.index ++; } else if(key == 0xa) { if(num.index > 0){return;} num.numstr[0] = '-'; num.index ++; return; } else if(0 <= key && key < 10) { num.numstr[num.index] = key + '0'; num.index ++; } } void num_show(unsigned char pos) { // LCD_ShowString_BIG(140 + 220 * (pos - 1) * 2 / PAGE_SIZE , 70 + LINE_DIS * (((pos - 1)) % (PAGE_SIZE / 2)), " ", WHITE,1); // LCD_ShowString_BIG(140 + 220 * (pos - 1) * 2 / PAGE_SIZE , 70 + LINE_DIS * (((pos - 1)) % (PAGE_SIZE / 2)), num.numstr, WHITE,1); LCD_ShowString(180, 180 , " ", WHITE,1); LCD_ShowString(180, 180 , num.numstr, WHITE,1); } void int2str() { unsigned char k = 0; unsigned char i = 0; num.init(); unsigned int tmp = num.intvalue; for(k = 9;tmp != 0 && k >= 0; tmp = tmp / 10,k --) {num.numstr[k] = tmp % 10 + '0';num.index ++;} for(i = 0;i < 10;i ++) { num.numstr[i] = num.numstr[i + k + 1]; if(i + k > 8) {num.numstr[i] = ' ';} } num.numstr[i] = 0; if(num.intvalue == 0) { num.numstr[0] = '0'; } } void float2str_3() { signed char k = 0; signed char i = 0; signed char find_nonzero = 0; unsigned char neg = 0; float tmp_1 = num.floatvalue; if(tmp_1 == 0) { num.numstr[0] = '0'; num.numstr[1] = '.'; num.numstr[2] = '0'; num.numstr[3] = 0; return; } if(tmp_1 < 0) { tmp_1 = - tmp_1; neg = 1; } num.init(); float tmp_2 = tmp_1 * 1000; num.intvalue = tmp_2; if(tmp_1 >= 1) { num.int2str(); for(k = num.index; k > num.index - 3;k --) { if(num.numstr[k - 1] != '0'){num.numstr[k] = ' ';find_nonzero = 1;} if(find_nonzero == 0){num.numstr[k] = ' ';continue;} num.numstr[k] = num.numstr[k - 1]; } num.numstr[k] = '.'; if(find_nonzero == 0) { num.numstr[k + 1] = '0'; num.numstr[k + 2] = ' '; num.numstr[k + 3] = ' '; } } else { signed char k = 0; signed char i = 0; signed int tmp = tmp_1 * 1000; for(k = 2;k >= 0; tmp = tmp / 10,k --) {num.numstr[k] = tmp % 10 + '0';} for(k = 3; k > 0;k --) { if(num.numstr[k - 1] != '0'){num.numstr[k + 1] = ' ';find_nonzero = 1;} if(find_nonzero == 0){ num.numstr[k + 1] = ' ';continue;} num.numstr[k + 1] = num.numstr[k - 1]; } num.numstr[0] = '0'; num.numstr[5] = ' '; num.numstr[6] = ' '; num.numstr[k + 1] = '.'; } if(neg == 1) { for(k = 10;k >= 0;k --) { num.numstr[k + 1] = num.numstr[k]; } num.numstr[0] = '-'; } } void float2str_6() { signed char k = 0; signed char i = 0; signed char find_nonzero = 0; char neg = 0; num.init(); float tmp_1 = num.floatvalue; if(tmp_1 == 0) { num.numstr[0] = '0'; num.numstr[1] = '.'; num.numstr[2] = '0'; num.numstr[3] = 0; return; } if(tmp_1 < 0) { tmp_1 = - tmp_1; neg = 1; } float tmp_2 = tmp_1 * 1000000; num.intvalue = tmp_2; if(tmp_1 > 1) { num.int2str(); for(k = num.index; k > num.index - 6;k --) { if(num.numstr[k - 1] != '0'){find_nonzero = 1;} if(find_nonzero == 0){ num.numstr[k] =' ';continue;} num.numstr[k] = num.numstr[k - 1]; } num.numstr[k] = '.'; } else { signed char k = 0; signed char i = 0; signed int tmp = tmp_1 * 1000000; for(k = 5;k >= 0; tmp = tmp / 10,k --) {num.numstr[k] = tmp % 10 + '0';} for(k = 6; k > 0;k --) { if(num.numstr[k - 1] != '0'){find_nonzero = 1;} if(find_nonzero == 0){ num.numstr[k + 1] = ' '; continue;} num.numstr[k + 1] = num.numstr[k - 1]; } num.numstr[0] = '0'; num.numstr[k + 1] = '.'; } if(neg == 1) { for(k = 10;k >= 0;k --) { num.numstr[k + 1] = num.numstr[k]; } num.numstr[0] = '-'; } } void str2int() { signed char k = 0; signed char i = 0; num.intvalue = 0; for(k = 0;k < num.index;k ++) { if(num.numstr[k] == '.'){continue;} if(num.numstr[k] == '-'){continue;} num.intvalue *= 10; num.intvalue += num.numstr[k] - '0'; } num.numstr[num.index] = 0; } void str2float() { signed char k = 0; signed short s = 1; num.floatvalue = 0; if(num.dotpos > 0) { for(k = 0;k < num.index - num.dotpos - 1; k++) {s = s * 10;} } num.str2int(); num.floatvalue = num.intvalue / (float)(s); if(num.numstr[0] == '-'){num.floatvalue = - num.floatvalue;} }
C
#include <Wire.h> struct { char Year; char Month; char Date; char Day; char Hour; char Min; char Sec; char TempYear; char TempMonth; char TempDate; char TempDay; char TempHour; char TempMin; char TempSec; } DS3231_Data; void DS3231_ReadData() { Wire.beginTransmission(0x68); Wire.write(0x00); //Set DS3231 REG Pointer Wire.endTransmission(); Wire.requestFrom(0x68, 7, 0); if (Wire.available() == 7) { DS3231_Data.Sec = Wire.read(); DS3231_Data.Min = Wire.read(); DS3231_Data.Hour = Wire.read(); DS3231_Data.Day = Wire.read(); DS3231_Data.Date = Wire.read(); DS3231_Data.Month = Wire.read(); DS3231_Data.Year = Wire.read(); DS3231_Data.Sec = (DS3231_Data.Sec / 16) * 10 + (DS3231_Data.Sec % 16); DS3231_Data.Min = (DS3231_Data.Min / 16) * 10 + (DS3231_Data.Min % 16); DS3231_Data.Hour = (DS3231_Data.Hour / 16) * 10 + (DS3231_Data.Hour % 16); DS3231_Data.Date = (DS3231_Data.Date / 16) * 10 + (DS3231_Data.Date % 16); } else { //Clear Buffer while (Wire.available()) Wire.read(); } } void DS3231_WriteData() { Wire.beginTransmission(0x68); Wire.write(0x00); //Set DS3231 REG Pointer DS3231_Data.TempSec = (DS3231_Data.TempSec / 10) * 16 + (DS3231_Data.TempSec % 10); DS3231_Data.TempMin = (DS3231_Data.TempMin / 10) * 16 + (DS3231_Data.TempMin % 10); DS3231_Data.TempHour = (DS3231_Data.TempHour / 10) * 16 + (DS3231_Data.TempHour % 10); DS3231_Data.TempDate = (DS3231_Data.TempDate / 10) * 16 + (DS3231_Data.TempDate % 10); Wire.write(DS3231_Data.TempSec); Wire.write(DS3231_Data.TempMin); Wire.write(DS3231_Data.TempHour); Wire.write(DS3231_Data.TempDay); Wire.write(DS3231_Data.TempDate); Wire.write(DS3231_Data.TempMonth); Wire.write(DS3231_Data.TempYear); Wire.endTransmission(); }
C
#include<stdio.h> #include<stdlib.h> struct node{ int info; struct node* link; }; struct node* first; void insert_rear(){ struct node* temp; temp=(struct node*)malloc(sizeof(struct node)); printf("Enter the integer\n"); scanf("%d",&temp->info); temp->link=NULL; if(first==NULL){ first=temp; } else{ struct node* p; p=first; while(p->link!=NULL){ p=p->link; } p->link=temp; } } void insert_front(){ struct node* temp; temp=(struct node*)malloc(sizeof(struct node)); printf("Enter the integer\n"); scanf("%d",&temp->info); temp->link=NULL; if(first==NULL){ first=temp; } else{ temp->link=first; first=temp; } } void insert_loc(){ struct node* temp; struct node* p; int loc,count=1; temp=(struct node*)malloc(sizeof(struct node)); printf("enter the location at which you want to insert\n"); scanf("%d",&loc); printf("Enter the integer\n"); scanf("%d",&temp->info); temp->link=NULL; p=first; while(loc>count){ p=p->link; count+=1; } temp->link=p->link; p->link=temp; } void display(){ struct node* temp; if(first==NULL){ printf("list is empty\n"); } else{ temp=first; while(temp!=NULL){ printf("%d\n",temp->info); temp=temp->link; } } } void main(){ int choice=15; while(choice!=0){ printf("Enter your choice\n 0 Exit\n 1 insert at the end \n 2 insert in the front \n 3 insert at a location \n 4 display the nodes\n"); scanf("%d",&choice); switch(choice){ case 0:{ break; } case 1:{ insert_rear(); break; } case 2:{ insert_front(); break; } case 3:{ insert_loc(); break; } case 4:{ display(); break; } default:{ printf("Wrong choice!\n"); break; } } } }
C
// Take substring of some variable string and give it to another function? // Concatenate two strings and branch on value of the string given that it // matches some other string (both variable and fixed) #include <stdlib.h> #include <stdio.h> #include <string.h> #include <klee/klee.h> #define SIZE 3 char* string_concat(char* front, char* back) { if (!front || !back) { printf("error! please provide valid inputs. \n"); return NULL; } int front_count = strlen(front); int back_count = strlen(back); char* return_val; return_val = malloc(front_count + back_count + 1); if (!return_val) return NULL; char* combined = strcat(front, back); strcpy(return_val, combined); return return_val; } int find_needle_in_haystack(char *hay1, char* hay2, char* needle) { char* haystack = string_concat(hay1, hay2); if (strcmp(needle, haystack) == 0) { return 1; } return 0; } int main() { // char hay1[] = "car"; // char hay2[] = "car"; // char needle[] = "car"; char hay1[SIZE]; char hay2[SIZE]; char needle[] = "car"; klee_make_symbolic(hay1, SIZE, "hay1"); klee_make_symbolic(hay2, SIZE, "hay2"); // assume null-terminated strings klee_assume(hay1[SIZE-1] == '\0'); klee_assume(hay2[SIZE-1] == '\0'); //klee_make_symbolic(needle, SIZE, "needle"); int is_there = find_needle_in_haystack(hay1, hay2, needle); return is_there; }
C
#ifdef _MSC_VER #define _CRT_SECURE_NO_WARNINGS #endif #include <stdlib.h> #include <stdarg.h> #include "lista_nos_internos.h" void imprime_nos_internos(int d, TListaNosInternos *lc) { int i; for (i = 0; i < lc->qtd; i++) { imprime_no_interno(d, lc->lista[i]); } } TListaNosInternos *cria_nos_internos(int d, int qtd, ...) { va_list ap; TListaNosInternos *lc = (TListaNosInternos *) malloc(sizeof(TListaNosInternos)); lc->qtd = qtd; lc->lista = (TNoInterno **) malloc(sizeof(TNoInterno *) * (qtd)); int i; va_start(ap, qtd); for (i = 0; i < qtd; i++) { lc->lista[i] = va_arg(ap, TNoInterno *); } va_end(ap); return lc; } void salva_nos_internos(int d, char *nome_arquivo, TListaNosInternos *lc) { FILE *out = fopen(nome_arquivo, "wb"); int i; for (i = 0; i < lc->qtd; i++) { salva_no_interno(d, lc->lista[i], out); } fclose(out); } TListaNosInternos * le_nos_internos(int d, char *nome_arquivo) { int qtd = 0; TListaNosInternos *lc = (TListaNosInternos *) malloc(sizeof(TListaNosInternos)); FILE *in = fopen(nome_arquivo, "rb"); if (in != NULL) { TNoInterno *no = NULL; while((no = le_no_interno(d, in)) != NULL) { qtd += 1; libera_no_interno(no); } fseek(in, 0, SEEK_SET); lc->qtd = qtd; lc->lista = (TNoInterno **) malloc(sizeof(TNoInterno *) * (qtd)); qtd = 0; while((no = le_no_interno(d, in)) != NULL) { lc->lista[qtd++] = no; } fclose(in); } else { lc->qtd = 0; lc->lista = NULL; } return lc; } int cmp_nos_internos(int d, TListaNosInternos *c1, TListaNosInternos *c2) { if (c1->qtd != c2->qtd) { return 0; } int i; for (i = 0; i < c1->qtd; i++) { if (!cmp_no_interno(d, c1->lista[i], c2->lista[i])) { return 0; } } return 1; } void libera_nos_internos(TListaNosInternos *lc) { int i; for (i = 0; i < lc->qtd; i++) { libera_no_interno(lc->lista[i]); } free(lc->lista); free(lc); }
C
int f(int x) { switch(x) { case 1: x = 2; break; case 2: x = x + 1; default: x = x*2; } return x; }
C
/* Sets and query's used by lightsaber */ set_ignited(int i){ ignited = i; } query_ignited(){ return ignited; } adj_wep_life(int i) { wep_life += i; } set_wep_life(int i){ wep_life = i; } query_wep_life(){ return wep_life; } query_wep_color(){ return wep_color; } set_is_jedi(int i){ is_jedi = i; } query_is_jedi(){ return is_jedi; } set_wep_color(string x){ if(x == "HIR" || x == "red"){ wep_color = HIR; } else if(x == "HIB" || x == "blue"){ wep_color = HIB; } else if(x == "HIG" || x == "green"){ wep_color = HIG; } else if(x == "HIY" || x == "yellow"){ wep_color = HIY; } else if(x == "HIM" || x == "magenta"){ wep_color = HIM; } else if(x == "HIC" || x == "cyan"){ wep_color = HIC; } else{ wep_color = NORM; } Color = x; } set_modtype(string str) { modtype = str; } query_modtype() { if(ATT && ComboAtt != ATT) return 0; tell_object(USER, HIB+"modtype: "+modtype+"\n"+NORM); return modtype; } set_modifier(int x) { modifier = x; } query_modifier() { return modifier; } int set_combo(string str) { int i; string ComboStr; /* This is not ideal, but faster than constantly resizing the array */ combo_status = 1; if(!combo) { combo = ({ "null","null","null","null","null","null","null","null","null","null", }); combo_index = 0; } combo[combo_index] = str; combo_index++; /* point to the next index where we will insert */ /* If we at at index 10, we need to start at the beginning again */ if(combo_index > 9) combo_index = 0; for(i=0, combo_no=0; i < MAX; i++) { if(combo[i] == str) combo_no++; /************ FOR TESTING ONLY ***************/ if(i == 0) ComboStr = combo[i]; else ComboStr += ":" + combo[i]; /*********************************************/ } tell_object(USER, HIR+"combos: "+ComboStr+"\n"+NORM); if(combo_no > 2) return combo_no - 2; else return 0; }
C
// // main.c // Cyborg Project // // Created by Zachary Downing on 2/5/20. // Copyright © 2020 Zachary Downing. All rights reserved. // #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <ctype.h> #include "encode.h" #include "decode.h" #include "utils.h" int encodeMode(const char *inputFile, const char *outputFile) { // char *inputFile = "test2.txt"; // char *outputFile = "out2.txt"; char *buffer; int read = readFile(inputFile, &buffer); if (read == -1) { printf("Failure: error reading file\n"); return -1; } // printf("%s\n", buffer); int len = (int) strlen(buffer); int *counts = (int*)calloc(len,sizeof(int)); int unique = getCounts(buffer, len, counts); // printf("Number unique: %d\n", unique); double entropy = getEntropy(counts, len, unique); printf("Entropy: %f\n", entropy); int codeLen = getCodeLength(counts, len, unique); printf("Optimal compressed size: %d\n", codeLen); char* encoded = runLengthEncode(buffer, len); // printf("Encoded: %s\n", encoded); int write = writeFile(outputFile, encoded); if (write == -1) { printf("Failure: error writing file\n"); return -1; } return 0; } int decodeMode(const char *inputFile, const char *outputFile) { // char *inputFile = "out2.txt"; // char *outputFile = "decoded2.txt"; char *buffer; int read = readFile(inputFile, &buffer); int len = (int) strlen(buffer); if (read == -1) { printf("Failure: error reading file\n"); return -1; } // printf("Encoded: %s\n", buffer); char *decoded = runLengthDecode(buffer, len); // printf("Decoded: %s\n", decoded); if (decoded == NULL) { printf("Failure: error occured in runLengthDecode func\n"); return -1; } int write = writeFile(outputFile, decoded); if (write == -1) { printf("Failure: error writing to file\n"); return -1; } return 0; } int main(int argc, const char * argv[]) { if (argc != 4) { printf("Failure: invalid number of arguments\n"); return -1; } const char *inputFile = argv[1]; const char *outputFile = argv[2]; int mode = atoi(argv[3]); printf("%d", mode); int ret = -1; if (mode == ENCODE_MODE) { printf("Running in encode mode\n"); ret = encodeMode(inputFile, outputFile); } else if (mode == DECODE_MODE) { printf("Running in decode mode\n"); ret = decodeMode(inputFile, outputFile); } else { printf("Invalid mode\n"); return -1; } if (ret == 0) { printf("Successful run\n"); return ret; } else { printf("Unsucessful run\n"); return ret; } }
C
#include "header.h" unsigned int clearBits(unsigned int parkingRow, int n) { for (int i = 0; i < n; i++) { parkingRow &= ~(1 << i); } return (parkingRow); }
C
/*Joo Vitor Moura Int. programao, turma 01 Item 07 Lista 5 */ #include <stdio.h> float Media_aritmetica(float,float,float); float Media_ponderada(float,float,float); float Media_harmonica(float,float,float); int main(){ int opcao; float nota1, nota2, nota3, media; printf("O programa clacula 3 tipos de media: aritmetica, ponderada e harmonica.\n"); printf("Digite as 3 notas cuja media deseja calcular:\n");//O usurio entra com as notas scanf("%f %f %f", &nota1, &nota2, &nota3); printf("Agora:\nDigite 1 para media aritmetica\nDigite 2 para media ponderada\nDigite 3 para media harmonica:\n");//O Usurio entra com a opo de media scanf("%d", &opcao); (opcao==1)?printf("A media aritmetica eh: %.2f\n", Media_aritmetica(nota1,nota2,nota3)):(opcao==2)?printf("A media ponderada eh: %.2f\n", Media_ponderada(nota1,nota2,nota3)):printf("A media harmonica eh: %.2f\n", Media_harmonica(nota1,nota2,nota3));//A media eh impressa de a cordo com a opo escolhida return 0; } float Media_aritmetica(float nota, float Nota, float NOTA){//Funo que calcula a mdia aritmtica float media; media=(nota+Nota+NOTA)/3; return media; } float Media_ponderada(float nota, float Nota, float NOTA){//Funo que calcula a mdia ponderada float media; media=(3*nota+3*Nota+4*NOTA)/10; return media; } float Media_harmonica(float nota, float Nota, float NOTA){//Funo que calcula a mdia harmnica float media; media=3/((1/nota)+(1/Nota)+(1/NOTA)); return media; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_lstmap.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gmorros <gmorros@student.21-school.ru> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/05/01 11:59:34 by gmorros #+# #+# */ /* Updated: 2020/10/14 16:58:30 by gmorros ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include <stdlib.h> static t_list *ft_clear(t_list **lst, void (*del)(void *)) { ft_lstclear(lst, del); return (NULL); } t_list *ft_lstmap(t_list *lst, void *(*f)(void *), void (*del)(void *)) { t_list *tmp; t_list *new; new = (t_list *)malloc(sizeof(t_list)); if (new && f && lst) { tmp = new; while (lst) { tmp->content = f(lst->content); if (lst->next) { tmp->next = (t_list *)malloc(sizeof(t_list)); if (!(tmp->next)) return (ft_clear(&new, del)); } else tmp->next = NULL; tmp = tmp->next; lst = lst->next; } return (new); } return (NULL); }
C
#include<stdio.h> void main() { int b,h; float area; scanf("%d %d",&b,&h); area=0.5*b*h; printf("\n AREA=%f",area); }
C
//******************************************************************* // FIRST NAME: Angad Pal // LAST NAME: Dhanoa // kernel.c // Phase 0, Prep 4, Timer Event Handling //******************************************************************* #include <spede/flames.h> // some SPEDE stuff that helps... #include <spede/machine/asmacros.h> #include <spede/machine/io.h> #include <spede/machine/pic.h> #include <spede/machine/proc_reg.h> #include <spede/machine/seg.h> #include <spede/stdio.h> #define TIMER_EVENT 32 // timer interrupt event code #define PIC_MASK_REG 0x21 // I/O loc # of PIC mask #define PIC_MASK_VAL ~0x01 // mask code for PIC #define PIC_CONT_REG 0x20 // I/O loc # of PIc control #define TIMER_SERVED_VAL 0x60 // control code sent to PIC #define VGA_MASK_VAL 0x0f00 // bold face, white on black // prototype a void-return void-argument TimerEntry function: void TimerEntry(void); unsigned int time_count = 0; unsigned short *center_pos = (unsigned short *)0xb8000 + 12 * 80 + 40; struct i386_gate *idt; // interrupt descriptor table //Program a C function 'void TimerService(void)' void TimerService(void) { //first, notify PIC the event is served: outportb(PIC_CONT_REG, TIMER_SERVED_VAL); outportb(PIC_CONT_REG, TIMER_SERVED_VAL); //upcount time_count by 1 time_count+=1; /*as each second arrives: print/erase initials of your name on the center of the *screen, so it gives the effect of flashing out the initials at the rate of 2Hz *(i.e., 1 second on, 1 second off, see demo run), use time_count, center_pos and *VGA_MASK_VAL to achieve this */ if(time_count == 100) //When the time_count == 100 we will show the message. { //I have AP as my first name's initials. *(center_pos-1) = 'A' + VGA_MASK_VAL; *(center_pos) = 'P' + VGA_MASK_VAL; //This makes P in the center, and A and D on the outside. *(center_pos+1) = 'D' + VGA_MASK_VAL; } else if(time_count == 200) { *(center_pos-1) = ' ' + VGA_MASK_VAL; *(center_pos) = ' ' + VGA_MASK_VAL; *(center_pos+1) = ' ' + VGA_MASK_VAL; time_count = 0; } return; } //Program a C function 'int main(void)' int main(void) { //declare local char 'ch' char ch; //set 'idt' to the return of 'get_idt_base()' call idt = get_idt_base(); //set an entry in idt to handle future events of timer interrupts: fill_gate(&idt[TIMER_EVENT], (int)TimerEntry, get_cs(), ACC_INTR_GATE, 0); //send PIC_MASK_VAL to PIC_MASK_REG using outportb() call like above outportb(PIC_MASK_REG, PIC_MASK_VAL); //enable the CPU to handle interrupts using inline assembly macro: 'asm("sti");' asm("sti"); //perform an infinite loop that repeats: while(1) { //check the keyboard of the target PC, if it has just been pressed: if(cons_kbhit()) //Read the key being pressed into ch. { ch = cons_getchar(); cons_printf( "\nYou Pressed %c.\n", ch ); //Show the message onto target PC about the key being pressed. if(ch == 'x' || ch == 'X') //If 'X' or 'x' are pressed, terminate the program. { cons_printf( "Goodbye." ); break; } else { cons_printf( "%c does not Terminate me.\n", ch); } } } return 0; }
C
#include "variadic_functions.h" #include <stdio.h> #include <stdlib.h> #include <stdarg.h> /** *print_strings - prints a string *@separator: string to be printed between numbers *@n: number of integers passed to the function *Return: always 0 **/ void print_strings(const char *separator, const unsigned int n, ...) { va_list(arg); unsigned int i; char *string; if (separator == '\0') separator = ""; va_start(arg, n); for (i = 0; i < n; i++) { string = va_arg(arg, char *); /*pointer to the string*/ if (i >= (n - 1)) separator = ""; if (string == NULL) printf("(nil)%s", separator); else printf("%s%s", string, separator); } printf("\n"); va_end(arg); }
C
#include "main.h" // No borrar bool _mas_de_mitad(int *arr, size_t inicio, size_t fin, size_t n, int *contador) { if (*contador > n / 2) return true; int elem = arr[inicio]; while (inicio <= fin) { if (elem == arr[inicio]) *contador++; inicio++; } size_t medio = (inicio + fin) / 2; return _mas_de_mitad(arr, inicio, medio, (medio - inicio) + 1, &contador) && _mas_de_mitad(arr, medio, fin, (fin - medio) + 1, &contador); } bool mas_de_mitad(int* arr, size_t n) { if (n == 1) return true; int *contador = 0; return _mas_de_mitad(arr, 0, n-1, n, &contador); }
C
#pragma once #include <GL/glew.h> /************************ERROR HANDLING************************/ /* A backslash allows you to define a macro over multiple lines. */ /* If the x which is parsed into ASSERT() returns false, a debug break will occur which stops the process of the program and shows us where the error is. Only works in Debug mode (F5 not Ctrl + F5). */ #define ASSERT(x) \ if (!(x)) \ __debugbreak(); /* If there is an error, call GLLogCall() (see Renderer.cpp) Surround every OpenGL function with GLCall(). */ #define GLCall(x) GLClearError();\ x;\ ASSERT(GLLogCall(#x, __FILE__, __LINE__)) void GLClearError(); bool GLLogCall(const char* function, const char* file, int line);
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #define COMMON_DIVISOR "1011" char xor(char a, char b); char* divide(char* dividend, char* divisor); char* encode(char* data); void decode(char* data); void main() { char data[7]; printf("Enter 4-bit data : "); scanf("%s", data); printf("Data to send : %s\n", encode(data)); printf("Data to recieve : "); scanf("%s", data); decode(data); } char xor(char a, char b) { return (a==b)? '0' : '1'; } char* divide(char* dividend, char* divisor) { char rem[4]; char *zeros = "0000"; int i; while(strlen(dividend) >= strlen(divisor)) { if( dividend[0] == '1') strcpy(rem, divisor); else strcpy(rem, zeros); for(i = 0; i < strlen(rem); i++) dividend[i] = xor(dividend[i], rem[i]); dividend++; } return dividend; } char* encode(char* data) { char initialData[7]; sprintf(initialData, "%s000", data); char* checksum = divide(initialData, COMMON_DIVISOR); static char encodedData[7]; sprintf(encodedData, "%s%s", data, checksum); return encodedData; } void decode(char* data) { char* checksum = divide(data, COMMON_DIVISOR); if(strcmp(checksum, "000") == 0) printf("Error-free\n"); else printf("Error detected\n"); }
C
/* ********************************* * Using typedef with struct * ******************************** */ #include <stdio.h> #include <string.h> int main() { struct person { char name[50]; int iq; }; struct person me; strcpy(me.name,"George Calin"); me.iq=100; printf("%s has an IQ of %d. \n",me.name,me.iq); return (0); }
C
#include <stdio.h> #include <stdlib.h> #define m 2 #define n 3 int main() { int i,j,k,(*m1)[n],(*m2)[m],a[m][n],b[n][m],sum=0; m1=a; m2=b; printf("Enter first matrix:\n"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { scanf("%d",(*(m1+i)+j)); } } printf("Enter second matrix:\n"); for(i=0;i<n;i++) { for(j=0;j<m;j++) { scanf("%d",(*(m2+i)+j)); } } printf("The product matrix is:\n"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { for(k=0;k<n;k++) sum+=*(*(m1+i)+k)**(*(m2+k)+j); printf("%d\t",sum); sum=0; } printf("\n"); } return 0; }
C
/* * https://www.geeksforgeeks.org/array-rotation/ * * Program for array rotation * * Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements. * Input = 1,2,3,4,5,6,7 * Rotation of the above array by 2 will make array * Output = 3,4,5,6,7,1,2 */ #include <stdio.h> #include <stdlib.h> void rotate(int *array, int d, int n) { int *temp = NULL; int i = 0; int j = 0; temp = (int *)malloc(sizeof(int) * d); if(temp == NULL) { printf("Memory allocatoion failed\n"); return; } for(i=0;i<d;i++) { temp[i] = array[i]; } for(i=0,j=d;j<n;i++,j++) { array[i] = array[j]; } for(j=0;i<n;i++,j++) { array[i] = temp[j]; } if(temp != NULL) free(temp); } void print(int *array, int n) { int i = 0; for(i=0;i<n;i++) { printf("Index %d = %d\n",i,array[i]); } } int main(int argc, char *arg[]) { int input[] = {1,2,3,4,5,6,7}; rotate(input, 2, sizeof(input)/sizeof(int)); print(input, sizeof(input)/sizeof(int)); }
C
// // countWord.c // Pointer // // Created by Harun Öz on 11/26/18. // Copyright © 2018 Harun Öz. All rights reserved. // #include <stdio.h> int countWord(char * s1){ int count=0; int len=strlen(s1); if(isalnum(*s1)){ count=1; } for(int j=1; j<len;j++){ if(isalnum(*(s1+j)) && !(isalnum(*(s1+j-1)))){ count++; } } return count; }
C
#include <stdio.h> #define BOUND 1000000 #define SQUARES_CACHE_SIZE 1000 #define PRIMES_SIZE 1000000 int primes[PRIMES_SIZE]; int num_primes = 0; int squares_cache[SQUARES_CACHE_SIZE]; int sum_cache[PRIMES_SIZE]; int max_sequence = 6; int max_prime = 41; int squares(int n) { if (squares_cache[n] == 0) squares_cache[n] = n*n; return squares_cache[n]; } int is_prime(int n) { int i = 2; while (squares(i) <= n) { if (n%i == 0) return 0; i++; } return 1; } void find_primes() { int n = 3; int i = 1; primes[0] = 2; while (n < BOUND) { if (is_prime(n)) { primes[i] = n; i++; } n += 2; } num_primes = i; } void add_primes() { int i; sum_cache[0] = 2; for (i = 0; i < PRIMES_SIZE-1; i++) sum_cache[i+1] = sum_cache[i]+primes[i+1]; } inline int get_sum(int start, int end) { int *p; if (start == 0) return sum_cache[end]; return sum_cache[end]-sum_cache[start-1]; } int find_longest_sequence(int n, int bound) { int i, j; int sum; int max = 0; for (i = 0; primes[i] < bound; i++) { sum = 0; j = 1; while (sum < n) { sum = get_sum(i, j); j++; } if (sum == n) if (max < j-i) max = j-i; } return max; } void init() { int i, j; for (i = 0; i < SQUARES_CACHE_SIZE; i++) squares_cache[i] = 0; find_primes(); add_primes(); } int main() { int i; int sequence; init(); for (i = 0; i < num_primes; i++) { sequence = find_longest_sequence(primes[i], primes[i]/max_sequence); if (max_sequence < sequence) { max_sequence = sequence; max_prime = primes[i]; } } printf("Result: %d\n", max_prime); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <strings.h> #include <conio.h> #include <ctype.h> #include "funciones.h" int main() { EMovie* peliculas; FILE* pFile; EMovie* aux; int validacion = 0; int cont=0; char seguir='s'; int opcion=0; int* contador=&cont; int bajaPelicula; peliculas=malloc(sizeof(EMovie)*15); if(peliculas==NULL) { printf("No se encontro espacio"); exit(1); } pFile=fopen("Peliculas.dat", "rb"); if(pFile==NULL) { pFile=fopen("Peliculas.dat", "wb"); if(pFile==NULL) { printf("Error en la carga del archivo"); exit(1); } validacion=1; } if(validacion==0) { fread(contador,sizeof(int),1,pFile); while(!feof(pFile)) { fread(peliculas,sizeof(EMovie),*contador,pFile); } } fclose(pFile); while(seguir=='s') { if(cont>14) { aux=(EMovie*)realloc(peliculas,45*sizeof(EMovie)); if(aux==NULL) { exit(1); } else { peliculas=aux; } } printf("1- Agregar pelicula\n"); printf("2- Borrar pelicula\n"); printf("3- Modificar pelicula\n"); printf("4- Guardar datos en archivo\n"); printf("5- Generar pagina web\n"); printf("6- Salir\n"); scanf("%d",&opcion); switch(opcion) { case 1: cont++; alta(cont,peliculas); break; case 2: bajaPelicula=baja(cont,peliculas); if(bajaPelicula==1) { cont--; } break; case 3: modificacion(cont,peliculas); break; case 4: moverDatosAlArchivo(cont,peliculas,contador); break; case 5: crearPaginaWeb(cont,peliculas,contador); break; case 6: seguir = 'n'; break; default: printf("La opcion ingresada no es correcta\n"); break; } } return 0; }
C
#include <stdio.h> int main() { char kadi[20], pass[20]; tekrar: printf("Username: "); scanf("%s", &kadi); printf("Password: "); scanf("%s", &pass); if (strcmp(kadi, "admin") == 0 && strcmp(pass, "12345") == 0) { printf("Giris Basarili!"); } else { printf("Hatali Giris\n"); goto tekrar; } }
C
/** @file * Implements Grover's algorithm for unstructured search, * using only X, H and multi-controlled Z gates * * Compile and run from within the build folder, using: cmake .. -DUSER_SOURCE=../examples/grovers_search.c \ -DOUTPUT_EXE=grovers make ./grovers * * * @author Tyson Jones */ #include <stdio.h> #include <math.h> #include <time.h> #include <stdlib.h> #include "QuEST.h" /* effect |solElem> -> -|solElem> via a * multi-controlled phase flip gate */ void applyOracle(Qureg qureg, int numQubits, int solElem) { // apply X to transform |111> into |solElem> for (int q=0; q<numQubits; q++) if (((solElem >> q) & 1) == 0) pauliX(qureg, q); // effect |111> -> -|111> int ctrls[numQubits]; for (int q=0; q<numQubits; q++) ctrls[q] = q; multiControlledPhaseFlip(qureg, ctrls, numQubits); // apply X to transform |solElem> into |111> for (int q=0; q<numQubits; q++) if (((solElem >> q) & 1) == 0) pauliX(qureg, q); } /* apply 2|+><+|-I by transforming into the Hadamard basis * and effecting 2|0><0|-I. We do this, by observing that * c..cZ = diag{1,..,1,-1} * = I - 2|1..1><1..1| * and hence * X..X c..cZ X..X = I - 2|0..0><0..0| * which differs from the desired 2|0><0|-I state only by * the irrelevant global phase pi */ void applyDiffuser(Qureg qureg, int numQubits) { // apply H to transform |+> into |0> for (int q=0; q<numQubits; q++) hadamard(qureg, q); // apply X to transform |11..1> into |00..0> for (int q=0; q<numQubits; q++) pauliX(qureg, q); // effect |11..1> -> -|11..1> int ctrls[numQubits]; for (int q=0; q<numQubits; q++) ctrls[q] = q; multiControlledPhaseFlip(qureg, ctrls, numQubits); // apply X to transform |00..0> into |11..1> for (int q=0; q<numQubits; q++) pauliX(qureg, q); // apply H to transform |0> into |+> for (int q=0; q<numQubits; q++) hadamard(qureg, q); } int main() { // prepare the hardware-agnostic QuEST environment QuESTEnv env = createQuESTEnv(); // choose the system size int numQubits = 15; int numElems = (int) pow(2, numQubits); int numReps = ceil(M_PI/4 * sqrt(numElems)); printf("numQubits: %d, numElems: %d, numReps: %d\n", numQubits, numElems, numReps); // randomly choose the element for which to search srand(time(NULL)); int solElem = rand() % numElems; // prepare |+> Qureg qureg = createQureg(numQubits, env); initPlusState(qureg); // apply Grover's algorithm for (int r=0; r<numReps; r++) { applyOracle(qureg, numQubits, solElem); applyDiffuser(qureg, numQubits); // monitor the probability of the solution state printf("prob of solution |%d> = " REAL_STRING_FORMAT "\n", solElem, getProbAmp(qureg, solElem)); } // free memory destroyQureg(qureg, env); destroyQuESTEnv(env); return 0; }
C
#include <stdio.h> #include <cs50.h> #include <string.h> #include <ctype.h> #include <math.h> int count_letters(string text); /* function for counting letters*/ int count_words(string text); /* function for counting words*/ int count_sentences(string text); /* function for counting sentences*/; int main(void) { float l; /* variable for letters*/ float s; /* variable for sentences*/ float w; /* variable for words*/ int index; /*variable for index*/ string text = get_string("Text: "); /* prompt the user for text*/ l = count_letters(text); /*get letters count*/ s = count_sentences(text); /* get sentences count*/ w = count_words(text); /* get words count*/ index = round(0.0588 * (100 * l / w) - 0.296 * (100 * s / w) - 15.8); if (index < 1) { printf("Before Grade 1\n"); } else if (index > 16) { printf("Grade 16+\n"); } else { printf("Grade %i\n", index); /*print out the grade index*/ } } int count_letters(string text) { int letter_count = 0; /* variable for letter count*/ int letter_count_counter = 0; /* counter to go through the text*/ while (text[letter_count_counter] != '\0') { if (islower(text[letter_count_counter]) || isupper(text[letter_count_counter])) /* check whether it is alphabet*/ { letter_count++; /*increase the count*/ } letter_count_counter++; /*increase the array count*/ } return letter_count; /*return the letter count*/ } int count_words(string text) { int word_count = 0; /* variable for storing the word count*/ int word_count_counter = 0; /* counter to go thru the text*/ while (text[word_count_counter] != '\0') { if (isspace(text[word_count_counter])) /* check whether it is a space*/ { word_count++; /*increase the count*/ } word_count_counter++; /*increase the array count*/ } word_count++; /* there is no space for the last word, so +1*/ return word_count; /*return the word count*/ } int count_sentences(string text) { int sentence_count = 0; /* variable for sentence count*/ int sentence_count_counter = 0; /* counter to go thru the text*/ while (text[sentence_count_counter] != '\0') { if (text[sentence_count_counter] == '.' || text[sentence_count_counter] == '!' || text[sentence_count_counter] == '?') /* check for punctuation*/ { sentence_count++; /*increment the sentence count*/ } sentence_count_counter++; /* increase the array counter*/ } return sentence_count; /*return the sentence count*/ }
C
#include<stdio.h> main() { // Integar int x = 7; // declaration and initialization int y = 8; // declaration and initialization int z = 9; // declaration and initialization // single output printf("The Number Is Equal to %d \n", x); // multiple output printf("X = %d \t Y = %d \t Z = %d \n", x, y, z); // Float float xx = 7.123; // declaration and initialization float yy = 8.22; // declaration and initialization float zz = 9; // declaration and initialization // single output printf("The Number Is Equal to %f \n", xx); // specific decimals printf("The Number Is Equal to %0.1f \n", xx); // multiple output printf("XX = %f \t YY = %f \t ZZ = %f \n", xx, yy, zz); // Double float xxx = 7.123; // declaration and initialization float yyy = 8.22; // declaration and initialization float zzz = 9; // // declaration and initialization // single output printf("The Number Is Equal to %lf \n", xxx); // multiple output printf("XXX = %lf \t YYY = %lf \t ZZX = %lf", xxx, yyy, zzz); }
C
#include<stdio.h> #include<conio.h> void main() { int i,a,b,x,y; clrscr(); printf("\n enter the numbers "); scanf("%d%d",&a,&b); x=a*b; for(i=0;i<(x/2);i++) { y=i*i; } if(y==x) printf("\nyes "); else printf("\n NO "); }
C
#include<stdlib.h> #include<stdio.h> #include<string.h> #include<time.h> #include "chtbl.h" int list_dest_elm(void *key, void *data); char* list_print_elm(void *key, void *data); int vstrcmp(void *key1, void *key2); int chtbl_init(CHTbl *htbl, int buckets, unsigned long (*h)(const void *key), int (*match)(const void *key1, const void *key2), void (*destroy)(void *key)) { int i; if((htbl->table = (List *)malloc(buckets*sizeof(List))) == NULL) return -1; htbl->buckets = buckets; for(i = 0; i < htbl->buckets; ++i) list_init(&htbl->table[i], list_dest_elm, NULL, list_print_elm); htbl->h = h; htbl->destroy = destroy; htbl->match = match; htbl->size = 0; return 0; } int chtbl_insert(CHTbl **htbl, const void *key, const void *data) { int error_code; int bucket; if(chtbl_lookup(*htbl, (void *)key, (void **) &data) == 0) return 1; bucket = (*htbl)->h(key) % (*htbl)->buckets; if((error_code = list_append(&((*htbl)->table[bucket]), (const void*)key, (const void*)data)) == 0) (*htbl)->size++; if((((float)(*htbl)->size)/((float)(*htbl)->buckets)) > 1) { if(((*htbl)->table = realloc((*htbl)->table, sizeof(List)*((*htbl)->buckets)*2)) == NULL) return -1; error_code = rehash(*htbl); } return error_code; } int chtbl_lookup(CHTbl *htbl, void *key, void **data) { ListElmt *element; int bucket; bucket = htbl->h(key)%htbl->buckets; for(element = list_head(&htbl->table[bucket]); element != NULL; element = list_next(element)) { if(!htbl->match(key, list_key(element))) { *data = list_data(element); return 0; } } return -1; } /* int vstrcmp(void *key, void *key2) { return (strcmp((char *) key, (char *) key2)); } */
C
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <cilk/cilk.h> int main(int argc, char * argv[]) { int n = (argc > 1 ) ? atoi(argv[1]) : 1000; double * x = malloc(n*sizeof(double)); assert(x!=NULL); double * y = malloc(n*sizeof(double)); assert(y!=NULL); for (int i=0; i<n; i++) { x[i] = (double)i; } for (int i=0; i<n; i++) { y[i] = (double)(-i); } cilk_for (int i=0; i<n; i++) { y[i] += x[i]; } for (int i=0; i<n; i++) { printf("y[%d] = %lf\n", i, y[i]); } free(y); free(x); return 0; }
C
#include <stdio.h> #include "func.h" extern fbscr_t fb_v; int fb_one_pixel(int x, int y, u32_t color) { *((u32_t *)fb_v.memo + x + y*fb_v.w) = color; return 0; } int square(int x, int y, int len, u32_t color) { int i = 0; int j = 0; for(j=0; j<len; j++) { for(i=0; i<len; i++) { fb_one_pixel(x+i, y+j, color); } } return 0; }
C
/* ************************************************************************** */ /* */ /* :::::::: */ /* exec_create_files.c :+: :+: */ /* +:+ */ /* By: mavan-he <mavan-he@student.codam.nl> +#+ */ /* +#+ */ /* Created: 2019/08/06 16:16:21 by mavan-he #+# #+# */ /* Updated: 2019/11/05 15:30:46 by jbrinksm ######## odam.nl */ /* */ /* ************************************************************************** */ #include "vsh.h" static int check_if_directory(char *file) { struct stat statbuf; if (stat(file, &statbuf) == 0) { if (S_ISDIR(statbuf.st_mode)) { ft_eprintf(E_ISDIR, file); g_state->exit_code = EXIT_FAILURE; return (FUNCT_ERROR); } } return (FUNCT_SUCCESS); } static int check_if_valid_file(char *file) { int fd; fd = open(file, O_RDONLY | O_CREAT | O_NONBLOCK, REG_PERM); if (fd == -1) { ft_eprintf(E_FAIL_OPEN_P, file); g_state->exit_code = EXIT_FAILURE; return (FUNCT_ERROR); } close(fd); return (FUNCT_SUCCESS); } static int find_files(t_ast *ast) { char *file; if (ast == NULL) return (FUNCT_FAILURE); if (find_files(ast->left) == FUNCT_ERROR) return (FUNCT_ERROR); if (ast->type == DGREAT || ast->type == SGREAT) { if (ast->right->type == IO_NUMBER) file = ast->right->left->value; else file = ast->right->value; if (check_if_valid_file(file) == FUNCT_ERROR) return (FUNCT_ERROR); if (check_if_directory(file) == FUNCT_ERROR) return (FUNCT_ERROR); } return (FUNCT_SUCCESS); } int exec_create_files(t_ast *ast) { if (find_files(ast) == FUNCT_ERROR) return (FUNCT_ERROR); return (FUNCT_SUCCESS); }
C
/** boot.h ====== Header file relative to boot information **/ #ifndef BOOT_H #define BOOT_H /** Includes -------- - define.h - types.h **/ #include <define.h> #include <types.h> /** Constants: types of memory in a memory map ------------------------------------------- **/ #define BOOT_AVAILABLE 0x1 #define BOOT_RESERVED 0x2 #define BOOT_ACPI 0x3 #define BOOT_ACPI_NVS 0x4 /** Structure: struct boot_info --------------------------- Structure containing information retrieved during boot and architecture dependant setup Members are: - mods_count : Number of boot modules - mods_addr : Boot modules list address - mmap_length : Number of memory map entries - mmap_addr : Memory map address - bitmap : Physical pages bitmap - bitmap_size : Bitmap size - vm_stack : Kernel virtual pages stack - vm_stack_size : Stack size - start : First available byte after kernel **/ PUBLIC struct boot_info { u32_t mods_count; addr_t mods_addr; u32_t mmap_length; addr_t mmap_addr; addr_t bitmap; size_t bitmap_size; addr_t vm_stack; size_t vm_stack_size; addr_t start; }__attribute__((packed)); /** Structure: struct boot_mmap_entry -------------------------------------- Item in a memory map. Members are self explanatory. **/ PUBLIC struct boot_mmap_entry { u32_t size; u64_t addr; u64_t len; u32_t type; }__attribute__((packed)); /** Structure: struct boot_mod_entry ------------------------------------- Item in the modules list provided by bootloader Members are: - start : Address of the first byte - end : Ending address - cmdline : Command line (module arguments or parameters) - pad : Padding to keep things aligned **/ PUBLIC struct boot_mod_entry { addr_t start; addr_t end; u32_t cmdline; u32_t pad; }__attribute__((packed)); /** Global: boot ------------ **/ struct boot_info boot; #endif
C
#include <stdio.h> #include <stdlib.h> #define TAM 2 void mostrarAlumnos(int leg[], int age[], char sex[], int n1[], int n2[], float prom[], int tam); void mostrarAlumno(int leg, int age, char sex, int n1, int n2, float prom); int main() { char sexos[TAM]; int legajos[TAM]; int edades[TAM]; int nota1[TAM]; int nota2[TAM]; float promedio[TAM]; for(int i = 0; i< TAM; i++) { printf("Ingrese legajo: "); fflush(stdin); scanf("%d", &legajos[i]); printf("Ingrese edad: "); fflush(stdin); scanf("%d", &edades[i]); printf("Ingrese sexo: "); fflush(stdin); scanf("%c", &sexos[i]); printf("Ingrese nota primer parcial: "); fflush(stdin); scanf("%d", &nota1[i]); printf("Ingrese nota segundo parcial: "); fflush(stdin); scanf("%d", &nota2[i]); promedio[i] = (float) (nota1[i] + nota2[i]) / 2; } mostrarAlumnos(legajos, edades, sexos, nota1, nota2, promedio, TAM); return 0; } void mostrarAlumnos(int leg[], int age[], char sex[], int n1[], int n2[], float prom[], int tam) { printf("\nLegajo Edad Sexo Nota1 Nota2 Promedio\n"); for(int i = 0; i< tam; i++) { mostrarAlumno(leg[i], age[i], sex[i], n1[i], n2[i], prom[i]); } printf("\n\n"); } void mostrarAlumno(int leg, int age, char sex, int n1, int n2, float prom){ printf(" %d %d %c %d %d %.2f\n", leg, age, sex, n1, n2, prom); }
C
/* * main.c * * Created: 3/10/2021 9:56:16 AM * Author: rik vos */ #include <avr/io.h> #include <util/delay.h> #include <avr/interrupt.h> #define BIT(x) (1 << (x)) int enabled = 0; ISR(INT0_vect){ enabled = !enabled; } // wait(): busy waiting for 'ms' millisecond // Used library: util/delay.h void wait( int ms ) { for (int tms=0; tms<ms; tms++) { _delay_ms( 1 ); // library function (max 30 ms at 8MHz) } } // Initialize ADC: 10-bits (left justified), free running void adcInit( void ) { ADMUX = 0b01100001; // AREF=VCC, result left adjusted, channel1 at pin PF1 ADCSRA = 0b11100110; // ADC-enable, no interrupt, start, free running, division by 64 } // Main program: ADC at PF1 int main( void ) { DDRD = 0x00; // set PORTD for input DDRF = 0x00; // set PORTF for input (ADC) DDRA = 0xFF; // set PORTA for output DDRB = 0xFF; // set PORTB for output adcInit(); // initialize ADC EICRA |= 0x0B; // INT1 falling edge, INT0 rising edge EIMSK |= 0x03; // Enable INT1 & INT0 // Enable global interrupt system //SREG = 0x80; // Of direct via SREG of via wrapper sei(); while (1) { if(enabled){ PORTB = ADCL; // Show MSB/LSB (bit 10:0) of ADC PORTA = ADCH; enabled = !enabled; } wait(100); // every 100 ms (busy waiting) } }
C
#include <stdio.h> #include <cs50.h> int main(void) { long number = get_long("Number: ");; int counter = 0; long sumOfOdd = 0; long sumOfEven = 0; long first = 0; long second = 0; while (number > 0) { second = first; first = number % 10; if (counter % 2 == 0) { // Even places digits sumOfEven += first; } else { long mul = 2 * first; sumOfOdd = sumOfOdd + mul / 10 + mul % 10; } number = number / 10; counter++; } bool isValid = (sumOfEven + sumOfOdd) % 10 == 0; long firstTwoDigits = (first * 10) + second; if (isValid && first == 4 && counter >= 13 && counter <= 16) { printf("VISA\n"); } else if (isValid && (firstTwoDigits == 34 || firstTwoDigits == 37)) { printf("AMEX\n"); } else if (isValid && (firstTwoDigits == 51 || firstTwoDigits == 52 || firstTwoDigits == 53 || firstTwoDigits == 54 || firstTwoDigits == 55)) { printf("MASTERCARD\n"); } else { printf("INVALID\n"); } }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <signal.h> struct pw_element { int len; const char *str; int flags; }; /* * Flags for the pw_element */ #define CONSONANT 0x0001 #define VOWEL 0x0002 #define DIPTHONG 0x0004 #define NOT_FIRST 0x0008 #define DIGIT 0x0010 #define FIRST 0x0020 #define UPPERS 0x8000 /* * Flags for the pwgen function */ #define PW_DIGITS 0x0001 /* At least one digit */ #define PW_UPPERS 0x0002 /* At least one upper letter */ #define PW_SYMBOLS 0x0004 #define PW_AMBIGUOUS 0x0008 #define PW_NO_VOWELS 0x0010 #define PW_NO_DIPTHONG_VOWEL 0x0020 static int global_print = 0; static int64_t global_count = 0; static char* global_buffer[11] = {0}; static int global_size = 5; static int global_index = -1; static int global_print_all = 0; void pw_process(int pw_length, int deny_flags, int prev, int first, int feature_flags); #define strcpy(a, b) *(a) = (b) inline void process_digits(int pw_length, int deny_flags, int prev, int first, int feature_flags) { int i; int next_deny_flags = 0; static char* digit[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", 0 }; if( deny_flags & DIGIT || first) return; feature_flags &= ~PW_DIGITS; for(i = 0; digit[i]; ++i){ strcpy(global_buffer + global_index, digit[i]); pw_process(pw_length + 1, next_deny_flags, DIGIT, 1, feature_flags); } } inline void process_vowels(int pw_length, int deny_flags, int prev, int first, int feature_flags) { int i; int next_deny_flags = 0; static char* vowel[] = { "a", "e", "i", "o", "u", 0 }; if( deny_flags & VOWEL ) return; if( prev & VOWEL ) next_deny_flags |= VOWEL; if( first ) next_deny_flags |= DIGIT; for(i = 0; vowel[i]; ++i){ strcpy(global_buffer + global_index, vowel[i]); pw_process(pw_length + 1, next_deny_flags, VOWEL, 0, feature_flags); } } inline void process_vowels_upper(int pw_length, int deny_flags, int prev, int first, int feature_flags) { int i; int next_deny_flags = 0; static char* vowel_upper[] = { "A", "E", "I", "O", "U", 0 }; if( deny_flags & VOWEL ) return; if( first == 0 ) return; else next_deny_flags |= DIGIT; if( prev & VOWEL ) next_deny_flags |= VOWEL; feature_flags &= ~PW_UPPERS; for(i = 0; vowel_upper[i]; ++i){ strcpy(global_buffer + global_index, vowel_upper[i]); pw_process(pw_length + 1, next_deny_flags, VOWEL, 0, feature_flags); } } inline void process_vowels_dipthong(int pw_length, int deny_flags, int prev, int first, int feature_flags) { int i; int next_deny_flags = VOWEL; static char* vowel_dipthong[] = { "ah", "oh"/*, "ae", "ai", "ee", "ei", "ie", "oo" */, 0 }; if( prev & VOWEL ) return; if( deny_flags & (VOWEL | DIPTHONG) ) return; if( first ) next_deny_flags |= DIGIT; for(i = 0; vowel_dipthong[i]; ++i){ strcpy(global_buffer + global_index, vowel_dipthong[i]); pw_process(pw_length + 2, next_deny_flags, VOWEL | DIPTHONG, 0, feature_flags); } } inline void process_vowels_dipthong_upper(int pw_length, int deny_flags, int prev, int first, int feature_flags) { int i; int next_deny_flags = VOWEL; static char* vowel_dipthong_upper[] = { "Ah", "Oh"/*, "Ae", "Ai", "Ee", "Ei", "Ie", "Oo" */, 0 }; if( prev & VOWEL ) return; if( deny_flags & (VOWEL | DIPTHONG) ) return; if( first == 0 ) return; else next_deny_flags |= DIGIT; feature_flags &= ~PW_UPPERS; for(i = 0; vowel_dipthong_upper[i]; ++i){ strcpy(global_buffer + global_index, vowel_dipthong_upper[i]); pw_process(pw_length + 2, next_deny_flags, VOWEL | DIPTHONG, 0, feature_flags); } } inline void process_consonants(int pw_length, int deny_flags, int prev, int first, int feature_flags) { int i; int next_deny_flags = CONSONANT; static char* consonant[] = { "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "r", "s", "t", "v", "w", "x", "y", "z", 0 }; if( deny_flags & CONSONANT ) return; if( first ) next_deny_flags |= DIGIT; for(i = 0; consonant[i]; ++i){ strcpy(global_buffer + global_index, consonant[i]); pw_process(pw_length + 1, next_deny_flags, CONSONANT, 0, feature_flags); } } inline void process_consonants_upper(int pw_length, int deny_flags, int prev, int first, int feature_flags) { int i; int next_deny_flags = CONSONANT; static char* consonant_upper[] = { "B", "C", "D", "F", "G", "H", "J", "K", "L", "M", "N", "P", "R", "S", "T", "V", "W", "X", "Y", "Z", 0 }; if( deny_flags & CONSONANT ) return; if( first ) next_deny_flags |= DIGIT; feature_flags &= ~PW_UPPERS; for(i = 0; consonant_upper[i]; ++i){ strcpy(global_buffer + global_index, consonant_upper[i]); pw_process(pw_length + 1, next_deny_flags, CONSONANT, 0, feature_flags); } } inline void process_consonants_dipthong(int pw_length, int deny_flags, int prev, int first, int feature_flags) { int i; int next_deny_flags = CONSONANT; static char* consonant_dipthong[] = { "ch", "gh", "ng", "ph", "qu", "sh", "th", 0 }; if( (deny_flags & (CONSONANT | DIPTHONG)) || first ) return; for(i = 0; consonant_dipthong[i]; ++i){ strcpy(global_buffer + global_index, consonant_dipthong[i]); pw_process(pw_length + 2, next_deny_flags, CONSONANT | DIPTHONG, 0, feature_flags); } } inline void process_consonants_dipthong_upper(int pw_length, int deny_flags, int prev, int first, int feature_flags) { int i; int next_deny_flags = CONSONANT; static char* consonant_dipthong_upper[] = { "Ch", "Gh", "Ng", "Ph", "Qu", "Sh", "Th", 0 }; if( (deny_flags & (CONSONANT | DIPTHONG)) || first ) return; feature_flags &= ~PW_UPPERS; for(i = 0; consonant_dipthong_upper[i]; ++i){ strcpy(global_buffer + global_index, consonant_dipthong_upper[i]); pw_process(pw_length + 2, next_deny_flags, CONSONANT | DIPTHONG, 0, feature_flags); } } inline void process_at_first_consonants_dipthong(int pw_length, int deny_flags, int prev, int first, int feature_flags) { int i; int next_deny_flags = CONSONANT | DIGIT; static char* at_first_consonant_dipthong[] = { "ch", "ph", "qu", "sh", "th", 0 }; if( (deny_flags & DIPTHONG) || first == 0 ) return; for(i = 0; at_first_consonant_dipthong[i]; ++i){ strcpy(global_buffer + global_index, at_first_consonant_dipthong[i]); pw_process(pw_length + 2, next_deny_flags, CONSONANT | DIPTHONG, 0, feature_flags); } } inline void process_at_first_consonants_dipthong_upper(int pw_length, int deny_flags, int prev, int first, int feature_flags) { int i; int next_deny_flags = CONSONANT | DIGIT; static char* at_first_consonant_dipthong_upper[] = { "Ch", "Ph", "Qu", "Sh", "Th", 0 }; if( (deny_flags & DIPTHONG) || first == 0 ) return; feature_flags &= ~PW_UPPERS; for(i = 0; at_first_consonant_dipthong_upper[i]; ++i){ strcpy(global_buffer + global_index, at_first_consonant_dipthong_upper[i]); pw_process(pw_length + 2, next_deny_flags, CONSONANT | DIPTHONG, 0, feature_flags); } } #define ALL_PARAM pw_length, deny_flags, prev, first, feature_flags void pw_process(int pw_length, int deny_flags, int prev, int first, int feature_flags) { /* Time to print */ if( pw_length == global_size ){ /* At least one upper and one digit */ if( (feature_flags & (PW_DIGITS | PW_UPPERS)) == 0 ){ if( global_print ){ int i; char password[11] = ""; if( global_print_all == 0 ){ global_print = 0; printf("%lld ",global_count); } for(i = 0; i <= global_index; ++i) strcat(password, global_buffer[i]); puts(password); } global_count++; return; } return; } if( pw_length == global_size - 1 ){ deny_flags |= DIPTHONG; if( (feature_flags & PW_UPPERS) && ((feature_flags & PW_DIGITS) || (prev & CONSONANT)) ) return; if( feature_flags & PW_DIGITS ) deny_flags |= VOWEL | CONSONANT; } global_index++; process_vowels(ALL_PARAM); process_vowels_upper(ALL_PARAM); process_vowels_dipthong(ALL_PARAM); process_vowels_dipthong_upper(ALL_PARAM); process_consonants(ALL_PARAM); process_consonants_upper(ALL_PARAM); process_consonants_dipthong(ALL_PARAM); process_consonants_dipthong_upper(ALL_PARAM); process_at_first_consonants_dipthong_upper(ALL_PARAM); process_at_first_consonants_dipthong(ALL_PARAM); process_digits(ALL_PARAM); global_index--; } void pw_phonemes(int pw_flags) { pw_process(0, 0, 0, 1, pw_flags); } void print_current_pwd(int a) { global_print = 1; } int main(int argc, char *argv[]) { global_print = 1; if( argc >= 2 ) global_size = atoi(argv[1]); if( argc >= 3 ) global_print_all = 1; signal(SIGUSR1, print_current_pwd); pw_phonemes(PW_UPPERS | PW_DIGITS); fprintf(stderr, "%lld pwd generated\n", global_count); return 0; }
C
/** * Copyright (C) 2017-2019 Jakob Riedle <riedle@validas.de>, Validas AG * * This file is part of the ForeC++ Target Framework. * * All Rights reserved. Unauthorized copying of this file via any medium * is strictly prohibited. Proprietary and confidential. */ #ifndef _TARGET_UNITTEST_UTILITY_BIGFLOAT_COMPARISON_H_ #define _TARGET_UNITTEST_UTILITY_BIGFLOAT_COMPARISON_H_ #include <target/c/bigfloat/predefines.h> /** Define isless for multiprecision floating point type */ UTT_LINKAGE bool utt_islessm( const utt_bigfloat_t left , const utt_bigfloat_t right ) { if( utt_isnanm(left) || utt_isnanm(right) ) return false; bool sbl = utt_signbitm(left); if( sbl != utt_signbitm(right) ) return sbl; /* Compute first byte difference, excluding the signbit */ int difference = ( left.data[0] & 0x7F ) - ( right.data[0] & 0x7F ); /* Difference in first byte? */ if( !difference ) difference = utt_memcmp( (char*)&left + 1 , (char*)&right + 1 , sizeof(utt_bigfloat_t) - 1 ); return sbl ? difference > 0 : difference < 0; } #endif
C
/* Combustivel */ #include <stdio.h> int main (void) { float litros; int quilometragem, horas,distancia; scanf("%d", &horas); scanf("%d", &quilometragem); distancia = quilometragem * horas; litros = distancia / 12.0; printf("%.3f\n", litros); return 0; }
C
#include <stdio.h> int main (void) { //Faz um comentário com / /*Faz outro comentário, mas precisa terminar no final do texto e pode ter várias linhas*/ printf ("comida\n boa.\n"); // "/n" pula linha return 0; }
C
#include <unistd.h> int main(){ if((write(1, "Welcome to System Programming", 27)) != 27) write(2, "A write error has occurred on file descriptor 1\n", 47); exit(0); }
C
#include <stdio.h> extern int sum(int a, int b); int main() { int a = 10, b = 2; int c = sum(a, b); printf("This is 'C'\n"); printf("result = %d\n", c); return 0; }
C
/************************************************************************* > File Name : alloc.c > Author : lirongwei > Mail : a2413044193@gmail.com > Created Time : 2020/07/08 11:00:41 ************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int *p = (int *)calloc(10, sizeof(int)); for (int i = 0; i < 10; i++) { printf("%d\n", p[i]); } free(p); return 0; } int main1(int argc, char **argv) { // 基本数据类型在栈和堆上 int a = 100; printf("a=%d\n", a); int *p = (int *)malloc(1 * sizeof(int)); *p = 100; printf("*p=%d\n", *p); // printf("sizeof(int)=%ld\n", sizeof(int)); // printf("sizeof(int*)=%ld\n", sizeof(int*)); // 数组类型在栈和堆上 int arr[10]; int *pa = (int *)malloc(10 * sizeof(int)); // memset(pa, 0, 10*sizeof(int)); memset(pa, 1, 10 * sizeof(int)); for (int i = 0; i < 10; i++) { printf("%d\n", pa[i]); } return 0; }
C
#include <stdio.h> int main(void) { int a; for(a = 1; a < 21; a= a + 2){ if(a != 5){ if (a != 11){ if(a !=15){ printf("%d \n",a); } } } } return 0; }
C
#include "graph.h" t_graph *init_graph(size_t size) { t_graph *graph; t_lst **arr; graph = (t_graph *)malloc(sizeof(t_graph)); check_malloc(graph); arr = (t_lst **)malloc(sizeof(t_lst *) * size); check_malloc(arr); for(size_t i = 0; i < size; i++) { arr[i] = NULL; } graph->arr = arr; graph->V = size; return (graph); } void graph_destroy(t_graph *graph, size_t size) { for(size_t i = 0; i < size; i++) destroy_list(&graph->arr[i]); free(graph->arr); free(graph); } int is_edge(t_graph *graph, int src, int end) { t_lst *edges; edges = graph->arr[src]; while (edges) { if (edges->data == end) { return (1); } edges = edges->next; } return (0); } void add_edge(t_graph *graph, int src, int end) { t_lst **arr; if (src >= 0 && src <= graph->V && end >= 0 && end <= graph->V && !is_edge(graph, src, end)) { arr = graph->arr; push_front(&arr[src], end); push_front(&arr[end], src); } } int vertex_count(t_graph *graph) { return (graph->V); } int edge_count(t_graph *graph) { int count; count = 0; for (int i = 0; i < graph->V; i++) { count = count + count_list(graph->arr[i]); } return (count / 2); }
C
#include <stdio.h> #include <winpr/crt.h> #include <winpr/path.h> #include <winpr/tchar.h> #include <winpr/winpr.h> static const TCHAR testExtDot[] = _T(".exe"); static const TCHAR testExtNoDot[] = _T("exe"); static const TCHAR testPathNoExtension[] = _T("C:\\Windows\\System32\\cmd"); static const TCHAR testPathExtension[] = _T("C:\\Windows\\System32\\cmd.exe"); int TestPathCchAddExtension(int argc, char* argv[]) { HRESULT status; TCHAR Path[PATHCCH_MAX_CCH]; /* Path: no extension, Extension: dot */ _tcscpy(Path, testPathNoExtension); status = PathCchAddExtension(Path, PATHCCH_MAX_CCH, testExtDot); if (status != S_OK) { _tprintf(_T("PathCchAddExtension status: 0x%08X\n"), status); return -1; } if (_tcscmp(Path, testPathExtension) != 0) { _tprintf(_T("Path Mismatch: Actual: %s, Expected: %s\n"), Path, testPathExtension); return -1; } /* Path: no extension, Extension: no dot */ _tcscpy(Path, testPathNoExtension); status = PathCchAddExtension(Path, PATHCCH_MAX_CCH, testExtNoDot); if (status != S_OK) { _tprintf(_T("PathCchAddExtension status: 0x%08X\n"), status); return -1; } if (_tcscmp(Path, testPathExtension) != 0) { _tprintf(_T("Path Mismatch: Actual: %s, Expected: %s\n"), Path, testPathExtension); return -1; } /* Path: extension, Extension: dot */ _tcscpy(Path, testPathExtension); status = PathCchAddExtension(Path, PATHCCH_MAX_CCH, testExtDot); if (status != S_FALSE) { _tprintf(_T("PathCchAddExtension status: 0x%08X\n"), status); return -1; } if (_tcscmp(Path, testPathExtension) != 0) { _tprintf(_T("Path Mismatch: Actual: %s, Expected: %s\n"), Path, testPathExtension); return -1; } /* Path: extension, Extension: no dot */ _tcscpy(Path, testPathExtension); status = PathCchAddExtension(Path, PATHCCH_MAX_CCH, testExtDot); if (status != S_FALSE) { _tprintf(_T("PathCchAddExtension status: 0x%08X\n"), status); return -1; } if (_tcscmp(Path, testPathExtension) != 0) { _tprintf(_T("Path Mismatch: Actual: %s, Expected: %s\n"), Path, testPathExtension); return -1; } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int n; char v[6]; scanf("%d ", &n); while(n!=0) { gets(v); if(strlen(v)>=5) { printf("3\n"); } else { if((v[0]='o' && (v[1]=='n' || v[2]=='e')) || (v[1]='n' && (v[0]=='o' || v[2]=='e')) || (v[2]='e' && (v[0]=='o' || v[1]=='n'))) { printf("1\n"); } else printf("2\n"); } n--; } return 0; }
C
#include<stdio.h> #include<string.h> void main() { char s[20],s2[20]; printf("enter the strings:\n"); scanf("%s\n%s",&s,&s2); strcat(s,s2); printf("%s",s); }
C
/* *************************************************************************** Name: Max N. Philip Student Number: 836472 Login ID: mphilip1 Program written by Max Philip for Assignment 2 of Computer Systems (COMP20023) Semester 1, 2018. C program that reads in a CSV file of paths to TLS certificate files and the URL from which the certificate belongs. The program then steps through each line of the CSV file, loads the specified certificate and validates it, also checking the following URL. For every line, the program writes to another CSV file, keeping the same input columns and adding a "valid" column with the value 1 if the certificate is valid and 0 if it is invalid. The code provided in the Assignment git repository was used as a basis for this program, primarily for initially reading the certificates and extracting certificate extensions. Repo URL: https://gitlab.eng.unimelb.edu.au/COMP30023/Assignment2.git **************************************************************************** */ #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/bio.h> #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/evp.h> #include <stdio.h> #include <string.h> #include <time.h> /* ************************************************************************* */ // field values #define COMMON_NAME_EQ "CN=" #define BASIC_CON_F "CA:FALSE" #define KEY_USAGE "TLS Web Server Authentication" #define BYTE_BITS 8 #define MIN_RSA_LEN 2048 #define BUF_SIZE 256 #define LARG_BUF 1024 // characters #define NULL_BYTE '\0' #define COMMA "," #define F_SLASH "/" #define FULL_STOP "." #define COMMA_SPACE ", " #define STRP_NEWLINE "\r\n" #define WILD "*" // numbers #define DNS_OFFSET 4 #define CA_OFFSET 3 #define SPACE_OFFSET 1 /* ************************************************************************* */ /* FUNCTION PROTOTYPES */ const char * get_extension(X509_EXTENSION *ex); int check_key_usage(X509_EXTENSION *ex_key); int check_alt_name(X509_EXTENSION *ex, char *out_url); int check_basic_constraints(X509_EXTENSION *ex); int domain_validation(char *url, char *common_name); void string_slice(char *my_str, char *buf, int start, int end); const char * get_domain(X509 cert); char * shift_string_left(char *my_str); int check_date(X509 cert); int get_rsa_bits(X509 cert); int pass_all_checks(int date, int rsa_bits, int domain, int basic_con, int alt_name, int key_usage); /* ************************************************************************* */ /* FUNCTION DEFINITIONS */ int main(int argc, char **argv) { /* Initialise openSSL */ OpenSSL_add_all_algorithms(); ERR_load_BIO_strings(); ERR_load_crypto_strings(); /* Read in the CSV from command line input */ FILE *file = fopen(argv[1], "r"); char *line; char *cert_path, *url; char buffer[LARG_BUF]; /* Initialise the output CSV file */ FILE *output_file; output_file = fopen("output.csv", "w+"); if (!file) { fprintf(stderr, "Error in loading certificate"); exit(EXIT_FAILURE); } /* Read the CSV file line by line */ while ((line = fgets(buffer, sizeof(buffer), file)) != NULL) { cert_path = strtok(line, COMMA); url = strtok(NULL, COMMA); /* Strip trailing newline at the end of the URL */ url[strcspn(url, STRP_NEWLINE)] = 0; char out_url[BUF_SIZE], out_path[BUF_SIZE]; strcpy(out_url, url); strcpy(out_path, cert_path); BIO *certificate_bio = NULL; X509 *cert = NULL; /* Create BIO object to read certificate */ certificate_bio = BIO_new(BIO_s_file()); /* Read certificate into BIO */ if (!(BIO_read_filename(certificate_bio, cert_path))) { fprintf(stderr, "Error in reading cert BIO filename"); exit(EXIT_FAILURE); } if (!(cert = PEM_read_bio_X509(certificate_bio, NULL, 0, NULL))) { fprintf(stderr, "Error in loading certificate"); exit(EXIT_FAILURE); } /* Begin validation checks */ /* Validates the Not Before and Not After dates */ int date = check_date(*cert); /* RSA bits */ int rsa_bits = get_rsa_bits(*cert); /* Validates whether the domain name is in the Common name*/ char common_name[BUF_SIZE]; strcpy(common_name, get_domain(*cert)); int valid_domain = domain_validation(url, common_name); /* Validate whether the URL is present in the certificate's alternate names */ X509_EXTENSION *ex_alt = X509_get_ext(cert, X509_get_ext_by_NID(cert, NID_subject_alt_name, -1)); int alt_name_valid = check_alt_name(ex_alt, out_url); /* Validate the certificate's BasicConstraints (CA:FALSE)*/ X509_EXTENSION *ex_basic_con = X509_get_ext(cert, X509_get_ext_by_NID(cert, NID_basic_constraints, -1)); int valid_basic_con = check_basic_constraints(ex_basic_con); /* Checks if "TLS Web Server Authentication" is in the certificate's Enhanced Key Usage */ X509_EXTENSION *ex_key = X509_get_ext(cert, X509_get_ext_by_NID(cert, NID_ext_key_usage, -1)); int valid_key_usage = check_key_usage(ex_key); /* Using all the previous validations, check whether the certificate passes the required tests */ int passed_all = pass_all_checks(date, rsa_bits, valid_domain, valid_basic_con, alt_name_valid, valid_key_usage); /* Write the two input values, and whether the certificate is valid, to the output CSV file */ fprintf(output_file, "%s,%s,%d\n", out_path, out_url, passed_all); X509_free(cert); BIO_free_all(certificate_bio); } fclose(output_file); exit(0); } /* Helper function that gets the X509 extension. Returns the extension as a string */ const char * get_extension(X509_EXTENSION *ex) { ASN1_OBJECT *obj = X509_EXTENSION_get_object(ex); char buff[LARG_BUF]; OBJ_obj2txt(buff, LARG_BUF, obj, 0); BUF_MEM *bptr = NULL; char *buf = NULL; if (strlen(buff) > 0) { BIO *bio = BIO_new(BIO_s_mem()); if (!X509V3_EXT_print(bio, ex, 0, 0)) { fprintf(stderr, "Error in reading extensions"); } BIO_flush(bio); BIO_get_mem_ptr(bio, &bptr); //bptr->data is not NULL terminated - add null character buf = (char *)malloc((bptr->length + 1) * sizeof(char)); memcpy(buf, bptr->data, bptr->length); buf[bptr->length] = NULL_BYTE; } return buf; } /* Validate whether the Enhanced Key Usage contains the "TLS Web Server Authentication" string. */ int check_key_usage(X509_EXTENSION *ex_key) { char key_usages[BUF_SIZE], *usage, key_nospace[BUF_SIZE], temp[BUF_SIZE]; strcpy(key_usages, get_extension(ex_key)); usage = strtok(key_usages, COMMA); /* If the correct key usage is the only one existing in the certificate, then immediately validate */ if (strcmp(usage, KEY_USAGE) == 0) { return 1; } /* Tokenize the rest of the string if there are more */ while(usage != NULL) { usage = strtok(NULL, ","); if (usage) { strcpy(temp, usage); string_slice(temp, key_nospace, SPACE_OFFSET, strlen(temp)); /* Return 1 if any of the following usages are correct */ if (strcmp(key_nospace, KEY_USAGE) == 0) { return 1; } } } return 0; } /* Check if the input URL matches any certificate Subject Alternative Name (SAN) extensions, including wildcards */ int check_alt_name(X509_EXTENSION *ex, char *out_url) { char alt_names[BUF_SIZE], alt_names_strip[BUF_SIZE], test_name[BUF_SIZE]; char *name, name_strip[BUF_SIZE], *strp_alts[BUF_SIZE]; int i=0; if (get_extension(ex)){ /* Strip the "DNS:" prefix from the first SAN, if it exists */ strcpy(alt_names, get_extension(ex)); string_slice(alt_names, alt_names_strip, DNS_OFFSET, strlen(alt_names)); /* Tokenize the string containing all the alternate names by ",". Then store each stripped name in an array */ name = strtok(alt_names_strip, COMMA); strp_alts[i] = name; while(name != NULL) { name = strtok(NULL, COMMA_SPACE); if (name){ /* Strip the "DNS:" prefix from each SAN */ strcpy(test_name, name); string_slice(test_name, name_strip, DNS_OFFSET, strlen(name)); i++; strp_alts[i] = strdup(name_strip); } } /* Validate each SAN, and return 1 if any of the names are valid */ for (int j=0; j <= i; j++){ if (domain_validation(out_url, strp_alts[j])){ return 1; } } } return 0; } /* Validates whether BasicConstraints include the "CA:FALSE" string */ int check_basic_constraints(X509_EXTENSION *ex) { char basic_constraints[BUF_SIZE]; strcpy(basic_constraints, get_extension(ex)); if (strcmp(basic_constraints, BASIC_CON_F) == 0) { return 1; } return 0; } /* Validates the domain name based on the certificate's common names only. SAN checking is done elsewhere. Returns 1 if the certificate is valid */ int domain_validation(char *url, char *common_name) { /* Immediately validate if the common name and domain name are the same */ if (strcmp(url, common_name) == 0) { return 1; } char t_url[BUF_SIZE], t_com_name[BUF_SIZE]; char *dom2_in, *dom3_in; char * dom1_out, *dom2_out, *dom3_out; strcpy(t_url, url); strcpy(t_com_name, common_name); /* Tokenize the input URL, and common name being checked, by "." char. */ strtok(t_url, FULL_STOP); dom2_in = strtok(NULL, FULL_STOP); dom3_in = strtok(NULL, FULL_STOP); dom1_out = strtok(t_com_name, FULL_STOP); dom2_out = strtok(NULL, FULL_STOP); dom3_out = strtok(NULL, FULL_STOP); /* Check if the common name in the certificate is a wildcard */ if (strcmp(dom1_out, WILD) == 0) { if (strcmp(dom2_in, dom2_out) == 0 && strcmp(dom3_in, dom3_out) == 0) { return 1; } } return 0; } /* Get the common names from the certificate, stripping the "CA=" prefix */ const char * get_domain(X509 cert) { char cn[100], *token, *domain; char eq[8]; /* Tokenize the common name by "/", separating each of the common names */ strcpy(cn, (&cert)->name); token = strtok(cn, F_SLASH); while(token != NULL) { /* Strip the "CA=" from each string */ string_slice(token, eq, 0, CA_OFFSET); if (strcmp(eq, COMMON_NAME_EQ) == 0) { domain = malloc(LARG_BUF); string_slice(token, domain, CA_OFFSET, strlen(token)); break; } token = strtok(NULL, F_SLASH); } return domain; } /* Helper function that slices an input string from a start and end position, assigning the new string to another input string */ void string_slice(char *my_str, char *new_str, int start, int end) { int i=0, j=0; for (i = start; i < end; i++) { new_str[j] = my_str[i]; j++; } new_str[j] = NULL_BYTE; } /* Check whether the key length for RSA is at least 2048 bits. */ int get_rsa_bits(X509 cert) { EVP_PKEY *pub_key = X509_get_pubkey(&cert); RSA *rsa_key = EVP_PKEY_get1_RSA(pub_key); int k_len = RSA_size(rsa_key); RSA_free(rsa_key); /* Return 1 if the key length is long enough */ if (k_len*BYTE_BITS >= MIN_RSA_LEN) { return 1; } return 0; } /* Check whether the Not Before (Issue) and Not After (Expiration) dates are valid. Return 1 if both are valid, otherwise return 0. */ int check_date(X509 cert) { const ASN1_TIME *issue_date = X509_get_notBefore(&cert); const ASN1_TIME *exp_date = X509_get_notAfter(&cert); int days, secs; int is_valid = 1; /* If the Not After date is after the current date, then invalid. If the Not Before date is before the current date, then invalid. */ if (!ASN1_TIME_diff(&days, &secs, NULL, exp_date)) { is_valid = 0; } if (days < 0 || secs < 0) { is_valid = 0; } if (!ASN1_TIME_diff(&days, &secs, NULL, issue_date)) { is_valid = 0; } if (days > 0 || secs > 0) { is_valid = 0; } return is_valid; } /* Checks that the certificate is valid with all the tested criteria */ int pass_all_checks(int date, int rsa_bits, int domain, int basic_con, int alt_name, int key_usage) { /* All checks must be true, except for domain, which only needs either the domain or SAN to be valid*/ if (date && rsa_bits && (domain || alt_name) && basic_con && key_usage) { return 1; } else { return 0; } }
C
#include <stdio.h> #include <stdlib.h> #include <mpi.h> int main( int argc, char**argv) { MPI_Init(&argc,&argv); const int N = 20; int *array[N]; int *new_array[N]; for (int i=0;i<N;i++) { array[i] = malloc(sizeof(int)); new_array[i] = malloc(sizeof(int)); } for (int i=0;i<N;i++) { *array[i] = i; *new_array[i] = 0; } int world_size; MPI_Comm_size(MPI_COMM_WORLD, &world_size); int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); int loop_length = N/world_size; /*MPI_Request *reqs[2*N]; for (int i=0;i<2*N;i++) { reqs[i]= malloc(sizeof(int)); } */ MPI_Request request = MPI_REQUEST_NULL; if (rank==0) { MPI_Irecv(&new_array[0], 1, MPI_INT, world_size-1, 11, MPI_COMM_WORLD, &request); for (int i=1; i<loop_length; i++) { *new_array[i] = *array[i-1]; } MPI_Isend(&array[loop_length -1], 1, MPI_INT, 1, 11, MPI_COMM_WORLD, &request); //MPI_Isend(&buffer, count, MPI_INT, destination, tag, MPI_COMM_WORLD, &request); } if ((rank % (world_size-1)) != 0) { MPI_Irecv(&new_array[rank*loop_length], 1, MPI_INT, rank-1, 11, MPI_COMM_WORLD, &request); for (int i=rank*loop_length; i<(rank*loop_length)+loop_length-1; i++) { *new_array[i] = *array[i-1]; } MPI_Isend(&array[loop_length*rank + 1], 1, MPI_INT, rank+1, 11, MPI_COMM_WORLD, &request); } if (rank == world_size-1) { //MPI_Irecv(&new_array[-1], 1, MPI_INT, rank-1, 11, MPI_COMM_WORLD, &request); for (int i=rank*loop_length; i<(rank*loop_length)+loop_length-1; i++) { *new_array[i] = *array[i-1]; } //MPI_Isend(&array[N-1], 1, MPI_INT, 0, 11, MPI_COMM_WORLD, &request); } if (rank != 5) //Can't print first digits for rank=0 { for (int i=0;i<N;i++) { printf(" %d ", *new_array[i]); } printf("\n"); } else { for (int i=1;i<16;i++) { printf("rank 1:%d, %d \n", 16-i, *new_array[N-i]); } } MPI_Finalize(); return 0; }
C
#include <stdio.h> int main() { int p1,p2,q1,q2; double v1,v2; scanf("%i %i %lf", &p1, &q1, &v1); scanf("%i %i %lf", &p2, &q2, &v2); printf("VALOR A PAGAR: R$ %.2lf\n", (q1 * v1) + (q2 * v2)); return 0; }
C
#define _GNU_SOURCE #include <stdio.h> #include <sys/stat.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include "debugutil.h" #define GPIO_PATH "/sys/class/gpio/" /*New! now with static stack memmory allocation!:*/ #define FNAMEBUFFSZE (64) int set_gpio_toval (int gpionr, int val) { char filename[FNAMEBUFFSZE]; char tmp[FNAMEBUFFSZE]; FILE *fh; debugf("Ill try to set [%d] ", gpionr); snprintf (filename,(FNAMEBUFFSZE-1), GPIO_PATH "gpio%d/value", gpionr); filename[FNAMEBUFFSZE-1] = 0; debugf(": %s\n",filename); fh = fopen (filename, "w"); if (fh == NULL) { if (!(fh = fopen (GPIO_PATH "/export", "w"))){ debugf("Can't open export\n"); return -1; } fprintf(fh, "%d\n", gpionr); fclose (fh); snprintf(tmp,(FNAMEBUFFSZE-1), GPIO_PATH "gpio%d/direction", gpionr); tmp[FNAMEBUFFSZE-1] = 0; fh = fopen (tmp, "w"); if (fh == NULL) { debugf("Can't change direction of pin %d\n", gpionr); return -1; } fprintf(fh, "out"); fclose (fh); fh = fopen (filename, "w"); if (fh == NULL ) { debugf("Can't open gpio-pin %d\n", gpionr); return -1; } } fprintf(fh, "%d\n", val); fclose (fh); return 0; }
C
//#include <iostream> //#include <math.h> //#include "imesh2D.h" //#include "additional.h" int bigger(double x,double y,double s,double b){ double y2=s*x+b; if(y > y2) return 1; else return 0; } void segmentedCircle(Delaunay & dt,double xc,double yc, double r){ for(Finite_faces_iterator it = dt.finite_faces_begin(); it != dt.finite_faces_end(); it++){ double r2 =r*r; if( (pow(dt.triangle(it)[0].x()-xc, 2)+pow(dt.triangle(it)[0].y()-yc , 2) < r2 ) && (pow(dt.triangle(it)[1].x()-xc, 2)+pow(dt.triangle(it)[1].y()-yc , 2) < r2 ) && (pow(dt.triangle(it)[2].x()-xc, 2)+pow(dt.triangle(it)[2].y()-yc , 2) < r2 ) ){ it->info().m_label = 1; } else it->info().m_label = 0; } } void segmentedSquare(Delaunay & dt, double x, double y,double side){ double left,right,up,down; left=x;right=x+side;up=y;down=y-side; for(Finite_faces_iterator it = dt.finite_faces_begin(); it != dt.finite_faces_end(); it++){ if( (dt.triangle(it)[0].x() < right && dt.triangle(it)[0].x() > left && dt.triangle(it)[0].y() < up && dt.triangle(it)[0].y() > down) && (dt.triangle(it)[1].x() < right && dt.triangle(it)[1].x() > left && dt.triangle(it)[1].y() < up && dt.triangle(it)[1].y() > down) && (dt.triangle(it)[2].x() < right && dt.triangle(it)[2].x() > left && dt.triangle(it)[2].y() < up && dt.triangle(it)[2].y() > down) ){ it->info().m_label = 2; } } } void segmentedLine(Delaunay & dt, double s, double b){ for(Finite_faces_iterator it = dt.finite_faces_begin(); it != dt.finite_faces_end(); it++){ if( bigger(dt.triangle(it)[0].x(),dt.triangle(it)[0].y(),s,b) && bigger(dt.triangle(it)[1].x(),dt.triangle(it)[1].y(),s,b) && bigger(dt.triangle(it)[2].x(),dt.triangle(it)[2].y(),s,b) ){ it->info().m_label = 3; } } } void segmentation(Delaunay & dt, int windowWidth, int windowHeight){ double xc,yc,r; // center (xc,yc) and radio r double x,y,side; // left upper point of square (x,y) and area of square = side^2 r=(double)( rand()%(int)floor(windowHeight/4) ) + (windowHeight/6); xc=(double)( rand()%windowWidth ); yc=(double)( rand()%windowHeight ); segmentedCircle(dt,xc,yc,r); side=(double)( rand()%(int)floor(windowHeight/4) ) + (windowHeight/3); x=(double)(rand()%windowWidth - (int)(side/2) ); y=(double)(rand()%windowHeight + (int)(side/2) ) ; segmentedSquare(dt,x,y,side); }
C
#include "keyboard.h" #include "egpio.h" /* Must be power of 2 */ #define KBD_SCAN_SIZE 4 typedef enum { ksNone = 0, ksSelectRow, ksWaitSelectRow, ksGetValue, ksWaitGetValue, } kbd_state_t; static kbd_state_t _kbd_state = ksNone; static uint8_t _kbd_row_index; static uint8_t _kbd_scan_prev[KBD_SCAN_SIZE]; fifo_struct_t kbd_scan; void kbd_push_scancode(uint8_t scancode) { fifoPush(&kbd_scan, scancode); } void kbd_systimer(void) { twi_state_t st; switch(_kbd_state) { case ksSelectRow: egpioWriteReg(EGPIO_CONFIG, ~(1<<_kbd_row_index)); // Select row _kbd_state = ksWaitSelectRow; break; case ksWaitSelectRow: if((st = egpioCheckStatus()) != twiStNone) { _kbd_state = ksGetValue; } break; case ksGetValue: egpioReadReg(EGPIO_INPUT); _kbd_state = ksWaitGetValue; break; case ksWaitGetValue: if((st = egpioCheckStatus()) != twiStNone) { uint8_t now = (twi.reg_value>>4) | (((~PINC & 0x06)>>1)<<4); uint8_t change = _kbd_scan_prev[_kbd_row_index] ^ now; if(change) /* Have change keys */ { _kbd_scan_prev[_kbd_row_index] = now; uint8_t i; for(i=0; i<6; i++) { if(change & 1) { kbd_push_scancode( ((now&1)?0:0x80) | _kbd_row_index | (i<<2) ); } change >>= 1; now >>= 1; } } _kbd_row_index++; if(_kbd_row_index >= KBD_SCAN_SIZE) { /* Process scancode */ _kbd_row_index = 0; } _kbd_state = ksSelectRow; } break; default: // Empty break; } } void kbdInit(void) { uint8_t i; fifoInit(&kbd_scan); for(i=0; i<KBD_SCAN_SIZE; i++) { _kbd_scan_prev[i] = 0; } twi_state_t st; _kbd_state = ksSelectRow; _kbd_row_index = 0; egpioWriteReg(EGPIO_CONFIG, 0xFF); // All inputs while((st = egpioCheckStatus()) == twiStNone) wdr(); delay(); egpioWriteReg(EGPIO_POLARITY, 0xFF); // All inverted while((st = egpioCheckStatus()) == twiStNone) wdr(); delay(); egpioWriteReg(EGPIO_OUTPUT, 0); // Prepare output to keyboard scan while((st = egpioCheckStatus()) == twiStNone) wdr(); delay(); } // vim: sw=4:ts=4:si:et
C
// Compute kernel for a "scale" cell. A port of MATLAB's imresize using bicubic interpolation. // Note: this kernel is separable and could therefore be rewritten as two stages. #BLOCKSIZE 16 16 LAYER_PTR z = PZS(0); // Compute scaling factors. float pySpace = LAYER_Y_SPACE(z); float pxSpace = LAYER_X_SPACE(z); float yFactor = pySpace / Y_SPACE; // If less than 1 we are shrinking. float xFactor = pxSpace / X_SPACE; // Compute receptive field size. int yWidth = (yFactor < 1) ? (int)ceilf(4.0f / yFactor) : 4; int xWidth = (xFactor < 1) ? (int)ceilf(4.0f / xFactor) : 4; // Find receptive field index ranges. int vy1, vy2, vx1, vx2; // Clipped to fall within the image ("valid"). int y1, y2, x1, x2; // Unclipped, may go off image edges. FIND_LAYER_Y_NEAREST(z, yWidth, vy1, vy2, y1, y2); FIND_LAYER_X_NEAREST(z, xWidth, vx1, vx2, x1, x2); vy2 = min(vy2, PY_COUNT - 1); vx2 = min(vx2, PX_COUNT - 1); if ((2 * (vy2 - vy1 + 1) < yWidth) || (2 * (vx2 - vx1 + 1) < xWidth)) { // If more than halfway off the image edge in either dimension, quit. WRITE_VAL(CNS_FLTMIN); return; } // Determine internal filter coordinates. float yFiltSpace = (yFactor < 1) ? yFactor : 1.0f; float xFiltSpace = (xFactor < 1) ? xFactor : 1.0f; float yFiltStart = (LAYER_Y_CENTER(z, y1) - THIS_Y_CENTER) / pySpace * yFiltSpace; float xFiltStart = (LAYER_X_CENTER(z, x1) - THIS_X_CENTER) / pxSpace * xFiltSpace; VAL_HANDLE h = GET_LAYER_VAL_HANDLE(z); float num = 0.0f; // Result numerator. float den = 0.0f; // Result denominator. float xFilt = xFiltStart; for (int x = x1; x <= x2; x++, xFilt += xFiltSpace) { // Compute x component of filter. float fx = fabsf(xFilt); float wx; if (fx <= 1.0f) { wx = (1.5f * fx - 2.5f) * fx * fx + 1.0f; } else if (fx <= 2.0f) { wx = ((-0.5f * fx + 2.5f) * fx - 4.0f) * fx + 2.0f; } else { wx = 0.0f; } // Determine x index of image pixel to read. int vx = (x < vx1) ? vx1 : (x > vx2) ? vx2 : x; float yFilt = yFiltStart; for (int y = y1; y <= y2; y++, yFilt += yFiltSpace) { // Compute y component of filter. float fy = fabsf(yFilt); float wy; if (fy <= 1.0f) { wy = (1.5f * fy - 2.5f) * fy * fy + 1.0f; } else if (fy <= 2.0f) { wy = ((-0.5f * fy + 2.5f) * fy - 4.0f) * fy + 2.0f; } else { wy = 0.0f; } // Determine y index of image pixel to read. int vy = (y < vy1) ? vy1 : (y > vy2) ? vy2 : y; num += wy * wx * READ_VAL_HANDLE(h, 0, vy, vx); den += wy * wx; } } // Clip output to [0 1]. WRITE_VAL(fminf(fmaxf(num / den, 0.0f), 1.0f));
C
/* 13.03.2017 Pawel Swora Program wywietla zakresy minimalne i makksymalne zmiennych cakowitych ze znakiem i bez zbaku. */ #include <stdio.h> int main() { char zm_char=1; unsigned char zm_uchar=1; printf("Char ze znakiem \n\n"); printf("Wielkosc char w bajtach: %d\n",sizeof(zm_char)); zm_char=zm_char<<sizeof(zm_char)*8-1; zm_uchar=~zm_uchar+1; printf("Zakres Min to: %d\n",zm_char); printf("Zakres Max to: %d\n\n",~zm_char); printf("Zakres Max bez znaku to: %u\n",zm_uchar); printf("Char bez znaku to 0\n\n\n"); int zm_int=1; unsigned int zm_uint=1; printf("Int ze znakiem\n\n"); printf("Wielkosc int w bajtach: %d\n",sizeof(zm_int)); zm_int=zm_int<<sizeof(zm_int)*8-1; zm_uint=~zm_uint+1; printf("Zakres Min to: %d\n",zm_int); printf("Zakres Max to: %d\n\n",~zm_int); printf("Zakres Max bez znaku to: %u\n",zm_uint); printf("Int bez znaku to 0\n\n\n"); short zm_short=1; unsigned short zm_ushort=1; printf("Short ze znakiem\n\n"); printf("Wielkosc short w bajtach: %d\n",sizeof(zm_short)); zm_short=zm_short<<sizeof(zm_short)*8-1; zm_ushort=~zm_ushort+1; printf("Zakres Min to: %d\n",zm_short); printf("Zakres Max to: %d\n\n",~zm_short); printf("Zakres Max bez znaku to: %u\n",zm_ushort); printf("Short bez znaku to 0\n\n\n"); long zm_long=1; unsigned zm_ulong=1; printf("Long ze znakiem\n\n"); printf("Wielkosc long w bajtach: %d\n",sizeof(zm_long)); zm_long=zm_long<<sizeof(zm_long)*8-1; zm_ulong=~zm_ulong+1; printf("Zakres Min to: %d\n",zm_long); printf("Zakres Max to: %d\n\n",~zm_long); printf("Zakres Max bez znaku to: %u\n",zm_ulong); printf("Long bez znaku to 0\n\n\n"); long long zm_longlong=1ll; unsigned long long zm_ulonglong=1ll; printf("Long long ze znakiem\n\n"); printf("Wielkosc long long w bajtach: %d\n",sizeof(zm_longlong)); zm_longlong=zm_longlong<<sizeof(zm_longlong)*8-1; zm_ulonglong=~zm_ulonglong+1; printf("Zakres Min to: %lld\n",zm_longlong); printf("Zakres Max to: %lld\n\n",~zm_longlong); printf("Zakres Max bez znaku to: %llu\n",zm_ulonglong); printf("Long long bez znaku to 0\n\n\n"); system("pause"); }
C
/* * bno055.c * * Created on: Jun 24, 2021 * Author: by */ #include <bno055.h> extern UART_HandleTypeDef huart4; void BNO055Read(uint8_t reg, uint8_t* data, uint8_t resp_byte, uint16_t bytes) { //Concatenate data uint8_t read_command[4]; read_command[0] = 0xAA; read_command[1] = 0x01; read_command[2] = reg; read_command[3] = (uint8_t) bytes; //Number of bytes to read //Transmit READ command HAL_UART_Transmit(&huart4, read_command, 4, (uint32_t)100); //Receive read data uint8_t offset = 2; uint8_t response[bytes + offset]; for(uint8_t i = 0; i < bytes + offset; ++i) response[i] = 0x00; uint16_t size = bytes + offset; HAL_StatusTypeDef status = HAL_UART_Receive(&huart4, response, 2, (uint32_t)10000); // for(uint8_t i = 0; i < bytes + offset; ++i) // response[i] = 0x00; // HAL_UART_Receive(&huart4, response, 1, (uint32_t)100); // // for(uint8_t i = 0; i < bytes + offset; ++i) // response[i] = 0x00; // HAL_UART_Receive(&huart4, response, 1, (uint32_t)100); //Successful read if(response[0] == 0xBB && (uint8_t)response[1] == bytes) { for(uint8_t i = 0; i < bytes; ++i) data[i] = response[i + offset]; resp_byte = 0x00; } //Fail read else if(response[0] == 0xEE) resp_byte = 0xAA; } void BNO055Write(uint8_t reg, uint8_t* data, uint8_t resp_byte, uint16_t bytes) { //Concatenate data to write uint8_t offset = 4; uint8_t all_data[bytes + offset]; all_data[0] = 0xAA; //Start of write command all_data[1] = 0x00; //Write command all_data[2] = reg; //Register to write all_data[3] = (uint8_t)bytes; //How many bytes to write for(int i = offset; i < bytes + offset; ++i) all_data[i] = data[i - offset]; //Transmit WRITE data HAL_UART_Transmit(&huart4, all_data, bytes + offset, (uint32_t)100); //Get WRITE response uint8_t response[2]; HAL_UART_Receive(&huart4, response, 2, (uint32_t)100); //If response was valid from BNO055 if(response[0] == 0xEE) resp_byte = response[1]; else resp_byte = 0xAA; } void BNO055Init() { //Read address register uint8_t addr[1]; uint8_t resp = 0x00; BNO055Read(0x98, addr, resp, 18); if(resp == 0xAA) return; else if(addr[0] == 0xA0) return; }
C
#include <stdio.h> #include <stdlib.h> #include "stack.h" void matsolve(); void maze(); FILE *fptr; int main(){ int c; print("MAze generate : 0\nMAze Solve : 2\n"); scanf("%d",&c); if(c==0) maze(); else matsolve(); printf("\n"); return 0; } void maze(){ printf("\nMAze generation nxn : Enter n "); scanf("%d",&n); int dig=digc(n); mazegen(); char buf[16]; sprintf(buf,"maze/gm%dx",n); int len=strlen(buf); sprintf(buf+len,"%d",n); sprintf(buf+len+dig,"%s",".txt"); buf[len+dig+4]='\0'; printf("\n%s",buf); fptr=fopen(buf,"w"); if(fptr==NULL){ printf("File not created"); exit(0); } fprintf(fptr,"%d\n",n); int i,j; for(i=0 ; i<n ; i++) for(j=0 ; j<n ; j++){ if(mat[i][j]) fprintf(fptr,"%d %d\n",i,j); } fclose(fptr); sdealloc(NULL); } void matsolve(){ fptr=NULL; char fname[30]; print("\nEnter filename as maze/\n"); scanf("%s",fname); fptr=fopen(fname,"r"); if(fptr==NULL){ printf("File not found"); exit(0); } fscanf(fptr,"%d",&n); //printf("\nMAze of %dx%d\n",n,n); matgen(n); int v1,v2; while(fscanf(fptr,"%d%d",&v1,&v2)!=EOF){ mat[v1][v2]=1; } fclose(fptr); if(n<=20) matprint(); modt st; fsinit(&st); fsfirst(&st); //matprint(); fspush(&st); printf("\n"); sdealloc(&st); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_toolbox.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: craffate <craffate@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/01/11 13:40:04 by craffate #+# #+# */ /* Updated: 2017/03/17 15:16:13 by craffate ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wconversion" #pragma clang diagnostic ignored "-Wsign-conversion" size_t ft_extrabits(const wchar_t *s) { size_t i; unsigned int j; i = 0; j = 0; while (s[j]) { if (s[j] >= 0x10000) i += 3; else if (s[j] >= 0x800) i += 2; else if (s[j] >= 0x80) i += 1; j++; } return (i); } static size_t ft_getsize(unsigned long long n, unsigned int b) { size_t size; size = 1; while (n /= b) size += 1; return (size); } wchar_t *ft_ullitoa_base(unsigned long long n, unsigned int b, const char spe) { wchar_t *s; size_t len; len = ft_getsize(n, b); s = ft_wstrnew(len + 1); s[len--] = 0; while (n >= b) { s[len--] = ((spe > 64 && spe < 91) ? ("0123456789ABCDEF")[n % b] : ("0123456789abcdef")[n % b]); n /= b; } s[len--] = ((spe > 64 && spe < 91) ? ("0123456789ABCDEF")[n % b] : ("0123456789abcdef")[n % b]); return (s); } wchar_t *ft_llitoa_base(long long n, unsigned int b, const char spe) { wchar_t *s; size_t len; int neg; unsigned long long n2; neg = (n < 0); n2 = n < 0 ? -n : n; len = ft_getsize(n2, b); len += neg == 1 ? 1 : 0; s = ft_wstrnew(len); s[0] = neg == 1 ? '-' : s[0]; s[len--] = 0; while (n2 >= b) { s[len--] = ((spe > 64 && spe < 91) ? ("0123456789ABCDEF")[n2 % b] : ("0123456789abcdef")[n2 % b]); n2 /= b; } s[len--] = ((spe > 64 && spe < 91) ? ("0123456789ABCDEF")[n2 % b] : ("0123456789abcdef")[n2 % b]); return (s); } wchar_t *ft_strtowstr(char *s) { unsigned int i; wchar_t *s2; i = 0; s2 = ft_wstrnew(ft_strlen(s)); if (!s) return (NULL); while (*s) s2[i++] = *s++; return (s2); } #pragma clang diagnostic pop
C
#include <stdio.h> int GCD(int n,int m) { if(m==0) return n; return GCD(m,n%m); } int main() { int n,m,gcd; printf("Enter first number: "); scanf("%d",&n); printf("\nEnter second number: "); scanf("%d",&m); gcd=GCD(n,m); printf("\nGCD of %d and %d is: %d",n,m,gcd); return 0; }
C
#include "heuristic_solver.h" #include <stdlib.h> #include <stdio.h> #include <config/config.h> #include "log/verbose.h" #include "utils/str_utils.h" #include "utils/time_utils.h" #include "utils/assert_utils.h" #include "utils/mem_utils.h" #include "timeout/timeout.h" #include "finder/feasible_solution_finder.h" void heuristic_solver_config_init(heuristic_solver_config *config) { config->methods = g_array_new(false, false, sizeof(heuristic_solver_method_callback_parameterized)); config->max_time = 60; config->max_cycles = -1; config->multistart = false; config->restore_best_after_cycles = 50; config->starting_solution = NULL; config->dont_solve = false; config->new_best_callback.callback = NULL; config->new_best_callback.arg = NULL; } void heuristic_solver_config_add_method(heuristic_solver_config *config, heuristic_solver_method_callback method, void *param, const char *name, const char *short_name) { heuristic_solver_method_callback_parameterized method_parameterized = { .method = method, .param = param, .name = name, .short_name = short_name }; g_array_append_val(config->methods, method_parameterized); } void heuristic_solver_config_destroy(heuristic_solver_config *config) { g_array_free(config->methods, true); } void heuristic_solver_stats_init(heuristic_solver_stats *stats) { stats->cycle_count = 0; stats->move_count = 0; stats->best_restored_count = 0; stats->methods = NULL; stats->starting_time = LONG_MAX; stats->best_solution_time = LONG_MAX; stats->ending_time = LONG_MAX; } void heuristic_solver_stats_destroy(heuristic_solver_stats *stats) { if (stats->methods) { for (int m = 0; m < stats->n_methods; m++) { g_array_free(stats->methods[m].trend.current.before, true); g_array_free(stats->methods[m].trend.current.after, true); g_array_free(stats->methods[m].trend.best.before, true); g_array_free(stats->methods[m].trend.best.after, true); } free(stats->methods); } } void heuristic_solver_init(heuristic_solver *solver) { solver->error = NULL; } void heuristic_solver_destroy(heuristic_solver *solver) { free(solver->error); } const char *heuristic_solver_get_error(heuristic_solver *solver) { return solver->error; } /* Generate a solution if needed (i.e. first time or if multistart=true) */ static bool generate_feasible_solution_if_needed( const heuristic_solver_config *solver_conf, const feasible_solution_finder_config *finder_conf, heuristic_solver_state *state) { if (state->current_cost != INT_MAX && !solver_conf->multistart) // Nothing to generate return true; if (solver_conf->starting_solution) { // If a starting solution is given, start always from it verbose2("Starting from loaded solution..."); solution_copy(state->current_solution, solver_conf->starting_solution); } else { // Generate a new initial solution verbose2("Finding initial feasible solution..."); feasible_solution_finder finder; feasible_solution_finder_init(&finder); solution_clear(state->current_solution); if (!feasible_solution_finder_find(&finder, finder_conf, state->current_solution)) // Cannot find feasible solution (probably timed-out) return false; } // A new feasible solution have been generated state->current_cost = solution_cost(state->current_solution); verbose2("Starting from solution of cost = %d", state->current_cost); heuristic_solver_state_update(state); return true; } bool heuristic_solver_solve(heuristic_solver *solver, const heuristic_solver_config *solver_conf, const feasible_solution_finder_config *finder_conf, solution *sol_out, heuristic_solver_stats *statistics) { const model *model = sol_out->model; heuristic_solver_method_callback_parameterized *methods = (heuristic_solver_method_callback_parameterized *) solver_conf->methods->data; int n_methods = solver_conf->methods->len; if (get_verbosity()) { char *names[n_methods]; for (int i = 0; i < n_methods; i++) names[i] = strdup(methods[i].name); char *methods_str = strjoin(names, n_methods, ", "); for (int i = 0; i < n_methods; i++) free(names[i]); verbose("solver.methods = %s", methods_str); verbose("solver.time_limit = %d", solver_conf->max_time); verbose("solver.cycles_limit = %d", solver_conf->max_cycles); verbose("solver.multistart = %s", booltostr(solver_conf->multistart)); verbose("solver.restore_best_after_cycles = %d", solver_conf->restore_best_after_cycles); free(methods_str); } if (!n_methods) { solver->error = strmake("no methods provided to solver"); return false; } if (solver_conf->max_time >= 0) set_timeout(solver_conf->max_time); int cycles_limit = solver_conf->max_cycles >= 0 ? solver_conf->max_cycles : INT_MAX; bool collect_trend = get_verbosity(); solution current_solution; solution_init(&current_solution, model); // Initialize solver's state heuristic_solver_state *state = &solver->state; state->model = model; state->current_solution = &current_solution; state->current_cost = INT_MAX; state->best_solution = sol_out; state->best_cost = INT_MAX; state->cycle = 0; state->method = 0; state->non_improving_best_cycles = 0; state->non_improving_current_cycles = 0; state->_last_log_time = 0; state->config = solver_conf; state->stats = statistics; state->methods_name = mallocx(n_methods, sizeof(const char *)); state->stats->methods = mallocx(n_methods, sizeof(heuristic_solver_state_method_stats)); state->stats->n_methods = n_methods; for (int i = 0; i < n_methods; i++) { state->methods_name[i] = methods[i].name; state->stats->methods[i].execution_time = 0; state->stats->methods[i].move_count = 0; state->stats->methods[i].improvement_count = 0; state->stats->methods[i].improvement_count_after_first_cycle = 0; state->stats->methods[i].improvement_delta = 0; state->stats->methods[i].improvement_delta_after_first_cycle = 0; state->stats->methods[i].trend.current.before = g_array_new(false, false, sizeof(int)); state->stats->methods[i].trend.current.after = g_array_new(false, false, sizeof(int)); state->stats->methods[i].trend.best.before = g_array_new(false, false, sizeof(int)); state->stats->methods[i].trend.best.after = g_array_new(false, false, sizeof(int)); } state->stats->starting_time = ms() - 1; // just for avoid FPE long now; if (solver_conf->dont_solve) { generate_feasible_solution_if_needed(solver_conf, finder_conf, state); state->stats->ending_time = ms(); goto QUIT; } // Main solver loop: call all the methods in a round robin way while (state->best_cost > 0) { if (timeout) { verbose("Time limit reached (%ds), stopping here", solver_conf->max_time); break; } if (!(state->cycle < cycles_limit)) { verbose("Cycles limit reached (%d), stopping here", cycles_limit); break; } // Generate a solution the first time (or each time if multistart=true) if (!generate_feasible_solution_if_needed(solver_conf, finder_conf, state)) break; int cycle_begin_best_cost = state->best_cost; int cycle_begin_current_cost = state->current_cost; // Restore the best known solution after 'restore_best_after_cycles' if (solver_conf->restore_best_after_cycles > 0 && !solver_conf->multistart && state->non_improving_best_cycles >= solver_conf->restore_best_after_cycles) { verbose("Restoring best solution of cost %d after %d cycles not improving best", state->best_cost, state->non_improving_best_cycles); solution_copy(state->current_solution, state->best_solution); state->current_cost = state->best_cost; state->non_improving_best_cycles = 0; state->non_improving_current_cycles = 0; state->stats->best_restored_count++; } // Eventually print some stats if (get_verbosity()) { int lv = 2; if (get_verbosity() < lv) { now = clk(); if (now - state->_last_log_time > 1000) { // Print as verbose1 instead of verbose2 once each second state->_last_log_time = now; lv = 1; } } verbose_lv(lv, "================== CYCLE %d ==================\n" "Current = %d (%.2f%% of best)\n" "Best = %d\n" "Not improving local best since %d cycles\n" "Not improving global best since %d cycles\n" "Cycles = %d (cycles/s = %.2f)\n" "Moves = %d (moves/s = %.2f)\n", state->cycle, state->current_cost, (double) 100 * state->current_cost / state->best_cost, state->best_cost, state->non_improving_current_cycles, state->non_improving_best_cycles, state->cycle, (double) 1000 * (double) state->cycle / (double) (ms() - state->stats->starting_time), state->stats->move_count, (double) 1000 * (double) state->stats->move_count / (double) (ms() - state->stats->starting_time) ); } // Real methods loop for (int i = 0; i < solver_conf->methods->len; i++) { heuristic_solver_method_callback_parameterized *method = &methods[i]; verbose2("------------ %s BEGIN (%d) ------------", method->name, state->current_cost); state->method = i; now = clk(); if (collect_trend) { g_array_append_val(state->stats->methods[i].trend.current.before, state->current_cost); g_array_append_val(state->stats->methods[i].trend.best.before, state->best_cost); } method->method(state, method->param); // metaheuristic method call if (collect_trend) { g_array_append_val(state->stats->methods[i].trend.current.after, state->current_cost); g_array_append_val(state->stats->methods[i].trend.best.after, state->best_cost); } state->stats->methods[i].execution_time += (clk() - now); verbose2("------------ %s END (%d) --------------", method->name, state->current_cost); } state->non_improving_current_cycles = (state->current_cost < cycle_begin_current_cost) ? 0 : (state->non_improving_current_cycles + 1); state->non_improving_best_cycles = (state->best_cost < cycle_begin_best_cost) ? 0 : (state->non_improving_best_cycles + 1); state->cycle++; state->stats->cycle_count++; } state->stats->ending_time = ms(); // Eventually print some stats after the resolution if (get_verbosity()) { verbose("=============== SOLVER FINISHED ===============\n" "Best = %d (found after %.2f seconds)\n" "Execution time = %.2f seconds\n" "Cycles = %d (cycles/s = %.2f)\n" "Moves = %d (moves/s = %.2f)\n" "Best restored %d times", state->best_cost, (double) (state->stats->best_solution_time - state->stats->starting_time) / 1000, (double) (state->stats->ending_time - state->stats->starting_time) / 1000, state->cycle, (double) 1000 * (double) state->cycle / (double) (state->stats->ending_time - state->stats->starting_time), state->stats->move_count, (double) 1000 * (double) state->stats->move_count / (double) (state->stats->ending_time - state->stats->starting_time), state->stats->best_restored_count ); for (int i = 0; i < n_methods; i++) { verbose("%s:\n" " Execution time = %.2f seconds\n" " Moves = %d (moves/s = %.2f)\n" " Improvement count = %d (%d after first cycle\n" " Improvement delta = %d (%d after first cycle)", state->methods_name[i], (double) state->stats->methods[i].execution_time / 1000, state->stats->methods[i].move_count, (double) 1000 * (double) state->stats->methods[i].move_count / (double) (state->stats->methods[i].execution_time), state->stats->methods[i].improvement_count, state->stats->methods[i].improvement_count_after_first_cycle, state->stats->methods[i].improvement_delta, state->stats->methods[i].improvement_delta_after_first_cycle); } if (collect_trend) { verbose("================== TREND =================="); /* LS SA * _0 | _7777 -> (-7000) -> 777* | 777 -> ( -400) -> 377* * _1 | __377 -> ( -200) -> 177* | 177 -> ( -400) -> 177 */ int trend_len = state->stats->methods[0].trend.current.before->len; int n_cycles_strlen = snprintf(NULL, 0, "%ld", state->cycle); int spacing = (int) n_cycles_strlen + 18; for (int m = 0; m < n_methods; m++) { const char *method_name = methods[m].short_name; verbosef("%*s", spacing - (int) strlen(method_name) / 2, method_name); spacing = 32 - (int) strlen(method_name); } verbosef("\n"); for (int i = 0; i < trend_len; i++) { verbosef("%s%*d", i > 0 ? "\n" : "", n_cycles_strlen, i); for (int m = 0; m < n_methods; m++) { int bef = ((int *) state->stats->methods[m].trend.current.before->data)[i]; int aft = ((int *) state->stats->methods[m].trend.current.after->data)[i]; int delta = aft - bef; bool new_best = ((int *) state->stats->methods[m].trend.best.after->data)[i] < ((int *) state->stats->methods[m].trend.best.before->data)[i]; verbosef(" | %5d -> (%+6d) -> %5d%s", bef, delta, aft, new_best ? "*" : " "); } } verbosef("\n"); } } QUIT: free(state->methods_name); solution_destroy(state->current_solution); return strempty(solver->error); } /* * Must be called by metaherustics methods after each move: * eventually updates the best solution if the current is better * and update some stats-> */ bool heuristic_solver_state_update(heuristic_solver_state *state) { bool improved = false; if (state->current_cost < state->best_cost) { verbose("%s: found new best solution of cost %d", state->methods_name[state->method], state->current_cost); assert(solution_satisfy_hard_constraints(state->current_solution)); if (state->best_cost != INT_MAX) { int delta = state->current_cost - state->best_cost; state->stats->methods[state->method].improvement_count++; state->stats->methods[state->method].improvement_delta += delta; if (state->cycle > 0) { state->stats->methods[state->method].improvement_count_after_first_cycle++; state->stats->methods[state->method].improvement_delta_after_first_cycle += delta; } } state->stats->best_solution_time = ms(); // Copy the current solution to the best state->best_cost = state->current_cost; solution_copy(state->best_solution, state->current_solution); improved = true; // Eventually callback if (state->config->new_best_callback.callback) state->config->new_best_callback.callback( state->best_solution, state->stats, state->config->new_best_callback.arg); assert(state->best_cost == solution_cost(state->best_solution)); } state->stats->move_count++; state->stats->methods[state->method].move_count++; return improved; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> int computerGame (int); //Main program for the computer version of Mastermind. Can be called from website, as it is not interactive. The function computerGame is called. int main(int argc, char* argv[]) { if (argc != 2) { printf("Error - program %s expects one input code!\n", argv[0]); return 1; } int numericSecretCode; int found = sscanf(argv[1], "%d", &numericSecretCode); if (found != 1) { printf("Error - secret code %s is not numeric!\n", argv[1]); return 1; } int errorCode = computerGame(numericSecretCode); return errorCode; }
C
/** * @file queue.h * @author Ask and Sivaranjith * @brief Get the next floor and interact with the linked list, an queue wrapper for linked list * @version 0.1 * @date 2021-02-22 * * @copyright Copyright (c) 2021 * */ #ifndef QUEUE_H #define QUEUE_H #include "linked_list.h" typedef enum{ QUEUE_DIRECTION_UP, QUEUE_DIRECTION_DOWN, QUEUE_DIRECTION_STILL } QueueDirection; /** * @brief Add a new order to the queue * * @param to_floor the requested floor * @param priority the priority of the button press. Lower number means that this will be higher prioritized * @param direction The direction the button press is. Inside, Up or Down * @return FloorOrder* Return the new FloorOrder element created */ FloorOrder *queue_add_element(uint8_t to_floor, OrderPriority priority, OrderDirection direction); /** * @brief Delete all orders in the linked list * */ void queue_clear(); /** * @brief Gets the next floor to go to given the direction and current floor * * @param current_floor The last visited floor * @param current_direction The direction the elevator is traveling, Up or Down * @return FloorOrder* Floor Order object of the next target floor */ FloorOrder* queue_get_next_floor_order(uint8_t current_floor, QueueDirection current_direction); /** * @brief Deletes all floor orders on the given floor @p{floor} * * @param floor The floor to delete from */ void queue_delete_orders_at_floor(uint8_t floor); /** * @brief Delete a given floor order object * * @param floor_order The floor order object to delete */ void queue_delete_element(FloorOrder* floor_order); /** * @brief Check if the floor is in the queue * * @param floor The floor to check in the queue * @return uint8_t 0 if floor does not exist in the queue, 1 if it does */ uint8_t queue_order_on_floor(uint8_t floor); #endif
C
#include "includes.h" //̳߳е߳ void *qc_subthread_loop(void *arg) { qc_pthread_detach; if (! arg) { return NULL; } short witch = *((short *)arg); free(arg); char readbuf[10]; sleep(1); if (! qc_threadpool_check(witch, pthread_self())) { LOG_ERROR_INFO("not self!\n"); exit(-1); } while (1) { int len = qc_thread_pipe_read_cmd(witch, readbuf, 10); if (len <= 0) { //error break; } //process qc_threadwork_call((work_index_t)readbuf[0], &readbuf[1]); } return NULL; } //̳߳ bool qc_threadpool_create(short pool_cnt) { if (! qc_threadpool_init(pool_cnt)) { goto _error_; } short i; for (i = 0; i < pool_cnt; i ++) { thread_t thid; short *arg = calloc(sizeof(short), 1); if (! arg) { goto _error_; } *arg = i; if (! qc_pthread_create(&thid, NULL, qc_subthread_loop, arg)) { free(arg); goto _error_; } if (! qc_threadpool_add(thid)) { goto _error_; } } return true; _error_: qc_threadpool_destroy(); return false; }
C
/* * Saba Ramadan * Assignment 8 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "myGrep.h" FILE *f; char S[M]; char C[M]; char L[M]; char *x; int l = 0; int c = 0; int wc = 0; int n = 0; int temp = 0; W *h = NULL; W *t = NULL; int main(int argc, char *argv[]) { if (argc != 3) { printf("myGrep: improper number of arguments\nUsage: %s <filename> <word>\n", argv[0]); return -1; } else { f = fopen(argv[1], "r"); if (f == NULL) { printf("Unable to open file: %s\n", argv[1]); return -1; } while(fgets(S, M, f) != NULL) { n = 0; l++; if (strlen(S) >= c) { c = strlen(S); strcpy(L, S); } strcpy(C, S); x = strtok(C, " \n"); while(x != NULL) { temp = strcmp(x, argv[2]); if (temp == 0) { if (h == NULL) { h = (W*)malloc(sizeof(W)); t = h; (*t).wn = n; (*t).ln = l - 1; strcpy((*t).line, S); wc++; } else { (*t).next = (W*)malloc(sizeof(W)); t = (*t).next; (*t).wn = n; (*t).ln = l - 1; strcpy((*t).line, S); wc++; } } x = strtok(NULL, " \n"); n++; } } printf("%s %s %s\n", argv[0], argv[1], argv[2]); printf("longest line: %snum chars: %d\nnum lines: %d\ntotal occurrences of word: %d\n", L, c, l, wc); t = h; while(t) { h = (*t).next; printf("line %d; word %d; %s", (*t).ln, (*t).wn, (*t).line); t = h; } free(h); free(t); } return 0; }
C
/*Done By:- Frankline Bosire // Simeon Kengere // Iyvonne Bett Maluki Muthusi Gerry Kyalo */ #include<stdio.h> #include<stdlib.h> //Initialize variables int semaphore = 1, full = 0, empty = 0, x = 0, choice; //Prototype functions void producer(); void consumer(); int wait(int); int signal(int); //Driver Program int main() { printf("\nEnter the size of the buffer:"); scanf("%d",&empty); printf("\n1.Produce\n2.Consume\n3.Set New Buffer\n4.Exit"); while(1) { printf("\nChoice to do in 1, 2, 3 or 4 above): "); scanf("%d",&choice); switch(choice) { case 1: if((semaphore == 1)&&(empty != 0)) producer(); else printf("%d items in the Buffer! The buffer is full!!\n", full); break; case 2: if((semaphore == 1)&&(full != 0)) consumer(); else printf("You cannot consume... Buffer is empty!!"); break; case 3: printf("\nEnter the size of the buffer:"); scanf("%d",&empty); break; case 4: exit(0); break; } } return 0; } //define the functions int wait(int s) { return (--s); } int signal(int s) { return(++s); } void producer() { semaphore = wait(semaphore); full = signal(full); empty = wait(empty); x++; printf("\n1 Item Added\n%d items are in the buffer.\n",x); semaphore = signal(semaphore); } void consumer() { semaphore = wait(semaphore); full = wait(full); empty = signal(empty); printf("\nConsumer consumes item %d",x); x--; semaphore = signal(semaphore); }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> /* This code shows how to create a new file and then mmap it to put data inside of it. It creates the file in /hugepages, which should be where you have setup your hugepagefs. Running grep Huge /proc/meminfo should show that the equivalent of 20MB of space has been used by the program. When you are done delete the file manually. Original code: http://www.linuxquestions.org/questions/programming-9/mmap-tutorial-c-c-511265/ */ #define FILEPATH "/hugepages/mmapped.bin" #define FILESIZE 1024*1024*2*10 #define NUMINTS FILESIZE/sizeof(int) -1 int main(int argc, char *argv[]) { int i; int fd; int result; int *map; /* mmapped array of int's */ /* Open a file for writing. * - Creating the file if it doesn't exist. * - Truncating it to 0 size if it already exists. (not really needed) * * Note: "O_WRONLY" mode is not sufficient when mmaping. */ fd = open(FILEPATH, O_CREAT | O_RDWR, 0755); if (fd == -1) { perror("Error opening file for writing"); exit(EXIT_FAILURE); } /* Now the file is ready to be mmapped. */ map = mmap(0, FILESIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (map == MAP_FAILED) { close(fd); perror("Error mmapping the file"); exit(EXIT_FAILURE); } /* Now write int's to the file as if it were memory (an array of ints). */ for (i = 1; i <=NUMINTS; ++i) { map[i] = 2 * i; } /* Don't forget to free the mmapped memory */ if (munmap(map, FILESIZE) == -1) { perror("Error un-mmapping the file"); /* Decide here whether to close(fd) and exit() or not. Depends... */ } /* Un-mmaping doesn't close the file, so we still need to do that. */ close(fd); return 0; }
C
/** @file msort.c */ #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> //struct to contain inputs necessary for multi-threaded qsort typedef struct qsort_inputs { int * list; int num_to_sort; } qsort_inputs; //struct to contain inputs necessary for multi-threaded merge typedef struct merge_inputs { int * list1; int size1; int * list2; int size2; int new_size; } merge_inputs; //compare function necessary for qsort int cmpfunc (const void * a, const void * b) { return ( *(int*)a - *(int*)b ); } //qsort function that returns a void ptr void * void_qsort(void * arg) { struct qsort_inputs* x = (struct qsort_inputs *) arg; qsort(x->list, x->num_to_sort, sizeof(int), cmpfunc); fprintf(stderr, "Sorted %d elements.\n", x->num_to_sort); return x->list; } //merge function that returns a void ptr void * void_merge(void * arg) { struct merge_inputs* x = (struct merge_inputs *) arg; int i = 0; int j = 0; int k = 0; int dupes = 0; int* temp_list1 = malloc(sizeof(int) * x->size1); for(i = 0; i < x->size1; i++) temp_list1[i] = x->list1[i]; for(i = 0; i < x->new_size;) //merging all values into list1, noting duplicate values in dupes { if(j < x->size1 && k < x->size2) { if(temp_list1[j] < x->list2[k]) { x->list1[i] = temp_list1[j]; j++; } else if(x->list2[k] < temp_list1[j]) { x->list1[i] = x->list2[k]; k++; } else if(temp_list1[j] == x->list2[k]) { x->list1[i] = temp_list1[j]; j++; dupes++; } i++; } else if(j == x->size1) { for(; i < x->new_size;) { x->list1[i] = x->list2[k]; k++; i++; } } else { for(; i < x->new_size;) { x->list1[i] = temp_list1[j]; j++; i++; } } } free(temp_list1); fprintf(stderr, "Merged %d and %d elements with %d duplicates.\n", x->size1, x->size2, dupes); return x->list1; } int main(int argc, char **argv) { if(argc != 2) //if invalid argument size { printf("ERROR\n"); return 0; } //initial capacity set to 50, segment count determined from args int capacity = 50; int input_count = 0; int * input_list = malloc(sizeof(int) * 50); int segment_count = atoi(argv[1]); char input[12]; //assuming number will not be greater than 12 digits while(fgets(input, 12, stdin) != NULL) // { if(input_count == capacity) //resize if there are more than 50 inputs { input_list = realloc(input_list, sizeof(int) * capacity * 2); capacity = capacity * 2; } input_list[input_count++] = atoi(input); //increment input_count //and add an int-ify'd number to inputs } int values_per_segment; //determine values per segment int remainder = 0; if (input_count % segment_count == 0) //determine number of segments { values_per_segment = input_count / segment_count; remainder = values_per_segment; } else //if segments don't divide evenly, set a remainder { values_per_segment = (input_count / segment_count) + 1; remainder = input_count - (values_per_segment * (segment_count - 1)); } struct qsort_inputs* qin_list = malloc(sizeof(struct qsort_inputs) * segment_count); //list of "n" structs for qsort input int i; for(i = 0; i < segment_count; i++) //initialize list of structs { int index = i * values_per_segment; qin_list[i].list = input_list + index; qin_list[i].num_to_sort = values_per_segment; } qin_list[segment_count - 1].num_to_sort = remainder; //set the remainder pthread_t thread_name[segment_count]; //initialize array of threads for(i = 0; i < segment_count; i++) { pthread_create(&thread_name[i], NULL, void_qsort, &qin_list[i]); //perform multi-threaded qsort } for(i = 0; i <segment_count; i++) { pthread_join(thread_name[i], NULL); //join all threads } while(segment_count > 1) //while there are still multiple lists to be merged { int merge_count = segment_count/2; //find number of times to execute merge struct merge_inputs* merge_list = malloc(sizeof(merge_inputs) * merge_count); //array of structs for merge inputs for(i = 0; i < segment_count - 1 ; i += 2) //set all merge structs to their proper values { merge_list[i/2].list1 = qin_list[i].list; merge_list[i/2].list2 = qin_list[i+1].list; merge_list[i/2].size1 = qin_list[i].num_to_sort; merge_list[i/2].size2 = qin_list[i+1].num_to_sort; merge_list[i/2].new_size = qin_list[i].num_to_sort + qin_list[i+1].num_to_sort; } pthread_t thread_name[merge_count]; //initialize array of threads for(i = 0; i < merge_count; i++) { pthread_create(&thread_name[i], NULL, void_merge, &merge_list[i]); //perform multi-threaded merge } for(i = 0; i < merge_count;i++) { pthread_join(thread_name[i],NULL); //join threads } int new_segment_size = segment_count - merge_count; //merge_count + segment_count%2 for(i = 0; i < new_segment_size; i++) { if(segment_count%2 && i == new_segment_size - 1) //set new values if there is a remainder { qin_list[i].list = qin_list[segment_count - 1].list; qin_list[i].num_to_sort = qin_list[segment_count - 1].num_to_sort; } else //set new values assuming all segments are even { qin_list[i].list = merge_list[i].list1; qin_list[i].num_to_sort = merge_list[i].new_size; } } segment_count = new_segment_size; free(merge_list); } int a; for(a = 0; a < input_count; a++) printf("%d\n", qin_list[0].list[a]); //print all values //freeing memory free(input_list); free(qin_list); return 0; }
C
#include <cs50.h> #include <ctype.h> #include <stdio.h> #include <string.h> int main( int argc, string argv[]) { if (argc != 2) // validate the arguments { printf("Usage: ./substitution key\n"); return 1; } else if (strlen(argv[1]) != 26) { printf("Key must contain 26 characters.\n"); return 1; } else { int alcount[26] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; for (int i = 0; i < 26; i++) { if (isalpha(argv[1][i])) { int index = (int) toupper(argv[1][i]) - 65; alcount[index] += 1; if (alcount[index] > 1) { printf("Key must contain each letter of the alphabet.\n"); return 1; } } else { printf("Key must only contain letters.\n"); return 1; } } for (int i = 0; i < 26; i++) { if (!alcount[i]) { printf("Key must contain each letter of the alphabet.\n"); return 1; } } } string ptext = get_string("plaintext: "); // begin enciphering (doubt that's a word) printf("ciphertext: "); for (int i = 0, n = strlen(ptext); i < n; i++) { if (isalpha(ptext[i])) { char h = toupper(argv[1][(int) toupper(ptext[i])-65]); if ((int) ptext[i] > 96) { h = tolower(h); } printf("%c", h); } else { printf("%c", ptext[i]); } } printf("\n"); }
C
#include<stdio.h> #include<stdlib.h> typedef struct node { int data; struct node *left,*right; } node; void inorder(node *root) { if(root) { //printf("traverring...%d\n",root->data); //getch(); inorder(root->left); printf("%d",root->data); inorder(root->right); } else return; } void create_tree(node *root) { char c; // if(root==NULL) { root->left=NULL; root->right=NULL; } printf("Enter the node \n"); scanf("%d",&(root->data)); printf("Does %d have a left node ??",root->data); fflush(stdin); scanf("%c",&c); if(c=='y') { root->left= (node*)malloc(sizeof(node)); create_tree(root->left); } fflush(stdin); printf("Does %d have a right node ??",root->data); scanf("%c",&c); if(c=='y') { root->right= (node*)malloc(sizeof(node)); create_tree(root->right); } } int max(int one, int two) { return (one>two)?one:two; } //x is max_width int cal_width(node *root,int *x) { if(root) { printf("Travesing %d and x = %d\n",root->data,*x); //height taking left node int left = 1+cal_width(root->left,x); //height taking right node int right = 1+cal_width(root->right,x); //-1 cuz root node will be included twice if(*x < left+right-1) { *x = left+right-1 ; } return max(left,right); } return 0; } int main() { node *root; int *x; x=(int*)malloc(sizeof(int)); *x=0; int height[10]; root = (node*)malloc(sizeof(node)); create_tree(root); inorder(root); printf("\n"); cal_width(root,x); printf("Width of tree id %d",*x);//Radius and width are same thing.. getch(); }
C
#include <stdio.h> #include "quadrado.h" static int quadrado_valido(quadrado_t q); static int quadrado_valido(quadrado_t q){ if(q.l<=0){ printf("Não é um quadrado! Lados negativos ou nulos.\n"); return 0; } return 1; } quadrado_t cria_quadrado(void){ printf("Digite o lado do quadrado: "); quadrado_t q; do{ scanf("%lf",&q.l); }while(!quadrado_valido(q)); return q; } double area_quadrado(quadrado_t q){ return q.l*q.l; }
C
#include<stdio.h> #include<conio.h> #include<windows.h> int gotoxy(short x, short y){ COORD coord; HANDLE h_stdout; coord.X = x; coord.Y = y; if((h_stdout = GetStdHandle(STD_OUTPUT_HANDLE)) == INVALID_HANDLE_VALUE) return 0; if(SetConsoleCursorPosition(h_stdout, coord) == 0) return 0; return 1; } void delay(int x){ int i; for(i=0;i<=x*1000000; i++); } void barra(){ int i; system("COLOR f2"); //printf("color(f color fondo --- 2 color letra)\n"); for(i=30; i<60; i++){ delay(200); gotoxy(i,10);printf("%c",219); } system("pause"); } int main() { gotoxy(10,10); printf("Cargando programa "); barra(); delay(500); // fin del mientras return 0; }
C
#include "queue.h" #include <stdlib.h> #include <string.h> Queue* create(int typeSize, int noOfElements) { Queue *queue = malloc(sizeof(Queue)); queue->elements = calloc(noOfElements,typeSize); queue->noOfElements = noOfElements; queue->elementSize = typeSize; queue->front = 0; queue->rear = -1; return queue; } int enqueue(Queue *queue, void *inputElement){ if(queue->rear == queue->noOfElements-1) return 0; queue->rear = queue->rear + 1; memcpy(queue->elements+(queue->rear*queue->elementSize),inputElement,queue->elementSize); return 1; } void* dequeue(Queue *queue){ void* removedElement; if(queue->rear == -1) return NULL; removedElement = queue->elements + (queue->front * queue->elementSize); queue->front = queue->front + 1; return removedElement; }
C
/* * ===================================================================================== * * Filename: object.h * * Description: * * Version: 1.0 * Created: 02/01/2014 12:20:59 PM * Revision: none * Compiler: gcc * * Author: Neophytos Demetriou (), * Organization: * * ===================================================================================== */ #ifndef __OBJECT_H__ #define __OBJECT_H__ #include "common.h" #include <assert.h> #include <string.h> typedef struct { int refCount; /* when zero the object will be freed */ char *bytes; int nbytes; union { /* The internal representation: */ long longValue; /* - a long integer value. */ double doubleValue; /* - a double-precision floating value. */ void *otherValuePtr; /* - another, type-specific value. */ /*WideInt wideValue;*/ /* - a long long value. */ struct { /* - internal rep as two pointers. */ void *ptr1; void *ptr2; } twoPtrValue; struct { /* - internal rep as a wide int, tightly * packed fields. */ void *ptr; /* Pointer to digits. */ unsigned long value;/* Alloc, used, and signum packed into a * single word. */ } ptrAndLongRep; } internalRep; } object_t; static inline object_t *object_alloc() { return (object_t *) ckalloc(sizeof(object_t)); } static inline object_t *object_new(int nbytes) { object_t *objPtr = object_alloc(); /* If nbytes is 0, then malloc() returns either NULL, * or a unique pointer that can later be successfully * passed to free() */ objPtr->bytes = (char *) ckalloc(nbytes); objPtr->nbytes = nbytes; objPtr->refCount = 0; return objPtr; } static inline size_t object_size(const object_t *objPtr) { return objPtr->nbytes; } static inline void object_cleanup(object_t *objPtr) { if (object_size(objPtr)) { ckfree(objPtr->bytes); } } static inline void object_free(object_t *objPtr) { assert(objPtr->refCount == 0); // DBG(printf("object_free: %p\n", objPtr)); object_cleanup(objPtr); ckfree(objPtr); } static inline void object_set(object_t *objPtr, void *bytes) { memcpy(objPtr->bytes, bytes, objPtr->nbytes); } static inline const char *object_value(const object_t *const objPtr) { return objPtr->bytes; } static inline void decr_ref_count(object_t *objPtr) { assert(objPtr->refCount > 0); // DBG(printf("decr_ref_count: objPtr=%p refCount=%d\n", objPtr, objPtr->refCount)); if (--objPtr->refCount == 0) { object_free(objPtr); } } static inline void incr_ref_count(object_t *objPtr) { objPtr->refCount++; } #endif
C
/* A Fast 2D Point-On-Line Test by Alan Paeth from "Graphics Gems", Academic Press, 1990 */ #include "GraphicsGems.h" int PntOnLine(px,py,qx,qy,tx,ty) int px, py, qx, qy, tx, ty; { /* * given a line through P:(px,py) Q:(qx,qy) and T:(tx,ty) * return 0 if T is not on the line through <--P--Q--> * 1 if T is on the open ray ending at P: <--P * 2 if T is on the closed interior along: P--Q * 3 if T is on the open ray beginning at Q: Q--> * * Example: consider the line P = (3,2), Q = (17,7). A plot * of the test points T(x,y) (with 0 mapped onto '.') yields: * * 8| . . . . . . . . . . . . . . . . . 3 3 * Y 7| . . . . . . . . . . . . . . 2 2 Q 3 3 Q = 2 * 6| . . . . . . . . . . . 2 2 2 2 2 . . . * a 5| . . . . . . . . 2 2 2 2 2 2 . . . . . * x 4| . . . . . 2 2 2 2 2 2 . . . . . . . . * i 3| . . . 2 2 2 2 2 . . . . . . . . . . . * s 2| 1 1 P 2 2 . . . . . . . . . . . . . . P = 2 * 1| 1 1 . . . . . . . . . . . . . . . . . * +-------------------------------------- * 1 2 3 4 5 X-axis 10 15 19 * * Point-Line distance is normalized with the Infinity Norm * avoiding square-root code and tightening the test vs the * Manhattan Norm. All math is done on the field of integers. * The latter replaces the initial ">= MAX(...)" test with * "> (ABS(qx-px) + ABS(qy-py))" loosening both inequality * and norm, yielding a broader target line for selection. * The tightest test is employed here for best discrimination * in merging collinear (to grid coordinates) vertex chains * into a larger, spanning vectors within the Lemming editor. */ /* addenda: this first set of tests has been added to detect * the case where the line is of zero length. Remove this if * such a case is impossible. */ if ((px == qx) && (py == qy)) if ((tx == px) && (ty == py)) return 2; else return 0; if ( ABS((qy-py)*(tx-px)-(ty-py)*(qx-px)) >= (MAX(ABS(qx-px), ABS(qy-py)))) return(0); if (((qx<px)&&(px<tx)) || ((qy<py)&&(py<ty))) return(1); if (((tx<px)&&(px<qx)) || ((ty<py)&&(py<qy))) return(1); if (((px<qx)&&(qx<tx)) || ((py<qy)&&(qy<ty))) return(3); if (((tx<qx)&&(qx<px)) || ((ty<qy)&&(qy<py))) return(3); return(2); }
C
#include "ht.h" #define INITIAL_SIZE 32 #define MAX(A, B) (A > B ? A : B) #define FNV_OFFSET 14695981039346656037UL #define FNV_PRIME 1099511628211UL static size_t hash(const char* key) { size_t hash = FNV_OFFSET; for (const char* p = key; *p; p++) { hash ^= (size_t)(unsigned char)(*p); hash *= FNV_PRIME; } return hash; } HashTable* ht_create(size_t size) { HashTable* ret = (HashTable*)malloc(sizeof(HashTable)); ret->capacity = nextPowerOfTwo(size); ret->capacity = MAX(INITIAL_SIZE, ret->len); //ret->capacity = ret->capacity*sizeof(ht_item); ret->len = 0; ret->items = (ht_item*)calloc(ret->capacity, sizeof(ht_item)); if (ret->items == NULL) { free(ret->items); return NULL; } return ret; } void ht_free(HashTable* ht) { for (size_t i = 0; i < ht->capacity; i++) { if (ht->items[i].key != NULL) free(ht->items[i].key); if (ht->items[i].value != NULL) free(ht->items[i].value); } free(ht->items); free(ht); } void ht_insert(HashTable* ht, char* key, char* value) { size_t index = hash(key) & (ht->capacity - 1); while ((void*)ht->items[index].key != NULL) { if (strcmp(key, ht->items[index].key) == 0) { break; } index++; if (index >= ht->capacity) { index = 0; } } if (ht->items[index].key != NULL && strcmp(key, ht->items[index].key) == 1) ht->len++; key = strdup(key); value = strdup(value); ht->items[index].key = key; ht->items[index].value = value; } char* ht_search(HashTable* ht, char* key) { size_t index = hash(key) & (ht->capacity-1); while ((void*)ht->items[index].key != NULL) { if(strcmp(key, ht->items[index].key) == 0) return ht->items[index].value; index ++; if (index >= ht->capacity) index = 0; } return NULL; }
C
#include "quiz.h" #include <stdio.h> #include <stdlib.h> #include <string.h> void parseCSVStruct(struct quiz given[],unsigned fileLength,const char * fileName){ //standard file opening char temp[100]; FILE *f = fopen(fileName,"r"); if (f == NULL){ printf("The file cannot be found"); exit(1); } //interates thorugh all the lines of the file for (int i = 0; i < fileLength; i++){ //stores the current line of the file in a variable so it can be read fgets(temp,100,f); //parses first element of csv data char *tok = strtok(temp,","); //allocate the size of the string that needs to be stored given[i].state = malloc(strlen(tok)); //check for correct allocation if (given[i].state == NULL){ printf("Memory allocation failed\n"); exit(1); } //copy the first csv data into the state of the current structure from the array strcpy(given[i].state,tok); //this access second part of the csv data (expression access all subsequent data of csv file) tok = strtok(NULL,","); //allocate the size of the string to store to the struct string given[i].capital = malloc(strlen(tok)); //check the memory has been allocated if (given[i].capital == NULL){ printf("Memory allocation has failed\n"); exit(1); } //copy the data into the current structure strcpy(given[i].capital,tok); } fclose(f); }
C
#include<stdio.h> int main() { int a=10,b=20,sum; sum=a+b; printf("sum=%d",sum); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "indxlook.h" struct tree_node /* node in tree */ { struct tree_node *l_ptr, *r_ptr; /* left and right pointers */ INDEX *data_ptr; /* data pointer */ }; typedef struct tree_node TREE_NODE; void write_index(char *txtfile, char *ndxfile); void save_tree(TREE_NODE * root, FILE *fp); TREE_NODE *make_tree(FILE *fp, long *cnt_ptr); TREE_NODE *insert_tree(TREE_NODE *root, INDEX *rec_ptr, long *cnt_ptr); long bsearch_file(FILE *ifp, long first, long last, char *target); int main(int argc, char *argv[]) { if (argc != 3) { puts("Usage: INDEX text_file_name index_file_name\n"); puts("Note: The text file must consist of a number of records " "separated by lines"); puts(" containing a single period (\".\")"); return EXIT_FAILURE; } write_index(argv[1], argv[2]); return EXIT_SUCCESS; } void write_index(char *txtfile, char *ndxfile) { FILE *afp, *ifp; /* types of files */ TREE_NODE *root; static INDEX header = {"!", 0}; afp = fopen(txtfile, "r"); if ((root = make_tree(afp, &header.pos)) != NULL) { ifp = fopen(ndxfile, "wb"); fwrite(&header, sizeof(header), 1, ifp); save_tree(root, ifp); fclose(ifp); printf("\n%ld records\n", header.pos); } fclose(afp); } TREE_NODE *make_tree(FILE *fp, /* file */ long *cnt_ptr) /* count of records */ { TREE_NODE *root, *temp_ptr; char line[MAX_LINE]; long start_pos = 0; INDEX *next_ptr; Boolean_T new_record = True_, have_mem; *cnt_ptr = 0; while (start_pos = ftell(fp), have_mem && fgets(line,sizeof(line), fp)) { if (new_record) { if ((next_ptr = (INDEX *) malloc(sizeof(INDEX))) != NULL) { strncpy(next_ptr->key, line, MAX_KEY); next_ptr->pos = start_pos; temp_ptr = insert_tree(root, next_ptr, cnt_ptr); if (temp_ptr) root = temp_ptr; } have_mem = next_ptr && temp_ptr; } new_record = strcmp(line, END_REC) == 0; } if (!have_mem) fprintf(stderr, "Out of memory. Key: %s\n", line); return root; } void save_tree(TREE_NODE *root, FILE *fp) { if (root) { save_tree(root->l_ptr, fp); fwrite(root->data_ptr, sizeof(INDEX), 1, fp); save_tree(root->r_ptr, fp); } } TREE_NODE *insert_tree(TREE_NODE *root, /* pointer to tree */ INDEX *rec_ptr, /* record to install */ long *cnt_ptr) /* nodes in tree */ { if (root) { int cmp = strncmp(rec_ptr->key, root->data_ptr->key, MAX_KEY); if (cmp < 0) /* left side? */ root->l_ptr = insert_tree(root->l_ptr, rec_ptr, cnt_ptr); else if (cmp > 0) /* right side */ root->r_ptr = insert_tree(root->r_ptr, rec_ptr, cnt_ptr); else fprintf(stderr, "Duplicate key: %s\n", rec_ptr->key); } else if (root = (TREE_NODE *) malloc(sizeof(TREE_NODE)), root) { root->data_ptr = rec_ptr; root->l_ptr = root->r_ptr = NULL; } return root; } long bsearch_file(FILE *ifp, long first, long last, char *target) { long pos, mid =(first + last) / 2; INDEX next; int cmp; if (mid < first || fseek(ifp, mid * sizeof(INDEX), 0) != 0 || fread(&next, sizeof(INDEX), 1, ifp) == 0) { pos = -1; } else pos = ((cmp = strncmp(target, next.key, MAX_KEY)) == 0) ? next.pos : ((cmp < 0) ? bsearch_file(ifp, first, mid - 1, target) : bsearch_file(ifp, mid + 1, last, target)); return pos; }
C
#include <string.h> #include "is_winning.h" #include "player.h" #include "graph_struct.h" #include <dlfcn.h> #include <getopt.h> #include <time.h> #define NB_PLAYERS 2 #define MAX_TURN 300 #define TRUE 1 #define FALSE 0 #define FAILURE 1 static char shape = 'h'; static int m = 9; void parse_opts(int argc, char*argv[]){ int opt; while ((opt = getopt(argc, argv, "t:m:")) != -1) { switch (opt) { case 't': if ( optarg[0] != 'c' && optarg[0] != 'h' && optarg[0] != 't' ) { printf("Vous avez choisi in format incorrect\n"); }else{ shape = optarg[0]; } break; case 'm': m = atoi(optarg); if ( m <= 2) { printf("Le jeu ne peut pas avoir lieu avec le 'm' choisi\n"); } break; default: fprintf(stderr, "Usage: %s [-t shape of graph -m Number of side points] \n", argv[0]); exit(EXIT_FAILURE); } } } struct player{ char const* (* get_player_name)(); struct move_t (* propose_opening)(); int (*accept_opening)(const struct move_t opening); void (*initialize_graph)(struct graph_t* graph); void (*initialize_color)(enum color_t id); struct move_t (*play)(struct move_t previous_move); void (*finalize)(); enum color_t color; }; //initialize a player with the function of the library corresponding to handle struct player make_player(void* handle){ struct player p; p.get_player_name=dlsym(handle, "get_player_name"); p.propose_opening=dlsym(handle,"propose_opening"); p.accept_opening=dlsym(handle, "accept_opening"); p.initialize_graph=dlsym(handle, "initialize_graph"); p.initialize_color=dlsym(handle, "initialize_color"); p.play=dlsym(handle, "play"); p.finalize=dlsym(handle, "finalize"); p.color=NO_COLOR; return p; } //apply the move move on the board graph, return 1 if the move is valid, if not int apply_move(struct graph_t* graph, struct move_t move){ if((move.c==0 || move.c==1) && (!gsl_spmatrix_get(graph->o, WHITE, move.m) && !gsl_spmatrix_get(graph->o, BLACK, move.m))){ gsl_spmatrix_set(graph->o, move.c, move.m, 1); return 1; }else{ printf("invalid move : %ld \n", move.m); return 0; } } //determine the next player after the move prev_move enum color_t compute_next_player(struct move_t prev_move){ return !(prev_move.c); } int winning(){ return FALSE; } //////////////////////////////////////main//////////////////////////////////////// int main(int argc, char* argv[]){ srand(time(NULL)); parse_opts(argc , argv); printf("Le format de graphe choisi est %c\n",shape); printf("Le nombre de sommets de cote choisi est %d\n",m); if (argc<NB_PLAYERS){ return FAILURE; } //players initialisation struct player tab_players[NB_PLAYERS]; void* tab_handles[NB_PLAYERS]; for(int i=0; i<NB_PLAYERS; i++){ printf("%s\n",argv[i+optind]); tab_handles[i]=dlopen(argv[i+optind], RTLD_LAZY); // argv[argc-2+i] tab_players[i]=make_player(tab_handles[i]); tab_players[i].color=i; } enum color_t winner=NO_COLOR; //graph initialisation struct graph_t* graph=make_graph(m, shape); struct graph_t* tab_graph[NB_PLAYERS]; for(int i=0; i<NB_PLAYERS; i++){ tab_graph[i]=graph_copy(graph); tab_players[i].initialize_graph(tab_graph[i]); } //openning struct player *current_player; struct move_t move = tab_players[BLACK].propose_opening(); printf("%s Choses %zu as an openning\n", tab_players[BLACK].get_player_name(),move.m); if(!tab_players[WHITE].accept_opening(move)){ printf("%s Declines and Swaps\n", tab_players[WHITE].get_player_name()); struct player tmp=tab_players[BLACK]; tab_players[BLACK]=tab_players[WHITE]; tab_players[WHITE]=tmp; void* tmp_handle = tab_handles[0]; tab_handles[0]=tab_handles[1]; tab_handles[1]=tmp_handle; } else{ printf("%s accepts\n", tab_players[WHITE].get_player_name()); } current_player=&tab_players[BLACK]; tab_players[BLACK].initialize_color(BLACK); tab_players[WHITE].initialize_color(WHITE); apply_move(graph, move); //game loop for(int turn = 0; turn<MAX_TURN; turn ++){ current_player=&tab_players[compute_next_player(move)]; move = current_player->play(move); //printf("%s Choses move %zu\n", current_player->get_player_name(), move.m); if(!apply_move(graph, move)){ winner=!move.c; break; } winner=is_winning(graph, shape); if (winner!= NO_COLOR){ break; } //print_graph(graph, shape); } //finalization if(winner==NO_COLOR){ printf("no winner\n"); }else{ printf("the winner is %s !\n",tab_players[winner].get_player_name()); } print_graph(graph, shape); for(int i=0; i<NB_PLAYERS; i++){ tab_players[i].finalize(); dlclose(tab_handles[i]); } graph__free(graph); return 0; }
C
/* Tutti II sound emulation (C)2015-7 Cameron Kaiser. All rights reserved. */ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "SN76489AN.h" #if defined(__clang__) || defined(__GNUC__) # define LIKELY(x) (__builtin_expect(!!(x), 1)) # define UNLIKELY(x) (__builtin_expect(!!(x), 0)) #else # define LIKELY(x) (!!(x)) # define UNLIKELY(x) (!!(x)) #endif /* The SN76489 has four 4-bit volume registers, 3 10-bit tone registers and 1 3-bit noise register, making one two-bit sound chip (compared to the C64's SID :-) ). The lower the tone register value, the higher the frequency (they are treated like counter resets). 0x001 is 111.861kHz, but the highest generated frequency in practice is 18.643MHz (0x006), well-within the Nyquist frequency at our sampling rate of 44.1kHz. 0x3ff generates 0.109kHz. This is a range of approximately 10 octaves. Hz is computed by 3579545 / ((32)(register value)), so 440Hz is roughly 0x0fe. 0x0f is silent, 0x00 is maximum volume (!). We reverse this internally. The output waveform is approximately a simple "perfect" square wave, although there is some analogue distortion in the Tutor's output stage. Here we use a simplified approximation, but most Tutor applications did not exercise the DCSG very thoroughly, so that will suffice. */ /* internal oscillator settings */ uint8_t vol[4]; // Volume for internal mixer, also a register double freqstep[4]; // Step for frequency generator double freqstat[4]; // Current position on wave uint16_t noisenet; // Pseudorandom noise emulation shift register /* register status */ uint8_t latch; uint16_t freq[4]; // We don't track the internal status of the noise register; we // don't need to because of the way it is written to by the port. /* biases we use for mixing */ #define FACTOR 32768.0 #define AMPMAX 65535.0 /* precomputed */ uint8_t allquiet; // Fast all-clear marker uint8_t on[4]; // Which channels are on? double volf[4]; // Volume factor (computed from volume) // Internal utility functions. // Caches what's playing, if anything. inline void isallquiet() { #define ON_ANON(a) on[a] = !(freq[a] == 0 || vol[a] == 0); if(!on[a]) freqstat[a] = 0.0; ON_ANON(0) ON_ANON(1) ON_ANON(2) on[3] = !(vol[3] == 0); if (!on[3]) freqstat[3] = 0.0; allquiet = !(on[0] || on[1] || on[2] || on[3]); } // Convert volume bits to amplitude: each bit increment // drops the volume by 2dB. inline double dBtoamp(uint8_t db) { // Magic constants determined manually. double boost = pow(10.0, ((db*2.02468)/20.0)); return (boost - 1) * (A_AMPLITUDE / 32.0); } // Waveform generators. inline uint8_t noisebit() { // Noise generator. This needs separate processing to generate amplitude // (see SN76489AN_GenerateSamples). // // The SN76489A uses a 15-bit shift register. Taps are on bits 13 and 14 // and the output is bit 15. uint8_t newbit; // Compute parity of tapped bits. newbit = ((noisenet & 0x02) && (noisenet & 0x04)) ? 0 : (noisenet & 0x02) ? 1 : (noisenet & 0x04) ? 1 : 0; // Feed it back. noisenet |= newbit << 15; // Shift out next pseudorandom bit. newbit = noisenet & 1; noisenet >>= 1; return newbit; } inline double envelope(double freqstat, double vol) { // Tone synthesis generator, emitting a ready-to-use amplitude. // Square it off for that harsh Tomy sound! return vol * (sin(freqstat) + sin(3*freqstat)/3 + sin(5*freqstat)/5 + sin(7*freqstat)/7 + sin(9*freqstat)/9 + sin(11*freqstat)/11); } inline double mixer(double a, double b) { // Takes the output of two generators and returns a mixed version. double m; // Pre-bias the amplitudes. a += FACTOR; b += FACTOR; // Use a high quality mixing algorithm to reduce distortion. if (a < FACTOR && b < FACTOR) { m = (a * b) / FACTOR; } else { m = (2.0 * (a+b)) - ((a*b) / FACTOR) - AMPMAX; } if (m > AMPMAX) m=AMPMAX; // Remove the bias and return. return (m - FACTOR); } inline double noisedivider(uint8_t noise) { // The Tomy OS supports clock/512, clock/1024 and clock/2048 for the // noise channel (BASIC -1, -2 and -3 respectively). clock/512 is also // the value used in GBASIC for TONE NO4. if (noise == 4) return (3579545.0/512.0); if (noise == 5) return (3579545.0/1024.0); if (noise == 6) return (3579545.0/2048.0); // It wouldn't be hard to support using channel 2 (i.e., a value of 7), // but the Tomy OS doesn't seem to implement that, so we don't either. #if DEBUG fprintf(stderr, "unexpected noise divider: %i\n", noise); #endif return (3579545.0/512.0); } // Public API. void SN76489AN_Init() { size_t i; for(i=0; i<4; i++) { vol[i] = 0x0; freq[i] = 0x0; volf[i] = 0.0; freqstep[i] = 0.0; freqstat[i] = 0.0; on[i] = 0; } latch = 0; allquiet = 1; noisenet = 0x4000; // a guess } void SN76489AN_WritePort(uint8_t value) { int chan; // Tone registers do not wait for all 10 bits. This means that // multiple writes back to back could temporarily "eek" if we aren't // fast enough. if (!latch && !(value & 0x80)) return; // Spurious initial write if (value & 0x80) { int type = (value & 0x10); int data = (value & 0x0f); chan = (value & 0x60) >> 5; latch = value; if (type) { // volume. Precompute factor. vol[chan] = 15 - data; volf[chan] = dBtoamp(vol[chan]); isallquiet(); return; } else { // tone or noise data if (chan == 3) { freqstep[3] = noisedivider(data & 0x07); return; } // Place into "low four bits" (that means // upper, in this case). // ---- --00 00XX XXXX freq[chan] &= 0x03f0; freq[chan] |= data; // fall through to end } } else { // use existing latch int type = (latch & 0x10); int data = (value & 0x3f); chan = (latch & 0x60) >> 5; if (type) { // volume vol[chan] = 15 - (data & 0x0f); volf[chan] = dBtoamp(vol[chan]); isallquiet(); return; } else { if (chan == 3) { freqstep[3] = noisedivider(data & 0x07); return; } // Place into "upper six bits" freq[chan] &= 0x000f; freq[chan] |= data << 4; } } // Update oscillators. // Compute a new step (2 * pi * frequency / sample rate). if (freq[chan] == 0) { freqstep[chan] = 0.0; } else { double nufreq; nufreq = 3579545.0/(32.0*freq[chan]); freqstep[chan] = 2 * M_PI * nufreq / M_FREQUENCY; } isallquiet(); } void SN76489AN_GenerateSamples(int16_t *buffer, size_t count) { size_t i; uint8_t noisy; double a, b, m; // The Tutor uses channel 2 (of 0-2) for the system tones, plus noise, // and since the same routines service TONE NOa in GBASIC the same // applies to GRAPHIC mode. However, BASIC mode can theoretically // play all three channels with noise on any combination of channels. // Because the general mixer case can be expensive, we have a number of // optimized loops we will choose between to generate sound as cheaply // as possible. // // In the best case, no channels are playing at all. If so, just blank // the sound buffer and return. if (LIKELY(allquiet)) { #if __APPLE__ && __ppc__ // This seems to be a bit faster on 10.4 and 10.5. bzero((void *)buffer, count); #else (void)memset((void *)buffer, 0, count); #endif return; } count >>= 1; // Some sound is playing, somewhere. Try some optimizations first. // Handle solo tone synthesis voice cases with a tight non-mixed loop. #define SOLO(x, y, z, a) \ if (!on[x] && !on[y] && !on[z]) { \ for(i=0; i<count; i++) { \ buffer[i] = (int16_t)envelope(freqstat[a], volf[a]); \ freqstat[a] += freqstep[a]; \ } \ return; \ } // First handle channel 2 solo. This is the most common situation // (GRAPHIC, GBASIC and the menu). SOLO(0,1,3, 2) // Now handle channel 0 solo. This is the second most common situation // (BASIC SOUND() with the minimum number of arguments). SOLO(1,2,3, 0) // Now handle noise with or without channel 2, but no other channels. // We've handled solo 0 and 2, so if channel 1 isn't on, this must be // the situation. if (!on[0] && !on[1]) { #if DEBUG fprintf(stderr, "sound: noise/2\n"); #endif noisy = noisebit(); if (on[2]) { // Channel 2 plus noise (TONE NO4, etc.). for(i=0; i<count; i++) { a = envelope(freqstat[2], volf[2]); b = (noisy) ? volf[3] : -volf[3]; buffer[i] = (int16_t)mixer(a, b); freqstat[2] += freqstep[2]; freqstat[3] += freqstep[3]; if (freqstat[3] > M_FREQUENCY) { freqstat[3] -= M_FREQUENCY; noisy = noisebit(); } } return; } // Noise solo. This can only be triggered in BASIC with // something like SOUND(240,-1,0), but this is documented, // so it's not rare. for(i=0; i<count; i++) { b = (noisy) ? volf[3] : -volf[3]; buffer[i] = (int16_t)b; freqstat[3] += freqstep[3]; if (freqstat[3] > M_FREQUENCY) { freqstat[3] -= M_FREQUENCY; noisy = noisebit(); } } return; } // Now handle channel 1 solo. This can only happen if the channel 0 // argument for SOUND() had an amplitude of 30, which will mute it; // it does not occur in GBASIC or the menus. Nevertheless it's still // worth doing even though the situation is rare because it's very // inexpensive. SOLO(0,2,3, 1) // For other combinations of voices, we use this multistage mixer. // It does a lot of work inside the loop, so we try to avoid it. #if DEBUG fprintf(stderr, "sound: can't solo, using mixer\n"); #endif #define VOICE(n,v) \ if (!on[n]) { \ v = 0.0; \ } else { \ v = envelope(freqstat[n], volf[n]); \ freqstat[n] += freqstep[n]; \ } if (on[3]) noisy = noisebit(); // Prepare to generate noise. for(i=0; i<count; i++) { // Mix channels 0 and 1. VOICE(0, a) VOICE(1, b) m = mixer(a, b); // Mix channel 2, if enabled. if (on[2]) { a = envelope(freqstat[2], volf[2]); m = mixer(m, a); freqstat[2] += freqstep[2]; } // Mix noise, if enabled, and emit to buffer. if (!on[3]) { buffer[i] = (int16_t)m; } else { b = (noisy) ? volf[3] : -volf[3]; buffer[i] = (int16_t)mixer(m, b); freqstat[3] += freqstep[3]; if (freqstat[3] > M_FREQUENCY) { freqstat[3] -= M_FREQUENCY; noisy = noisebit(); } } } }
C
inherit "room/room"; static searched; string bush_desc; string ldesc; object sob; reset(arg) { if(arg) return; if(!searched) { bush_desc = "The bushes are deformed and twisted with somekind of dark magic.\nOne of bushes is moving and demonic roar can be heard from there"; ldesc ="This gloomy and deformed forest is filled with eerie sounds. The ground\n"+ "is full of corpses where are lots of maggots crawling and eating the flesh.\n"+ "A strange looking purple mist is covering the ground here and there and it\n"+ "makes breathing very hard. This forest is full of twisted and deformed\n"+ "looking trees and bushes. A mad cackling sound is coming from on of the\n"+ "bushes.\n"; } add_exit("south","room9"); add_exit("east","room7"); short_desc = "Deformed forest"; long_desc = ldesc; items = allocate(6); items[0] = "ground"; items[1] = "The ground is full of rottening corpses of different creatures"; items[2] = "mist"; items[3] = "The mist looks quite strange and magical"; items[4] = "bushes"; items[5] = bush_desc; } search_finished(string str) { if(str == "bushes" && !searched) { bush_desc = "The bushes are quite normal looking but still twisted and deformed!"; ldesc ="This gloomy and deformed forest is filled with eerie sounds. The ground\n"+ "is full of corpses where are lots of maggots crawling and eating the flesh.\n"+ "A strange looking purple mist is covering the ground here and there and it\n"+ "makes breathing very hard. This forest is full of twisted and deformed\n"+ "looking trees and bushes.\n"; write("You move one of the bushes and look behind it.\n"); write("Suddenly somebody with eyes full of rage jumps out of the bush and attacks you!\n"); sob = clone_object("/wizards/siki/forest/monsters/thuf"); move_object(sob, environment(this_player())); this_player()->attack_object(sob); searched = 1; this_object()->reset(); return 1; } write("You search around but find nothing special.\n"); return 1; }
C
#include <stdio.h> /* Hazrlayan : Muhammed Erdin - muhammederdinc.com */ int main() { int ilksayi=0,ikincisayi=1,i,son; printf("0 - 1 -"); for(i=0; i<=15; i++){ son = ilksayi+ikincisayi; ilksayi = ikincisayi; ikincisayi = son ; printf("%d - ",son); } return 0; }
C
typedef enum { ES_NO_EVENT, ES_SUBJECT_INPUT, ES_ENCODER_DATA } ES_EventTyp_t; typedef struct ES_Event_t { ES_EventTyp_t EventType; // what kind of event? uint16_t EventParam; // parameter value for use w/ this event }ES_Event; /**************************************************************************** Module data_collect.c Description Module for data collection and storage. It uses FIFO Queue system. Notes History When Who What/Why -------------- --- -------- 01/20/16 10:53 mal Begin coding ****************************************************************************/ #include "data_collect.h" #include "ES_Queue.h" /*----------------------------- Module Defines ----------------------------*/ typedef struct { ES_Event *pMem; // pointer to the memory uint8_t Size; // how big is it }ES_QueueDesc_t; #define NUM_SERVICES 2 #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0])) /*---------------------------- Module Variables ---------------------------*/ /****************************************************************************/ // The queues for the services static ES_Event Queue0[10]; #if NUM_SERVICES > 1 static ES_Event Queue1[10]; #endif #if NUM_SERVICES > 2 static ES_Event Queue2[10]; #endif #if NUM_SERVICES > 3 static ES_Event Queue3[10]; #endif #if NUM_SERVICES > 4 static ES_Event Queue4[10]; #endif #if NUM_SERVICES > 5 static ES_Event Queue5[10]; #endif #if NUM_SERVICES > 6 static ES_Event Queue6[10]; #endif #if NUM_SERVICES > 7 static ES_Event Queue7[10]; #endif #if NUM_SERVICES > 8 static ES_Event Queue8[10]; #endif #if NUM_SERVICES > 9 static ES_Event Queue9[10]; #endif #if NUM_SERVICES > 10 static ES_Event Queue10[10]; #endif /****************************************************************************/ // array of queue descriptors for posting by priority level static ES_QueueDesc_t const EventQueues[NUM_SERVICES] = { { Queue0, ARRAY_SIZE(Queue0) } #if NUM_SERVICES > 1 , { Queue1, ARRAY_SIZE(Queue1) } #endif #if NUM_SERVICES > 2 , { Queue2, ARRAY_SIZE(Queue2) } #endif #if NUM_SERVICES > 3 , { Queue3, ARRAY_SIZE(Queue3) } #endif #if NUM_SERVICES > 4 , { Queue4, ARRAY_SIZE(Queue4) } #endif #if NUM_SERVICES > 5 , { Queue5, ARRAY_SIZE(Queue5) } #endif #if NUM_SERVICES > 6 , { Queue6, ARRAY_SIZE(Queue6) } #endif #if NUM_SERVICES > 7 , { Queue7, ARRAY_SIZE(Queue7) } #endif #if NUM_SERVICES > 8 , { Queue8, ARRAY_SIZE(Queue8) } #endif #if NUM_SERVICES > 9 , { Queue9, ARRAY_SIZE(Queue9) } #endif #if NUM_SERVICES > 10 , { Queue10, ARRAY_SIZE(Queue10) } #endif }; /**************************************************************************** Function InitService Parameters nothing Returns nothing Description Initializes the necessary Queues for storing data Author Michael Lin, 01/20/16, 11:25 ****************************************************************************/ void InitDataService( void ) { // Initialize all Queues for (int i=0; i< ARRAY_SIZE(EventQueues); i++) { ES_InitQueue( EventQueues[i].pMem, EventQueues[i].Size ); } } /**************************************************************************** Function RunDataService Parameters nothing Returns void* Description Initializes the necessary Queues for storing data Author Michael Lin, 01/20/16, 11:25 ****************************************************************************/ void *RunDataService( void *arg ) { while (1) { for (int i=0; i< ARRAY_SIZE(EventQueues); i++) { ES_QueueDesc_t CurrentQueue = EventQueues[i]; ES_Event NewEvent; if (ES_IsQueueEmpty(CurrentQueue[i]) == false) { ES_DeQueue(CurrentQueue, &NewEvent); switch (NewEvent) { case ES_SUBJECT_INPUT: } } } } }
C
#pragma once #include <glm/vec2.hpp> /** * Represents a cell in the maze */ struct Cell { glm::vec2 location; float g_cost; // Distance from start cell float h_cost; // Distance from end cell float f_cost; // g cost + h cost Cell* previous = nullptr; };
C
/* * Test for salvager() */ #include "dominion.h" int failure = 0; int myassert(int x,char* msg) { if (x == 0) { printf("Assertion failed: %s\n",msg); failure = 1; return 0; } } void checkasserts() { if(!failure) { printf("Test successful! \n"); } } int main() { struct gameState gametime; int kingdom[] = {smithy,adventurer,gardens,embargo,cutpurse,mine,ambassador,outpost,baron,tribute}; initializeGame(2, kingdom, 555, &gametime); int i; i = gametime.numBuys; i = i + 1; int x = cardEffect(salvager, 1, NULL, NULL, &gametime, 0, NULL); int j; j = gametime.numBuys; myassert((i == j), "salvager card did not increment buys successfully. \n"); checkasserts(); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <malloc.h> // b 表示模式串,m 表示模式串的长度,本函数用于获取next数组 int* getNexts(char* b, int m) { int* next = (int*)malloc(sizeof(int)*m); next[0] = -1; int k = -1; for (int i = 1; i < m; ++i) { while (k != -1 && b[k + 1] != b[i]) { //如果b[k+1]!=b[i],则需要在i-1的最长匹配前缀子串中找到i-1的次长匹配前缀子串,这个次长匹配子串就是 最长匹配前缀子串的最长匹配前缀子串(有点像绕口令T T,结合图来理解) k = next[k]; } if (b[k + 1] == b[i]) { ++k; //如果b[k+1]==b[i],可以由next[i-1]直接得到next[i] } next[i] = k; } return next; } // a, b 分别是主串和模式串;n, m 分别是主串和模式串的长度。本函数返回匹配子串的首字符的位置,若不匹配则返回-1 int kmp(char* a, int n, char* b, int m) { int* next = getNexts(b, m); int j = 0; for (int i = 0; i < n; ++i) { while (j > 0 && a[i] != b[j]) { // 一直找到 a[i] 和 b[j] j = next[j - 1] + 1; } if (a[i] == b[j]) { ++j; } if (j == m) { // 找到匹配模式串的了 return i - m + 1; } } free(next); return -1; } int main() { char *a = "ababaeabac" ,*b = "abac"; int position = kmp(a,10,b,4); printf("%d",position); }
C
#include <stdio.h> #include <stdlib.h> #include <stdio.h> int main() { int num,base,mul=1,k; printf("Input the base value : "); scanf("%d",&num); printf("Input the value of power : "); scanf("%d",&base); k=power(num,base,mul); printf("The value of %d raised to the power %d is : %d",num,base,k); } int power (int num,int base,int mul) { if( base==0) { return mul; } mul=mul*num; base--; power(num,base,mul); }
C
//Some Parts Provided by Darrell Long # include "hash.h" # include <string.h> //# include "aes.c" # include "ll.c" static inline int realLength(int l) { return 16 * (l / 16 + (l % 16 ? 1 : 0)); } uint32_t hash(hashTable *h, const char *key) //Will return the position that it needs to get stored in { uint32_t output[4] = { 0x0 }; uint32_t sum = 0x0; int keyL = strlen(key); uint8_t *realKey = (uint8_t *) calloc(realLength(keyL), sizeof(uint8_t)); memcpy(realKey, key, keyL); for (int i = 0; i < realLength(keyL); i += 16) { AES128_ECB_encrypt((uint8_t *) h->s, // Salt (uint8_t *) realKey + i, // Input (uint8_t *) output); // Output sum ^= output[0] ^ output[1] ^ output[2] ^ output[3]; } free(realKey); return sum%(h->l); //return sum%(bloomSize); } hashTable *newHT(uint32_t l, uint32_t b[]) //Will set aside memory { hashTable *a = malloc(sizeof(struct hashTable)); for(int i=0;i<4;i++) { a->s[i] = b[i]; } a->l = l; //a->h = malloc(sizeof(listNode)*l); a->h = calloc(l,sizeof(listNode)); return a; } void delHT(hashTable *a) { // free(a->h); // free(a); //Help from TA for(uint32_t i=0; i < a->l ;i++) { delLL(a->h[i]); //Free up the individual hash positons } free(a->h); //Then free up the node free(a); } listNode *findHT(hashTable *a, const char *word) //Will give the node of that word, so you can do ->newspeak { uint32_t pos = hash(a,word); // return a->h[pos]; // return findLL(a->h,word); // if(moveToFront) // { // return moveToFrontfindLL(&(a->h[pos]),word); // } // else // { // return findLL(&(a->h[pos]),word); // } return findLL(&(a->h[pos]),word); //return moveToFrontfindLL(&(a->h[pos]),word); } void insertHT(hashTable *a, const char *old, const char *new) { uint32_t pos = hash(a,old); if(a->h[pos]==NULL) //If it does not detect a collison { a->h[pos] = newNode(old,new); } else { a->h[pos] = insertLL(&(a->h[pos]),old,new); //if it detects a collison } } void printHT(const hashTable *a) { printf("printHT is being used at the moment\n" ); for(uint32_t i=0; i<a->l;i++) //This is only for testing purposes { printLL(a->h[i]); } } // int main() // { // uint32_t initH[] = {0xDeadD00d, 0xFadedBee, 0xBadAb0de, 0xC0c0Babe}; // Hash table // hashTable *c = newHT(1,initH); // //insertHT(c,"hey","you"); // //insertHT(c,"hello","you"); // listNode **n = c->h; // // // // //listNode *temp = insertLL(&(c->h[0]),"The","Boss"); // // listNode *temp = insertLL(&(n[0]),"The","Boss"); // // listNode *temp2 = insertLL(&(n[0]),"giant","stuff"); // // // // listNode *newff = newNode("The","Boss"); // // listNode *tempForFind = findLL(&(n[0]),"The"); // // printf("%s\n",temp->oldspeak); // // //listNode *aNode = newNode("You suck","You win"); // //listNode temp = findLL(aNode,"hello"); // //printf("%s",temp->oldspeak); // //printHT(c); // //printLL(temp2); // printf("%s",tempForFind->oldspeak); // // return 0; // } // int main() // { // uint32_t initH[] = {0xDeadD00d, 0xFadedBee, 0xBadAb0de, 0xC0c0Babe}; // Hash table // hashTable *c = newHT(10,initH); // printf("%s\n",hash() ); // return 0; // }