language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C | //
// lib2048.c
// 2048-AI
//
// Created by Adam Rich on 4/11/16.
// Copyright © 2016 Adam Rich. All rights reserved.
//
#include "lib2048.h"
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <omp.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
// ========================================================================================
// Game Board Manipulation
// ========================================================================================
void print_game_board(uint8_t *game_board){
for (int ind = 0; ind < 4; ind++) {
printf("%d\t%d\t%d\t%d\n",game_board[0+4*ind],game_board[1+4*ind],game_board[2+4*ind]
,game_board[3+4*ind]);
}
}
// ========================================================================================
// Move Right
uint8_t *move_right(uint8_t *game_board){
// Allocate the new board and copy the old board into it
uint8_t *move_board = malloc(16*sizeof(uint8_t));
for (int ind = 0; ind<16; ind++) {
move_board[ind] = game_board[ind];
}
for (int repeat = 0; repeat < 3; repeat++) {
// Shift out zeros
for (int offset = 0; offset<13; offset +=4) {
for (int ind = 3; ind >0; ind--) {
// If The current value is zero
if (move_board[ind+offset] == 0) {
// shift value
move_board[ind+offset] = move_board[ind+offset-1];
move_board[ind-1+offset] = 0;
}
}
}
}
// Combine like blocks and shift
for (int offset = 0; offset<13; offset +=4) {
for (int ind = 3; ind >0; ind--) {
// if the two adjecent values are equal
if (move_board[ind+offset] == move_board[ind-1+offset] && move_board[ind+offset]>0) {
move_board[ind+offset] = move_board[ind+offset] + 1;
move_board[ind-1+offset] = 0;
}
}
}
// Shift out zeros
for (int offset = 0; offset<13; offset +=4) {
for (int ind = 3; ind >0; ind--) {
// If The current value is zero
if (move_board[ind+offset] == 0) {
// shift value
move_board[ind+offset] = move_board[ind+offset-1];
move_board[ind-1+offset] = 0;
}
}
}
return move_board;
}
// ========================================================================================
// Move Right
uint32_t *move_right32(uint32_t *game_board){
// Allocate the new board and copy the old board into it
uint32_t *move_board = malloc(16*sizeof(uint32_t));
for (int ind = 0; ind<16; ind++) {
move_board[ind] = game_board[ind];
}
for (int repeat = 0; repeat < 3; repeat++) {
// Shift out zeros
for (int offset = 0; offset<13; offset +=4) {
for (int ind = 3; ind >0; ind--) {
// If The current value is zero
if (move_board[ind+offset] == 0) {
// shift value
move_board[ind+offset] = move_board[ind+offset-1];
move_board[ind-1+offset] = 0;
}
}
}
}
// Combine like blocks and shift
for (int offset = 0; offset<13; offset +=4) {
for (int ind = 3; ind >0; ind--) {
// if the two adjecent values are equal
if (move_board[ind+offset] == move_board[ind-1+offset] && move_board[ind+offset]>0) {
move_board[ind+offset] = move_board[ind+offset] * 2;
move_board[ind-1+offset] = 0;
}
}
}
// Shift out zeros
for (int offset = 0; offset<13; offset +=4) {
for (int ind = 3; ind >0; ind--) {
// If The current value is zero
if (move_board[ind+offset] == 0) {
// shift value
move_board[ind+offset] = move_board[ind+offset-1];
move_board[ind-1+offset] = 0;
}
}
}
return move_board;
}
// ========================================================================================
// Move the Game Board left
uint8_t *move_left(uint8_t *game_board){
uint8_t *move_board = malloc(16*sizeof(uint8_t));
for (int ind = 0; ind<16; ind++) {
move_board[ind] = game_board[ind];
}
// Shift out zeros
for (int repeat = 0; repeat<3; repeat++) {
for (int offset = 0; offset<13; offset +=4) {
for (int ind = 0; ind < 3; ind++) {
// If The current value is zero
if (move_board[ind+offset] == 0) {
// shift value
move_board[ind+offset] = move_board[ind+offset+1];
move_board[ind+1+offset] = 0;
}
}
}
}
// Combine like blocks and shift
for (int offset = 0; offset<13; offset +=4) {
for (int ind = 0; ind < 3; ind++) {
// if the two adjecent values are equal
if (move_board[ind+offset] == move_board[ind+1+offset] && move_board[ind+offset]>0) {
move_board[ind+offset] +=1;
move_board[ind+1+offset] = 0;
}
}
}
// Shift out zeros
for (int offset = 0; offset<13; offset +=4) {
for (int ind = 0; ind < 3; ind++) {
// If The current value is zero
if (move_board[ind+offset] == 0) {
// shift value
move_board[ind+offset] = move_board[ind+offset+1];
move_board[ind+1+offset] = 0;
}
}
}
return move_board;
}
// ========================================================================================
// Move the Game Board up
uint8_t *move_up(uint8_t *game_board){
uint8_t *move_board = malloc(16*sizeof(uint8_t));
for (int ind = 0; ind<16; ind++) {
move_board[ind] = game_board[ind];
}
// Shift out zeros
for (int repeat = 0; repeat<4; repeat++) {
for (int offset = 0; offset<4; offset ++) {
for (int ind = 0; ind < 12; ind+=4) {
// If The current value is zero
if (move_board[ind+offset] == 0) {
// shift value
move_board[ind+offset] = move_board[ind+offset+4];
move_board[ind+4+offset] = 0;
}
}
}
}
// Combine like blocks and shift
for (int offset = 0; offset<4; offset ++) {
for (int ind = 0; ind < 12; ind+=4) {
// if the two adjecent values are equal
if (move_board[ind+offset] == move_board[ind+4+offset] && move_board[ind+offset]>0) {
move_board[ind+offset] +=1;
move_board[ind+4+offset] = 0;
}
}
}
// Shift out zeros
for (int repeat = 0; repeat<2; repeat++) {
for (int offset = 0; offset<4; offset ++) {
for (int ind = 0; ind < 12; ind+=4) {
// If The current value is zero
if (move_board[ind+offset] == 0) {
// shift value
move_board[ind+offset] = move_board[ind+offset+4];
move_board[ind+4+offset] = 0;
}
}
}
}
return move_board;
}
// ========================================================================================
// Move the Game Board down
uint8_t *move_down(uint8_t *game_board){
uint8_t *move_board = malloc(16*sizeof(uint8_t));
for (int ind = 0; ind<16; ind++) {
move_board[ind] = game_board[ind];
}
// Shift out zeros
for (int repeat = 0; repeat<4; repeat++) {
for (int offset = 0; offset<4; offset ++) {
for (int ind = 12; ind > 3 ; ind-=4) {
// If The current value is zero
if (move_board[ind+offset] == 0) {
// shift value
move_board[ind+offset] = move_board[ind+offset-4];
move_board[ind-4+offset] = 0;
}
}
}
}
// Combine like blocks and shift
for (int offset = 0; offset<4; offset ++) {
for (int ind = 12; ind > 3 ; ind-=4) {
// if the two adjecent values are equal
if (move_board[ind+offset] == move_board[ind-4+offset] && move_board[ind+offset]>0) {
move_board[ind+offset] +=1;
move_board[ind-4+offset] = 0;
}
}
}
// Shift out zeros
for (int repeat = 0; repeat<2; repeat++) {
for (int offset = 0; offset<4; offset ++) {
for (int ind = 12; ind > 3 ; ind-=4) {
// If The current value is zero
if (move_board[ind+offset] == 0) {
// shift value
move_board[ind+offset] = move_board[ind+offset-4];
move_board[ind-4+offset] = 0;
}
}
}
}
return move_board;
}
// ========================================================================================
// Count the number of zeros on the board
uint8_t count_zeros(uint8_t *game_board){
uint8_t zero_count = 0;
for (int ind =0; ind<16; ind++) {
if (game_board[ind]==0) {
zero_count++;
}
}
return zero_count;
}
// Compare to boards return 1 if they are the same
uint8_t compare_board(uint8_t *board1, uint8_t *board2){
int identical = 1;
for (int ind = 0; ind<16; ind++){
if (board1[ind] != board2[ind]){
identical = 0;
}
}
return identical;
}
// ========================================================================================
// Create a board with two or four added at a zero locations
uint8_t *create_random_board(uint8_t *game_board, int *last_zero_ind, uint8_t rand_value){
int ind;
uint8_t *rand_board = malloc(16*sizeof(uint8_t));
for (int ind = 0; ind<16; ind++) {
rand_board[ind] = game_board[ind];
}
for (ind = *last_zero_ind; ind<16; ind++) {
if (rand_board[ind]==0) {
rand_board[ind] = rand_value;
break;
}
}
*last_zero_ind = ind+1;
return rand_board;
}
// ========================================================================================
// adds a 2 or 4 to the board in a random location
uint8_t *add_random_number(uint8_t *game_board, int seed){
srand(seed);
int num_zeros, ind_z, rand_ind, rand_n, rand_num;
ind_z = 0;
num_zeros = count_zeros(game_board);
int *zero_inds;
zero_inds = malloc(sizeof(int)*num_zeros);
for (int ind =0; ind<16; ind++){
if (game_board[ind] ==0) {
zero_inds[ind_z] = ind;
ind_z++;
}
}
rand_ind = rand() % num_zeros + 0;
rand_n = rand() % 100;
if (rand_n < 11){
rand_num = 2;
}else{
rand_num = 1;
}
// printf("zero_ind %d, rand_n %d, rand_num %d\n", rand_ind, rand_n, rand_num);
game_board[zero_inds[rand_ind]] = rand_num;
//printf("\n rand ind %d zero ind %d rand num %d\n",rand_ind, zero_inds[rand_ind], rand_num);
//for (int ind = 0; ind<num_zeros; ind++){
// printf("%d ",zero_inds[ind]);
//}
free(zero_inds);
return game_board;
}
// Test the tree creation and deletion
void roll_out(uint8_t *game_board, int seed) {
srand(seed);
uint8_t *tmp_board;
int rand_num = 0;
int move_seed = 0;
int keep_moving = 1;
int num_moves = 0;
uint8_t *move_board = malloc(16*sizeof(uint8_t));
for (int ind = 0;ind<16;ind++){
move_board[ind] = game_board[ind];
}
// move_board = add_random_number(game_board_orig);
// print_game_board(game_board);
// printf("\n");
// print_game_board(move_board);
// printf("\n");
while (keep_moving>0){
// Choose a random move
rand_num = rand() % 4 + 1;
move_seed = rand() % 10000;
// printf("rand num %d \n", rand_num);
char next_move = 'a';
char up, down, left, right;
up = 'u';
down = 'd';
left = 'l';
right = 'r';
if (rand_num==1){
next_move = up;
}else if (rand_num==2){
next_move = down;
}else if (rand_num ==3){
next_move = left;
}else if (rand_num ==4){
next_move = right;
}
tmp_board = move_up(move_board);
if (next_move==up && !compare_board(tmp_board,move_board)){
move_board = move_up(move_board);
move_board = add_random_number(move_board, move_seed);
// print_game_board(move_board);
// printf("\n");
num_moves++;
}
tmp_board = move_down(move_board);
if(next_move==down && !compare_board(tmp_board,move_board)){
move_board = move_down(move_board);
move_board = add_random_number(move_board, move_seed);
// print_game_board(move_board);
// printf("\n");
num_moves++;
}
tmp_board = move_left(move_board);
if(next_move==left && !compare_board(tmp_board,move_board)){
move_board = move_left(move_board);
move_board = add_random_number(move_board, move_seed);
// print_game_board(move_board);
// printf("\n");
num_moves++;
}
tmp_board = move_right(move_board);
if(next_move==right && !compare_board(tmp_board,move_board)){
move_board = move_right(move_board);
move_board = add_random_number(move_board, move_seed);
// print_game_board(move_board);
// printf("\n");
num_moves++;
}
// If all the moves result in an identical board state
tmp_board = move_left(move_board);
if (compare_board(tmp_board,move_board)){
tmp_board = move_right(move_board);
if (compare_board(tmp_board,move_board)){
tmp_board = move_up(move_board);
if (compare_board(tmp_board,move_board)){
tmp_board = move_down(move_board);
if (compare_board(tmp_board,move_board)){
keep_moving = 0;
}
}
}
}
// printf("\nYou Lose\n");
for (int ind = 0;ind<16;ind++){
game_board[ind] = move_board[ind];
}
// print_game_board(game_board);
}
free(move_board);
}
uint32_t get_time(void){
uint32_t c_time = time(0);
printf("%d\n", c_time);
srand(c_time);
for (int ind = 0;ind<16;ind++){
printf("%d", rand() % 100);
}
printf("\n");
return c_time;
} |
C | #include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include "m.h"
#define CROSS_OVER 1
matrix newmatrix(int n) {
matrix a;
a = (matrix)malloc(sizeof(*a));
if (n <= CROSS_OVER) {
int i;
a->d = (double **)calloc(n, sizeof(double *));
for (i = 0; i < n; i++) {
a->d[i] = (double *)calloc(n, sizeof(double));
}
}
else {
n /= 2;
a->p = (matrix *)calloc(4, sizeof(matrix));
a11 = newmatrix(n);
a12 = newmatrix(n);
a21 = newmatrix(n);
a22 = newmatrix(n);
}
return a;
}
void randomfill(int n, matrix a){
if (n <= CROSS_OVER) {
int i, j;
double **p = a->d;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
p[i][j] = 1;
}
else {
n /= 2;
randomfill(n, a11);
randomfill(n, a12);
randomfill(n, a21);
randomfill(n, a22);
}
}
// Strassen Algorithm
void multiply(int n, matrix a, matrix b, matrix c, matrix d){
if (n <= CROSS_OVER) {
double sum, **p = a->d, **q = b->d, **r = c->d;
int i, j, k;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
for (sum = 0., k = 0; k < n; k++)
sum += p[i][k] * q[k][j];
r[i][j] = sum;
}
}
}
else {
n /= 2;
sub(n, a12, a22, d11);
add(n, b21, b22, d12);
multiply(n, d11, d12, c11, d21);
sub(n, a21, a11, d11);
add(n, b11, b12, d12);
multiply(n, d11, d12, c22, d21);
add(n, a11, a12, d11);
multiply(n, d11, b22, c12, d12);
sub(n, c11, c12, c11);
sub(n, b21, b11, d11);
multiply(n, a22, d11, c21, d12);
add(n, c21, c11, c11);
sub(n, b12, b22, d11);
multiply(n, a11, d11, d12, d21);
add(n, d12, c12, c12);
add(n, d12, c22, c22);
add(n, a21, a22, d11);
multiply(n, d11, b11, d12, d21);
add(n, d12, c21, c21);
sub(n, c22, d12, c22);
add(n, a11, a22, d11);
add(n, b11, b22, d12);
multiply(n, d11, d12, d21, d22);
add(n, d21, c11, c11);
add(n, d21, c22, c22);
}
}
/* c = a+b */
void add(int n, matrix a, matrix b, matrix c){
if (n <= CROSS_OVER) {
double **p = a->d, **q = b->d, **r = c->d;
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
r[i][j] = p[i][j] + q[i][j];
}
}
}
else {
n /= 2;
add(n, a11, b11, c11);
add(n, a12, b12, c12);
add(n, a21, b21, c21);
add(n, a22, b22, c22);
}
}
/* c = a-b */
void sub(int n, matrix a, matrix b, matrix c){
if (n <= CROSS_OVER) {
double **p = a->d, **q = b->d, **r = c->d;
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
r[i][j] = p[i][j] - q[i][j];
}
}
}
else {
n /= 2;
sub(n, a11, b11, c11);
sub(n, a12, b12, c12);
sub(n, a21, b21, c21);
sub(n, a22, b22, c22);
}
}
void printma(int n, matrix a){
if (n <= CROSS_OVER){
int i, j;
double **p = a->d;
for (i = 0; i < n; i++){
printf("\n");
for (j = 0; j < n; j++)
printf("%f", p[i][j]);
}
printf("\n");
}
else{
// printf("\n");
n /= 2;
printma(n, a11);
printma(n, a12);
printma(n, a21);
printma(n, a22);
}
printf("\n");
}
int main()
{
int n = 512;
matrix a, b, c, d;
a = newmatrix(n);
b = newmatrix(n);
c = newmatrix(n);
d = newmatrix(n);
randomfill(n, a);
randomfill(n, b);
clock_t t = clock();
multiply(n, a, b, c, d); /* strassen algorithm */
//printma(n, c);
t = clock() - t;
// Calculate the time
float time = ((float)t)/CLOCKS_PER_SEC;
printf("%f seconds \n", time);
return 0;
}
|
C | #include <stdio.h>
int buffer[100] = {1,1};
int count = 1;
// start with 0 ...
unsigned int fib(unsigned int n){
if(n>count){
for(int i=count+1;i<=n;i++){
buffer[i] = buffer[i-1]+buffer[i-2];
}
count = n;
}
return buffer[n];
}
int main(){
for(int i=0;i<10;i++)
printf("%d ",fib(i));
printf("\n");
return 0;
}
|
C | #include "fileManager.h"
void __filemanager_read_id (char *filename, char *id_buff) {
int i, j, fn_len, start_pos, end_pos;
fn_len = strlen (filename);
start_pos = 0;
/* Skip the possiblw path in the filename */
for (i = 0; i < fn_len; i ++) {
if (filename[i] == '/' || filename[i] == '\'') { /* Both windows and linux */
start_pos = i + 1;
}
}
/* skip the file extension */
for (end_pos = fn_len - 1; end_pos > start_pos && filename[end_pos] != '.'; end_pos --);
/* If the file has no extension */
if (start_pos == end_pos) end_pos = fn_len;
/* Copy file name bounded to the maximum label length */
for (i = start_pos, j = 0; i < end_pos && j < MAX_LABEL_LENGTH - 1; i ++, j ++) {
id_buff[j] = filename[i];
}
id_buff[j] = '\0';
}
seqfile_t __filemanager_get_filetype (struct filemanager *fmobj) {
unsigned int i;
for (i = fmobj->offset; i < fmobj->buffer_size; i ++) {
switch (fmobj->buffer[i]) {
case '>':
return FASTA;
case '@':
return FASTQ;
case ' ':
break;
default:
return UNKNOWN;
}
}
return UNKNOWN;
}
void filemanager_destroy (struct filemanager *fmobj) {
fclose (fmobj->pf);
free (fmobj);
fmobj = NULL;
}
struct filemanager *filemanager_init (char *filename) {
struct filemanager *fmobj;
if ((fmobj = (struct filemanager *) malloc (sizeof (struct filemanager))) == NULL) {
perror ("Memory allocation failure parsing input\n");
return NULL;
}
if ((fmobj->pf = fopen (filename, "r")) == NULL) {
free (fmobj);
perror ("Error opening input file\n");
return NULL;
}
__filemanager_read_id (filename, fmobj->empty_identifier);
fmobj->offset = 0;
fmobj->buffer_size = fread (fmobj->buffer, 1, BUFF_SIZE, fmobj->pf);
/* Check reading error */
if (fmobj->buffer_size < BUFF_SIZE && feof (fmobj->pf) == 0) {
perror ("Error reading input file\n");
free (fmobj);
return NULL;
}
fmobj->filetype = __filemanager_get_filetype (fmobj);
if (fmobj->filetype == UNKNOWN) {
perror ("Input file format not recognized\n");
free (fmobj);
return NULL;
}
return fmobj;
}
struct sequence_t *__filemanager_next_seq (struct filemanager *fmobj, struct sequence_t *seq) {
char next_char;
parse_status_t parse_status = H_PRE_SI;
int qual_read_char = 0; /* Count of the number of caracters read in quality score of fastq */
seq->label_size = 0;
seq->sequence_size = 0;
if (fmobj->finish == true) {
free (seq->sequence);
free (seq);
seq = NULL;
return NULL;
}
while (1) {
if (fmobj->offset == fmobj->buffer_size) {
if (feof (fmobj->pf) == 1) { /* End of file and end of buffer */
fmobj->finish = true;
break;
}
fmobj->offset = 0;
fmobj->buffer_size = fread (fmobj->buffer, 1, BUFF_SIZE, fmobj->pf);
/* Check reading error */
if (fmobj->buffer_size < BUFF_SIZE && feof (fmobj->pf) == 0) {
perror ("Error reading input file\n");
free (seq->sequence);
free (seq);
seq = NULL;
return NULL;
}
}
next_char = fmobj->buffer[fmobj->offset];
fmobj->offset ++;
/* From here on I process the sequence/header */
switch (parse_status) {
case H_PRE_SI:
switch (next_char) {
case '>':
case '@':
parse_status = H_PRE_LABEL;
break;
case ' ':
break;
default:
perror ("Input file parsing error");
free (seq->sequence);
free (seq);
seq = NULL;
return NULL;
}
break;
case H_PRE_LABEL:
switch (next_char) {
case '\n':
strcpy (seq->label, fmobj->empty_identifier);
seq->label_size = strlen (fmobj->empty_identifier);
parse_status = SEQUENCE;
break;
case ' ':
break;
default:
parse_status = H_LABEL;
fmobj->offset --; /* Reprocess this caracter */
break;
}
break;
case H_LABEL:
switch (next_char) {
case '\n':
parse_status = SEQUENCE;
break;
case ' ':
/* without break to allow spaces in fastq (instead trim in fasta) */
/* this will insert an extra space that will be removed in H_POST_LABEL */
if (fmobj->filetype == FASTA) parse_status = H_POST_LABEL;
default:
if (seq->label_size < MAX_LABEL_LENGTH - 1) { /* Prevent exceed buffer size with \0 */
seq->label[seq->label_size] = next_char;
seq->label_size ++;
seq->label[seq->label_size] = '\0';
}
break;
}
break;
case H_POST_LABEL: /* happens only with fmobj->filetype == FASTA */
if (next_char == '\n') {
parse_status = SEQUENCE;
/* Removes the extra space due to the absence of the break in the H_LABEL case */
seq->label_size --;
seq->label[seq->label_size] = '\0';
}
break;
case SEQUENCE:
switch (next_char) {
case ' ':
break;
case '\n':
break;
case '>': /* No break because in fastq the caracter is evaluated */
if (fmobj->filetype == FASTA) {
fmobj->offset --; /* Reprocess this caracter */
return seq;
}
case '+': /* No break because in fasta the caracter is evaluated */
if (fmobj->filetype == FASTQ) {
parse_status = FQ_PLUS;
break;
}
default:
/* Buffer extension is required here */
if (seq->sequence_size == seq->buffer_size - 1) {
seq->sequence = (char *) realloc (seq->sequence, (seq->buffer_size + BUFF_SIZE) * sizeof (char));
if (seq->sequence == NULL) {
perror ("Error reallocating memory while reading the input\n");
free (seq);
seq = NULL;
return NULL;
}
seq->buffer_size += BUFF_SIZE;
}
seq->sequence[seq->sequence_size] = next_char;
seq->sequence_size ++;
seq->sequence[seq->sequence_size] = '\0';
break;
}
break;
case FQ_PLUS:
if (next_char == '\n') parse_status = FQ_SCORE;
break;
case FQ_SCORE:
switch (next_char) {
case '\n':
break;
case '@': /* without break - if it is not the new element it is part of the score */
if (qual_read_char >= seq->sequence_size) {
fmobj->offset --; /* Reprocess this caracter */
return seq;
}
default:
qual_read_char ++;
break;
}
break;
}
}
return seq;
}
struct sequence_t *filemanager_next_seq (struct filemanager *fmobj, struct sequence_t *seq) {
if (seq == NULL) {
seq = (struct sequence_t *) malloc (sizeof (struct sequence_t));
if (seq == NULL) {
perror ("Memory error reading a new sequence\n");
return NULL;
}
seq->sequence = (char *) malloc (BUFF_SIZE * sizeof (char));
if (seq->sequence == NULL) {
free (seq);
perror ("Memory error reading a new sequence\n");
return NULL;
}
seq->buffer_size = BUFF_SIZE;
}
seq->label_size = 0;
seq->sequence_size = 0;
if (fmobj->filetype == FASTQ || fmobj->filetype == FASTA)
return __filemanager_next_seq (fmobj, seq);
return NULL;
}
|
C | /*
Threading routines
Written by Noel Cower
See LICENSE.md for license information
*/
#ifndef __SNOW__THREAD_H__
#define __SNOW__THREAD_H__
#include <snow-config.h>
#ifdef __SNOW__THREAD_C__
#define S_INLINE
#else
#define S_INLINE inline
#endif
#if defined(__cplusplus)
extern "C"
{
#endif /* __cplusplus */
typedef void *(*thread_fn_t)(void *context);
#if S_USE_PTHREADS
typedef pthread_t thread_t;
/*! Initializes a thread. */
S_INLINE void thread_create(thread_t *thread, thread_fn_t fn, void *context)
{
pthread_create(thread, NULL, fn, context);
}
S_INLINE void thread_kill(thread_t thread)
{
pthread_cancel(thread);
}
S_INLINE int thread_equals(thread_t left, thread_t right)
{
return pthread_equal(left, right);
}
S_INLINE void thread_detach(thread_t thread)
{
pthread_detach(thread);
}
S_INLINE void thread_join(thread_t thread, void **return_value)
{
pthread_join(thread, return_value);
}
S_INLINE void thread_exit(void *return_value)
{
pthread_exit(return_value);
}
S_INLINE thread_t thread_current_thread(void)
{
return pthread_self();
}
#else /* S_USE_PTHREADS */
/*! Initializes a thread. */
void thread_create(thread_t *thread, thread_fn_t fn, void *context);
void thread_create(thread_t *thread, thread_fn_t fn, void *context);
void thread_kill(thread_t thread);
int thread_equals(thread_t left, thread_t right);
void thread_detach(thread_t thread);
void thread_join(thread_t thread, void **return_value);
void thread_exit(void *return_value);
thread_t thread_current_thread(void);
#endif
#if defined(__cplusplus)
}
#endif /* __cplusplus */
#include <inline.end>
#endif /* end of include guard: __SNOW__THREAD_H__ */
|
C | /*
n = 4 için şekildeki gibi çıktı veren kod
1
2 3
4 5 6
7 8 9 10
*/
#include <stdio.h>
int main() {
int i,j,n;
int sayi = 1;
printf("satir sayisi giriniz: ");
scanf("%d",&n);
int b = n-1;
for (i=1; i<=n; i++) {
for (j=0; j<b; j++)
printf(" ");
for (j=0; j<i; j++,sayi++)
printf("%8d",sayi);
b--;
printf("\n");
}
return 0;
}
|
C | #include<stdio.h>
void main ()
{
int a;
float b,c;
printf("enter the values of a&b");
scanf("%d%f",&a,&b);
c=a+b;
printf("addition is %f",c);
}
|
C | #include<stdio.h>
int main()
{
int a,b,c,d,e,sum;
printf("enter a number");
scanf("%d%d%d%d%d",&a&b&c&d&e);
{
sum=a+b+c+d+e;
}
printf("%d",sum);
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_treat_string.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: edjavid <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/24 10:27:28 by edjavid #+# #+# */
/* Updated: 2021/04/24 11:34:09 by edjavid ### ########.fr */
/* */
/* ************************************************************************** */
#include "./ft_printf.h"
int ft_treat_string(va_list print_list, the_flags *flags, int nb)
{
char *str;
int count;
int i;
i = 0;
count = 0;
str = (char *)va_arg(print_list, char*);
if (flags[nb].precision > 0)
str = ft_substr(str, 0, flags[nb].precision);
if (flags[nb].minus == 1)
while (str[i])
{
write(1, &str[i], 1);
i++;
count++;
}
count += ft_treat_width(flags, flags[nb].zero, nb, ft_strlen(str));
if (flags[nb].minus == 0)
while (str[i])
{
write(1, &str[i], 1);
i++;
count++;
}
return (count);
}
|
C | #include<stdio.h>
#include<string.h>
void main(){
char c1[5]="abc",c2;
int a,val=0,i;
for ( i = 0; c1[i]!='\0'; i++)
{
val=val*128;
a=(int)c1[i];
val+=a;
}
printf("%d",val);
} |
C | //
// Created by Alexander Swanson on 2019-01-23.
// [email protected]
//
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include "warmup.aswanso2.h"
// Calculates the sum from "sum" to "n".
int calculateSum(int n, int *sum) {
if (n >= 0) {
// Calculate the sum
*sum = (n * (n + 1)) / 2;
return 0;
} else {
return 1;
}
}
// Creates a new StudentData record.
int createRecord(int id, char *name, StudentData **record) {
if (strlen(name) > 31) {
// Make pointer point to NULL
*record = NULL;
return 1;
} else {
StudentData *newRecord;
// Create memory for new "StudentData" struct
newRecord = (StudentData *) malloc(sizeof(StudentData));
// Define new values
(*newRecord).id = id;
strcpy((*newRecord).name, name);
// Define new pointer
*record = newRecord;
return 0;
}
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "command_utils.h"
#include "requests/get.h"
void log_request(command request) {
printf("Request received: \nMethod: \t %d\nURL: \t %s\nData type: \t %d\nData: \t %s\n",
request.method_code, request.url, request.data_type, request.data);
}
int parse_command(char *raw_request, int file_descriptor) {
char *token;
int line = 0;
command request;
printf("%s", raw_request);
// Allocations only for testing
// Dinamic allocations will soon be added
request.data = (char*) calloc(100, sizeof(char));
token = strtok(raw_request, ";");
while (token != NULL) {
if (line == 0) {
// deal with method
if (strcmp(token, "GET") == 0) {
request.method_code = GET_TYPE;
} else if (strcmp(token, "POST") == 0) {
request.method_code = POST_TYPE;
} else if (strcmp(token, "DELETE") == 0) {
request.method_code = DELETE_TYPE;
} else if (strcmp(token, "PUT") == 0) {
request.method_code = PUT_TYPE;
} else if (strcmp(token, "PATCH") == 0) {
request.method_code = PATCH_TYPE;
} else {
// handle error
}
} else if (line == 1) {
request.url = (char*) calloc(strlen(token) + 1, sizeof(char));
strcpy(request.url, token);
} else if (line == 2) {
// deal with content type
if (strcmp(token, "application/json") == 0) {
request.data_type = APPLICATION_JSON;
} else if (strcmp(token, "application/xml") == 0) {
request.data_type = APPLICATION_XML;
} else if (strcmp(token, "text") == 0) {
request.data_type = TEXT;
} else {
//TODO: Might add automated data typing
printf("Invalid data type, trying text");
request.data_type = TEXT;
}
} else {
// deal with data itself
request.data = (char*) calloc(strlen(token) + 1, sizeof(char));
strcpy(request.data, token);
}
++line;
token = strtok(NULL, ";");
}
free(token);
log_request(request);
execute_command(request, file_descriptor);
return 0;
}
int dummy_callback(char* incoming, int file_descriptor) {
printf("Inside handler\n");
//incoming[strlen(incoming) - 2] = '\0';
printf("Data received: %s\n", incoming);
printf("Data expected: %s\n", "ping");
printf("Comparison: %d\n", strcmp(incoming, "ping"));
if (strcmp(incoming, "ping") == 0) {
send(file_descriptor, "pong", strlen("pong"), 0);
}
else {
send(file_descriptor, "pingme", strlen("pingme"), 0);
}
}
int creation_callback(char* incoming, int file_descriptor) {
char* connection_message = "WebServer by Richard v1.0";
char* disconnect_message = "Goodbye from WebServer v1.0!";
if (strcmp(incoming, "connect") == 0) {
send(file_descriptor, connection_message, strlen(connection_message), 0);
} else if (strcmp(incoming, "disconnect") == 0) {
send(file_descriptor, disconnect_message, strlen(disconnect_message), 0);
}
}
void add_dummy_get() {
printf("Adding the creation path\n");
add_path("http://localhost:8080/connect");
set_callback("http://localhost:8080/connect", &creation_callback);
printf("Added the creation path\n");
printf("Adding the dummy path\n");
add_path("http://localhost:8080/ping");
set_callback("http://localhost:8080/ping", &dummy_callback);
printf("Added the dummy path\n");
}
int execute_command(command request, int file_descriptor) {
char *url = (char*) calloc(30, sizeof(char));
char *data = (char*) calloc(100, sizeof(char));
add_dummy_get();
switch (request.method_code) {
case 1:
strcpy(url, request.url);
strcpy(data, request.data);
get_request new_request = find_request(url);
get(new_request, data, file_descriptor);
free(url);
free(data);
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
default:
// handle error
break;
}
}
|
C | #include "hash_tables.h"
/**
* hash_table_get - gets the value associated with a key in a hash table
* @ht: pointer to hash table
* @key: key, string
* Return: description
**/
char *hash_table_get(const hash_table_t *ht, const char *key)
{
unsigned long int i;
hash_node_t *node;
if (ht == NULL || strlen(key) == 0)
return (NULL);
i = key_index((const unsigned char *)key, ht->size);
node = ht->array[i];
while (node)
{
if (node->key && strcmp(key, (const char *)node->key) == 0)
return (node->value);
node = node->next;
}
return (NULL);
}
|
C | #include<stdio.h>
int main()
{
int link[100],data[100],head=0,size=1,i=0;
memset(data,0,sizeof(data));
printf("Enter the link of head node\n");
scanf("%d",&head);
link[0]=head;
while(scanf("%d",&data[link[i]])!=EOF){
printf("Enter the link of the next element\n");
i++;
scanf("%d",&link[i]);
size++;
}
for(int i=0; i<100; i++){
if(data[i]>0)
printf("%d ",data[i]);
}
return 0;
}
|
C | //node struct
typedef struct Node{
int size;
int addr;
Node* nxt;
}Node;
typedef struct LinkedList{
Node *head;
}LinkedList;
|
C | #ifndef MATH_H
#define MATH_H
#ifdef __cplusplus
extern "C" {
#endif
typedef float float_t;
typedef double double_t;
// C90
int abs(int x);
double acos (double x);
float acosf(float x);
long double acosl(long double x);
double asin (double x);
float asinf(float x);
long double asinl(long double x);
double atan (double x);
float atanf(float x);
long double atanl(long double x);
double atan2 (double y, double x);
float atan2f(float y, float x);
long double atan2l(long double y, long double x);
double ceil (double x);
float ceilf(float x);
long double ceill(long double x);
double cos (double x);
float cosf(float x);
long double cosl(long double x);
double cosh (double x);
float coshf(float x);
long double coshl(long double x);
double exp (double x);
float expf(float x);
long double expl(long double x);
double fabs (double x);
float fabsf(float x);
long double fabsl(long double x);
double floor (double x);
float floorf(float x);
long double floorl(long double x);
double fmod (double x, double y);
float fmodf(float x, float y);
long double fmodl(long double x, long double y);
double frexp (double value, int* exp);
float frexpf(float value, int* exp);
long double frexpl(long double value, int* exp);
double ldexp (double value, int exp);
float ldexpf(float value, int exp);
long double ldexpl(long double value, int exp);
double log (double x);
float logf(float x);
long double logl(long double x);
double log10 (double x);
float log10f(float x);
long double log10l(long double x);
double modf (double value, double* iptr);
float modff(float value, float* iptr);
long double modfl(long double value, long double* iptr);
double pow (double x, double y);
float powf(float x, float y);
long double powl(long double x, long double y);
double sin (double x);
float sinf(float x);
long double sinl(long double x);
double sinh (double x);
float sinhf(float x);
long double sinhl(long double x);
double sqrt (double x);
float sqrtf(float x);
long double sqrtl(long double x);
double tan (double x);
float tanf(float x);
long double tanl(long double x);
double tanh (double x);
float tanhf(float x);
long double tanhl(long double x);
// C99
bool signbit(double x);
int fpclassify(double x);
bool isfinite(double x);
bool isinf(double x);
bool isnan(double x);
bool isnormal(double x);
bool isgreater(double x, double y);
bool isgreaterequal(double x, double y);
bool isless(double x, double y);
bool islessequal(double x, double y);
bool islessgreater(double x, double y);
bool isunordered(double x, double y);
double acosh (double x);
float acoshf(float x);
long double acoshl(long double x);
double asinh (double x);
float asinhf(float x);
long double asinhl(long double x);
double atanh (double x);
float atanhf(float x);
long double atanhl(long double x);
double cbrt (double x);
float cbrtf(float x);
long double cbrtl(long double x);
double copysign (double x, double y);
float copysignf(float x, float y);
long double copysignl(long double x, long double y);
double erf (double x);
float erff(float x);
long double erfl(long double x);
double erfc (double x);
float erfcf(float x);
long double erfcl(long double x);
double exp2 (double x);
float exp2f(float x);
long double exp2l(long double x);
double expm1 (double x);
float expm1f(float x);
long double expm1l(long double x);
double fdim (double x, double y);
float fdimf(float x, float y);
long double fdiml(long double x, long double y);
double fma (double x, double y, double z);
float fmaf(float x, float y, float z);
long double fmal(long double x, long double y, long double z);
double fmax (double x, double y);
float fmaxf(float x, float y);
long double fmaxl(long double x, long double y);
double fmin (double x, double y);
float fminf(float x, float y);
long double fminl(long double x, long double y);
double hypot (double x, double y);
float hypotf(float x, float y);
long double hypotl(long double x, long double y);
int ilogb (double x);
int ilogbf(float x);
int ilogbl(long double x);
double lgamma (double x);
float lgammaf(float x);
long double lgammal(long double x);
long long llrint (double x);
long long llrintf(float x);
long long llrintl(long double x);
long long llround (double x);
long long llroundf(float x);
long long llroundl(long double x);
double log1p (double x);
float log1pf(float x);
long double log1pl(long double x);
double log2 (double x);
float log2f(float x);
long double log2l(long double x);
double logb (double x);
float logbf(float x);
long double logbl(long double x);
long lrint (double x);
long lrintf(float x);
long lrintl(long double x);
long lround (double x);
long lroundf(float x);
long lroundl(long double x);
double nan (const char* str);
float nanf(const char* str);
long double nanl(const char* str);
double nearbyint (double x);
float nearbyintf(float x);
long double nearbyintl(long double x);
double nextafter (double x, double y);
float nextafterf(float x, float y);
long double nextafterl(long double x, long double y);
double nexttoward (double x, long double y);
float nexttowardf(float x, long double y);
long double nexttowardl(long double x, long double y);
double remainder (double x, double y);
float remainderf(float x, float y);
long double remainderl(long double x, long double y);
double remquo (double x, double y, int* pquo);
float remquof(float x, float y, int* pquo);
long double remquol(long double x, long double y, int* pquo);
double rint (double x);
float rintf(float x);
long double rintl(long double x);
double round (double x);
float roundf(float x);
long double roundl(long double x);
double scalbln (double x, long ex);
float scalblnf(float x, long ex);
long double scalblnl(long double x, long ex);
double scalbn (double x, int ex);
float scalbnf(float x, int ex);
long double scalbnl(long double x, int ex);
double tgamma (double x);
float tgammaf(float x);
long double tgammal(long double x);
double trunc (double x);
float truncf(float x);
long double truncl(long double x);
#ifdef __cplusplus
}
#endif
#endif
|
C | #include "sort.h"
/**
*shell_sort - sorts an array of integers in ascending order
*using the Shell sort algorithm, using the Knuth sequence
*@array: the array
*@size: the size
*Return: Nothing
*/
void shell_sort(int *array, size_t size)
{
size_t h = 1, i, n;
int number;
if (array == NULL || size < 2)
return;
while (h < size / 3)
{
h = h * 3 + 1;
}
for (; h >= 1; h /= 3)
{
for (i = h; i < size; i++)
{
n = i;
while (n >= h && array[n] < array[n - h])
{
number = array[n];
array[n] = array[n - h];
array[n - h] = number;
n -= h;
}
}
print_array(array, size);
}
}
|
C | /*************************************************************************
> File Name: exp-6-52.c
> Author: xiaoxiaoh
> Mail: [email protected]
> Created Time: Tue Aug 1 11:53:10 2017
************************************************************************/
/*
* Star pattern programs - Write a C program to print the given star patterns.
*
*/
#include <stdio.h>
int printSquareStar();
int printHollowSquareStar();
int printRhombusStar();
int printHollowRhombusStar();
int printMirroredRhombusStar();
int printHollowMirroredRhombusStar();
int printRightTriangleStar();
int printHollowRightTriangleStar();
int printMirrioredRightTriangleStar();
int printHollowMirroredRightTriangleStar();
int printInvertedRightTriangleStar();
int printHollowInvertedRightTriangleStar();
int printInvertedMirroredRightTriangleStar();
int printHollowInvertedMirroredRightTriangleStar();
int printPyramidStar();
int printHollowPyramidStar();
int printInvertedPyramidStar();
int printHollowInvertedPyramidStar();
int printHalfDiamondStar();
int printMirroredHalfDiamondStar();
int printDiamondStar();
int printHollowDiamondStar();
int printRightArrowStar();
int printLeftArrowStar();
int printPlusStar();
int printXStart();
int printEightStar();
int printHeartStar();
int main()
{
//printSquareStar();
//printHollowSquareStar();
//printRhombusStar();
//printHollowRhombusStar();
//printMirroredRhombusStar();
//printHollowMirroredRhombusStar();
//printRightTriangleStar();
//printHollowRightTriangleStar();
//printMirroredRightTriangleStar();
//printHollowMirroredRightTriangleStar();
//printInvertedRightTriangleStar();
//printHollowInvertedRightTriangleStar();
//printInvertedMirroredRightTriangleStar();
//printHollowInvertedMirroredRightTriangleStar();
//printPyramidStar();
//printHollowPyramidStar();
//printInvertedPyramidStar();
//printHollowInvertedPyramidStar();
//printHalfDiamondStar();
//printMirroredHalfDiamondStar();
//printDiamondStar();
//printHollowDiamondStar();
//printRightArrowStar();
//printLeftArrowStar();
//printPlusStar();
//printXStart();
printEightStar();
//printHeartStar();
}
int printHeartStar()
{
int i, j, m, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=num/2; i<=num; i+=2)
{
for(j=1; j<num-i; j+=2)
{
printf("%2c", ' ');
}
for(j=1; j<=i; j++)
{
printf("%2c", '*');
}
for(j=1; j<=num-i; j++)
{
printf("%2c", ' ');
}
for(j=1; j<=i; j++)
{
printf("%2c", '*');
}
printf("\n");
}
for(i=num; i>=1; i--)
{
for(j=i; j<num; j++)
{
printf("%2c", ' ');
}
for(j=1; j<=(i*2)-1; j++)
{
printf("%2c", '*');
}
printf("\n");
}
return 0;
}
int printEightStar()
{
int i, j, k, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=1; i<=(2*num-1); i++)
{
for(j=1; j<=num; j++)
{
printf("%2c", ' ');
if((i==1) ||(i==num) ||(j==1) ||(j==num) ||(i==(2*num-1)))
printf("%2c", '*');
else
printf("%2c", ' ');
}
printf("\n");
}
return 0;
}
int printXStart()
{
int i, j, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=1; i<=(2*num-1); i++)
{
for(j=1; j<=(2*num-1); j++)
{
if((i==j) || (i+j)==(2*num))
printf("%2c", '*');
else
printf("%2c", ' ');
}
printf("\n");
}
return 0;
}
int printPlusStar()
{
int i, j, k, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=1; i<=num-1; i++)
{
for(j=1; j<=num-1; j++)
{
printf("%2c", ' ');
}
printf("%2c\n", '*');
}
for(k=1; k<=(2*num-1); k++)
{
printf("%2c", '*');
}
printf("\n");
for(j=1; j<=num-1; j++)
{
for(i=1; i<=num-1; i++)
{
printf("%2c", ' ');
}
printf("%2c\n", '*');
}
return 0;
}
int printLeftArrowStar()
{
int i, j, k, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
for(j=i; j<=num; j++)
{
printf("%2c", ' ');
}
for(k=num; k>=i; k--)
{
printf("%2c", '*');
}
printf("\n");
}
for(i=2; i<=num; i++)
{
for(j=1; j<=i; j++)
{
printf("%2c", ' ');
}
for(k=1; k<=i; k++)
{
printf("%2c", '*');
}
printf("\n");
}
return 0;
}
int printRightArrowStar()
{
int i, j, k, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
for(j=0; j<=2*i; j++)
{
printf("%2c", ' ');
}
for(k=num; k>=i; k--)
{
printf("%2c", '*');
}
printf("\n");
}
for(i=num-1; i>=1; i--)
{
for(j=0; j<=2*i; j++)
{
printf("%2c", ' ');
}
for(k=num; k>=i; k--)
{
printf("%2c", '*');
}
printf("\n");
}
return 0;
}
int printHollowDiamondStar()
{
int i, j, m, n, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
for(j=i; j<=num; j++)
{
printf("%2c", '*');
}
for(m=1; m<(2*i-1); m++)
{
printf("%2c", ' ');
}
for(n=i; n<=num; n++)
{
printf("%2c", '*');
}
printf("\n");
}
for(i=1; i<=num; i++)
{
for(j=1; j<=i; j++)
{
printf("%2c", '*');
}
for(m=i; m<=(2*num-i-1); m++)
{
printf("%2c", ' ');
}
for(n=1; n<=i; n++)
{
printf("%2c", '*');
}
printf("\n");
}
return 0;
}
int printDiamondStar()
{
int i, j, k, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
for(j=i; j<=num; j++)
{
printf("%2c", ' ');
}
for(k=1; k<=2*i; k++)
{
printf("%2c", '*');
}
printf("\n");
}
for(i=1; i<=num; i++)
{
for(j=1; j<=i; j++)
{
printf("%2c", ' ');
}
for(k=i; k<=(2*num-i); k++)
{
printf("%2c", '*');
}
printf("\n");
}
return 0;
}
int printMirroredHalfDiamondStar()
{
int i, j, k, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
for(k=num; k>=i; k--)
{
printf("%2c", ' ');
}
for(j=1; j<=i; j++)
{
printf("%2c", '*');
}
printf("\n");
}
for(i=1; i<=num; i++)
{
for(j=1; j<=i; j++)
{
printf("%2c", ' ');
}
for(k=i; k<=num; k++)
{
printf("%2c", '*');
}
printf("\n");
}
return 0;
}
int printHalfDiamondStar()
{
int i, j, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
for(j=1; j<=i; j++)
{
printf("%2c", '*');
}
printf("\n");
}
for(i=num; i>=1; i--)
{
for(j=1; j<=i; j++)
{
printf("%2c", '*');
}
printf("\n");
}
return 0;
}
int printHollowInvertedPyramidStar()
{
int i, j, k, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
for(j=1; j<=i; j++)
{
printf("%2c", ' ');
}
for(k=i; k<=(2*num-i); k++)
{
if((i==1) || (k==i) || (k==(2*num-i)))
printf("%2c", '*');
else
printf("%2c", ' ');
}
printf("\n");
}
return 0;
}
int printInvertedPyramidStar()
{
int i, j, k, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=num; i>=1; i--)
{
for(j=i; j<=num; j++)
{
printf("%2c", ' ');
}
for(j=1; j<=(2*i-1); j++)
{
printf("%2c", '*');
}
printf("\n");
}
return 0;
}
int printHollowPyramidStar()
{
int i, j, k, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
for(k=i; k<=num; k++)
{
printf("%2c", ' ');
}
for(j=1; j<=(2*i-1); j++)
{
if((i==num) || (j==1) || (j==(2*i-1)))
printf("%2c", '*');
else
printf("%2c", ' ');
}
printf("\n");
}
return 0;
}
int printInvertedMirroredRightTriangleStar()
{
int i, j, k, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
for(j=1; j<=i; j++)
{
printf("%2c", ' ');
}
for(k=i; k<=num; k++)
{
printf("%2c", '*');
}
printf("\n");
}
return 0;
}
int printHollowInvertedMirroredRightTriangleStar()
{
int i, j, k, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
for(j=1; j<=i; j++)
{
printf("%2c", ' ');
}
for(k=i; k<=num; k++)
{
if((k==num) ||(i==1)||(k==i))
{
printf("%2c", '*');
}
else
printf("%2c", ' ');
}
printf("\n");
}
return 0;
}
int printPyramidStar()
{
int i, j, k, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
for(j=i; j<=num; j++)
{
printf("%2c", ' ');
}
for(k=1; k<=(2*i-1); k++)
{
printf("%2c", '*');
}
printf("\n");
}
return 0;
}
int printHollowInvertedRightTriangleStar()
{
int i, j, k, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
for(j=i; j<=num; j++)
{
if((i==1) || (j==num) || (i==j))
printf("%2c", '*');
else
printf("%2c", ' ');
}
for(k=1; k<=i; k++)
{
printf("%2c", ' ');
}
printf("\n");
}
return 0;
}
int printInvertedRightTriangleStar()
{
int i, j, k, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
for(j=i; j<=num; j++)
{
printf("%2c", '*');
}
for(k=1; k<=i; k++)
{
printf("%2c", ' ');
}
printf("\n");
}
return 0;
}
int printHollowMirroredRightTriangleStar()
{
int i, j, k, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
for(j=i; j<=num; j++)
{
printf("%2c", ' ');
}
for(k=1; k<=i; k++)
{
if((k==1) || (i==num) || (i==k))
printf("%2c", '*');
else
printf("%2c", ' ');
}
printf("\n");
}
return 0;
}
int printMirroredRightTriangleStar()
{
int i, j, k, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
for(j=i; j<=num; j++)
{
printf("%2c", ' ');
}
for(k=1; k<=i; k++)
{
printf("%2c", '*');
}
printf("\n");
}
return 0;
}
int printHollowRightTriangleStar()
{
int i, j, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
for(j=1; j<=i; j++)
{
if((j==1) || (i==num) || (j==i))
printf("%2c", '*');
else
printf("%2c", ' ');
}
printf("\n");
}
return 0;
}
int printRightTriangleStar()
{
int i, j, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
for(j=1; j<=i; j++)
{
printf("%2c", '*');
}
printf("\n");
}
return 0;
}
int printHollowMirroredRhombusStar()
{
int i, j, k, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
for(j=1; j<=i; j++)
{
printf("%2c", ' ');
}
for(k=1; k<=num; k++)
{
if((k==1) || (k==num) || (i==1) || (i==num))
printf("%2c", '*');
else
printf("%2c", ' ');
}
printf("\n");
}
return 0;
}
int printMirroredRhombusStar()
{
int i, j, k, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
for(j=1; j<=i; j++)
{
printf("%2c", ' ');
}
for(k=1; k<=num; k++)
{
printf("%2c", '*');
}
printf("\n");
}
return 0;
}
int printHollowRhombusStar()
{
int i, j, k, num;
printf("Enter row number from user: ");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
for(j=num; j>=i; j--)
{
printf("%2c", ' ');
}
for(k=1; k<=num; k++)
{
if((i==1) ||(i==num) || (k==1) || (k==num))
printf("%2c", '*');
else
printf("%2c", ' ');
}
printf("\n");
}
return 0;
}
int printRhombusStar()
{
int i, j, k, num;
printf("Enter row number: ");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
for(j=num; j>=i; j--)
{
printf("%2c", ' ');
}
for(k=1; k<=num; k++)
{
printf("%2c", '*');
}
printf("\n");
}
return 0;
}
int printHollowSquareStar()
{
int i, j, num;
printf("Enter row number: ");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
for(j=1; j<=num; j++)
{
if((j==1) || (j==num) || (i==1) || (i==num))
{
printf("%2c", '*');
}
else
{
printf("%2c", ' ');
}
}
printf("\n");
}
return 0;
}
int printSquareStar()
{
int i, j, num;
//Read the row number from user
printf("Enter row number: ");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
for(j=1; j<=num; j++)
{
printf("%2c", '*');
}
printf("\n");
}
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_numlen.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: yshawn <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/01/13 23:51:21 by yshawn #+# #+# */
/* Updated: 2020/03/07 00:53:24 by yshawn ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
** The function takes an unsigned number, and the number system
** and returns its length, necessary for writing this number to a string
**
** Функция принимает беззнаковое число, а также систему счисления
** и возвращает его длину, нужную для записи этого числа в строку
*/
int ft_numlen(long long value, int base)
{
int i;
int neg;
if (base < 2 || base > 16 || base % 2 != 0)
return (0);
i = 0;
neg = 0;
if (value == 0)
return (1);
if (value < 0)
neg = 1;
while (value)
{
value /= base;
i++;
}
return (i + neg);
}
|
C | #include "lsmtree.h"
/*
SECTION 1: functions for initializing, creating, loading, maintaining, and saving the LSM tree.
*/
lsmtree *new_lsmtree(void) {
/*
Initializes new LSM tree.
*/
lsmtree *tree = malloc(sizeof(lsmtree));
return tree;
}
int empty_lsmtree(lsmtree *tree, char *name) {
/*
Creates new empty LSM tree.
*/
// initialize names
tree->name = malloc(MAX_DIR_LEN);
tree->data_dir = malloc(MAX_DIR_LEN);
// initialize tree variables
tree->num_levels = malloc(sizeof(int));
tree->num_pairs = malloc(sizeof(int));
tree->pairs_per_level = calloc(MAX_NUM_LEVELS, sizeof(size_t));
tree->run_ctr = malloc(sizeof(int));
*tree->num_levels = 2; // buffer and L1
*tree->num_pairs = 0;
*tree->run_ctr = 0;
// initialize buffer
tree->buff = malloc(sizeof(buffer));
tree->buff->size = malloc(sizeof(int));
tree->buff->keys = calloc(BUFF_CAPACITY, sizeof(KEY_TYPE));
tree->buff->vals = calloc(BUFF_CAPACITY, sizeof(VAL_TYPE));
tree->buff->dels = calloc(BUFF_CAPACITY, sizeof(DEL_TYPE));
// initialize levels and first level
tree->levels = calloc(MAX_NUM_LEVELS, sizeof(level *));
tree->levels[0] = malloc(sizeof(level));
tree->levels[0]->num_runs = malloc(sizeof(int));
*tree->levels[0]->num_runs = 0;
tree->levels[0]->runs = calloc(RATIO, sizeof(run *));
// create directory for data
char dir_name[MAX_DIR_LEN] = DATA_DIR;
strcat(dir_name, name);
struct stat status = {0};
if (stat(dir_name, &status) == 0) {
// directory already exist
printf("LSM tree with given name already exists.\n");
return 1;
}
mkdir(dir_name, 0700);
strcpy(tree->data_dir, dir_name);
strcpy(tree->name, name);
return 0;
}
char *run_filepath(lsmtree *tree, run *r, bool keys, bool dels) {
// create string containing file path of run r on disk
char *filepath = malloc(MAX_DIR_LEN);
char str[MAX_DIR_LEN];
sprintf(str, "%d", *r->num);
strcpy(filepath, tree->data_dir);
strcat(filepath, "/run_");
strcat(filepath, str);
if(dels) {
strcat(filepath, "_dels");
}
else if(keys) {
strcat(filepath, "_keys");
}
else {
strcat(filepath, "_vals");
}
return filepath;
}
void write_run(lsmtree *tree, run *new_run) {
// writes a run to disk
char *keys_filepath = run_filepath(tree, new_run, true, false);
char *vals_filepath = run_filepath(tree, new_run, false, false);
char *dels_filepath = run_filepath(tree, new_run, false, true);
FILE *f_keys = fopen(keys_filepath, "wb");
if (f_keys) {
fwrite(new_run->buff->keys, sizeof(KEY_TYPE), *new_run->buff->size, f_keys);
fclose (f_keys);
}
else {
printf("Unable to write to disk.\n");
exit(EXIT_FAILURE);
}
FILE *f_vals = fopen(vals_filepath, "wb");
if (f_vals) {
fwrite(new_run->buff->vals, sizeof(VAL_TYPE), *new_run->buff->size, f_vals);
fclose (f_vals);
}
else {
printf("Unable to write to disk.\n");
exit(EXIT_FAILURE);
}
// TODO: pack bits
FILE *f_dels = fopen(dels_filepath, "wb");
if (f_dels) {
fwrite(new_run->buff->dels, sizeof(DEL_TYPE), *new_run->buff->size, f_dels);
fclose (f_dels);
}
else {
printf("Unable to write to disk.\n");
exit(EXIT_FAILURE);
}
free(keys_filepath);
free(vals_filepath);
free(dels_filepath);
}
void read_keys(lsmtree *tree, run *r, buffer *buff, int idx_start, int idx_stop) {
// reads keys of specified run between idx_start and idx_stop (inclusive)
// into provided buffer
char *keys_filepath = run_filepath(tree, r, true, false);
// calculate where to read
int offset = idx_start * sizeof(KEY_TYPE);
int num_keys = idx_stop - idx_start + 1;
// read from disk
FILE *f_keys = fopen(keys_filepath, "rb");
if (f_keys) {
fseek(f_keys, offset, SEEK_SET);
fread(buff->keys, sizeof(KEY_TYPE), num_keys, f_keys);
fclose(f_keys);
}
else {
printf("Unable to read from disk.\n");
exit(EXIT_FAILURE);
}
free(keys_filepath);
}
void read_vals_dels(lsmtree *tree, run *r, buffer *buff, int idx_start, int idx_stop) {
// reads vals and dels of specified run between idx_start and idx_stop (
// inclusive) into provided buffer
char *vals_filepath = run_filepath(tree, r, false, false);
char *dels_filepath = run_filepath(tree, r, false, true);
// calculate where to read
int offset_vals = idx_start * sizeof(VAL_TYPE);
int offset_dels = idx_start * sizeof(DEL_TYPE);
int num_keys = idx_stop - idx_start + 1;
// read from disk
FILE *f_vals = fopen(vals_filepath, "rb");
if (f_vals) {
fseek(f_vals, offset_vals, SEEK_SET);
fread(buff->vals, sizeof(VAL_TYPE), num_keys, f_vals);
fclose(f_vals);
}
else {
printf("Unable to read from disk.\n");
exit(EXIT_FAILURE);
}
FILE *f_dels = fopen(dels_filepath, "rb");
if (f_dels) {
fseek(f_dels, offset_dels, SEEK_SET);
fread(buff->dels, sizeof(DEL_TYPE), num_keys, f_dels);
fclose(f_dels);
}
else {
printf("Unable to read from disk.\n");
exit(EXIT_FAILURE);
}
free(vals_filepath);
free(dels_filepath);
}
void read_run(lsmtree *tree, run *r, buffer *buff) {
// reads all keys, vals, and del flags of the run into provided buffer
char *keys_filepath = run_filepath(tree, r, true, false);
char *vals_filepath = run_filepath(tree, r, false, false);
char *dels_filepath = run_filepath(tree, r, false, true);
// printf("read run\n");
// read from disk
FILE *f_keys = fopen(keys_filepath, "rb");
if (f_keys) {
fread(buff->keys, sizeof(KEY_TYPE), *r->buff->size, f_keys);
fclose (f_keys);
}
else {
}
FILE *f_vals = fopen(vals_filepath, "rb");
if (f_vals) {
fread(buff->vals, sizeof(VAL_TYPE), *r->buff->size, f_vals);
fclose (f_vals);
}
else {
}
FILE *f_dels = fopen(dels_filepath, "rb");
if (f_dels) {
fread(buff->dels, sizeof(DEL_TYPE), *r->buff->size, f_dels);
fclose (f_dels);
}
else {
exit(EXIT_FAILURE);
}
free(keys_filepath);
free(vals_filepath);
free(dels_filepath);
}
void erase_run(lsmtree *tree, run *r) {
// from disk
char *keys_filepath = run_filepath(tree, r, true, false);
char *vals_filepath = run_filepath(tree, r, false, false);
char *dels_filepath = run_filepath(tree, r, false, true);
remove(keys_filepath);
remove(vals_filepath);
remove(dels_filepath);
free(keys_filepath);
free(vals_filepath);
free(dels_filepath);
}
level *read_level(lsmtree *tree, int level_num) {
// reads a level (>= 1) into memory from disk
level *l = malloc(sizeof(level));
l->num_runs = malloc(sizeof(int));
*l->num_runs = *tree->levels[level_num - 1]->num_runs;
l->runs = calloc(*(l->num_runs), sizeof(run *));
for (int run_num = 0; run_num < *(l->num_runs); run_num++) {
l->runs[run_num] = malloc(sizeof(run));
l->runs[run_num]->num = malloc(sizeof(int));
*l->runs[run_num]->num = *tree->levels[level_num - 1]->runs[run_num]->num;
l->runs[run_num]->fp = malloc(sizeof(fencepointer));
l->runs[run_num]->fp = tree->levels[level_num - 1]->runs[run_num]->fp;
l->runs[run_num]->bf = malloc(sizeof(bloomfilter));
l->runs[run_num]->bf = tree->levels[level_num - 1]->runs[run_num]->bf;
l->runs[run_num]->buff = malloc(sizeof(buffer));
l->runs[run_num]->buff->size = malloc(sizeof(int));
*l->runs[run_num]->buff->size = *tree->levels[level_num - 1]->runs[run_num]->buff->size;
l->runs[run_num]->buff->keys = calloc(*l->runs[run_num]->buff->size, sizeof(KEY_TYPE));
l->runs[run_num]->buff->vals = calloc(*l->runs[run_num]->buff->size, sizeof(VAL_TYPE));
l->runs[run_num]->buff->dels = calloc(*l->runs[run_num]->buff->size, sizeof(DEL_TYPE));
read_run(tree, tree->levels[level_num - 1]->runs[run_num], l->runs[run_num]->buff);
}
return l;
}
void sort(lsmtree *tree, buffer *buff) {
// sorts buffer in place
// stably accounts for updates and deletes, updating buff->size
if (*buff->size == 0) {
return;
}
// insertion sort--replace with merge sort
KEY_TYPE temp_key;
VAL_TYPE temp_val;
DEL_TYPE temp_del;
int j;
int i = 1;
while (i < *buff->size) {
j = i - 1;
temp_key = buff->keys[i];
temp_val = buff->vals[i];
temp_del = buff->dels[i];
while (j >= 0 && buff->keys[j] > temp_key) {
buff->keys[j+1] = buff->keys[j];
buff->vals[j+1] = buff->vals[j];
buff->dels[j+1] = buff->dels[j];
j--;
}
i++;
buff->keys[j+1] = temp_key;
buff->vals[j+1] = temp_val;
buff->dels[j+1] = temp_del;
}
// account for updates and deletes
// int repeats = 0;
// int num_insert_repeats = 0;
// int insert_idx = 0;
// KEY_TYPE curr;
// for (int i = 0; i < *buff->size - 1; i++) {
// curr = buff->keys[i];
// while (buff->keys[i + 1] == curr && i < *buff->size - 1) {
// i++;
// repeats++;
// if (!buff->dels[i + 1]) {
// num_insert_repeats++;
// }
// }
// insert_idx++;
// }
// (*buff->size) -= repeats;
// (*tree->num_pairs) -= num_insert_repeats;
}
void merge(lsmtree *tree, int level_num, run *new_run) {
// merges sorted runs on level_num (>= 1)
// updates new_run argument with sorted buffer and sets buff->size
// read level into memory
level *l = read_level(tree, level_num);
// calculate parameters of new run
int num_runs = *l->num_runs;
int sum_sizes = 0;
for (int run_num = 0; run_num < *l->num_runs; run_num++) {
sum_sizes += (*l->runs[run_num]->buff->size);
}
*new_run->buff->size = sum_sizes;
// create new buffer for merged runs
new_run->buff->keys = calloc(sum_sizes, sizeof(KEY_TYPE));
new_run->buff->vals = calloc(sum_sizes, sizeof(VAL_TYPE));
new_run->buff->dels = calloc(sum_sizes, sizeof(DEL_TYPE));
// perform merge, counting duplicate keys; inefficient--should be nlog(n)
int head_idxs[num_runs];
for (int i = 0; i < num_runs; i++) {
head_idxs[i] = 0;
}
long min_key = MAX_KEY;
int min_run_num;
int min_run_idx;
int insert_idx = 0;
int repeats = 0;
int num_insert_repeats = 0;
KEY_TYPE last_key;
for (int i = 0; i < sum_sizes; i++) {
for (int run = num_runs - 1; run >= 0; run--) {
if (head_idxs[run] < *l->runs[run]->buff->size) {
// run not emptied
if (l->runs[run]->buff->keys[head_idxs[run]] <= min_key) {
min_key = l->runs[run]->buff->keys[head_idxs[run]];
min_run_num = run;
min_run_idx = head_idxs[run];
}
}
}
new_run->buff->keys[insert_idx] = l->runs[min_run_num]->buff->keys[min_run_idx];
new_run->buff->vals[insert_idx] = l->runs[min_run_num]->buff->vals[min_run_idx];
new_run->buff->dels[insert_idx] = l->runs[min_run_num]->buff->dels[min_run_idx];
insert_idx++;
// de-duplicate
// if (i == 0) {
// new_run->buff->keys[insert_idx] = l->runs[min_run_num]->buff->keys[min_run_idx];
// new_run->buff->vals[insert_idx] = l->runs[min_run_num]->buff->vals[min_run_idx];
// new_run->buff->dels[insert_idx] = l->runs[min_run_num]->buff->dels[min_run_idx];
// }
// else {
// if (l->runs[min_run_num]->buff->keys[min_run_idx] != last_key) {
// // don't overwrite
// insert_idx++;
// }
// else {
// // overwrite
// repeats++;
// if (!l->runs[min_run_num]->buff->dels[min_run_idx]) {
// num_insert_repeats++;
// }
// }
// new_run->buff->keys[insert_idx] = l->runs[min_run_num]->buff->keys[min_run_idx];
// new_run->buff->vals[insert_idx] = l->runs[min_run_num]->buff->vals[min_run_idx];
// new_run->buff->dels[insert_idx] = l->runs[min_run_num]->buff->dels[min_run_idx];
// }
// last_key = new_run->buff->keys[insert_idx];
// printf("min was %ld=%d at run %d, idx %d\n", min_key, l->runs[min_run_num]->buff->keys[min_run_idx], min_run_num, min_run_idx);
head_idxs[min_run_num]++;
min_key = MAX_KEY;
}
// (*new_run->buff->size) -= repeats;
// (*tree->num_pairs) -= num_insert_repeats;
free_level_data(l);
}
run *merge_level(lsmtree *tree, int level_num) {
// sort merges level and returns pointer to newly created run
run *new_run = malloc(sizeof(run));
new_run->num = malloc(sizeof(int));
(*tree->run_ctr)++;
*new_run->num = *tree->run_ctr;
// create new buffer
new_run->buff = malloc(sizeof(buffer));
new_run->buff->size = malloc(sizeof(int));
if(level_num == 0) {
// point buffer to CO array, sort buffer
new_run->buff->keys = tree->buff->keys;
new_run->buff->vals = tree->buff->vals;
new_run->buff->dels = tree->buff->dels;
*new_run->buff->size = *tree->buff->size;
sort(tree, new_run->buff);
}
else {
// merge, populating new run
merge(tree, level_num, new_run);
}
// construct bloom filter and fence pointers
new_run->fp = create_fencepointer(new_run->buff->keys, *new_run->buff->size);
int len = opt_table_size_constrained();
new_run->bf = create_bloomfilter(new_run->buff->keys, len);
return new_run;
}
void merge_lsmtree(lsmtree *tree, int level_num) {
// merges at specified level_num of lsm tree, if necessary
// uses tiering
// at termination, no merges remain
int level_capacity = RATIO;
run *new_run;
if(level_num == 0) {
// only called when L0 is full, must merge
new_run = merge_level(tree, level_num);
}
else {
// check if level at capacity
if (*tree->levels[level_num - 1]->num_runs == level_capacity) {
// maintain level count
if (level_num >= MAX_NUM_LEVELS) {
// printf("Increase MAX_NUM_LEVELS.\n");
exit(EXIT_FAILURE);
}
// add level if necessary
if (level_num == *tree->num_levels - 1) {
(*tree->num_levels)++;
tree->levels[level_num] = malloc(sizeof(level));
tree->levels[level_num]->num_runs = malloc(sizeof(int));
*tree->levels[level_num]->num_runs = 0;
tree->levels[level_num]->runs = calloc(RATIO * level_capacity, sizeof(run *));
}
// sort merge runs
new_run = merge_level(tree, level_num);
}
else {
// level not full
return;
}
}
// add run to level_num + 1
tree->levels[level_num]->runs[*tree->levels[level_num]->num_runs] = new_run;
// write run to disk from memory; erase old level from disk
write_run(tree, new_run);
if (level_num != 0) {
// free_run_data(new_run);
erase_level(tree, level_num);
}
// add count of pairs to next level
tree->pairs_per_level[level_num + 1] += *new_run->buff->size;
// clear runs from level_num
tree->pairs_per_level[level_num] = 0;
if(level_num != 0) {
*tree->levels[level_num - 1]->num_runs = 0;
}
else {
*tree->buff->size = 0;
}
(*tree->levels[level_num]->num_runs) += 1;
// merge next level
merge_lsmtree(tree, level_num + 1);
}
void probe_run(lsmtree *tree, run *r, KEY_TYPE key, VAL_TYPE **res, DEL_TYPE **del) {
// probes run r for specified key. If found, allocates memory and
// populates pointers to res and del
// NULL => before start of run
// i => after fence i
// printf("probe_run\n");
if (*r->buff->size == 0) {
return;
}
// first, probe bloom filter
bool found = query_bloomfilter(r->bf, key);
if (!found) {
return;
}
// if there are no fence pointers, simply query run
if (r->fp->num_fences == 0) {
buffer *buff = malloc(sizeof(buff));
buff->size = malloc(sizeof(int));
*buff->size = *r->buff->size;
buff->keys = calloc(*r->buff->size, sizeof(KEY_TYPE));
buff->vals = calloc(*r->buff->size, sizeof(VAL_TYPE));
buff->dels = calloc(*r->buff->size, sizeof(DEL_TYPE));
read_run(tree, r, buff);
for (int i = *r->buff->size - 1; i >= 0; i--) {
if (buff->keys[i] == key) {
*res = malloc(sizeof(VAL_TYPE));
*del = malloc(sizeof(DEL_TYPE));
**res = buff->vals[i];
**del = buff->dels[i];
free(buff->vals);
free(buff->dels);
break;
}
}
free(buff->size);
free(buff->keys);
free(buff);
}
// if there are fence pointers, use them
else {
int *fence_num = query_fencepointer(r->fp, key);
if (fence_num) {
// find range of key indices
int idx_start = (*fence_num - 1) * r->fp->keys_per_fence;
int idx_stop = ((*fence_num) * r->fp->keys_per_fence) - 1;
if (idx_stop > *r->buff->size - 1) {
idx_stop = *r->buff->size - 1;
}
int num_keys = idx_stop - idx_start + 1;
buffer *buff = malloc(sizeof(buff));
buff->size = malloc(sizeof(int));
buff->keys = calloc(num_keys, sizeof(KEY_TYPE));
// // read portion of run from disk
read_keys(tree, r, buff, idx_start, idx_stop);
// check for key in portion
for (int i = num_keys - 1; i >= 0; i--) {
if (buff->keys[i] == key) {
buff->vals = calloc(num_keys, sizeof(VAL_TYPE));
buff->dels = calloc(num_keys, sizeof(DEL_TYPE));
read_vals_dels(tree, r, buff, idx_start, idx_stop);
*res = malloc(sizeof(VAL_TYPE));
*del = malloc(sizeof(DEL_TYPE));
**res = buff->vals[i];
**del = buff->dels[i];
free(buff->vals);
free(buff->dels);
break;
}
}
free(buff->size);
free(buff->keys);
free(buff);
}
else {
// key not in run
return;
}
}
}
/*
SECTION 2: functions for querying LSM tree.
*/
void put(lsmtree *tree, KEY_TYPE key, VAL_TYPE val, DEL_TYPE del) {
if (tree->pairs_per_level[0] < BUFF_CAPACITY) {
tree->buff->keys[tree->pairs_per_level[0]] = key;
tree->buff->vals[tree->pairs_per_level[0]] = val;
tree->buff->dels[tree->pairs_per_level[0]] = del;
tree->pairs_per_level[0]++;
(*tree->buff->size)++;
if (del) {
// assume key already in tree to avoid cost of maintaining true
// count
(*tree->num_pairs)--;
}
else {
(*tree->num_pairs)++;
}
}
else {
// flush buffer to L1 and merge if necessary
merge_lsmtree(tree, 0);
// now space in buffer; call put again
put(tree, key, val, del);
}
}
VAL_TYPE *get(lsmtree *tree, KEY_TYPE key) {
// returns pointer to val if found, otherwise NULL
// caller must free return value if not NULL
// printf("getting\n");
VAL_TYPE *res = NULL;
// scan L0 backwards
for (int i = *tree->buff->size - 1; i >= 0; i--) {
if (tree->buff->keys[i] == key) {
if (!tree->buff->dels[i]) {
// not deleted
res = malloc(sizeof(VAL_TYPE));
*res = tree->buff->vals[i];
}
return res; // still NULL if deleted
}
}
// probe disk
for (int level_num = 1; level_num < *tree->num_levels; level_num++) {
// printf("level_num: %d\n", level_num);
level *l = tree->levels[level_num - 1];
for (int run_num = *l->num_runs - 1; run_num >= 0; run_num--) {
// printf("run_num: %d\n", run_num);
VAL_TYPE *res = NULL;
DEL_TYPE *del = NULL;
run *r = l->runs[run_num];
probe_run(tree, r, key, &res, &del);
if (res) {
// key found
if (*del) {
// deleted
res = NULL;
}
free(del);
return res;
}
}
}
// not found in tree
return res;
}
buffer *range(lsmtree *tree, KEY_TYPE key_start, KEY_TYPE key_stop) {
return 0;
}
void delete(lsmtree *tree, KEY_TYPE key) {
put(tree, key, 0, true);
}
void load(lsmtree *tree, char *filepath) {
// loads all key-value pairs in specified binary file. Reads from disk in
// chunks to trade off between memory overhead and I/O
long num_pairs_read;
long idx;
KEY_TYPE key;
VAL_TYPE val;
KEY_TYPE chunk[2 * LOAD_NUM_PAIRS];
FILE *f = fopen(filepath, "rb");
if (f) {
while(!feof(f)) {
num_pairs_read = fread(chunk, sizeof(KEY_TYPE), 2 * LOAD_NUM_PAIRS, f) / 2;
if (num_pairs_read > 0) {
for (int i = 0; i < num_pairs_read; i++) {
idx = 2 * i;
key = chunk[idx];
val = chunk[idx + 1];
put(tree, key, val, false);
}
}
}
}
else {
printf("Load file file not found.\n");
}
}
void print_stats(lsmtree *tree) {
printf("Total pairs: %d\n\n", *tree->num_pairs);
for (int level_num = 0; level_num < *tree->num_levels; level_num++) {
printf("LVL%d: %d\n", level_num, tree->pairs_per_level[level_num]);
}
printf("\nContents:\n\n");
for (int level_num = 0; level_num < *tree->num_levels; level_num++) {
if (level_num == 0) {
// buffer
for (int idx = 0; idx < tree->pairs_per_level[0]; idx++) {
if (!tree->buff->dels[idx]) {
printf("%d:%d:L%d ", tree->buff->keys[idx],
tree->buff->vals[idx], 0);
}
}
printf("\n\n");
}
else {
// on disk
for (int run = 0; run < *tree->levels[level_num-1]->num_runs;
run++) {
buffer *buff = malloc(sizeof(buffer));
buff->keys = calloc(*tree->levels[level_num-1]->runs[run]->buff->size, sizeof(KEY_TYPE));
buff->vals = calloc(*tree->levels[level_num-1]->runs[run]->buff->size, sizeof(VAL_TYPE));
buff->dels = calloc(*tree->levels[level_num-1]->runs[run]->buff->size, sizeof(DEL_TYPE));
read_run(tree, tree->levels[level_num-1]->runs[run], buff);
for (int idx = 0; idx < *tree->levels[level_num-1]->runs[run]->buff->size; idx++) {
if (!(buff->dels[idx])) {
printf("%d:%d:L%d ", buff->keys[idx], buff->vals[idx], level_num);
}
}
free_buffer_data(buff);
}
printf("\n\n");
}
}
}
/*
SECTION 3: functions cleaning up, freeing memory.
The _data functions free the data arrays allocated to each contained buffer,
not the structs themselves.
*/
void erase_level(lsmtree *tree, int level_num) {
// from disk
for (int run_num = 0; run_num < *tree->levels[level_num - 1]->num_runs; run_num++) {
erase_run(tree, tree->levels[level_num - 1]->runs[run_num]);
}
}
void free_buffer_data(buffer *buff) {
free(buff->keys);
free(buff->vals);
free(buff->dels);
}
void free_run_data(run *r) {
free_buffer_data(r->buff);
}
void free_level_data(level *l) {
for (int run_num = 0; run_num < *l->num_runs; run_num++) {
free_run_data(l->runs[run_num]);
}
}
void free_lsmtree_data(lsmtree *tree) {
free(tree->buff);
for (int level_num = 0; level_num < *tree->num_levels; level_num++) {
free_level_data(tree->levels[level_num]);
}
}
void free_buffer(buffer *buff) {
free_buffer_data(buff);
free(buff->size);
}
void free_run(run *r) {
free_run_data(r);
free_fencepointer(r->fp);
if (*r->buff->size > RUN_MIN) {
free_bloomfilter(r->bf);
}
free(r->num);
}
void free_level(level *l) {
for (int run_num = 0; run_num < *l->num_runs; run_num++) {
free_run(l->runs[run_num]);
}
free(l->runs);
free(l->num_runs);
}
void free_lsmtree(lsmtree *tree) {
free_lsmtree_data(tree);
free(tree->num_levels);
free(tree->num_pairs);
free(tree->pairs_per_level);
free(tree->run_ctr);
free(tree->name);
free(tree->data_dir);
}
int load_lsmtree(lsmtree *tree) {
/*
Loads existing serialized LSM tree from disk.
*/
return 0;
}
void serialize_lsmtree(lsmtree *tree) {
/*
Serializes memory resident LSM tree data to disk.
*/
}
|
C | // Arthur Chu
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <string.h>
void birth(int* x) {
int process = fork();
if(process < 0) {
//fork didn't fork
fprintf(stderr, "You forked up\n");
exit(1);
} else if (process == 0) {
//child is born
printf("Hello I am the child. I like the number 4. Have you seen my parent?\n");
*x = 4;
exit(0);
} else {
//parent
printf("Hello I am the parent. I like the number 13. Have you met my child?\n");
*x = 13;
}
}
void forkOpen(char* fileName) {
char* c;
int file = open(fileName, O_WRONLY|O_CREAT|O_TRUNC, S_IRWXU);
int p = fork();
if(p < 0) {
fprintf(stderr, "You forked up\n");
} else if (p == 0) {
char* cString = {"I, the child, am making my mark\n"};
write(file, cString, strlen(cString));
exit(0);
} else {
char* pString = {"I, the parent, am making a mark\n"};
write(file, pString, strlen(pString));
}
close(file);
}
void forkPrint() {
int p = fork();
if(p < 0) {
fprintf(stderr, "You forked up\n");
} else if(p == 0) {
printf("hello\n");
exit(0);
} else {
sleep(1);
printf("goodbye\n");
}
}
void forkExec() {
int p = fork();
int status;
if(p < 0) {
fprintf(stderr, "You forked up\n");
} else if( p == 0 ) {
execl("/bin/ls", "ls", NULL);
exit(0);
} else {
wait(&status);
}
}
void twiddle() {
int status;
int p = fork();
if(p < 0) {
fprintf(stderr, "You forked up\n");
} else if( p == 0 ) {
printf("I, the child, am going to twiddle my thumbs for a second\n");
exit(0);
} else {
wait(&status);
printf("Alright I'm done waiting for the child\n");
}
}
void twiddlePID() {
int p = fork();
int status;
if (p < 0) {
fprintf(stderr, "You forked up\n");
} else if(p == 0) {
printf("I, the child, am twiddling my thumbs once again\n");
exit(0);
} else {
waitpid(-1 , &status, 0);
printf("Finally, the child is done\n");
}
}
void standardOutKill() {
int p = fork();
if (p < 0) {
fprintf(stderr, "You forked up\n");
} else if(p == 0) {
close(STDOUT_FILENO);
printf("Can I, the child, still print?\n");
exit(0);
} else {
}
}
int main() {
//Question 1
printf("1. Fork\n");
int x = 100;
printf("The number of the day is %d, for now. Here comes a family.\n", x);
birth(&x);
printf("Someone changed the number of the day to %d!\n", x);
//Both the parent and the child process changed the value of x.
//The final value of x depends only on which process was slower and changed the number last.
//Question 2
printf("2. Fork and Open\n");
forkOpen("temp.txt");
int tmpFile = open("temp.txt", O_RDWR);
char tmpString[30];
printf("temp.txt contents:\n");
for(int i = 0; i < 2; i++) {
read(tmpFile, &tmpString, 32);
printf("%s", tmpString);
}
//Question 3
printf("3. Fork and Printing\n");
forkPrint();
//Question 4
printf("4. Fork and Exec\n");
forkExec();
//Question 5
printf("5. Wait\n");
twiddle();
//Question 6
printf("6. Waitpid\n");
twiddlePID();
//Question 7
printf("7. Standard Out\n");
standardOutKill();
return 1;
}
|
C | #include <stdio.h>
int calculo(int numero);
int main(){
int numero, cifras;
printf("Ingrese un numero: ");
scanf("%i",&numero);
cifras = calculo(numero);
printf("El numero introducido es: %i.\n",numero);
printf("El numero introducido %i tiene %i cifra(s).\n",numero,cifras);
system("pause");
return 0;
}
int calculo(int numero){
static int cifras = 1;
while(numero/10>0)
{
numero = numero / 10;
cifras++;
}
return cifras;
}
|
C | #include "holberton.h"
/**
* _strlen - Length of a string
* @s: String
* Return: Length
*/
int _strlen(char *s)
{
int i;
for (i = 0; s[i] != '\0'; i++)
{
}
return (i);
}
/**
* _strncat - Concatenate two strings
* @dest: String stored
* @src: Source
* @n: Numbers of bytes
* Return: Return dest
*/
char *_strncat(char *dest, char *src, int n)
{
int l_dest, l_src, i;
l_dest = _strlen(dest);
l_src = _strlen(src);
for (i = 0; i < n && i <= l_src; i++, l_dest++)
dest[l_dest] = src[i];
dest[l_dest + 1] = '\0';
return (dest);
}
|
C | /*
A simple client in the internet domain using TCP
Usage: ./client hostname port (./client 192.168.0.151 10000)
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> // define structures like hostent
#include <stdlib.h>
#include <strings.h>
void error(char *msg) {
perror(msg);
exit(0);
}
int main(int argc, char *argv[]) {
int sockfd; // Socket descriptor
int portno, n;
struct sockaddr_in serv_addr;
struct hostent *server; // contains tons of information,
// including the server's IP address
char buffer[256];
if (argc < 3) {
fprintf(stderr, "usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0); // create a new socket
if (sockfd < 0)
error("ERROR opening socket");
// takes a string like "www.yahoo.com", and returns a struct hostent which
// contains information, as IP address, address type, address length...
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr, "ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET; // initialize server's address
bcopy((char *) server->h_addr, (char *) &serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(portno);
// establish a connection to the server
if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("ERROR connecting");
printf("Please enter the message: ");
bzero(buffer, 256);
fgets(buffer, 255, stdin);
// n = send(sockfd, buffer, strlen(buffer), 0); // send to the socket
n = write(sockfd, buffer, strlen(buffer)); // write to the socket
if (n < 0)
error("ERROR writing to socket");
bzero(buffer, 256);
n = read(sockfd, buffer, 255); // read from the socket
if (n < 0)
error("ERROR reading from socket");
printf("%s\n", buffer);
close(sockfd); // close socket
return 0;
}
|
C | #include"data.h"
#include<stdlib.h>
#include<time.h>
int gameArea[20][30]={0};
int fruit_x,fruit_y;
Snake snake;
static int checkFruitCoordinate();
void initData()
{
srand(time(NULL));
int x,y;
for(x=0;x<20;x++)
{
for(y=0;y<30;y++)
{
if(x==0||x==19||y==0||y==29)
gameArea[x][y]=1;
else
gameArea[x][y]=0;
}
}
snake.len=5;
snake.dir=0;
int i;
for(i=0;i<5;i++)
{
snake.body[i].x=8+i;
snake.body[i].y=15;
}
do
{
fruit_x=random()%18+1;
fruit_y=random()%28+1;
}while(checkFruitCoordinate());
}
void eat()
{
do
{
fruit_x=random()%18+1;
fruit_y=random()%28+1;
}while(checkFruitCoordinate());
}
static int checkFruitCoordinate()
{
int i;
for(i=0;i<snake.len;i++)
{
if(fruit_x==snake.body[i].x&&fruit_y==snake.body[i].y)
return 1;
}
return 0;
}
|
C | #include "holberton.h"
/**
* print_numbers - Prints the numbers, from 0 to 9.
* Return: Alwais 0 (susses)
*/
void print_numbers(void)
{
int digit;
for (digit = '0'; digit <= '9'; digit++)
_putchar(digit);
_putchar('\n');
}
|
C | //
// Created by Alina Mihut on 12/22/19.
//
#include "drinks.h"
void displayTypesOfDrinks (foodType *foodTypes, int noOfDrinks, drink *drinks ){
printf("Please choose a drink to go with your %s\n", foodTypes);
for (int i = 0; i < noOfDrinks; i++) {
putchar('a' + i);
printf(") %s (%.2f) \n", drinks[i].name, drinks[i].price);
}
printf("%c) Go back\n", 'a' + noOfDrinks);
}
void freeDrinks(drink *d)
{
free(d->name);
}
|
C | // Part of the CBSD Project
// Convert and out bytes to human readable form
#include <stdio.h>
#include <libutil.h>
#include <stdlib.h>
#include <ctype.h>
#include <libutil.h>
#include <string.h>
#ifdef __DragonFly__
#include "expand_number.c"
#endif
#define MAX_VAL_LEN 1024
int
prthumanval(uint64_t bytes)
{
char buf[6];
int flags;
// flags = HN_NOSPACE | HN_DECIMAL | HN_DIVISOR_1000;
// flags = HN_NOSPACE | HN_DECIMAL;
flags = HN_NOSPACE;
humanize_number(buf, sizeof(buf) - 1, bytes, "", HN_AUTOSCALE, flags);
(void)printf("%s", buf);
return 0;
}
int
is_number(const char *p)
{
do {
if (!isdigit(*p) && (*p) != '.') {
return 1;
}
} while (*++p != '\0');
return 0;
}
int
main(int argc, char *argv[])
{
int i = 0;
uint64_t number;
int is_float = 0;
char metrics[] = "bkmgtpe";
char in_metrics;
int len = 0;
int in_index = -1;
int new_val;
char stringnum[MAX_VAL_LEN];
char buf[MAX_VAL_LEN];
float f = 0;
if (argc != 2) {
return (1);
}
len = strlen(argv[1]);
if (len > MAX_VAL_LEN) {
fprintf(stderr, "too long: %s\n", argv[1]);
exit(1);
}
memset(stringnum, 0, sizeof(stringnum));
memset(buf, 0, sizeof(buf));
if (is_number(argv[1]) == 1) {
// is float?
for (i = 0; i < len; i++) {
if (argv[1][i] == '.') {
is_float = 1;
}
if ((argv[1][i] >= '.') &&
(argv[1][i] <= '9')) { // '.' - 46 code
stringnum[i] = argv[1][i];
}
}
if (is_float == 1) {
char in_metrics = argv[1][len - 1];
for (i = 0; i < strlen(metrics); i++) {
if (metrics[i] == in_metrics) {
in_index = i;
break;
}
}
if (in_index < 0) {
fprintf(stderr,
"unable to determine index of metric: %s\n",
argv[1]);
exit(1);
}
f = atof(stringnum);
new_val = f * 1024; // convert to prev metrics
sprintf(buf, "%d%c", new_val,
metrics[in_index - 1]); // and shift metrics index
} else {
strncpy(buf, argv[1], strlen(argv[1]));
}
if (expand_number(buf, &number) == -1) {
// invalid value for val argument
// printf("Bad value\n");
exit(1);
} else {
printf("%lu", (unsigned long)number);
exit(0);
}
} else {
prthumanval(atol(argv[1]));
}
return 0;
}
|
C | #include <stdio.h>
#include <locale.h>
#include <stdlib.h>
/*truct horario
{
int horas;
int minutos;
int segundos;
};*/
int main (void){
setlocale(LC_ALL,"portuguese");
//DEFININDO ESTRUTURA
struct horario //tipo da estrutura, nome da estrutura
{
int horas;
int minutos;
int segundos;
double teste;
char letra;
};
//DECLARANDO ESTRUTURA
struct horario agora; //NOME DA ESTRUTURA
//VARIAVES DA ESTRUTURA ------- NOME DA ESTRUTURA MAIS VARIAVEL
agora.horas;
printf("DIGITE AS HORAS\n");
scanf("%i", &agora.horas);
agora.minutos;
printf("DIGITE OS MINUTOS\n");
scanf("%i", &agora.minutos);
agora.segundos;
printf("DIGITE OS SEGUNDOS\n");
scanf("%i", &agora.segundos);
printf("São exatos: %i Horas: %i Minutos e : %i Segundos \n ", agora.horas, agora.minutos, agora.segundos );
struct horario depois;
depois.horas = agora.horas +10;
depois.minutos = agora.minutos *2;
depois.segundos = agora.segundos -5;
depois.teste = 50.55 / 123;
depois.letra = 'r';
printf("Fuso Horario: %i Horas :%i Minutos :%i Segundos :\n", depois.horas, depois.minutos, depois.segundos);
printf("O valor da operação é: %f\n", depois.teste);
printf("Valor referente ao %c\n", depois.letra);
return 0;
}
|
C | # include <stdio.h>
/*
* 定义不同类型的变量
* short
* int
* long
* float
* double
* char
*
*/
int main(void)
{
printf("%d", sizeof(int));
} |
C | #define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_8__ TYPE_1__ ;
/* Type definitions */
struct TYPE_8__ {scalar_t__ kind; } ;
typedef TYPE_1__ svn_lock_t ;
typedef int /*<<< orphan*/ svn_error_t ;
typedef TYPE_1__ svn_dirent_t ;
struct ls_baton {int /*<<< orphan*/ locks; int /*<<< orphan*/ dirents; int /*<<< orphan*/ pool; } ;
typedef int /*<<< orphan*/ apr_pool_t ;
/* Variables and functions */
int /*<<< orphan*/ * SVN_NO_ERROR ;
char* apr_pstrdup (int /*<<< orphan*/ ,char const*) ;
TYPE_1__* svn_dirent_dup (TYPE_1__ const*,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ svn_hash_sets (int /*<<< orphan*/ ,char const*,TYPE_1__ const*) ;
scalar_t__ svn_node_file ;
char* svn_path_basename (char const*,int /*<<< orphan*/ ) ;
__attribute__((used)) static svn_error_t *
store_dirent(void *baton, const char *path, const svn_dirent_t *dirent,
const svn_lock_t *lock, const char *abs_path, apr_pool_t *pool)
{
struct ls_baton *lb = baton;
/* The dirent is allocated in a temporary pool, so duplicate it into the
correct pool. Note, however, that the locks are stored in the correct
pool already. */
dirent = svn_dirent_dup(dirent, lb->pool);
/* An empty path means we are called for the target of the operation.
For compatibility, we only store the target if it is a file, and we
store it under the basename of the URL. Note that this makes it
impossible to differentiate between the target being a directory with a
child with the same basename as the target and the target being a file,
but that's how it was implemented. */
if (path[0] == '\0')
{
if (dirent->kind == svn_node_file)
{
const char *base_name = svn_path_basename(abs_path, lb->pool);
svn_hash_sets(lb->dirents, base_name, dirent);
if (lock)
svn_hash_sets(lb->locks, base_name, lock);
}
}
else
{
path = apr_pstrdup(lb->pool, path);
svn_hash_sets(lb->dirents, path, dirent);
if (lock)
svn_hash_sets(lb->locks, path, lock);
}
return SVN_NO_ERROR;
} |
C | #include "wav.h"
void wavStructInit(WAV_STRUCT * wavFileEg){
wavFileEg->numSamples = 0;
wavFileEg->dataSize = 0;
wavFileEg->data = NULL;
}
Boolean isDataChunk(WAV_DATASubchunk wd){
if(wd.subchunk2ID[0] == 'd' && wd.subchunk2ID[1] == 'a' &&
wd.subchunk2ID[2] == 't' && wd.subchunk2ID[3] == 'a')
return TRUE;
else return FALSE;
}
void printWaveFileHeaderInfo(WAV_HEADER wh){
printf("chunkID: %.4s\n",wh.wavFileRIFFChunk.chunkID);
printf("chunkSize: %u\n",wh.wavFileRIFFChunk.chunkSize);
printf("format: %.4s\n",wh.wavFileRIFFChunk.format);
printf("subchunk1ID: %.4s\n",wh.fmt.subchunk1ID);
printf("subchunk1Size: %u\n",wh.fmt.subchunk1Size);
printf("audioFormat: %u\n",wh.fmt.audioFormat);
printf("numChannels: %u\n",wh.fmt.numChannels);
printf("sampleRate: %u\n",wh.fmt.sampleRate);
printf("byteRate: %u\n",wh.fmt.byteRate);
printf("blockAlign: %u\n",wh.fmt.blockAlign);
printf("bitsPerSample: %u\n",wh.fmt.bitsPerSample);
printf("subchunk2ID: %.4s\n",wh.dataHeader.subchunk2ID);
printf("subchunk2Size: %u\n",wh.dataHeader.subchunk2Size);
}
double * wavFile_execute(char * fileName, WAV_STRUCT * wavFileEg){
FILE * fin = NULL;
fin = fopen(fileName,"rb");
if(!fin){
printf("%s cannot open this file\n", fileName);
exit(0);
}
else printf("%s opened successfully\n", fileName);
fread(wavFileEg, sizeof(wavFileEg->wavHeader), 1, fin);
while(isDataChunk(wavFileEg->wavHeader.dataHeader) == FALSE){
int cnt = wavFileEg->wavHeader.dataHeader.subchunk2Size;
while(cnt > 0){
fgetc(fin);
--cnt;
}
fread(&(wavFileEg->wavHeader.dataHeader),sizeof(wavFileEg->wavHeader.dataHeader),1,fin);
}
wavFileEg->dataSize = (int)wavFileEg->wavHeader.dataHeader.subchunk2Size;
wavFileEg->numSamples = (int)wavFileEg->dataSize*8/wavFileEg->wavHeader.fmt.bitsPerSample/wavFileEg->wavHeader.fmt.numChannels;
wavFileEg->data = (signed char *)malloc(sizeof(byte)*wavFileEg->dataSize);
int i = 0;
while(i < wavFileEg->dataSize && !feof(fin)){
wavFileEg->data[i] = fgetc(fin);
++i;
}
fclose(fin);
double *originData = (double *)malloc(sizeof(double)*wavFileEg->numSamples);
int gap = wavFileEg->wavHeader.fmt.bitsPerSample / 8 * wavFileEg->wavHeader.fmt.numChannels;
if(wavFileEg->wavHeader.fmt.bitsPerSample == 8){
i = 0;
while(i < wavFileEg->numSamples){
unsigned int tmp = wavFileEg->data[i * gap];
originData[i] = (double)tmp / 255;
}
}
else {
i = 0;
while(i < wavFileEg->numSamples){
int tmp = (wavFileEg->data[i*gap+1])<<8|(wavFileEg->data[i*gap]);
if(tmp > 0) originData[i] = (double)tmp/32767;
else originData[i] = (double)tmp/32768;
++i;
}
}
return originData;
} |
C | #include <stdio.h>
int htoi(char s[]);
int hctoi(char c);
int main(int argc, const char *argv[])
{
char str[]= "0x1fa9";
printf("%d\n", htoi(str));
return 0;
}
int hctoi(char c) {
char str[] = "aAbBcCdDeEfF";
int i;
int ret;
for (i = 0; str[i] != '\0'; i++) {
if(c == str[i]) {
ret = 10 + (i / 2);
}
}
return ret;
}
int htoi(char s[]){
int i = 0;
int ret = 0;
if(s[i] == '0') {
++i;
if(s[i] == 'x' || s[i] == 'X') {
++i;
}
}
while(s[i] != '\0') {
ret = ret * 16;
if(s[i] >= '0' && s[i] <= '9') {
ret = ret + (s[i] - '0');
} else {
int hc = hctoi(s[i]);
ret = ret + hc;
}
++i;
}
return ret;
}
|
C | /**
* tcpkit -- toolkit to analyze tcp packet
* Copyright (C) 2018 @git-hulk
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
**/
#include <time.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include "log.h"
static FILE *log_fp = NULL;
static enum LEVEL log_level = INFO;
void print_redirect(FILE *fp) {
log_fp = fp;
}
void raw_printf(char *fmt, ...) {
va_list args;
va_start(args, fmt);
color_printf(NULL, fmt, args);
va_end(args);
}
void color_printf(const char *color, char *fmt, ...) {
va_list ap;
char buf[4096];
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
if(log_fp != stdout || color == NULL) {
fprintf(log_fp, "%s", buf);
fflush(log_fp);
} else {
fprintf(log_fp, "%s%s"NONE"", color, buf);
}
}
void log_message(enum LEVEL loglevel, char *fmt, ...) {
va_list ap;
time_t now;
char buf[4096];
char t_buf[64];
char *msg = NULL;
const char *color = "";
if(loglevel < log_level) return;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
switch(loglevel) {
case DEBUG: msg = "DEBUG"; break;
case INFO: msg = "INFO"; color = GREEN; break;
case WARN: msg = "WARN"; color = YELLOW; break;
case ERROR: msg = "ERROR"; color = RED; break;
case FATAL: msg = "FATAL"; color = RED; break;
}
now = time(NULL);
strftime(t_buf,64,"%Y-%m-%d %H:%M:%S",localtime(&now));
if(log_fp != stdout) {
fprintf(log_fp, "[%s] [%s] %s\n", t_buf, msg, buf);
fflush(log_fp);
} else {
fprintf(log_fp, "%s[%s] [%s] %s"NONE"\n", color, t_buf, msg, buf);
}
if(loglevel > ERROR) {
exit(1);
}
}
|
C | #ifndef SYS_PROG_H
#define SYS_PROG_H
#include <stdbool.h>
#include <stddef.h>
#include <sys/types.h>
#include <stdint.h>
#include <unistd.h>
//
// NOTE THE FILE I/O MUST USE OPEN, READ, WRITE, CLOSE, SEEK, STAT with file descriptors (NO FILE*)
// Make sure to uint8_t or uint32_t, you are dealing with system dependent sizes
// Read contents from the passed into an destination
// \param input_filename the file containing the data to be copied into the destination
// \param dst the variable that will be contain the copied contents from the file
// \param offset the starting location in the file, how many bytes inside the file I start reading
// \param dst_size the total number of bytes the destination variable contains
// return true if operation was successful, else false
bool bulk_read(const char *input_filename, void *dst, const size_t offset, const size_t dst_size);
// Writes contents from the data source into the outputfile
// \param src the source of the data to be wrote to the output_filename
// \param output_filename the file that is used for writing
// \param offset the starting location in the file, how many bytes inside the file I start writing
// \param src_size the total number of bytes the src variable contains
// return true if operation was successful, else false
bool bulk_write(const void *src, const char *output_filename, const size_t offset, const size_t src_size);
// Returns the file metadata given a filename
// \param query_filename the filename that will be queried for stats
// \param metadata the buffer that contains the metadata of the queried filename
// return true if operation was successful, else false
bool file_stat(const char *query_filename, struct stat *metadata);
// Converts the endianess of the source data contents before storing into the dst_data.
// The passed source data bits are swapped from little to big endian and vice versa.
// \param src_data the source data that contains content to be stored into the destination
// \param dst_data the destination that stores src data
// \param src_count the number of src_data elements
// \return true if successful, else false for failure
bool endianess_converter(uint32_t *src_data, uint32_t *dst_data, const size_t src_count);
#endif
|
C | #include "osconfig.h"
#include "stm8s.h"
#include <IntrOS/kernel/os.h>
static void initialize_clock();
//static void initialize_tim1();
static inline void led_init(void);
static inline void led_set(void);
static inline void led_clear(void);
static inline void led_toggle(void);
/*void tim1_interrupt(void) __interrupt(11)
{
// clear update interrupt flag
TIM1->SR1 &= ~(TIM1_SR1_UIF);
}*/
OS_SEM(sem, 0, semBinary);
OS_TSK_DEF(sla)
{
sem_wait(sem);
led_toggle();
}
OS_TSK_DEF(mas)
{
tsk_delay(MSEC * 200);
sem_give(sem);
}
void main()
{
led_init();
sys_init();
/*__asm__("sim");
initialize_tim1();
__asm__("rim");*/
tsk_start(sla);
tsk_start(mas);
tsk_stop();
}
#define LED_PORT GPIOB
#define LED_PIN GPIO_PIN_5
static inline void led_init(void)
{
GPIO_Init(LED_PORT, GPIO_PIN_5, GPIO_MODE_OUT_PP_HIGH_SLOW);
}
static inline void led_set(void)
{
GPIO_WriteLow(LED_PORT, GPIO_PIN_5);
}
static inline void led_clear(void)
{
GPIO_WriteHigh(LED_PORT, LED_PIN);
}
static inline void led_toggle(void)
{
GPIO_WriteReverse(LED_PORT, LED_PIN);
}
/*static void initialize_tim1()
{
TIM1->PSCRH = 0;
TIM1->PSCRL = 0; // 1 - frequency division -> timer clock equals system clock = 16MHz
// enable ARR register buffering through register
// so when we write our value it's buffered and written
// as entire 16-bit value
TIM1->CR1 |= TIM1_CR1_ARPE;
// count to 16000 (0x3E80)
TIM1->ARRH = 0x3E;
TIM1->ARRL = 0x80;
// clear counter
TIM1->CNTRH = 0;
TIM1->CNTRL = 0;
// enable Update interrupts for the timer
TIM1->IER |= TIM1_IER_UIE;
// clear any pending update interrupts
TIM1->SR1 |= TIM1_SR1_UIF;
// Set direction; use as down-counter
// and enable counter
TIM1->CR1 |= TIM1_CR1_DIR | TIM1_CR1_CEN;
}*/
|
C | #include <stdio.h>
int power = 16;
union dbl { int i[2]; double d; }
x, tot;
int bit;
double saved;
void normalize(ad)
double *ad;
{
asm( "SETZB 1,2\n"
"DFAD 1,@-1(17)\n"
"DMOVEM 1,@-1(17)\n" );
}
main()
{
int i;
x.d = 1.0;
bit = 26+35;
while (bit >= 0) {
/* Apply current bit downwards */
saved = x.d;
if (bit > 35)
x.i[0] -= (1 << (bit-35));
else {
x.i[1] -= (1 << bit);
if (x.i[1] < 0) {
x.i[1] &= (~0U)>>1;
x.i[0] -= 1;
}
}
normalize(&x.d);
/* See if new X is bad, back up if so */
if (x.d <= 0) {
x.d = saved;
--bit; /* Try smaller bit next time */
continue;
}
/* Now test X */
tot.d = x.d;
for (i = power; --i > 0; ) {
tot.d *= x.d;
if (tot.d <= 0 || tot.d > x.d)
break; /* Over/underflowed, stop */
}
printf("Bit %d, X=%g, Res=%g %s\n",
bit, x.d, tot.d, (i ? "BARF" : "OK"));
if (i) { /* If prematurely stopped, */
x.d = saved; /* Restore previous value */
--bit; /* and use smaller increment */
}
}
printf("Power %d done, X=%.20g { %#o, %#o } \n",
power, x.d, x.i[0], x.i[1]);
}
|
C | /**
* @file
* @brief Test unit for stdlib/bsearch.
*
* @date Nov 19, 2011
* @author Avdyukhin Dmitry
*/
#include <embox/test.h>
#include <stdlib.h>
#include <stdio.h>
EMBOX_TEST_SUITE("stdlib/qsort test");
/**
* Compare pointers to integer numbers
*/
static int int_comp(const void *fst, const void *snd) {
return *((int *)fst) - *((int *)snd);
}
/* Test array of numbers. */
static const int a[] = {0, 1, 2, 2, 4, 5, 10, 10, 20};
/* Count of numbers in array. */
static const int cnt = 9;
/* Check if number wasn't found. */
static void not_found(void *res) {
test_assert(res == NULL);
}
/**
* Check if number was found
* and result pointer corresponds to expected index ans.
*/
static void found(void * res, size_t ans) {
test_assert((res - (void *)a) / sizeof(int) == ans);
}
static void * find(int num) {
return bsearch((int *)&num, a, cnt, sizeof(int), int_comp);
}
TEST_CASE("Test that not-existing too small item won't be found") {
not_found(find(-10));
}
TEST_CASE("Test that not-existing too large item won't be found") {
not_found(find(100));
}
TEST_CASE("Test that not-existing medium item won't be found") {
not_found(find(3));
}
TEST_CASE("Test that existing unique item will be found") {
found(find(5), 5);
}
TEST_CASE("Test that existing last unique item will be found") {
found(find(20), 8);
}
TEST_CASE("Test that existing not-unique item will be found. "
"Result must be the rightmost one") {
found(find(2), 3);
}
|
C | #include "libc.h"
int main(int argc, char** argv) {
const char* tn = argv[1];
printf("*** [%s] argc = %d\n", tn, argc);
for (int i = 0; i < argc; i++)
printf("*** [%s] argv[%d] = %s\n", tn, i, argv[i]);
if (argv[argc] != 0)
printf("*** [%s] failed to null-terminate, argv[%d] = %s\n",
tn, argc, argv[argc]);
for (int i = 0; i < 5; i++)
if ("exec"[i] != argv[2][i]) goto test;
printf("*** [%s] successfully executed from symbolic link\n", tn);
return 0;
test: {
int fd = open("/files/link1", 0);
if (fd < 0)
printf("*** [%s] failed to open %s\n", tn, "/files/link1");
printf("*** [%s] ", tn);
cp(fd, 1);
fd = open("/files/link2", 0);
if (fd < 0)
printf("*** [%s] failed to open %s\n", tn, "/files/link2");
printf("*** [%s] ", tn);
cp(fd, 1);
fd = open("/files/link3", 0);
if (fd < 0)
printf("*** [%s] failed to open %s\n", tn, "/files/link3");
printf("*** [%s] ", tn);
cp(fd, 1);
fd = open("/files/link4", 0);
if (fd < 0)
printf("*** [%s] failed to open %s\n", tn, "/files/link4");
printf("*** [%s] ", tn);
cp(fd, 1);
int id = fork();
if (id < 0) {
printf("*** [%s] fork failed\n", tn);
} else if (id == 0) {
int rc = execl("/files/link5", "link5", argv[1], "exec", 0);
printf("*** [%s] execl failed, rc = %d\n", tn, rc);
return -1;
} else {
uint32_t status = 0xffffffff;
wait(id, &status);
printf("*** [%s] result = %ld\n", tn, status);
}
id = fork();
if (id < 0) {
printf("*** [%s] fork failed\n", tn);
} else if (id == 0) {
int rc = execl("/files/link2", "link2", argv[1], "exec", 0);
printf("*** [%s] failed to execute %s\n", tn, "files/link2");
printf(" rc = %d\n", rc);
return -1;
} else {
uint32_t status = 0xffffffff;
wait(id, &status);
printf("*** [%s] result = %ld\n", tn, status);
}
}
return 0;
}
|
C | #include <stdio.h>
#include <string.h>
char* Strstr(char*ch, char*sr)
{
int a;
int iCnt = 0;
int iCount = 0;
while (ch[iCnt++] != 0);
while (sr[iCount++] != 0);
iCnt--; iCount--;
for (int i = 0; i < iCnt;i++)
{
a = 0;
if (*(ch + i) == *(sr+0))
{
for (int j = 1; j < iCount; j++)
{
if (*(ch + i + j) != *(sr + j))
{
a++;
break;
}
}
if(!a)
{
return ch+i;
}
}
}
return NULL;
}
int main(void)
{
char *s1 = "This is a string";
char *s2 = "a st";
char *ptr;
ptr = Strstr(s1, s2);
printf("string : %s\n", s1);
printf("%s ϴ s1 \n ڿ : %s\n", s2, ptr);
ptr = strpbrk(s1, s2);
printf("ù ڰ ġϴ s1 \n ڿ : %s\n", ptr);
return 0;
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
void main(){
setlocale(LC_ALL, "Portuguese");
int vecRa[5], i=0; //store the ra number (15119)
vecRa[0] = 1;
vecRa[1] = 5;
vecRa[2] = 1;
vecRa[3] = 1;
vecRa[4] = 9;
int vecKey[5]; //store the input number
printf("============ COFRE ==========\n\n");
do{
system("cls");
printf("\nDigite o %d dgito da senha: ", i+1);
scanf("%d", &vecKey[i]);
if(vecRa[i] != vecKey[i]){
printf("\nSequncia Incorreta\n\n");
printf("Tente novamente...\n\n\n");
i = 0;
system("pause");
}else{
i++;
}
}while (i<5);
if (i == 5){
printf("\n===========+++++++========\n");
printf("Porta aberta\n");
printf("===========+++++++========\n\n");
}
} |
C | #!/usr/bin/tcc -run -w
#include <stdio.h>
main(argc, argv)
int argc;
char **argv;
{
int err = 0;
if (argc <= 1) {
fprintf(stderr, "usage: %s dir ...\n", argv[0]);
exit(1);
}
while (--argc > 0)
if (mkdir(*++argv, 0777) < 0) {
perror(*argv);
err = 1;
}
exit(err);
}
|
C | #include <stdio.h>
#include <myconio.h>
#include <string.h>
#include "..\blockChain\blockChain.h"
/** CONSTANTES **/
#define DIM 3
int main(void)
{
/** VARIABLES **/
int i, j, nb_blocs, valideChain;
char *contenu = NULL;
char *chaine = NULL;
char *transactions[9] = {"Transaction 1","Transaction 2","Transaction 3","Transaction 4","Transaction 5","Transaction 6","Transaction 7","Transaction 8","Transaction 9"};
BLOCK *bloc = NULL;
BLOCK blocs[DIM];
/** CRATION DE LA BLOCCHAIN **/
i = 0; valideChain = 1; nb_blocs = DIM;
while(i<=nb_blocs-1)
{
if(i == 0)
bloc = creerBlock(transactions, 3, NULL, (i+1));
else
bloc = creerBlock(transactions, 3, blocs[i-1].hashCode, (i+1));
/* COPIE DU BLOC */
strcpy(blocs[i].hashCode, bloc->hashCode);
contenu = blocs[i].contenuBloc.transactions[0];
chaine = bloc->contenuBloc.transactions[0];
for(j=0; j<=sizeof(CONTENU_BLOC)-1; j++)
contenu[j] = chaine[j];
free(bloc);
i++;
}
/** VALIDATION DE LA BLOCKCHAIN **/
valideChain = validerBlockChain(blocs, i);
/** DCHIFFREMENT DU CONTENU DES BLOCS **/
for(i=0; i<=nb_blocs-1; i++)
{
contenu = blocs[i].contenuBloc.transactions[0];
chaine = dechiffrer(contenu, sizeof(CONTENU_BLOC)); // dchiffrement du contenu
for(j=0; j<=sizeof(CONTENU_BLOC)-1; j++) // copie de chaque caractre dchiffr dans le contenu
contenu[j] = chaine[j];
free(chaine); // libration de l'emplacement ram allou par le chiffrement
}
/** AFFICHAGE DES BLOCS **/
for(i=0; i<=nb_blocs-1; i++)
{
textcolor(LIGHTRED); textbackground(WHITE); MYclrwin(1, 1+i*8, 30, 1+i*8);
printf("\t BLOC %s\n", blocs[i].contenuBloc.numBlocString);
textcolor(WHITE); textbackground(LIGHTGRAY); MYclrwin(1, 2+i*8, 30, 7+i*8);
printf("HASHCODE:\t%s\n", blocs[i].hashCode);
printf("HASHCODEPREC:\t%s\n", blocs[i].contenuBloc.hashCodePrec);
printf("TRANSACTIONS:\t%s\n", blocs[i].contenuBloc.transactions[0]);
printf("\t\t%s\n", blocs[i].contenuBloc.transactions[1]);
printf("\t\t%s\n", blocs[i].contenuBloc.transactions[2]);
if(valideChain != 1 && valideChain == ((i+1)*-1))
printf("STATUS:\t\tinvalide\n\n");
else
printf("STATUS:\t\tvalide\n\n");
}
getch();
textattr(BLACK*16+LIGHTGRAY);
return (0);
}
|
C | #include <stdio.h>
#include <stdlib.h>
/**
computes points for every throwing
@return the point of throwing
*/
int calculation_function_first(int throwing_point_2, char type_of_place_2)
{
if (type_of_place_2 == 'I') {
throwing_point_2 = 50;
} else if (type_of_place_2 == 'S') {
throwing_point_2 *= 1;
} else if (type_of_place_2 == 'O') {
throwing_point_2 = 25;
} else if (type_of_place_2 == 'D') {
throwing_point_2 *= 2;
} else if (type_of_place_2 == 'T') {
throwing_point_2 *= 3;
}
return throwing_point_2;
}
/**
computes remaining point from target
@return the remainder
*/
int calculation_function_second(int aim_3, int calculated_throwing_point, char type_of_place_3)
{
int remainder;
remainder = aim_3 - calculated_throwing_point;
return remainder;
}
int main()
{
char type_of_place_1;
int throwing_point_1, aim_1, aim_2;
printf("Target: ");
scanf("%d", &aim_1);
aim_2 = aim_1;
while (aim_2 == aim_1) {
printf("\nThrow: ");
scanf("%d %c", &throwing_point_1, &type_of_place_1);
if (type_of_place_1 == 'D' && calculation_function_second(aim_2, calculation_function_first(throwing_point_1, type_of_place_1), type_of_place_1) < aim_2) {
aim_2 = calculation_function_second(aim_2, calculation_function_first(throwing_point_1, type_of_place_1), type_of_place_1);
}
printf("Points: %d", aim_2);
while (aim_2 != aim_1 && aim_2 != 0) {
printf("\nThrow: ");
scanf("%d %c", &throwing_point_1, &type_of_place_1);
if (type_of_place_1 == 'D' && calculation_function_first(throwing_point_1, type_of_place_1) <= aim_2) {
aim_2 = calculation_function_second(aim_2, calculation_function_first(throwing_point_1, type_of_place_1), type_of_place_1);
} else if (type_of_place_1 == 'I' && calculation_function_first(throwing_point_1, type_of_place_1) < aim_2) {
aim_2 = calculation_function_second(aim_2, calculation_function_first(throwing_point_1, type_of_place_1), type_of_place_1);
} else if (type_of_place_1 == 'O' && calculation_function_first(throwing_point_1, type_of_place_1) < aim_2) {
aim_2 = calculation_function_second(aim_2, calculation_function_first(throwing_point_1, type_of_place_1), type_of_place_1);
} else if (type_of_place_1 == 'S' && calculation_function_first(throwing_point_1, type_of_place_1) < aim_2) {
aim_2 = calculation_function_second(aim_2, calculation_function_first(throwing_point_1, type_of_place_1), type_of_place_1);
} else if (type_of_place_1 == 'T' && calculation_function_first(throwing_point_1, type_of_place_1) < aim_2) {
aim_2 = calculation_function_second(aim_2, calculation_function_first(throwing_point_1, type_of_place_1), type_of_place_1);
}
printf("Points: %d", aim_2);
}
}
printf("\n");
return EXIT_SUCCESS;
}
|
C | /*!
* @file
* @brief Linked list that contains nodes allocated by clients.
*
* Nodes can contain arbitrary data by defining a type that contains
* a tiny_list_node_t:
*
* typedef struct client_node_t {
* tiny_list_node_t node;
* int data;
* }
*
* This type must be cast to a tiny_list_node_t to be added but can
* be cast back by the client so that the data can be accessed.
*/
#ifndef tiny_list_h
#define tiny_list_h
#include <stdbool.h>
#include <stdint.h>
#include "tiny_utils.h"
typedef struct tiny_list_node_t {
struct tiny_list_node_t* next;
} tiny_list_node_t;
typedef struct {
tiny_list_node_t head;
} tiny_list_t;
typedef struct
{
tiny_list_node_t* current;
} tiny_list_iterator_t;
/*!
* Initializes the list.
*/
void tiny_list_init(tiny_list_t* self);
/*!
* Adds the node to the front of the list.
*/
void tiny_list_push_front(tiny_list_t* self, tiny_list_node_t* node);
/*!
* Adds the node to the back of the list.
*/
void tiny_list_push_back(tiny_list_t* self, tiny_list_node_t* node);
/*!
* Removes the node from the front of the list. Returns the node.
*/
tiny_list_node_t* tiny_list_pop_front(tiny_list_t* self);
/*!
* Removes the node at the back of the list. Returns the node.
*/
tiny_list_node_t* tiny_list_pop_back(tiny_list_t* self);
/*!
* Removes a specified node if present in the list.
*/
void tiny_list_remove(tiny_list_t* self, tiny_list_node_t* node);
/*!
* Returns the number of nodes contained in the list.
*/
uint16_t tiny_list_count(tiny_list_t* self);
/*!
* Returns true if the specified node is in the list and false otherwise.
*/
bool tiny_list_contains(tiny_list_t* self, tiny_list_node_t* node);
/*!
* Gives the index of a given node in the list.
*/
uint16_t tiny_list_index_of(tiny_list_t* self, tiny_list_node_t* node);
/*!
* Initialize an iterator for the provided list.
*/
void tiny_list_iterator_init(tiny_list_iterator_t* self, tiny_list_t* list);
/*!
* Return a pointer to the next node or NULL if there are no more nodes.
*/
tiny_list_node_t* tiny_list_iterator_next(tiny_list_iterator_t* self, tiny_list_t* list);
#define tiny_list_for_each(_list, _type, _item, ...) \
do { \
tiny_list_iterator_t _it; \
tiny_list_iterator_init(&_it, _list); \
_type* _item; \
while((_item = (_type*)tiny_list_iterator_next(&_it, _list))) { \
__VA_ARGS__ \
} \
} while(0)
#endif
|
C | #ifndef QUEUE_H
#define QUEUE_H
#include <stdbool.h>
typedef int Item;
typedef struct queue_type *Queue;
Queue create(int size);
void destroy(Queue q);
void make_empty(Queue q);
bool is_empty(Queue q);
bool is_full(Queue q);
void add_last(Queue q, Item i);
Item remove_first(Queue q);
Item get_first(Queue q);
Item get_last(Queue q);
#endif
|
C | #ifndef SATAPI_H_
#define SATAPI_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
/******************************************************************************
* typedefs
******************************************************************************/
typedef char BOOLEAN; //signed
typedef unsigned long c2dSize; //for variables, clauses, and various things
typedef signed long c2dLiteral; //for literals
typedef double c2dWmc; //for (weighted) model count
typedef struct var Var;
typedef struct literal Lit;
typedef struct clause Clause;
typedef struct sat_state_t SatState;
/******************************************************************************
* function prototypes
******************************************************************************/
/******************************************************************************
* Variables
******************************************************************************/
Var* sat_index2var(c2dSize index, const SatState* sat_state);
c2dSize sat_var_index(const Var* var);
Var* sat_literal_var(const Lit* lit);
BOOLEAN sat_instantiated_var(const Var* var);
BOOLEAN sat_irrelevant_var(const Var* var);
c2dSize sat_var_count(const SatState* sat_state);
c2dSize sat_var_occurences(const Var* var);
Clause* sat_clause_of_var(c2dSize index, const Var* var);
BOOLEAN sat_marked_var(const Var* var);
void sat_mark_var(Var* var);
void sat_unmark_var(Var* var);
/******************************************************************************
* Literals
******************************************************************************/
Lit* sat_index2literal(c2dLiteral index, const SatState* sat_state);
c2dLiteral sat_literal_index(const Lit* lit);
Lit* sat_pos_literal(const Var* var);
Lit* sat_neg_literal(const Var* var);
BOOLEAN sat_implied_literal(const Lit* lit);
c2dWmc sat_literal_weight(const Lit* lit);
Clause* sat_decide_literal(Lit* lit, SatState* sat_state);
void sat_undo_decide_literal(SatState* sat_state);
/******************************************************************************
* Clauses
******************************************************************************/
Clause* sat_index2clause(c2dSize index, const SatState* sat_state);
c2dSize sat_clause_index(const Clause* clause);
Lit** sat_clause_literals(const Clause* clause);
c2dSize sat_clause_size(const Clause* clause);
BOOLEAN sat_subsumed_clause(const Clause* clause);
c2dSize sat_clause_count(const SatState* sat_state);
c2dSize sat_learned_clause_count(const SatState* sat_state);
Clause* sat_assert_clause(Clause* clause, SatState* sat_state);
BOOLEAN sat_marked_clause(const Clause* clause);
void sat_mark_clause(Clause* clause);
void sat_unmark_clause(Clause* clause);
/******************************************************************************
* SatState
******************************************************************************/
SatState* sat_state_new(const char* file_name);
void sat_state_free(SatState* sat_state);
BOOLEAN sat_unit_resolution(SatState* sat_state);
void sat_undo_unit_resolution(SatState* sat_state);
BOOLEAN sat_at_assertion_level(const Clause* clause, const SatState* sat_state);
#endif //SATAPI_H_
/******************************************************************************
* end
******************************************************************************/
|
C | /*
@author : Rahul Thapar
ID : 1410110321
Problem : Implement Fractional Knapscak Problem
Algorithm
__________
1. Calculate DENSITY : value per weight for each item
2. Sort the items as per the value density in descending order
3. Take as much item as possible not already taken in the knapsack
*/
#include <stdio.h>
int n;
int cost[50];
int value[50];
int W;
int q;
void knapsack_fill() {
int current_weight;
float total_value;
int i, maximum_i;
int used[10];
for (i = 0; i < n; ++i)
used[i] = 0;
current_weight = W;
while (current_weight > 0) { // While the bag is NOT full : add
// Find the suitable object to ADD
maximum_i = -1;
for (i = 0; i < n; ++i)
if ((used[i] == 0) &&((maximum_i == -1) || ((float)value[i]/cost[i] > (float)value[maximum_i]/cost[maximum_i])))
maximum_i = i;
used[maximum_i] = 1; // Maximum value used
current_weight -= cost[maximum_i];
total_value += value[maximum_i];
if (current_weight >= 0)
printf("\tObject Added : %d\t VALUE : %d\t PROFIT : %d\t Space Left : %d\n", maximum_i + 1, value[maximum_i], cost[maximum_i], current_weight);
else {
printf("\tObject Added : %d\t VALUE : %d\t PROFIT : %d\t Space Left : %d\n", (int)((1 + (float)current_weight/cost[maximum_i]) * 100), value[maximum_i], cost[maximum_i], maximum_i + 1);
total_value -= value[maximum_i];
total_value += (1 + (float)current_weight/cost[maximum_i]) * value[maximum_i];
}
}
printf("\n\n");
printf("Final VALUE in the bag : %.2f.\n\n", total_value);
}
int main(){
printf("\n\n");
printf("\tImplementation of Fractional Knapsack Problem\n");
printf("\t=================================================\n\n");
printf("\t Number of objects : ");
scanf("%d",&n);
printf("\t COST of each object - ");
for(q=0;q<n;q++){
scanf("%d",&cost[q]);
}
printf("\t PROFIT on each corresponding object - ");
for(q=0;q<n;q++){
scanf("%d",&value[q]);
}
printf("\tTotal Weight of the BAG : ");
scanf("%d",&W);
printf("\n\n");
knapsack_fill();
return 0;
} |
C | /* lcdScreen.c
* Samuel Scherer
* 4/5/17
*
* Sets up LCD screen
*/
#include <fcntl.h>
#include <stdio.h> // for File IO and printf
#include <string.h> //for strcat
#include <time.h> // for usleep
#include <sys/stat.h>
#include <unistd.h>
#define GPIO_PIN9 27 // LED pin unused
#define GPIO_PIN10 65 // LED pin unused
#define MAX_BUF 3
// function declarations
void setPins(FILE *val[], int input);
void setPinsEn(FILE *val[], int input);
void usleep();
int main() {
// Creates the File pointers to create the gpio file system,
// set the direction of the GPIO, and change the data stored there.
FILE *sys, *dir;
FILE *val[7];
int pins[7] = {69, 45, 44, 26, 47, 46, 27};
int count = 0;
for (int i = 0; i < 7; i++){
int a = i;
sys = fopen("/sys/class/gpio/export", "w");
fprintf(sys, "%d", pins[i]);
fflush(sys);
fclose(sys);
}
//Set the gpio to output
for (int i = 0; i < 7; i++){
char directoryName[80];
char pinNum[80];
memset(directoryName, 0, 80);
strcat(directoryName, "/sys/class/gpio/gpio");
sprintf(pinNum, "%d", pins[i]);
strcat(directoryName, pinNum);
strcat(directoryName, "/direction");
printf("%s \n", directoryName);
dir = fopen(directoryName, "w");
fseek(dir, 0, SEEK_SET);
fprintf(dir, "%s", "out");
fflush(dir);
fclose(dir);
}
//Open the files that control if the pin is high or low
for (int i = 0; i < 7; i++){
char directoryName[80];
char pinNum[80];
memset(directoryName, 0, 80);
strcat(directoryName, "/sys/class/gpio/gpio");
sprintf(pinNum, "%d", pins[i]);
strcat(directoryName, pinNum);
strcat(directoryName, "/value");
printf("%s \n", directoryName);
val[i] = fopen(directoryName, "w");
fseek(val[i], 0, SEEK_SET);
}
//power on
usleep(500000);//more than 15 ms
//initialize board (4 bit)
setPinsEn(val, 3); //Function set command 1100000
setPinsEn(val, 3); //Function set command 1100000
setPinsEn(val, 3); //Function set command 1100000
setPinsEn(val, 2); //Function set command (to 4 bit)0100000
setPinsEn(val, 2); //Function set 0100000
setPinsEn(val, 12); //N = bit 4 number of lines, F = bit 3 font 0011000
setPinsEn(val, 0); //display off 0000000
setPinsEn(val, 8);
setPinsEn(val, 0); //clear display 0000000
setPinsEn(val, 1); // 1000000
setPinsEn(val, 0); //entry mode set
setPinsEn(val, 6); // 0110000
setPinsEn(val, 0); //display on
setPinsEn(val, 15); // 1111000
// create a pipe (same file as in write_to_screen.c) and a buffer for reading the pipe
char* myfifo = "/tmp/myfifo";
char buf[MAX_BUF];
// keep track of the number of characters printed so far
int charsInLine = 0;
// open, read, and display the message from the FIFO
while(1) {
// read input
int fd = open(myfifo, O_RDONLY);
read(fd, buf, MAX_BUF);
int charIn = (int)buf[0];
// if we pass in "\n" and we are on the first line, go to the next line
if ((charIn == 10) && (charsInLine < 16)) {
setPinsEn(val, 12);
setPinsEn(val, 0);
charsInLine = 16;
}
// if we pass in "\n" and we are on the second, clear screen and reset
else if ((charIn == 10) && (charsInLine >= 16)) {
setPinsEn(val, 0);
setPinsEn(val, 1);
charsInLine = 0;
}
// otherwise, just print the character
else {
// set pins
setPinsEn(val, charIn/16 + 64 + 32);
setPinsEn(val, (charIn % 16) + 64);
// update the number of characters
charsInLine++;
// move to line 2 when first line full, and clear everything and reset when both are full
if (charsInLine == 16) {
setPinsEn(val, 12);
setPinsEn(val, 0);
} else if (charsInLine == 33) {
setPinsEn(val, 0);
setPinsEn(val, 1);
charsInLine = 0;
}
}
// print to console and close
printf("%d: %d %d\n", charIn, charIn/16 + 64 + 32, (charIn % 16) + 64);
usleep(5000);
close(fd);
}
return 0;
}
// ============= //
// FUNCTIONS //
// ============= //
//move cursor
//when operating in 4 bit mode, send high order nibble, then low order nibble
//setting both numbers to 0 gets the cursor in upper right, column navigation on the first row is still unclear
/*
setPinsEn(val, 0);//sets row (4 is second row)
setPinsEn(val, 0);//sets column (0 is leftmost, 15 is rightmost character)*/
//sets pins
void setPins(FILE *val[7], int input){
for (int i= 6; i>=0; i--){
int pinValue;
pinValue = (input>>(6-i))%2;
fprintf(val[i], "%d", pinValue);
fflush(val[i]);
}
}
//sets pins, flicks enable up and down
void setPinsEn(FILE *val[7], int input){
// add 2^4 = 16 to flip enable pin to 1
int inputPlusSixteen = input + 16;
// print to all pins with EN = 0
for (int i= 6; i>=0; i--){
int pinValue;
pinValue = (input>>(6-i))%2;
fprintf(val[i], "%d", pinValue);
fflush(val[i]);
}
usleep(5000);
// print to all pins with EN = 1
for (int i= 6; i>=0; i--){
int pinValue;
pinValue = (inputPlusSixteen>>(6-i))%2;
fprintf(val[i], "%d", pinValue);
fflush(val[i]);
}
usleep(5000);
// print to all pins with EN = 0
for (int i= 6; i>=0; i--){
int pinValue;
pinValue = (input>>(6-i))%2;
fprintf(val[i], "%d", pinValue);
fflush(val[i]);
}
usleep(5000);
}
|
C | #include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
/* for Fortran - j*n + i */
//#define IDX(i, j, n) (((i) * (n)) + (j))
#define IDX(i, j, n) (((j)+ (i)*(n)))
int
chol(double *A, unsigned int n)
{
unsigned int i;
unsigned int j;
unsigned int k;
for (j = 0; j < n; j++) {
for (i = j; i < n; i++) {
for (k = 0; k < j; ++k) {
A[IDX(i, j, n)] -= A[IDX(i, k, n)] *
A[IDX(j, k, n)];
}
}
if (A[IDX(j, j, n)] < 0.0) {
return (1);
}
A[IDX(j, j, n)] = sqrt(A[IDX(j, j, n)]);
for (i = j + 1; i < n; i++)
A[IDX(i, j, n)] /= A[IDX(j, j, n)];
}
return (0);
}
int
main()
{
double *A;
int i, j, n, ret;
n = 2000;
A = (double*)calloc(n*n, sizeof(double));
assert(A != NULL);
for(i=0; i<n; i++)
A[IDX(i, i, n)] = 2;
chol(A,n);
// if (!chol(A, n));
// else
// fprintf(stderr, "Error: matrix is either not symmetric or not positive definite.\n");
free(A);
return 0;
}
|
C | /*******************************************************************************
FILE NAME : main.c
DESCRIPTION : Generic main file
*******************************************************************************/
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "nucleoboard.h"
#include "hw_init.h"
#include "print.h"
#include "pseudo_random.h"
/* Public variables ----------------------------------------------------------*/
__IO uint32_t timer;
PRINT_DEFINEBUFFER(); /* required for lightweight sprintf */
/* Private variables ----------------------------------------------------------*/
char clr_scrn[] = { 27, 91, 50, 74, 0 }; // esc[2J
// A small array of random value to initialize
int array[20];
/* Private prototype ---------------------------------------------------------*/
void delay(uint32_t time);
extern void bubbleSort(int A[], int cnt, int val);
/*******************************************************************************
Function Name : main
Description :
Parameters :
Return value : */
void main() {
int i;
uint32_t count;
Hw_init();
// Initialize Pseudo-Random Generator
Initialize(0xdeadbeef);
PrintString(clr_scrn); /* Clear entire screen */
RETAILMSG(1, ("Lab Week 3: Built %s %s.\r\n\r\n",
__DATE__,
__TIME__));
// Initialize the entire array to pseudo-random numbers
PrintString("Array before sort:\n\n");
count = sizeof(array)/sizeof(int);
for (i = 0; i < count; i++)
{
// Allow negatives and low byte for clarity
array[i] = ExtractU32() & 0x800000FF;
PrintHex(array[i]);
PrintByte(0x20);
}
// Sort the array in ascending order
bubbleSort(array, count, 0 /*ascending*/);
// Display array contents
PrintString("\n\n Ascending sort:\n");
for (i = 0; i < count; i++) {
PrintHex(array[i]);
PrintByte(0x20);
}
PrintString("\n\n");
// Initialize the entire array to new pseudo-random numbers
PrintString("Array before sort:\n\n");
for (i = 0; i < count; i++)
{
// Allow negatives and low byte for clarity
array[i] = ExtractU32() & 0x800000FF;
PrintHex(array[i]);
PrintByte(0x20);
}
// Sort the array in descending order
bubbleSort(array, count, 1 /*descending*/);
// Display the array contents
PrintString("\n\n Descending sort:\n");
for (i = 0; i < count; i++) {
PrintHex(array[i]);
PrintByte(0x20);
}
PrintString("\n");
PrintString("\n STOP");
while (1) {
// loop forever
asm("nop"); // an example of inline assembler
}
}
/*******************************************************************************
Function Name : delay
Description : Add a delay for timing perposes.
Parameters : Time - In ms. 1 = .001 second
Return value : None */
void delay(uint32_t time) {
timer = time;
while(timer) {}
}
/*******************************************************************************
Function Name : SystemInit
Description : Called by IAR's assembly startup file.
Parameters :
Return value : */
void SystemInit(void) {
// System init is called from the assembly .s file
// We will configure the clocks in hw_init
asm("nop");
} |
C | #include <stdio.h>
int v[50];
int fibo(int n){
if (n==0)
return 0;
else if (n==1)
return 1;
else
return fibo(n-1)+fibo(n-2);
}
int fibo_memoria(int n) {
if (v[n]!=0)
return v[n];
if (n==0)
return 0;
if (n==1)
return 1;
v[n] = fibo_memoria(n-1)+fibo_memoria(n-2);
return v[n];
}
int main(void){
printf("Fibonacci %lld\n", fibo_memoria(45));
printf("Fibonnaci %lld", fibo(45));
return 0;
}
|
C | #include<stdio.h>
#include<stdlib.h>
struct node
{
int info;
struct node *next;
};
typedef struct node *np;
np getnode()
{
np p;
p=(np)malloc(sizeof(struct node));
return p;
}
void ins(np p,int x)
{
np q;
q=getnode();
q->info=x;
q->next=p->next;
p->next=q;
}
void del(np p)
{
np q;
if(p->next==NULL)
{
printf("no nodes \n");
}
else
{
q=p->next;
printf("the delete node's info is %d\n",q->info);
p->next=q->next;
free(q);
}
}
np fin(int x,np list)
{
np q=list;
do
{
if(q->info==x)
return q;
q=q->next;
}while(q!=NULL);
return NULL;
}
void dis(np list)
{
np p=list;
do
{
p=p->next;
printf("\n->%d\n",p->info);
}while(p->next!=NULL);
}
int main()
{
np p=NULL,list=NULL;
list=getnode();
list->info=0;
list->next=NULL;
int c=0,x;
while(c!=6)
{
printf("\n1.insert f\t2.delf\t3.ins after\t4.del after\t5.display\t6.exit\n");
scanf("%d",&c);
switch(c)
{
case 1:printf("enter ele to insert\n");
scanf("%d",&x);
ins(list,x);
break;
case 2:del(list);
break;
case 3:printf("enter ele to ins after\n");
scanf("%d",&x);
p=fin(x,list);
if(p==NULL)
printf("No node found\n");
else
{
printf("enter data of new node\n");
scanf("%d",&x);
ins(p,x);
}
break;
case 4:printf("enter ele to ins after\n");
scanf("%d",&x);
p=fin(x,list);
if(p==NULL)
printf("No node found\n");
else
del(p);
break;
case 5:dis(list);
break;
case 6:printf("Tired huh.....???\n");
break;
default:printf("Wrong input\n");
}
}
return 0;
}
|
C | /***
Copyright (c) 2008 ӢʱƼ˾Ȩ
ֻ EOS ԴЭ飨μ License.txtеʹЩ롣
ܣʹЩ롣
ļ: __main.c
: ȫֱ캯ĵߡ
*******************************************************************************/
typedef void (*func_ptr) (void);
extern func_ptr __CTOR_LIST__[];
void __main(void)
{
unsigned long i;
i = (unsigned long) __CTOR_LIST__[0];
//
// 0Ԫûָijͳijȡ
//
if (i == -1) {
for (i = 0; __CTOR_LIST__[i + 1]; i++);
}
//
// ȫֶĹ캯
//
while (i > 0) {
__CTOR_LIST__[i--] ();
}
}
|
C | #include <stdio.h>
int main()
{
int n,f,d,i,sum=0;
printf("enter the first term\n");
scanf("%d",&f);
printf("enter the difference\n");
scanf("%d",&d);
printf("enter the no of terms\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
sum=sum+(f+i*d);
}
printf("%d",sum);
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Big_num{
char value[3000];
int length;
};
struct Big_num answer[1001];
void Multiplication( struct Big_num *target , int num )
{
struct Big_num *temp;
temp = (struct Big_num*)calloc( 1 , sizeof(struct Big_num) );
int i , j , k ;
k = 0;
temp->length = target->length;
do{
for ( i = 0 ; i < target->length ; i++ ){
temp->value[i+k] += target->value[i]*(num%10);
j = i+k;
while ( temp->value[j] > 9 ){
temp->value[j+1] += temp->value[j]/10;
temp->value[j] = temp->value[j]%10;
j++;
if( j+1 > temp->length )
temp->length++;
}
}
/*if( k + target->length > temp->length )*/
temp->length++;
k++;
num = num/10;
}while (num != 0);
target->length = temp->length;
for ( i = temp->length-1 ; i >= 0 ; i-- ){
target->value[i] = temp->value[i];
}
free(temp);
}
int main()
{
FILE *in ;
int num;
int i ;
int check;
in = stdin;/*fopen("623.in","r");*/
answer[0].value[0] = 1;
answer[0].length = 1;
for ( i = 0 ; i < 1000 ; i++ ){
Multiplication( &answer[i] , i+1 );
memcpy( &(answer[i+1]) , &(answer[i]) , sizeof(struct Big_num) );
}
while ( fscanf(in , "%d" , &num) != EOF ){
printf("%d!\n",num);
if ( num == 0 ){
printf("1\n");
continue;
}
check = 0;
for ( i = answer[num-1].length-1 ; i >= 0 ; i-- ){
if ( answer[num-1].value[i] != 0 && check == 0 )
check = 1;
if ( check == 0 )
continue;
printf("%d",answer[num-1].value[i]);
}
printf("\n");
}
return 0;
}
|
C | #include<stdio.h>
#include<stdlib.h>
void qwer(int *q[]);
int main(void)
{
int i;
int a[3] = { 3,5,7 };
for (i = 0; i <= 2; i++)
{
printf("%d ",a[i]);
}
printf("\n");
qwer(&a);
for (i = 0; i <= 2; i++)
{
printf("%d ", a[i]);
}
printf("\n");
system("pause");
return 0;
}
void qwer(int *q[])
{
int k,j,abc;
for (k=0;k<=2;k++)
{
for (j=0;j<=2;j++)
{
if (q[j]>q[j-1])
{
abc = q[j];
q[j] = q[j - 1];
q[j - 1] = abc;
}
}
}
}
|
C | //Print all the nodes reachable from a given starting node in a digraph using BFS method.
#include<stdio.h>
#include<stdlib.h>
int a[20][20], n, vis[20];
int q[20],front=-1,rear=-1;
int s[20],top=-1;
void bfs(int v)
{
int i,curr;
vis[v] = 1;
q[++rear] = v;
while(front!=rear){
curr = q[++front];
for(i=1;i<=n;i++){
if((a[curr][i]==1)&&(vis[i]==0)){
q[++rear] = i;
vis[i] = 1;
printf("%d ", i);
}
}
}
}
int main()
{
int ch, start, i,j;
printf("\nEnter no. of vertices: ");
scanf("%d",&n);
printf("\nEnter adjacency matrix:\n");
for(i=1; i<=n; i++){
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
}
for(i=1;i<=n;i++)
vis[i]=0;
printf("\nEnter starting vertex: ");
scanf("%d",&start);
printf("\n1.Print all nodes reachable from a given starting node");\
printf("\n2.Exit");
printf("\nEnter choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nNodes reachable from starting vertex %d are: ", start);
bfs(start);
for(i=1;i<=n;i++)
{
if(vis[i]==0)
printf("\n Vertex that is not reachable is %d" ,i);
}
break;
case 2: exit(0);
default: printf("\nInvalid Choice");
}
}
|
C | #include<stdio.h>
#include<stdlib.h>
#include<math.h>
typedef struct _Monomio{
float
coef;
int
exp;
struct _Monomio
*prox;
} Monomio;
typedef Monomio * Polinomio;
Polinomio AlocaMonomio(){
Polinomio
p;
p = (Polinomio)malloc(sizeof(Monomio));
if(p == NULL){
printf("Falta de memoria!\n");
exit(1);
}
return p;
}
Polinomio PolinomioNulo(){/*Nó cabeça*/
Polinomio
p;
p = AlocaMonomio();
p->exp = -1;
p->coef = 0.0;
p->prox = p;
return p;
}
void InsereMonomio(Polinomio p, int exp, float coef){
Polinomio
ant,
dep,
q;
if(coef == 0)
return;
q = AlocaMonomio();
q->coef = coef;
q->exp = exp;
ant = p;
dep = p->prox;
while(dep->exp > exp){
ant = dep;
dep = dep->prox;
}
q->prox = dep;
ant->prox = q;
}
void RemoveAposMonomio(Polinomio p){
Polinomio
q;
q = p->prox;
p->prox = q->prox;
free(q);
}
void LiberaPolinomio(Polinomio p){
while(p != p->prox)
RemoveAposMonomio(p);
free(p);
}
float Valor(Polinomio p, float x){
Polinomio
q;
float
soma = 0;
if(p == p->prox){
return 0;
}
q = p->prox;
do{
soma += q->coef * pow(x, q->exp);
q = q->prox;
}
while(q != p);
return soma;
}
Polinomio Derivada(Polinomio p){
Polinomio
d,
q;
d = PolinomioNulo();
q = p->prox;
do{
InsereMonomio(d, q->exp - 1, q->exp * q->coef);
q = q->prox;
}
while(q != p);
return d;
}
Polinomio DerivadaSegunda(Polinomio p){
Polinomio
d,
ds;
d = Derivada(p);
ds = Derivada(d);
LiberaPolinomio(d);
return ds;
}
Polinomio CriaPolinomio(char expr[]){
Polinomio
p;
int
exp,
r,
n,
nn;
float
coef,
sinal = 1.0;
char
c;
nn = 0;
p = PolinomioNulo();
while(1){
r = sscanf(expr+nn," %f * x ^ %d %n",&coef, &exp, &n);
if(r == 0 || r == EOF)
break;
nn += n;
InsereMonomio(p, exp, sinal * coef);
r = sscanf(expr+nn,"%c %n", &c, &n);
if(r == EOF || r == 0)
break;
nn += n;
if(c == '-')
sinal = -1.0;
else
sinal = 1.0;
}
return p;
}
void ImprimePolinomio(Polinomio p){
Polinomio
t;
t = p->prox;
while(t != p){
printf("%.2f*x^%d",t->coef,t->exp);
t = t->prox;
if(t != p){
if(t->coef >= 0.0)
printf(" + ");
else
printf(" ");
}
}
printf("\n");
}
int main(){
Polinomio
p,
q,
r;
p = CriaPolinomio("5.0*x^3 -4.0*x^1 + 2.0*x^0");
ImprimePolinomio(p);
q = CriaPolinomio(" 8.0*x^4 + 2.0*x^3 + 4.0*x^1");
ImprimePolinomio(q);
r = DerivadaSegunda(q);
ImprimePolinomio(r);
printf("Valor: %f", Valor(p, 1.7));
LiberaPolinomio(p);
LiberaPolinomio(q);
LiberaPolinomio(r);
return 0;
}
|
C | //
// hw0202.c
// hw0202
//
// Created by Michael Leong on 2021/3/18.
//
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "longtobinary.h"
int main() {
char floatingPointStr[65];
char *pEnd = NULL;
doubleFP floatingPointNum;
char exponentStr[11] = {0};
char mantissaStr[53] = {0};
printf("Please enter a floating-point number (double precision): ");
fgets(floatingPointStr, 65, stdin);
floatingPointNum.doubleNum = strtod(floatingPointStr, &pEnd);
if(pEnd != NULL) {
printf("%lf\n", floatingPointNum.doubleNum);
} else {
printf("Conversion failed\n");
return 1;
}
longToBin(floatingPointNum.ieeeDouble.exponent, exponentStr, 11);
longToBin(floatingPointNum.ieeeDouble.mantissa, mantissaStr, 52);
printf("sign: %d\n", floatingPointNum.ieeeDouble.sign);
printf("exponent: %s\n", exponentStr);
printf("mantissa: %s\n", mantissaStr);
printDoubleConvert(floatingPointNum);
return 0;
}
|
C | /**
* @file
*
* Digital I/O driver
*
* $Id: dio.c 11351 2013-11-19 17:41:32Z pr4 $
*/
/**
* @ingroup dio
* @{
* @file
* @}
*/
#include "hardware.h"
#include "basic_types.h"
#include "dio.h"
/** PUPAE bit mask in PUCR register */
#define PUCR_PUPAE 0x01u
/** PUPBE bit mask in PUCR register */
#define PUCR_PUPBE 0x02u
/** PUPEE bit mask in PUCR register */
#define PUCR_PUPEE 0x10u
/** PUPKE bit mask in PUCR register */
#define PUCR_PUPKE 0x80u
/*
* documented in header
*/
CONST struct dio_hw_mapping_s dio_mapping[] = {
/* output_portp input_portp ddrp pull en / dis pull polarity per pin / per port pull per port bit mask */
{ &PORTA, &PORTA, &DDRA, &PUCR, NULL, Dio_pull_per_port, PUCR_PUPAE},
{ &PORTB, &PORTB, &DDRB, &PUCR, NULL, Dio_pull_per_port, PUCR_PUPBE},
{ &PORTE, &PORTE, &DDRE, &PUCR, NULL, Dio_pull_per_port, PUCR_PUPEE},
{ &PTH, &PTIH, &DDRH, &PERH, &PPSH, Dio_pull_per_pin, 0x00u},
{ &PTJ, &PTIJ, &DDRJ, &PERJ, &PPSJ, Dio_pull_per_pin, 0x00u},
{ &PORTK, &PORTK, &DDRK, &PUCR, NULL, Dio_pull_per_port, PUCR_PUPKE},
{ &PTM, &PTM, &DDRM, &PERM, &PPSM, Dio_pull_per_pin, 0x00u},
{ &PTP, &PTIP, &DDRP, &PERP, &PPSP, Dio_pull_per_pin, 0x00u},
{ &PTT, &PTIT, &DDRT, &PERT, &PPST, Dio_pull_per_pin, 0x00u},
{ &PTS, &PTIS, &DDRS, &PERS, &PPSS, Dio_pull_per_pin, 0x00u},
};
/**
* @par Implementation
*
* Sets DDR register bits for digital outputs and clears them for inputs.
*
* Uses #dio_mapping[] to get the data direction register for the port.
*
* Drives all outputs to their inactive state to avoid glitching an active state
* if they are active-low.
*
* Throw an internal error if the interface is Dio_interface_function and an
* output variable is NULL.
*
* Reads back the values on the pins and sets the dmd variables.
*
* @note If the ADC digital ports are used, this function will have to set the
* DIEN digital enable register for both inputs and outputs. This is probably
* best done with explicit code <tt>if (cfgp->port == PT0AD0)...</tt> rather
* than by augmenting the dio_mapping array
*/
void dio_init(void)
{
CONST struct dio_in_cfg_s *cfg_in_p; /* pointer to ip channel config */
CONST struct dio_out_cfg_s *cfg_out_p; /* pointer to op channel config */
CONST struct dio_hw_mapping_s *hw_mapping; /* pointer to h/w info */
CONST struct dio_pull_cfg_s *cfg_pull_p; /* pointer to pull resistor config */
bool_t pinlevel; /* state of pin: high -> TRUE, low -> FALSE */
uint8_t ccr; /* CCR byte for interrupt save/restore */
uint8_t i;
/* ECLK and ECLKX2 overlaps with PORTE, this port is owned by DIO so
* disable the ECLK device (ECLKX2 should be disabled out of reset) */
DIO_DISABLE_ECLK();
for (i = 0u ; i < dio_n_outputs; i++)
{
cfg_out_p = &dio_output_cfg[i];
if ((cfg_out_p->interface == Dio_interface_function) &&
(cfg_out_p->var == NULL))
{
/** @polyspace<MISRA-C:14.2:Not a defect:Justify with annotations> For test purposes only.*/
INTERNAL_ERROR();
}
hw_mapping = &dio_mapping[cfg_out_p->port];
/*
* calculate the desired pin state depending
* on whether the output is active high or low
*/
pinlevel = (cfg_out_p->active_high_low == Dio_active_high)? FALSE : TRUE;
if (pinlevel == TRUE)
{
SAVE_INTERRUPTS(ccr);
*hw_mapping->output_portp |= (uint8_t) (1u << cfg_out_p->bitnum);
RESTORE_INTERRUPTS(ccr);
}
else
{
SAVE_INTERRUPTS(ccr);
*hw_mapping->output_portp &=
(uint8_t) ~(uint8_t) (1u << cfg_out_p->bitnum);
RESTORE_INTERRUPTS(ccr);
}
/* set the data direction register to 'output' */
*hw_mapping->ddrp |= (uint8_t) (1u << cfg_out_p->bitnum);
/* Set most recently requested level */
if (cfg_out_p->dmd != NULL)
{
*cfg_out_p->dmd = pinlevel;
}
/* Read back the value on the pin */
/** @polyspace:begin<MISRA-C:13.2:Low:Investigate> Could code be changed to fix this? */
if (cfg_out_p->read_back != NULL)
{
*cfg_out_p->read_back = (*hw_mapping->input_portp
& (uint8_t) (1u << cfg_out_p->bitnum)) ?
(cfg_out_p->active_high_low == Dio_active_high) :
(cfg_out_p->active_high_low == Dio_active_low);
}
/** @polyspace:end<MISRA-C:13.2:Low:Investigate> Could code be changed to fix this? */
}
for (i = 0u ; i < dio_n_inputs; i++)
{
cfg_in_p = &dio_input_cfg[i];
hw_mapping = &dio_mapping[cfg_in_p->port];
if ((cfg_in_p->interface == Dio_interface_function) &&
(cfg_in_p->var == NULL))
{
/** @polyspace<MISRA-C:14.2:Not a defect:Justify with annotations> For test purposes only.*/
INTERNAL_ERROR();
}
/* set the data direction register to 'input' */
*hw_mapping->ddrp &= (uint8_t) ~ (uint8_t) (1u << cfg_in_p->bitnum);
}
for (i = 0u ; i < dio_n_pull_cfgs; i++)
{
cfg_pull_p = &dio_pull_cfg[i];
hw_mapping = &dio_mapping[cfg_pull_p->port];
if((hw_mapping->pull_per == Dio_pull_per_port) && (cfg_pull_p->bitmask != 0xffu))
{
/* pull resistor bit mask of ports, which may be configured per port basis only
* must be equal to 0xffu. */
/** @polyspace<MISRA-C:14.2:Not a defect:Justify with annotations> For test purposes only.*/
INTERNAL_ERROR();
}
if((hw_mapping->pull_polarity == NULL) && (cfg_pull_p->pull_cfg == Dio_pull_down))
{
/* ports with polarity register not specified may be enabled with pull up device only */
/** @polyspace<MISRA-C:14.2:Not a defect:Justify with annotations> For test purposes only.*/
INTERNAL_ERROR();
}
if(cfg_pull_p->pull_cfg == Dio_pull_default)
{
/* do nothing */
}
else if(cfg_pull_p->pull_cfg == Dio_pull_none)
{
/* disable pull resistors */
if(hw_mapping->pull_per == Dio_pull_per_pin)
{
*hw_mapping->pull_cfg &= (uint8_t) ~ (uint8_t) cfg_pull_p->bitmask;
}
else
{
*hw_mapping->pull_cfg &= (uint8_t) ~ (uint8_t) hw_mapping->pull_per_port_mask;
}
}
else
{
/* enable pull resistors */
if(hw_mapping->pull_per == Dio_pull_per_pin)
{
*hw_mapping->pull_cfg |= cfg_pull_p->bitmask;
}
else
{
*hw_mapping->pull_cfg |= hw_mapping->pull_per_port_mask;
}
/* configure polarity if polarity register is defined */
if(hw_mapping->pull_polarity)
{
if(cfg_pull_p->pull_cfg == Dio_pull_down)
{
*hw_mapping->pull_polarity |= cfg_pull_p->bitmask;
}
else
{
*hw_mapping->pull_polarity &= (uint8_t) ~ (uint8_t) cfg_pull_p->bitmask;
}
}
}
}
}
void dio_read_inputs(void)
{
uint8_t i;
bool_t pinlevel; /* state of pin: high -> TRUE, low -> FALSE */
CONST struct dio_in_cfg_s *cfgp; /* pointer to channel configuration */
CONST struct dio_hw_mapping_s *hw_mapping; /* pointer to h/w info */
for (i = 0u ; i < dio_n_inputs ; i++)
{
if (dio_input_cfg[i].interface == Dio_interface_function)
{
/* handled by this function so read pin */
cfgp = &dio_input_cfg[i]; /* config for this input line */
hw_mapping = &dio_mapping[cfgp->port]; /* h/w registers for this
port */
/* read the state of the pin */
pinlevel = ((*hw_mapping->input_portp
& (uint8_t) (1u << cfgp->bitnum)) != FALSE) ? TRUE : FALSE;
/*
* write the application boolean variable pointed to by cfgp->var,
* inverting the pin level if channel is active low
*/
if (cfgp->active_high_low == Dio_active_high)
{
*cfgp->var = pinlevel;
}
else
{
*cfgp->var = (pinlevel == TRUE)? FALSE:TRUE;
}
}
else
{
/* this one handled elsewhere, so do nothing */
}
}
}
/**
* @par Implementation
*
* Interrupts are disabled around the read-modify-write for each output port.
* This will prevent corruption of writes by higher-priority tasks on the S12
* but will not prevent possible corruption if the XGATE writes to the same
* port.
*/
void dio_write_outputs(void)
{
uint8_t i;
uint8_t ccr; /* CCR byte for interrupt save/restore */
bool_t pinlevel;
CONST struct dio_out_cfg_s *cfgp; /* pointer to channel configuration */
CONST struct dio_hw_mapping_s *hw_mapping; /* pointer to h/w info */
for (i = 0u ; i < dio_n_outputs ; i++)
{
if (dio_output_cfg[i].interface == Dio_interface_function)
{
/* handled here so write pin */
cfgp = &dio_output_cfg[i]; /* config for this output line */
hw_mapping = &dio_mapping[cfgp->port]; /* h/w registers for this
port */
/*
* Check to see if the overrride calibration is enabled.
* If so set the output to the override value (cfgp->override_val),
* set to user application desired value (cfgp->var) otherwise.
*/
if ((cfgp->override_en != FNULL) &&
(cfgp->override_val != FNULL) &&
(*cfgp->override_en == TRUE))
{
pinlevel = *cfgp->override_val;
}
else
{
pinlevel = *cfgp->var;
}
/*
* Take active level configuration into account
*/
if (cfgp->active_high_low == Dio_active_low)
{
/* invert the level */
if(pinlevel == TRUE)
{
pinlevel = FALSE;
}
else
{
pinlevel = TRUE;
}
}
else
{
/* no need to invert */
}
if (pinlevel == TRUE)
{
SAVE_INTERRUPTS(ccr);
*hw_mapping->output_portp |= (uint8_t) (1u << cfgp->bitnum);
RESTORE_INTERRUPTS(ccr);
}
else
{
SAVE_INTERRUPTS(ccr);
*hw_mapping->output_portp &=
(uint8_t) ~(uint8_t) (1u << cfgp->bitnum);
RESTORE_INTERRUPTS(ccr);
}
/* Set most recently requested level */
if (cfgp->dmd != NULL)
{
*cfgp->dmd = pinlevel;
}
/* Read back the value on the pin */
/** @polyspace:begin<MISRA-C:13.2:Low:Investigate> Could code be changed to fix this? */
if (cfgp->read_back != NULL)
{
*cfgp->read_back = (*hw_mapping->input_portp
& (uint8_t) (1u << cfgp->bitnum)) ?
(cfgp->active_high_low == Dio_active_high) :
(cfgp->active_high_low == Dio_active_low);
}
/** @polyspace:end<MISRA-C:13.2:Low:Investigate> Could code be changed to fix this? */
}
else
{
/* this one handled elsewhere, so do nothing */
}
}
}
|
C | #include "stm32f10x.h"
#include "string.h"
#include "stdio.h"
char carry[50];
/* ݴʽ */
void data_encode(char *data){
unsigned char length = strlen(data);
unsigned char sum = 0x00;
unsigned char i;
carry[0] = 0x3C; //ʼλ
carry[1] = 0x02; //λ
carry[2] = length; //͵λ
/* ͵ */
for (i = 0; i < length; ++i)
carry[i + 3] = data[i];
for (i = 0; i < length + 3; ++i)
sum += carry[i];
carry[length + 3] = sum; //У
carry[length + 4] = 0x0D; //β
for (i = 0; i <= length + 4; ++i)
printf("%c", carry[i]);
}
|
C | /*
** Name: Yeti3D PRO
** Desc: Portable GameBoy Advanced 3D Engine
** Auth: Derek J. Evans <[email protected]>
**
** Copyright (C) 2003-2004 Derek J. Evans. All Rights Reserved.
**
** YY YY EEEEEE TTTTTT IIIIII 33333 DDDDD
** YY YY EE TT II 33 DD DD
** YYYY EEEE TT II 333 DD DD
** YY EE TT II 33 DD DD
** YY EEEEEE TT IIIIII 33333 DDDDD
*/
#include "y3d_entity.h"
#include "y3d_fixed.h"
#include "y3d_draw.h"
/******************************************************************************/
/*
** Name: entity_visual_init
** Desc:
*/
void entity_visual_init(entity_visual_t *entity_visual)
{
CLEARMEM(entity_visual);
entity_visual->mode = DRAW_MODE_COPY;
}
/******************************************************************************/
/*
** Name: entity_destroy
** Desc:
*/
void entity_destroy(entity_t *e)
{
CLEARMEM(e);
}
/*
** Name: entity_init
** Desc:
*/
void entity_init(entity_t *e, int x, int y, int z)
{
entity_destroy(e);
e->x = x;
e->y = y;
e->z = z;
entity_visual_init(&e->visual);
}
/*
** Name: entity_reinit
** Desc: Initilize a entity without moving its position. Used for when
** you want to change an entity to another type.
*/
void entity_reinit(entity_t *e)
{
entity_init(e, e->x, e->y, e->z);
}
/*
** Name: entity_freeze
** Desc: Zeros all entity velocities. Used for pain & death AI.
*/
void entity_freeze(entity_t *e)
{
e->xx = e->yy = e->zz = e->tt = e->rr = e->pp = 0;
}
/******************************************************************************/
void entity_friction(entity_t *e, int amount)
{
e->xx = ansic_friction(e->xx, amount);
e->yy = ansic_friction(e->yy, amount);
}
void entity_move_forward(entity_t *e)
{
e->xx += fixsin(e->t) >> 4;
e->yy += fixcos(e->t) >> 4;
}
void entity_move_backwards(entity_t *e)
{
e->xx -= fixsin(e->t) >> 4;
e->yy -= fixcos(e->t) >> 4;
}
void entity_turn_right(entity_t *e)
{
e->tt += i2f(3);
}
void entity_turn_left(entity_t *e)
{
e->tt -= i2f(3);
}
void entity_turn_towards(entity_t *e, int x, int y)
{
int x1 = x - (e->x + fixsin(e->t + i2f(14)));
int y1 = y - (e->y + fixcos(e->t + i2f(14)));
int x2 = x - (e->x + fixsin(e->t - i2f(14)));
int y2 = y - (e->y + fixcos(e->t - i2f(14)));
if ((x1 * x1 + y1 * y1) < (x2 * x2 + y2 * y2)) {
entity_turn_right(e);
} else {
entity_turn_left(e);
}
}
/*
** Name: entity_look_at
** Desc: I think this is the old version. Doesn't use a sqrt, but doesn't calc
** the pitch correctly.
*/
void entity_look_at(entity_t *e, int x, int y, int z)
{
x = x - e->x;
y = y - e->y;
z = e->z - z;
e->t = fixangle(x, y);
e->p = fixangle(ABS(z), ABS(y));
if (e->p > i2f(32)) {
e->p = i2f(32);
}
}
/*
** Name: entity_look_at2
** Desc: Setup a entities turn and pitch so it points towards a given
** point.
*/
void entity_look_at2(entity_t *e, int x, int y, int z)
{
x -= e->x;
y -= e->y;
z -= e->z;
e->t = fixangle(x, y);
e->p = fixangle(-z, isqrt(x * x + y * y));
}
/*
** Name: entity_set_velocity
** Desc: Setup a entities velocity based on its turn & pitch.
*/
void entity_set_velocity(entity_t *e)
{
e->xx = fixsin(e->t);
e->yy = fixcos(e->t);
e->zz = fixsin(e->p);
}
void entity_force_towards(entity_t *e, int x, int y, int z, int shift)
{
e->xx = (x - e->x) >> shift;
e->yy = (y - e->y) >> shift;
e->zz = (z - e->z) >> shift;
}
/******************************************************************************/
|
C | #include <stdlib.h>
#include "map.h"
int main(void)
{
size_t n1 = 42;
size_t n2 = 43;
struct map *map = map_init(10);
map_add(map, "toto", &n1, NULL);
map_add(map, "tata", &n2, NULL);
map_remove(map, "tyty", NULL);
if (map->size != 2)
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
|
C | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define COUNT 4
enum sorting {first, second};
struct name {
const char * first_name;
const char * last_name;
};
typedef struct name name;
int sort_first (const void * a, const void * b) {
name * n1 = (name *) a;
name * n2 = (name *) b;
return strcmp(n1->first_name, n2->first_name);
}
int sort_last (const void * a, const void * b) {
name * n1 = (name *) a;
name * n2 = (name *) b;
return strcmp(n1->last_name, n2->last_name);
}
void print_names (name * name_list, enum sorting type){
for (int i = 0; i<COUNT; i++){
if (type ==first) {
printf("%s, %s \n",name_list[i].first_name, name_list[i].last_name);
}
else {
printf("%s, %s \n",name_list[i].last_name, name_list[i].first_name);
}
}
printf("\n");
}
int main() {
name names[COUNT] = {
{"Grace", "Hopper"},
{"Dennis", "Ritchie"},
{"Ken", "Thompson"},
{"Bjarne", "Stroustrup"},
};
// sort array using qsort by first name
qsort(names,COUNT,sizeof(name),sort_first);
// print array
print_names (names, first);
// sort array using qsort
qsort(names,COUNT,sizeof(name),sort_last);
print_names (names, second);
}
|
C | #include <stdio.h> //라이브러리 임포트
int multi(int x, int y); //함수 명세 표시= 스프링의 인터페이스와 같은 역할
void main() {
int a, b, c; // 정수형 변수 a,b,c 선언
printf("곱하기 할 첫번째 수를 입력하세요 : ");
scanf("%d", &a);
printf("곱하기 할 두번째 수를 입력하세요 : ");
scanf("%d", &b);
c=multi(a,b); //함수호출
printf("실행결과 : %d X %d = %d\n", a, b, c);
}
int multi(int x, int y){
return (x*y);
} |
C | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
//#define D_DEBUG
//#define D_TEST
#ifdef D_DEBUG
#define D_OK (0)
#define D_NG (1)
#define D_LOG(...) fprintf( stderr, "%s(%d):", __func__, __LINE__ ); printf( __VA_ARGS__ ); printf( "\n" );
#else
#define D_LOG(...)
#endif
#define D_OUT_MAX_LENGTH (100000 * 3)
#define D_CHAR_KIND_NUM (26)
typedef struct {
int n;
int m;
char s[100000];
char t[100000];
} in_t;
static void count( const char* str, int len, int *list )
{
int i;
const char *p = str;
D_LOG( "len:%d, str:%s", len, str );
for( i = 0; i < len; i++ ) {
list[ *p - 'a' ]++;
p++;
}
}
static void exec( in_t* in, char* out )
{
int result = 0, i;
int ls[D_CHAR_KIND_NUM];
int lt[D_CHAR_KIND_NUM];
memset( ls, 0, sizeof( ls ) );
memset( lt, 0, sizeof( lt ) );
count( in->s, in->n, ls );
count( in->t, in->m, lt );
for( i = 0; i < D_CHAR_KIND_NUM; i++ ){
if( ls[i] < lt[i] ) {
result += lt[i] - ls[i];
}
}
sprintf( out, "%d\n", result );
}
static void print_in( in_t *in )
{
D_LOG( "[in] n:%d, m:%d", in->n, in->m );
D_LOG( "[in] s:%s", in->s );
D_LOG( "[in] t:%s", in->t );
}
#ifndef D_TEST
static void get_param( in_t* in )
{
scanf( "%d %d", &in->n, &in->m );
fflush( stdin );
scanf( "%s", in->s );
fflush( stdin );
scanf( "%s", in->t );
fflush( stdin );
print_in( in );
}
#else
static void get_param_test( in_t* in, char* in_str )
{
char *p;
char *buf = (char*)malloc( strlen( in_str ) + 1 );
memcpy( buf, in_str, strlen( in_str ) );
p = strtok( buf, "\n" );
sscanf( p, "%d %d", &in->n, &in->m );
p = strtok( NULL, "\n" );
sscanf( p, "%s", in->s );
p = strtok( NULL, "\n" );
sscanf( p, "%s", in->t );
print_in( in );
free( buf );
}
static int test( char* in_str, const char* expect )
{
static int testn = 0;
in_t in;
char out[D_OUT_MAX_LENGTH];
testn++;
memset( out, 0, sizeof( out ) );
get_param_test( &in, in_str );
exec( &in, out );
if( strncmp( out, expect, strlen( out ) ) == 0 ){
D_LOG( "[%d:OK]", testn );
return D_OK;
} else {
D_LOG( "[%d:NG]", testn );
D_LOG( "--- in ---\n%s--- out ---\n%s--- expect---\n%s", in_str, out, expect );
return D_NG;
}
}
#endif
int main( int argc, char* argv[])
{
#ifdef D_TEST
test( "5 5\npizza\npaiza\n", "1\n" );
test( "3 5\nant\nmaven\n", "3\n" );
test( "1 27\na\nabcdefghijklmnopqrstuvwxyza\n", "26\n" );
test( "27 1\nabcdefghijklmnopqrstuvwxyza\na\n", "0\n" );
#else
in_t in;
char out[D_OUT_MAX_LENGTH];
get_param( &in );
exec( &in, out );
printf( "%s", out );
#endif
return 0;
}
|
C | #ifndef _STACK_H
#define _STACK_H
struct node;
typedef struct node *node_t;
typedef node_t stack;
int is_empty(stack s);
stack create_stack();
void make_empty(stack s);
void push(void* element, stack s);
void* pop(stack s);
void* peer(stack s);
struct node{
void* element;
node_t next;
};
#endif |
C | /**
* @file
*
* @brief System monitor task
*
* Monitors system health, e.g. tasks alive/messages. Resets watchdog if all seems OK.
*/
#ifndef TASK_MONITOR_H
#define TASK_MONITOR_H
#include "xep_dispatch.h"
#include <stdbool.h>
#define MAX_TASKS 10
typedef struct monitor_task_t_ {
int id;
void* task_handle;
uint32_t stack_size;
volatile int tick_counter;
int timeout_ms;
} monitor_task_t;
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Initialize Monitor task.
*
* @return Status of execution
*/
uint32_t task_monitor_init(XepDispatch_t* dispatch);
/**
* @brief Register a task to the monitor system.
*
* @param monitor_task_handle Monitor task handle with info about the task registered.
* @param timeout_ms Maximum time between calls to @ref monitor_task_alive
* @param stack_size Size of allocated stack for task
* @return Status of execution as defined in @ref xt_error_codes_t
*/
int monitor_task_register(monitor_task_t ** monitor_task_handle, const uint32_t timeout_ms, uint32_t stack_size);
/**
* @brief Get information of a task registered in the monitor system.
*
* @param monitor_task_handle Monitor task handle with info about the task registered.
* @param i Index of the task to get
* @return Status of execution as defined in @ref xt_error_codes_t
*/
uint32_t monitor_task_get_info(monitor_task_t* monitor_task, uint32_t i);
/**
* @brief Signal "alive" to the monitor task
*
* @param monitor_task_handle Initated monitor_task_handle - ref. @ref monitor_task_register
* @return Status of execution as defined in @ref xt_error_codes_t
*/
uint32_t monitor_task_alive(monitor_task_t * monitor_task_handle);
#ifdef __cplusplus
}
#endif
#endif // TASK_MONITOR_H
|
C | /*
** my_is_prime.c for my_is_prime in /home/thomas.couacault/CPool_Day05
**
** Made by Thomas Couacault
** Login <[email protected]>
**
** Started on Fri Oct 7 16:09:03 2016 Thomas Couacault
** Last update Wed Oct 12 10:13:48 2016 Thomas Couacault
*/
int my_is_prime(int nb)
{
int divider;
divider = 1;
if (nb >= 2)
{
while (divider <= nb)
{
if (nb % divider == 0)
{
if (divider > 1 && divider < nb)
return (0);
else if (divider == nb)
return (1);
}
else
return (1);
divider++;
}
}
else
return (0);
}
|
C | /**
* Easy Match
* Author: Michael Kohn
* Email: [email protected]
* Web: http://www.mikekohn.net/
* License: GPLv3
*
* Copyright 2016-2019 by Michael Kohn
*
*/
#include "generate.h"
int generate_code(struct _generate *generate, uint8_t len, ...)
{
va_list argp;
int i, data;
va_start(argp, len);
for (i = 0; i < len; i++)
{
data = va_arg(argp, int);
generate->code[generate->ptr++] = data;
}
va_end(argp);
return 0;
}
int generate_insert(struct _generate *generate, int offset, int len)
{
int i = generate->ptr;
while(i >= offset)
{
generate->code[i + len] = generate->code[i];
i--;
}
generate->ptr += len;
return 0;
}
|
C | void max_heapify(int *A, int i, int len)
left = 2*i;
right = 2*i+1;
if( (left <= len-1) && (A[i] < A[left]) ) largest = left;
else largest = i;
if( (right <= len-1) && (A[largest] < A[right]) ) largest = right;
if(largest != i)
tmp = A[largest];
A[largest] = A[i];
A[i] = tmp;
max_heapify(A, largest, len);
void build_max_heap(int *A, int len)
for(i = (len-1)/2; i> 0; i--)
max_heapify(A, i, len);
void heap_sort(int *A, int len)
build_max_heap(A, len);
for(i = len-1; i >= 2; i--)
swap(A[i], A[1]);
len--;
max_heapify(A, 1, len);
|
C | #include <pthread.h>
#include <stdlib.h>
#include "queue.h"
queue_t* qinit(int max_size)
{
queue_t* q = (queue_t*)malloc(sizeof(queue_t));
q->max_size = max_size;
q->head = 0;
q->tail = 0;
q->empty = 1;
q->not_empty = (pthread_cond_t*)malloc(sizeof(pthread_cond_t));
pthread_cond_init(q->not_empty, NULL);
q->mutex = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t));
pthread_mutex_init(q->mutex, NULL);
return q;
}
void enqueue(queue_t* q, slave_t* s)
{
q->slaves[q->tail++] = s;
if(q->tail == q->max_size)
q->tail = 0;
q->empty = 0;
}
slave_t* dequeue(queue_t* q)
{
slave_t* s = q->slaves[q->head++];
if(q->head == q->max_size)
q->head = 0;
if(q->head == q->tail)
q->empty = 1;
return s;
}
void qfree(queue_t* q)
{
pthread_cond_destroy(q->not_empty);
pthread_mutex_destroy(q->mutex);
free(q->not_empty);
free(q->mutex);
free(q);
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* map.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: besellem <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/29 00:56:58 by besellem #+# #+# */
/* Updated: 2021/07/04 00:43:06 by besellem ### ########.fr */
/* */
/* ************************************************************************** */
#include "so_long.h"
struct s_lookup_texture
{
int texture_char;
int texture_id;
};
static t_img __get_texture__(t_so_long *sl, char c)
{
const struct s_lookup_texture g_lookup_txtrs[] = {
{'1', TXTR_WALL},
{'0', TXTR_EMPTY},
{'C', TXTR_COLLECTIBLE},
{'E', TXTR_EXIT},
{'P', TXTR_PLAYER},
{0, 0}
};
int i;
i = 0;
while (g_lookup_txtrs[i].texture_char)
{
if (g_lookup_txtrs[i].texture_char == c)
return (sl->txtrs[g_lookup_txtrs[i].texture_id]);
++i;
}
return (sl->txtrs[g_lookup_txtrs[0].texture_id]);
}
static void __put_texture__(t_so_long *sl, int x, int y, t_img txtr)
{
const double ratio_x = ((double)sl->win_w / sl->map_size_x);
const double ratio_y = ((double)sl->win_h / sl->map_size_y);
double tx_x;
double tx_y;
char *ptr;
tx_y = 0.0;
while (tx_y < ratio_y)
{
tx_x = 0.0;
while (tx_x < ratio_x)
{
ptr = txtr.addr;
ptr += (size_t)((tx_y / ratio_y) * txtr.y) * txtr.size_line;
ptr += (size_t)((tx_x / ratio_x) * txtr.x) * (txtr.bpp / 8);
ft_pixel_put(
sl,
(x * ratio_x) + tx_x,
(y * ratio_y) + tx_y,
*(uint32_t *)ptr
);
tx_x += ft_fmax(ratio_x, txtr.x) / ft_fmax(txtr.x, ratio_x);
}
tx_y += ft_fmax(ratio_y, txtr.y) / ft_fmax(txtr.y, ratio_y);
}
}
static void put_map(t_so_long *sl)
{
const char **map = (const char **)sl->map;
int x;
int y;
y = 0;
while (map[y])
{
x = 0;
while (map[y][x])
{
__put_texture__(sl, x, y, __get_texture__(sl, map[y][x]));
++x;
}
++y;
}
}
static void print_player(t_so_long *sl)
{
__put_texture__(sl, sl->pos_x, sl->pos_y, __get_texture__(sl, 'P'));
}
void display_minimap(t_so_long *sl)
{
put_map(sl);
print_player(sl);
}
|
C | #include "key.h"
#include "config.h"
volatile uint8 idata KeyCurrent,KeyOld,KeyNoChangedTime;
volatile uint8 idata KeyPress;
volatile uint8 idata KeyDown,KeyUp,KeyLast;
volatile uint8 KeyCanChange;
/********************************************************************
ܣʱ0ʼɨ衣
ڲޡ
أޡ
עޡ
********************************************************************/
void InitTimer0(void)
{
TMOD&=0xF0;
TMOD|=0x01;
ET0=1;
TR0=1;
}
/*******************************************************************/
/********************************************************************
ܣ̳ʼ
ڲޡ
أޡ
עޡ
********************************************************************/
void InitKeyboard(void)
{
KeyIO=0xFF; //̶ӦĿΪ״̬
KeyPress=0; //ް
KeyNoChangedTime=0;
KeyOld=0;
KeyCurrent=0;
KeyLast=0;
KeyDown=0;
KeyUp=0;
InitTimer0(); //ʼʱ
KeyCanChange=1; //ֵı
}
/*******************************************************************/
/********************************************************************
ܣʱ0жϴ
ڲޡ
أޡ
ע22.1184MԼ5msжһΡ
********************************************************************/
void Timer0Isr(void) interrupt 1
{
//ʱ0װʱΪ5ms15Ϊװʱ
//ֵͨȷöϵ㣬ʹ
//ʱպΪ5msɡ
TH0=(65536-FCLK/1000/12*5+15)/256;
TL0=(65536-FCLK/1000/12*5+15)%256; //
if(!KeyCanChange)return; //ڴɨ
//ʼɨ
//水״̬ǰ
//KeyCurrentܹ8bit
//ijذʱӦbitΪ1
KeyCurrent=GetKeyValue(); //ȡֵGetKeyValue()ʵǸ꣬Ǻ
//дɺӣۡĶ
//key.hļ
if(KeyCurrent!=KeyOld) //ֵȣ˵˸ı
{
KeyNoChangedTime=0; //̰ʱΪ0
KeyOld=KeyCurrent; //浱ǰ
return; //
}
else
{
KeyNoChangedTime++; //ʱۼ
if(KeyNoChangedTime>=1) //ʱ㹻
{
KeyNoChangedTime=1;
KeyPress=KeyOld; //水
KeyDown|=(~KeyLast)&(KeyPress); //°µļ
KeyUp|=KeyLast&(~KeyPress); //ͷŵļ
KeyLast=KeyPress; //浱ǰ
}
}
}
/*******************************************************************/
|
C | /*
* Author: plasticuproject
* Purpose: This program prints out my name to the screen.
* Date: June 23, 2021
*/
#include <stdio.h>
int main(void) {
// this code is displaying my name
char name[100];
int number;
printf("What is your name and number: ");
scanf("%s %d", name, &number);
printf("\nHello %s, number: %d\n", name, number);
return 0;
}
|
C | // Unit Test Framework Includes
#include "atf.h"
// File To Test
#include <stdc.h>
#include <utf8.h>
static bool is_rejected(char* seq) {
Rune rune = 0;
size_t length = 0;
while (*seq && !utf8decode(&rune, &length, *seq))
seq++;
return (rune == RUNE_ERR);
}
//-----------------------------------------------------------------------------
// Begin Unit Tests
//-----------------------------------------------------------------------------
TEST_SUITE(Utf8) {
TEST(Verify_all_runes_in_the_unicode_database_can_be_encoded_and_decoded)
{
FILE* db = fopen("UnicodeData-8.0.0.txt", "r");
while (!feof(db)) {
char* rec = efreadline(db);
ulong val = strtoul(rec, NULL, 16);
/* Encode the raw val to utf8 first */
char utf8[UTF_MAX] = {0};
CHECK(utf8encode(utf8, (Rune)val) > 0);
/* Decode the encoded utf8 */
Rune rune = 0;
size_t index = 0, len = 0;
while (!utf8decode(&rune, &len, utf8[index]))
index++;
/* Check that the values match */
if ((Rune)val != rune)
printf("0x%04lx == 0x%04lx - %s", val, (ulong)rune, rec);
CHECK((Rune)val == rune);
free(rec);
}
}
TEST(Verify_overlong_sequences_are_rejected)
{
for (unsigned char ch = 1; ch < 0x80; ch++) {
unsigned char overlong2[] = { 0xC0, ch, 0x00 };
CHECK(is_rejected((char*)overlong2));
unsigned char overlong3[] = { 0xE0, 0x80, ch, 0x00 };
CHECK(is_rejected((char*)overlong3));
unsigned char overlong4[] = { 0xF0, 0x80, 0x80, ch, 0x00 };
CHECK(is_rejected((char*)overlong4));
unsigned char overlong5[] = { 0xF8, 0x80, 0x80, 0x80, ch, 0x00 };
CHECK(is_rejected((char*)overlong5));
unsigned char overlong6[] = { 0xFC, 0x80, 0x80, 0x80, 0x80, ch, 0x00 };
CHECK(is_rejected((char*)overlong6));
unsigned char overlong7[] = { 0xFE, 0x80, 0x80, 0x80, 0x80, 0x80, ch, 0x00 };
CHECK(is_rejected((char*)overlong7));
}
}
}
|
C | #include <stdio.h>
#include <math.h>
int distanciadospuntos(float x1, float x2, float y1, float y2, float distancia);
int main(void)
{
float x1=5;
float x2=6.7;
float y1=8.3;
float y2=4.5;
float distancia=8;
float distancias = distanciadospuntos(x1,x2,y1,y2,distancia);
printf("\nLa distancia entre dos puntos es: %f",distancias);
return 0;
}
int distanciadospuntos(float x1, float x2, float y1, float y2, float distancia)
{
return distancia=sqrt((x1-y1)*(x1-y1)+(x2-y2)*(x2-y2));
}
|
C | /*************************************************************************
> File Name: free.c
> Author:
> Mail:
> Created Time: 2015年07月22日 星期三 11时13分40秒
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
free(a);
}
|
C | // chin set insertion point after one byte character insert
#include "../libk.h"
void chin(char c, int fetch) //fetch text[fetch].row
{
assert(glob.iy == fetch); possibleLine; possibleIxIy;
int limit = text[fetch].size + 1 ;
char *new = malloc((limit)*sizeof(char));
char *orig = text[fetch].row;
int no; int mo = 0;
for (no = 0 ; no < limit; no++)
{
if (no != glob.ix) {new[no] = orig[mo];mo++;}
else {new[no] = c; }
}
if (text[fetch].row != NULL) free(text[fetch].row);
text[fetch].row = new;
text[fetch].size = limit;
glob.ix++;
possibleLine; possibleIxIy;
return;
}
|
C | #include "biblio.h"
typedef struct msg
{
GtkWidget *mg;
int type;
char *txt;
}msg;
msg *init_msg(xmlNode *root)
{
msg *m;
m = (msg*)malloc(sizeof(msg));
if(!m) EXIT_FAILURE;
xmlChar *propertyContent;
propertyContent = xmlGetProp(root,"type");
if(propertyContent)
m->type = atoi(propertyContent);
else
m->type = 0;
propertyContent = xmlGetProp(root,"message");
if(propertyContent)
{
m->txt = (char*)malloc(strlen(propertyContent)*sizeof(char));
strcpy(m->txt, propertyContent);
}
else
m->txt = NULL;
return m;
}
void create_msg(msg *m)
{
switch(m->type)
{
case 1: m->mg = gtk_message_dialog_new(NULL,GTK_DIALOG_MODAL,GTK_MESSAGE_WARNING,GTK_BUTTONS_OK,"%s",m->txt);break;
case 2: m->mg = gtk_message_dialog_new(NULL,GTK_DIALOG_MODAL,GTK_MESSAGE_ERROR,GTK_BUTTONS_OK_CANCEL,"%s",m->txt);break;
case 3: m->mg = gtk_message_dialog_new(NULL,GTK_DIALOG_MODAL,GTK_MESSAGE_QUESTION,GTK_BUTTONS_YES_NO,
"%s",m->txt);break;
default: m->mg = gtk_message_dialog_new(NULL,GTK_DIALOG_MODAL,GTK_MESSAGE_INFO,GTK_BUTTONS_CLOSE,"%s",m->txt);break;
}
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
/**
* 计算一个字符串的唯一hash值.
*/
unsigned int
hash(char *s) {
unsigned int h = 0;
size_t i;
for (i = 0; s[i] != 0; ++i) {
if ('a' <= s[i] && s[i] <= 'z')
h = (h << 6) + 2 * (s[i] - 'a' + 1) - 1;
else if ('A' <= s[i] && s[i] <= 'Z')
h = (h << 6) + 2 * (s[i] - 'A' + 1);
}
return h;
}
int *
findSubstring(char *s, char **words, int wordsSize, int *returnSize) {
int i, j;
int slen, wordlen;
unsigned int sum = 0, check;
unsigned int *h, *match;
int *ret;
*returnSize = 0;
slen = strlen(s);
wordlen = strlen(*words);
if (wordsSize == 0 || slen < wordlen)
return NULL;
/* 计算每个子串的hash值,并将所有子串的hash之和保存. */
h = (unsigned int *) malloc(wordsSize * sizeof(unsigned int));
for (i = 0; i < wordsSize; ++i) {
h[i] = hash(words[i]);
sum += h[i];
}
match = (unsigned int *) calloc(slen, sizeof(unsigned int));
/* 遍历s,并记录每个下标处的匹配信息. */
for (i = 0; i <= slen - wordlen; ++i) {
for (j = 0; j < wordsSize; ++j) {
if (strncmp(s + i, words[j], wordlen) == 0) {
/* 成功匹配一个子串,记录子串的hash值,i就是子串的起始下标. */
match[i] = h[j];
break;
}
}
}
/* 遍历匹配信息match数组.
* 若下标i处match[i] > 0,说明从此处开始匹配了一个子串,接着取
* match[i + wordlen]处的值,若也大于0,则说明连续匹配继续取下
* 一个wordlen处的值,否则说明不是连续匹配,下标i递增.何时停止
* 循环呢?注意到所有子串的总长度为wordsSize * wordlen,故i的
* 最大取值为slen - wordsSize * wordlen.
*/
ret = (int *) malloc(slen * sizeof(int));
for (i = 0; i <= slen - wordsSize * wordlen; ++i) {
if (match[i] == 0)
continue;
check = 0;
for (j = 0; j < wordsSize && match[i + j * wordlen] != 0; ++j)
check += match[i + j * wordlen];
if (j == wordsSize && check == sum)
ret[(*returnSize)++] = i;
}
free(h);
free(match);
return ret;
}
int
main() {
char s[] = "aaaaaaaa";
char *words[] = {
"aa",
"aa",
"aa"
};
int size = 0;
int *ret;
ret = findSubstring(s, words, 3, &size);
while (size-- > 0)
printf("%d ", ret[size]);
printf("\n");
return 0;
}
|
C | #include<stdio.h>
void ter(long long int a);
int main()
{
long long int a;
while(scanf("%lld",&a)==1)
{
if(a<0) break;
else if(a==0)
printf("0");
ter(a);
printf("\n");
}
return 0;
}
void ter(long long int a)
{
if(a==0)
return;
ter(a/3);
printf("%lld",a%3);
return ;
}
|
C | /*
* Copyright 2010, 2011, 2012 Paul Chote
* This file is part of Puoko-nui, which is free software. It is made available
* to you under the terms of version 3 of the GNU General Public License, as
* published by the Free Software Foundation. For more information, see LICENSE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include <string.h>
#include "aperture.h"
#include "fit.h"
#include "helpers.h"
extern int verbosity;
// Optimize the centering of a circular aperture (radius r, initial position xy)
// over a star in frame
// Input position is modified in place, or an error code returned
static int center_aperture_inner(double2 *xy, double rd, double sky_intensity, double sky_std_dev, framedata *frame)
{
// Square within the frame to sample
uint16_t x = floor(xy->x);
uint16_t y = floor(xy->y);
uint16_t r = ceil(rd) + 1;
// Calculate x and y marginals (sum the image into 1d lines in x and y)
double *xm = calloc(2*r, sizeof(double));
double *ym = calloc(2*r, sizeof(double));
if (!xm || !ym)
return error("\tmalloc failed");
double total = 0;
for (uint16_t j = 0; j < 2*r; j++)
for (uint16_t i = 0; i < 2*r; i++)
{
// Ignore pixels outside the circle
if ((i-r)*(i-r) + (j-r)*(j-r) > r*r)
continue;
double px = frame->data[frame->cols*(y+j-r) + (x+i-r)] - sky_intensity;
if (fabs(px) < 3*sky_std_dev)
continue;
xm[i] += px;
ym[j] += px;
total += px;
}
if (total == 0)
return error("\tNo signal inside aperture");
// Calculate x and y moments
double xc = 0, yc = 0;
for (size_t i = 0; i < 2*r; i++)
{
xc += i*xm[i] / total;
yc += i*ym[i] / total;
}
free(xm);
free(ym);
xy->x = xc + x - r;
xy->y = yc + y - r;
return 0;
}
// Iterate center_aperture to converge on the best aperture position
int center_aperture(aperture r, framedata *frame, double2 *center)
{
// Allow up to 20 iterations to center
double2 pos[20];
double move;
uint8_t n = 0;
// Set initial center from the given aperture
pos[0].x = r.x;
pos[0].y = r.y;
// Iterate until we move less than 1/16 of a pixel or reach 20 iterations
do
{
n++;
// Most apertures converge within 3 iterations.
// If we haven't converged by 20, we are probably in a cycle
if (n == 19)
{
pos[n].x = pos[n].y = 0;
for (uint8_t i = 14; i < 19; i++)
{
pos[n].x += pos[i].x;
pos[n].y += pos[i].y;
}
pos[n].x /= 5;
pos[n].y /= 5;
if (verbosity >= 1)
error("\tConverge failed - using average of last 5 iterations: (%f,%f)", pos[n].x, pos[n].y);
break;
}
// Set initial position from the previous iteration
pos[n] = pos[n-1];
// Check that the position is valid
int16_t tx = floor(pos[n].x);
int16_t ty = floor(pos[n].y);
int16_t tr = ceil(r.r) + 1;
if (tx < tr || tx + tr >= frame->cols ||
ty < tr || ty + tr >= frame->rows)
return (verbosity >= 1) ? error("\tAperture outside chip - skipping %f %f", pos[n].x, pos[n].y) : 1;
// Calculate new background
double sky_intensity, sky_std_dev;
if (calculate_background(r, frame, &sky_intensity, &sky_std_dev))
return error("\tcalculate_background failed");
// Iterate centering
if (center_aperture_inner(&pos[n], r.r, sky_intensity, sky_std_dev, frame))
return error("\tcenter_aperture_inner failed");
// Calculate shift
move = (pos[n].x - pos[n-1].x)*(pos[n].x - pos[n-1].x) + (pos[n].y - pos[n-1].y)*(pos[n].y - pos[n-1].y);
} while (move >= 0.00390625);
*center = pos[n];
return 0;
}
// Calculate the mode intensity and standard deviation within an annulus
// Pixels brighter than 10 x standard deviation are discarded
// This provides a robust method for calculating the background sky intensity and uncertainty
int calculate_background(aperture r, framedata *frame, double *sky_mode, double *sky_std_dev)
{
uint16_t minx = (uint16_t)fmax(floor(r.x - r.s2), 0);
uint16_t maxx = (uint16_t)fmin(ceil(r.x + r.s2), frame->cols-1);
uint16_t miny = (uint16_t)fmax(floor(r.y - r.s2), 0);
uint16_t maxy = (uint16_t)fmin(ceil(r.y + r.s2), frame->rows-1);
// Copy pixels into a flat list that can be sorted
// Allocate enough space to store the entire aperture region, but only copy pixels
// within the annulus.
double *data = calloc((maxy - miny + 1)*(maxx - minx + 1), sizeof(double));
if (!data)
return error("malloc failed");
size_t n = 0;
for (uint16_t j = miny; j <= maxy; j++)
for (uint16_t i = minx; i <= maxx; i++)
{
double d2 = (r.x - i)*(r.x - i) + (r.y - j)*(r.y - j);
if (d2 > r.s1*r.s1 && d2 < r.s2*r.s2)
data[n++] = frame->data[frame->cols*j + i];
}
// Sort data into ascending order
qsort(data, n, sizeof(double), compare_double);
// Calculate initial mean value
double mean = 0;
for (size_t i = 0; i < n; i++)
mean += data[i];
mean /= n;
// Calculate initial stddev
double std = 0;
for (size_t i = 0; i < n; i++)
std += (data[i] - mean)*(data[i] - mean);
std = sqrt(std/n);
// Discard pixels brighter than mean + 10*stddev
size_t filtered_n = n;
while (data[filtered_n - 1] > mean + 10*std)
filtered_n--;
if (verbosity >= 1 && filtered_n != n)
printf("\tdiscarding %zu bright sky pixels\n", n - filtered_n);
// Recalculate mean and median ignoring discarded pixels
if (n != filtered_n)
{
mean = std = 0;
for (size_t i = 0; i < filtered_n; i++)
mean += data[i];
mean /= filtered_n;
for (size_t i = 0; i < filtered_n; i++)
std += (data[i] - mean)*(data[i] - mean);
std = sqrt(std/filtered_n);
}
// Set return values and clean up
double median = (data[filtered_n/2] + data[filtered_n/2+1])/2;
if (sky_mode)
*sky_mode = 3*mean - 2*median;
if (sky_std_dev)
*sky_std_dev = std;
free(data);
return 0;
}
// Finds the intersection point of the line defined by p1 and p2 (both x,y)
// with the circle c (x,y,r).
// Assumes that there is only one intersection (one point inside, one outside)
// Returns (x,y) of the intersection
// See logbook 07/02/11 for calculation workthrough
static double2 line_circle_intersection(double x, double y, double r, double2 p0, double2 p1)
{
// Line from p1 to p2
double2 dp = {p1.x - p0.x, p1.y - p0.y};
// Line from c to p1
double2 dc = {p0.x - x, p0.y - y};
// Polynomial coefficients
double a = dp.x*dp.x + dp.y*dp.y;
double b = 2*(dc.x*dp.x + dc.y*dp.y);
double c = dc.x*dc.x + dc.y*dc.y - r*r;
// Solve for line parameter x.
double d = sqrt(b*b - 4*a*c);
double x1 = (-b + d)/(2*a);
double x2 = (-b - d)/(2*a);
// The solution we want will be 0<=x<=1
double sol = (x1 >= 0 && x1 <= 1) ? x1 : x2;
double2 ret = {p0.x + sol*dp.x, p0.y + sol*dp.y};
return ret;
}
// Calculate the area inside a chord, defined by p1,p2 on the edge of a circle radius r
static double chord_area(double2 p1, double2 p2, double r)
{
// b is 0.5*the length of the chord defined by p1 and p2
double b = sqrt((p2.x-p1.x)*(p2.x-p1.x) + (p2.y-p1.y)*(p2.y-p1.y))/2;
return r*r*asin(b/r) - b*sqrt(r*r-b*b);
}
// Calculate the area of a polygon defined by a list of points
// Returns the area
static double polygon_area(double2 v[], size_t nv)
{
double a = 0;
size_t n = 0;
for (size_t i = 0; i < nv; i++)
{
n = i == 0 ? nv-1 : i-1;
a += v[n].x*v[i].y - v[i].x*v[n].y;
}
return fabs(a/2);
}
// Convenience function to get a corner, with indices that go outside the indexed range
static double2 corners[4] = {
{0,0},
{0,1},
{1,1},
{1,0}
};
static double2 c(int8_t k)
{
while (k < 0) k += 4;
while (k > 3) k -= 4;
return corners[k];
}
// Calculate the intesection between the unit pixel (with TL corner at the origin)
// and the aperture defined by x,y,r.
// Returns a number between 0 and 1 specifying the intersecting area
// Origin is defined as the bottom-left of the pixel
static double pixel_aperture_intesection(double x, double y, double r)
{
// We don't yet handle the extra cases for r < 1
if (r < 1)
return 0;
// Determine which pixels are inside and outside the aperture
uint8_t hit[4];
uint8_t numhit = 0;
for (uint8_t k = 0; k < 4; k++)
if ((corners[k].x - x)*(corners[k].x - x) + (corners[k].y - y)*(corners[k].y - y) <= r*r)
hit[numhit++] = k;
switch (numhit)
{
// If 0 edges are inside the aperture, but aperture is inside pixel then the aperture is completely inside
case 0:
{
// Check that aperture doesn't intersect with each edge of the pixel in turn
// If so, the intersecting area is a sector
// See whiteboard photo from 13/7/11 for working
// Aperture must be within r distance from the pixel for it to intersect
if (x < -r || y < -r || x > r + 1 || y > r + 1)
return 0;
// Aperture is centered inside the pixel, but intersects no edges.
// It must be fully contained inside the pixel
// We don't yet handle this case, so return 0
if (x >= 0 && y >= 0 && x <= 1 && y <= 1)
return 0;
// Aperture cannot intersect the pixel without having one of the
// vertices inside if it lies in one of these corner regions
if ((x < 0 && y < 0) || (x < 0 && y > 1) || (x > 1 && y > 1) || (x > 1 && y < 0))
return 0;
// Remaining aperture positions may potentially intersect the pixel twice, without
// containing a vertex. Check each in turn.
// TODO: Check each edge for intersections
return 0;
}
case 4: return 1;
case 1:
{
// Intersection points
double2 pts[3] =
{
line_circle_intersection(x, y, r, c(hit[0] - 1), c(hit[0])),
c(hit[0]),
line_circle_intersection(x, y, r, c(hit[0]), c(hit[0] + 1))
};
// Area is triangle + chord
return polygon_area(pts, 3) + chord_area(pts[0], pts[2], r);
}
break;
case 2:
{
// Find the first inside the aperture
int first = (hit[1] - hit[0] == 3) ? hit[1] : hit[0];
// Intersection points
double2 pts[4] =
{
line_circle_intersection(x, y, r, c(first - 1), c(first)),
c(first),
c(first+1),
line_circle_intersection(x, y, r, c(first + 1), c(first + 2))
};
// Area is a quadralateral + chord
return polygon_area(pts, 4) + chord_area(pts[0], pts[3], r);
}
break;
case 3:
{
int outside = 3;
for (uint8_t k = 0; k < numhit; k++)
if (hit[k] != k)
{
outside = k;
break;
}
// Intersection points
double2 pts[3] =
{
line_circle_intersection(x, y, r, c(outside - 1), c(outside)),
c(outside),
line_circle_intersection(x, y, r, c(outside), c(outside + 1))
};
// Area is square - triangle + chord
return 1 - polygon_area(pts, 3) + chord_area(pts[0], pts[2], r);
}
break;
}
return 0;
}
// Integrates the flux within the specified aperture,
// accounting for partially covered pixels.
// Takes the aperture (x,y,r) and the image data
// Returns the contained flux (including background)
double integrate_aperture(double2 xy, double r, framedata *frame)
{
double total = 0;
uint16_t bx = floor(xy.x);
uint16_t by = floor(xy.y);
uint16_t br = ceil(r) + 1;
for (int32_t i = bx - br; i < bx + br; i++)
for (int32_t j = by - br; j < by + br; j++)
total += pixel_aperture_intesection(xy.x - i, xy.y - j, r)*frame->data[i + frame->cols*j];
return total;
}
void integrate_aperture_and_noise(double2 xy, double r, framedata *frame, framedata *dark, double readnoise, double gain, double *signal, double *noise)
{
*signal = 0;
*noise = 0;
uint16_t bx = floor(xy.x);
uint16_t by = floor(xy.y);
uint16_t br = ceil(r) + 1;
for (int32_t i = bx - br; i < bx + br; i++)
for (int32_t j = by - br; j < by + br; j++)
{
double area = pixel_aperture_intesection(xy.x - i, xy.y - j, r);
double flux = frame->data[i + frame->cols*j];
double darkflux = dark ? dark->data[i + frame->cols*j] : 0;
*signal += area*flux;
*noise += area*(readnoise*readnoise + (flux + darkflux)/gain);
}
// Convert variance to standard deviation
*noise = sqrt(*noise);
}
double estimate_fwhm(framedata *frame, double2 xy, double bg, double max_radius)
{
int ret = 0;
size_t max = (size_t)max_radius;
double *profile = calloc(2*max, sizeof(double));
double *radius = calloc(2*max, sizeof(double));
if (!profile || !radius)
error_jump(error, ret, "Allocation error");
double last_intensity = 0;
size_t n = 0;
for (size_t i = 0; i < max; i++)
{
double r = i + 1;
if (xy.x < r || xy.x + r >= frame->cols || xy.y < r || xy.y + r >= frame->rows)
error_jump(error, ret, "FWHM calculation extends outside frame");
double intensity = integrate_aperture(xy, r, frame) - bg*M_PI*r*r;
double p = (intensity - last_intensity) / (M_PI*(2*r - 1));
last_intensity = intensity;
if (p > 1)
{
profile[2*n + 1] = profile[2*n] = p;
radius[2*n] = r;
radius[2*n + 1] = -r;
n++;
}
}
double sigma, ampl;
if (fit_gaussian(radius, profile, 2*n, 1, max, 0.1, &sigma, &l))
error_jump(error, ret, "Gaussian fit failed");
error:
free(profile);
free(radius);
return ret ? -1 : 2*sqrt(2*log(2))*sigma;
}
|
C | /*
* Copyright (C) 2015 University of Oregon
*
* You may distribute under the terms of either the GNU General Public
* License or the Apache License, as specified in the LICENSE file.
*
* For more information, see the LICENSE file.
*/
/*
*/
#include <stdio.h>
#define NINETRACK 1
#define STREAMER 2
main( argc, argv )
int argc;
char *argv[];
{
char tchar;
int argp, tdevice, tspec, unum;
if (argc < 2) {
tape_help();
exit( 2 );
}
tspec = 0;
tdevice = STREAMER;
unum = 0;
argp = 1;
while ( argp < argc ) {
if (*argv[ argp ] != '-') { /* Not a switch */
if (tdevice == NINETRACK)
ntape_main( argc-argp, argv+argp );
else
stape_main( argc-argp, argv+argp );
exit();
}
/* Get the 2nd character of the current argument string. */
tchar = *(argv[ argp++ ]+1);
switch (tchar) {
case 'q':
case 'Q':
case 's':
case 'S':
if (tspec) {
printf(
"Can't specify device more than once\n"
);
exit( 10 );
}
tdevice = STREAMER;
tspec = 131071;
break;
case 'n':
case 'N':
case 'h':
case 'H':
case '9':
if (tspec) {
printf(
"Can't specify device more than once\n"
);
exit( 10 );
}
tdevice = NINETRACK;
tspec = 131071;
break;
/* case 'u':
case 'U':
unum = atoi( argv[ argp++ ] );
if (unum < 0 || unum > 3) {
printf( "Invalud unit number\n" );
exit( 1 );
}
break; */
default:
printf( "Invalid switch %c\n", tchar );
exit( 1 );
}
}
printf( "tape: You must specify an option\n" );
}
tape_help()
{
printf( "Usage:\n\n" );
printf( " tape -q <option>\n" );
printf( " tape -s <option> to access the streaming tape\n\n" );
printf( " tape -9 <option>\n" );
printf( " tape -h <option>\n" );
printf( " tape -n <option> to access the 9-track tape\n\n" );
printf( "The default is the streaming tape.\n\n" );
printf( "You must specify an option. Use the 'help' option for\n" );
printf( "more information about the individual interface\n" );
}
|
C | /*
* AVRADV34_ACileADC.c
*
* Created: 21.3.2021 09:39:07
* Author : GDokmetas
*/
#include <avr/io.h>
#include "bitfieldarduino.h"
#define F_CPU 16000000UL
#include <util/delay.h>
#include <avr/interrupt.h>
#include <stdio.h>
#include "uart.h"
void adc_oku();
unsigned int analog_deger;
int main(void)
{
D2_dir = OUTPUT;
D2_out = HIGH;
ACSR |= (1<<ACIE);
ACSR |= (1<<ACIS1); // interrupt falling
sei();
uart_init(UART_BAUD_SELECT(9600,F_CPU));
char buf[25];
_delay_ms(100);
while (1)
{
adc_oku();
_delay_us(1000);
sprintf(buf, "Analog Deger:%i \n", analog_deger);
uart_puts(buf);
}
}
void adc_oku()
{
D2_out = LOW; // Dearj
TCCR1B |= (1<<CS10); // Zamanlaycy balat kesme bekle
}
ISR(ANALOG_COMP_vect)
{
analog_deger = TCNT1;
TCCR1B &=~(1<<CS10);
TCNT1 = 0;
D2_out = HIGH; // arj Et
_delay_us(1000);
} |
C | /*
Bastian Ruppert
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "iniParser.h"
/*
* trim: get rid of trailing and leading whitespace...
* ...including the annoying "\n" from fgets()
*/
static char * trim (char * s)
{
// Initialize start, end pointers
char *s1 = s, *s2 = &s[strlen (s) - 1];
// Trim and delimit right side
while ( (isspace (*s2)) && (s2 >= s1) )
s2--;
*(s2+1) = '\0';
// Trim left side
while ( (isspace (*s1)) && (s1 < s2) )
s1++;
// Copy finished string
strcpy (s, s1);
return s;
}
int iniParser_getParam(char * file,char * param,char * target,int targetLen)
{
char *s, buff[64];
FILE *fp = fopen (file, "r");
int ret=-1;
if(targetLen<64)
return -1;
if (fp == NULL)
{
return -1;
}
// Read next line
while ((s = fgets (buff, sizeof buff, fp)) != NULL)
{
// Skip blank lines and comments
if (buff[0] == '\n' || buff[0] == '#')
continue;
// Parse name/value pair from line
char name[64], value[64];
s = strtok (buff, "=");
if (s==NULL)
continue;
else{
strncpy (name, s, 63);
trim (name);
}
s = strtok (NULL, "=");
if (s==NULL)
continue;
else
strncpy (value, s, 63);
trim (value);
//compare to requested param
if (strcmp(name,param)==0)
{
strncpy (target, value, 63);
ret = 0;
break;
}
}
// Close file
fclose (fp);
return ret;
}
int iniParser_getParamList(char * file,struct t_iniParserParams * parameter)
{
char *s, buff[64];
int ret=0;
FILE *fp = fopen (file, "r");
struct t_iniParserParams * param = parameter;
if (fp == NULL)
{
return -1;
}
// Read next line
while ((s = fgets (buff, sizeof buff, fp)) != NULL)
{
// Skip blank lines and comments
if (buff[0] == '\n' || buff[0] == '#')
continue;
// Parse name/value pair from line
char name[64], value[64];
s = strtok (buff, "=");
if (s==NULL)
continue;
else{
strncpy (name, s, 63);
trim (name);
}
s = strtok (NULL, "=");
if (s==NULL)
continue;
else
strncpy (value, s, 63);
trim (value);
//compare to requested param
param = parameter;
while(param->key)
{
if(!param->valid)
if (strcmp(name,param->key)==0)
{
strncpy (param->value, value, 63);
param->valid = 1;
break;
}
param++;
}
}
//operation successfull ?
param = parameter;
while(param->key)
{
if(!param->valid)
{
ret = -2;
break;
}
param++;
}
// Close file
fclose (fp);
return ret;
}
|
C | #include <stdio.h>
#include <emscripten/em_math.h>
int main()
{
printf("%f\n", emscripten_math_cbrt(8.0));
printf("%f\n", emscripten_math_pow(2.0, 4.0));
printf("%d\n", (int)(emscripten_math_random() >= 0 && emscripten_math_random() <= 1));
printf("%f\n", emscripten_math_sign(-42.0));
printf("%f\n", emscripten_math_exp(2.0));
printf("%f\n", emscripten_math_expm1(2.0));
printf("%f\n", emscripten_math_log(42.0));
printf("%f\n", emscripten_math_log1p(42.0));
printf("%f\n", emscripten_math_log10(42.0));
printf("%f\n", emscripten_math_log2(42.0));
printf("%f\n", emscripten_math_round(42.5));
printf("%f\n", emscripten_math_acos(0.5));
printf("%f\n", emscripten_math_acosh(42.0));
printf("%f\n", emscripten_math_asin(0.5));
printf("%f\n", emscripten_math_asinh(42.0));
printf("%f\n", emscripten_math_atan(42.0));
printf("%f\n", emscripten_math_atanh(0.9));
printf("%f\n", emscripten_math_atan2(42.0, 13.0));
printf("%f\n", emscripten_math_cos(42.0));
printf("%f\n", emscripten_math_cosh(0.6));
printf("%f\n", emscripten_math_hypot(3, 3.0, 4.0, 5.0));
printf("%f\n", emscripten_math_sin(42.0));
printf("%f\n", emscripten_math_sinh(0.6));
printf("%f\n", emscripten_math_tan(42.0));
printf("%f\n", emscripten_math_tanh(42.0));
}
|
C | #include "myHeader.h"
struct Node //Node of Binary Search Tree
{
struct Node *Left_Smaller;
int data;
struct Node *Right_Greater;
}*Root=NULL;
void display_Inorder(struct Node *Root) //Display-->Inorder
{
if(Root)
{
/* first recur on left child */
display_Inorder(Root->Left_Smaller);
/* then print the data of node */
printf("%d ", Root->data);
/* now recur on right child */
display_Inorder(Root->Right_Greater);
}
}
void Insert(int key) //Inserting element in BST
{
struct Node *p, *q, *r;
r=Root;
if(Root==NULL) //If root is not present then create a Root Node
{
p=(struct Node*) malloc(sizeof(struct Node));
p->data=key;
p->Left_Smaller=p->Right_Greater=NULL;
Root=p;
return;
}
while(r!=NULL) //Else search and insert element by creating a New node
{
q=r;
if(key<r->data)
r=r->Left_Smaller;
else if(key>r->data)
r=r->Right_Greater;
else
return;
}
r=(struct Node*)malloc(sizeof(struct Node));
r->data=key;
r->Left_Smaller=r->Right_Greater=NULL;
if(key<q->data)
q->Left_Smaller=r;
else
q->Right_Greater=r;
}
struct Node* Search(struct Node* t, int key) //Searching Node in BST
{
while(t!=NULL)
{
if(key==t->data)
return t;
else if(key<t->data)
t=t->Left_Smaller;
else
t=t->Right_Greater;
}
return NULL;
}
int Height(struct Node *p) //Height of BST
{
int left_subtree_height, right_subtree_height;
if(p==NULL)
return 0;
left_subtree_height=Height(p->Left_Smaller);
right_subtree_height=Height(p->Right_Greater);
return left_subtree_height>right_subtree_height?left_subtree_height+1:right_subtree_height+1;
}
struct Node* Inorder_Predecessor(struct Node *p)
{
while(p && p->Right_Greater!=NULL)
{
p=p->Right_Greater;
}
return p;
}
struct Node* Inorder_Successor(struct Node *p)
{
while(p && p->Left_Smaller!=NULL)
{
p=p->Left_Smaller;
}
return p;
}
struct Node* Delete(struct Node* t, int key) //Deleting a Node in a BST
{
struct Node *q;
if(t==NULL)
return NULL;
if(t->Left_Smaller==NULL && t->Right_Greater==NULL)
{
if(t==Root)
Root=NULL;
free(t);
return NULL;
}
if(key < t->data)
t->Left_Smaller=Delete(t->Left_Smaller, key);
else if(key > t->data)
t->Right_Greater=Delete(t->Right_Greater, key);
else
{
if(Height(t->Left_Smaller)>Height(t->Right_Greater))
{
q=Inorder_Predecessor(t->Left_Smaller);
t->data=q->data;
t->Left_Smaller=Delete(t->Left_Smaller, q->data);
}
else
{
q=Inorder_Successor(t->Right_Greater);
t->data=q->data;
t->Right_Greater=Delete(t->Right_Greater, q->data);
}
}
return t;
}
int main()
{
int number;
char ch;
struct Node *s;
while(1)
{
printf("Please enter your choice\n1. Enter Element\n2. Display Element\n3. Search Element\n4. Delete Element:\n");
scanf("%c", &ch);
if(ch<='1' && ch>='3')
printf("Please enter correct Input\n");
switch (ch)
{
case '1':printf("Please enter your data\n");
scanf("%d", &number);
Insert(number);
break;
case '2':printf("Displaying the Data in BST\n");
display_Inorder(Root);
break;
case '3':printf("Please enter your element for searching in BST\n");
scanf("%d", &number);
s=Search(Root, number);
if(s)
printf("Element is Found\n");
else
printf("Element is not found\n");
break;
case '4':printf("Please enter your element for deleting in BST\n");
scanf("%d", &number);
s=Delete(Root, number);
if(s)
printf("Element is Deleted\n");
else
printf("Element is not Deleted\n");
break;
default:
break;
}
}
}
|
C |
#include <windows.h>
#include <stdio.h>
#include "utils.h"
int main(int argc, char **argv)
{
intlong times = atol(argv[1]);
uintlong sum = 0;
LARGE_INTEGER c;
for (long i = 0; i < times; ++i)
{
QueryPerformanceCounter(&c);
sum += c.QuadPart;
}
printf("%" PRIduil "\n", sum);
return 0;
}
|
C | #include<stdio.h>
void main(){
int seen[10]={0},n,rem;
printf("Enter the numbers:");
scanf("%d",&n);
while(n>0){
rem=n%10;
if(seen[rem]==1)
break;
seen[rem]=1;
n=n/10;
}
if(n>0){
printf("yes");
}
else
printf("No");
}
|
C | // demo using forloop to underline string
#include<stdio.h>
#include<string.h>
int main(void)
{
/* string to underline */
char str[] = "Connie is learning C.";
/* print the upper underline */
int len = strlen(str);
for(int i = 0;i<len;i++){
putchar('-');
}
putchar('\n');
/* print the string */
printf("%s \n", str);
/* print the bottom underline */
for(int i = 0;i<len;i++){
putchar('-');
}
putchar('\n');
return 0;
} |
C | #include <stdio.h>
#include "Sort.h"
int SplitArray(TYPE *A, int l, int r)
{
int Index = l;
int End = r;
int Ruler = A[r];
int RulerIndex = l;
if (l == r)
{
return l;
}
while(Index != End)
{
if (A[Index] < Ruler)
{
A[End] = A[Index];
A[Index] = A[End-1];
End--;
}
else
{
RulerIndex++;
Index++;
}
}
A[RulerIndex] = Ruler;
return RulerIndex;
}
void QuickSplitAndMerge(TYPE *A, int l, int r)
{
int RulerIndex;
if (l == r)
{
return;
}
RulerIndex = SplitArray(A, l, r);
if (RulerIndex > l)
{
QuickSplitAndMerge(A, l, RulerIndex-1);
}
if (RulerIndex < r)
{
QuickSplitAndMerge(A, RulerIndex+1, r);
}
}
void QuickSort(TYPE *A, int Len)
{
QuickSplitAndMerge(A, 0, Len-1);
}
|
C | //
// memory_manager.c
// ObjectVM
//
// Created by Kyle Roucis on 14-4-2.
// Copyright (c) 2014 Kyle Roucis. All rights reserved.
//
#include "memory_manager.h"
#ifdef CLKWK_DEBUG_MEMORY
#include <stdio.h>
#endif
#include <memory.h>
struct mem_block
{
size_t size;
void* memory;
};
#ifdef CLKWK_TRACK_MEMORY
static size_t s_count = 0;
#endif
void* _debug_malloc(const char* file, int line, size_t size)
{
if (size == 0)
{
return NULL;
}
int rem = size % sizeof(void*) != 0;
if (rem != 0)
{
size -= rem;
size += sizeof(void*);
}
#ifndef CLKWK_TRACK_MEMORY
void* ptr = calloc(1, size);
return ptr;
#else
size = size + sizeof(size_t);
void* ptr = calloc(1, size);
if (ptr)
{
s_count += size;
#ifdef CLKWK_DEBUG_MEMORY
printf("Allocating %zu bytes. Total: %zu\n", size, s_count);
#endif
struct mem_block* mem = (struct mem_block*)ptr;
mem->size = size;
mem->memory = ptr + sizeof(size_t);
return ptr + sizeof(size_t);
}
else
{
return NULL;
}
#endif
}
void _debug_free(const char* file, int line, void* ptr)
{
if (!ptr)
{
return;
}
#ifndef CLKWK_TRACK_MEMORY
free(ptr);
#else
struct mem_block* mem = (struct mem_block*)(ptr - sizeof(size_t));
s_count -= mem->size;
#ifdef DEBUG_MEMORY
printf("Freeing %zu bytes. Total: %zu\n", mem->size, s_count);
#endif
free(mem);
#endif
}
//#include <stdlib.h>
//
//enum
//{
// MEM_FREE = 0,
// MEM_ALLOCATED = 1,
//};
//
//struct memory_block
//{
// uint8_t flags;
// uint16_t size;
// memory_block* next;
// void* data;
//};
//
//struct memory_manager
//{
// uint32_t poolSize;
// uint8_t* memory;
// uint8_t** freeArray;
// uint8_t** allocdArray;
//};
//
//static const uint8_t c_block_size = 32; // bytes
//
//memory_manager* memory_manager_init(uint32_t maxSize)
//{
// memory_manager* mman = malloc(sizeof(memory_manager));
// mman->poolSize = maxSize;
// mman->memory = calloc(maxSize, sizeof(uint8_t));
// uint16_t count = maxSize / 32;
//
// return mman;
//}
//
//memory_block* memory_manager_alloc(memory_manager* mman, uint16_t size)
//{
// return NULL;
//}
//
//void memory_manager_free(memory_manager* mman, memory_block* block)
//{
//
//}
//
//uint16_t memory_block_size(memory_block* block)
//{
// return block->size;
//}
//
//void* memory_block_data(memory_block* block)
//{
// return block->data;
//}
|
C | #include<stdio.h>
void FaC(int f)
{
float celcius=((f-32)*5)/9;
printf("\nTemp. Fahrenheit Temp. Celcius");
printf("\n%16.d %14.f", f, celcius);
}
int main()
{
int fahr;
char salir;
do
{
printf("Ingrese una temperatura en Fahrenheint: ");
scanf("%d", &fahr);
FaC(fahr);
printf("\nDesea ingresar otro valor? s/n: ");
fflush(stdin);
scanf("%c", &salir);
}
while(salir=='s' || salir=='S');
return 0;
}
|
C | /*
** EPITECH PROJECT, 2020
** PSU_2019_malloc
** File description:
** free
*/
#include "../include/malloc.h"
void free(void *ptr)
{
block_t *free = NULL;
if (ptr == NULL)
return;
free = (block_t *)ptr - 1;
free->avaible = 1;
}
void *calloc(size_t nmemb, size_t size)
{
size_t new_size = nmemb * size;
block_t *ptr = malloc(new_size);
if (ptr == NULL)
return (NULL);
memset(ptr, 0, size);
return (ptr);
}
void *realloc(void *ptr, size_t size)
{
block_t *block;
block_t *new_block;
if (ptr == NULL)
return (malloc(size));
block = (block_t *)ptr - 1;
if (block->size >= size)
return ptr;
new_block = malloc(size);
if (new_block == NULL)
return (NULL);
memcpy(new_block, ptr, block->size);
free(ptr);
return (new_block);
}
void *reallocarray(void *ptr, size_t nmemb, size_t size)
{
return (realloc(ptr, nmemb * size));
} |
C | // 컴파일은 visual studio 2019를 통해 하였으며 x64 릴리즈 모드의 옵션은 다음과 같습니다.
// C/C++
// 최적화: 사용 안 함(/Od)
// SDL 검사: 아니요(/sdl-)
// 링커
// 임의 기준 주소: 아니요(/DYNAMICBASE:NO)
// 이외의 옵션은 기본값을 사용하였습니다.
#include <stdio.h>
int numberConvert(char in) {
int ret = 0;
switch(in){
case 'q': ret = 1; break;
case 'w': ret = 2; break;
case 'e': ret = 3; break;
case 'r': ret = 4; break;
case 't': ret = 5; break;
case 'y': ret = 6; break;
case 'u': ret = 7; break;
case 'i': ret = 8; break;
case 'o': ret = 9; break;
case 'p': ret = 0; break;
default:{
printf("wrong input!\n");
exit(0);
}
}
return ret;
}
int check(unsigned char *input) {
int index = 0;
int now = numberConvert(input[index]);
index++;
while(input[index]) {
int operation = input[index];
int number = numberConvert(input[index+1]);
switch(operation) {
case 'a': now += number; break;
case 's': now -= number; break;
case 'd': now *= number; break;
case 'f': now /= number; break;
case '\0':break;
}
index += 2;
}
return now == 105;
}
int main(){
unsigned char *input = malloc(0x10);
memset(input, 0, 0x10);
printf("input: ");
input[0] = getchar();
input[1] = 'd';
input[2] = 'w';
input[3] = 's';
input[4] = 'q';
input[5] = 'a';
input[6] = 'w';
input[7] = 'd';
input[8] = 'u';
if (check(input)) {
puts("correct!");
}
else {
puts("wrong!");
}
} |
C | /**
* Time.c
*
* Created on: Dec 9, 2019
* Author: Daniel
*/
#include <Time.h>
/**
* @breif Gets the time from the rtc and sends it to the display
* @param none
* @retval none
*/
void update_time(){
uint8_t temp;
RTC_TimeTypeDef real_time;
clear_display();
real_time = get_time();
temp = real_time.Hours;
update_display((char)((temp / 10) + 48), 1, 0);
update_display((char)((temp % 10) + 48), 1, 0);
update_display(':', 1, 0);
temp = real_time.Minutes;
update_display((char)((temp / 10) + 48), 1, 0);
update_display((char)((temp % 10) + 48), 1, 0);
update_display(':', 1, 0);
temp = real_time.Seconds;
update_display((char)((temp / 10) + 48), 1, 0);
update_display((char)((temp % 10) + 48), 1, 0);
HAL_Delay(100);
}
/**
* @breif Gets the current time from the rtc
* @param none
* @retval time struct
*/
RTC_TimeTypeDef get_time() {
RTC_TimeTypeDef gTime;
RTC_DateTypeDef gDate;
HAL_RTC_GetTime(&hrtc, &gTime, RTC_FORMAT_BIN);
HAL_RTC_GetDate(&hrtc, &gDate, RTC_FORMAT_BIN);
return gTime;
}
/**
* @breif Sets the rtc's time by getting input from uart
* @param none
* @retval none
*/
void set_time() {
RTC_TimeTypeDef sTime;
RTC_DateTypeDef sDate;
sTime.StoreOperation = RTC_STOREOPERATION_RESET;
sTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
sTime.Hours = receiveUART();
sTime.Minutes = receiveUART();
sTime.Seconds = receiveUART();
HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BIN);
}
/**
* @breif Receives data from the uart port
* @param none
* @retval uart data
*/
uint8_t receiveUART() {
uint8_t uart = 0;
if (HAL_UART_Receive(&huart5, &uart, 1, HAL_MAX_DELAY) != HAL_OK) {
Error_Handler();
}
else{
return uart;
}
}
|
C | #include <stdio.h>
void swap(int *a,int *b);
int main()
{
int x=10,y=20;
printf("x is %i\n",x);
printf("y is %i\n",y);
printf("swapping......\n");
swap(&x,&y);
printf("swapped.\n");
printf("x is %i\n",x);
printf("y is %i\n",y);
}
void swap(int *a,int *b)
{
int temp=*a;
printf("temp =%i\n",temp);
//temp=a;
printf("temp =%i\n",temp);
*a=*b;
*b=temp;
printf("temp =%i\n",temp);
//printf("a =%i\nb =%i\n",a,b);
}
|
C | /******************************************************************************
* Student Name : Federick Kwok
* RMIT Student ID : s3666874
* COURSE CODE : CPT220
*
* Startup code provided by Paul Miller for use in "Programming in C",
* study period 2, 2018.
*****************************************************************************/
#include "helpers.h"
#include "io.h"
#include "shared.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef WORDMAP_H
#define WORDMAP_H
#define AL_NUM_LETTERS 26
#define NUM_TILE_DELIMS 2
#define NUM_TILE_TOKENS 3
#define NUM_LETTERS 100
/**
* a tile is a letter and tile pair.
**/
struct tile
{
/* int is used for letter rather than char in order to consistently
* use negative numbers
*/
int letter;
int score;
};
/**
* score_count stores both the tile and how many times that tile should occur.
**/
struct score_count
{
struct tile tile;
int count;
};
/**
* global const variable that indicates that an error has occured.
**/
extern const struct score_count error_score;
struct tile_list
{
struct tile* tiles;
int num_tiles;
int total_tiles;
};
struct tile new_tile(int, int);
void shuffle_tiles(struct tile [], int);
void print_tiles(struct tile [], int);
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.