language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <assert.h>
#define MAX_DIGITS 9
struct ast {
struct ast* left;
struct ast* right;
char num[MAX_DIGITS + 1];
char op;
};
static struct ast* parse(void);
static void parse_space(void);
static struct ast* parse_num(void);
static struct ast* parse_exp(void);
static void print_sml(struct ast*);
static void destroy_ast(struct ast*);
int main(void) {
struct ast* ast = parse();
if (ast) {
print_sml(ast);
puts("done");
destroy_ast(ast);
} else {
puts("Error during parsing!");
}
}
struct ast* parse(void) {
parse_space();
struct ast* node = parse_num();
parse_space();
if (node) return node;
node = parse_exp();
parse_space();
return node;
}
void parse_space(void) {
int c;
for (c = getchar(); c && isspace(c); c = getchar());
ungetc(c, stdin);
}
struct ast* parse_num(void) {
char num[MAX_DIGITS + 1] = {0};
int c = getchar();
for (int i = 0; i != MAX_DIGITS && isdigit(c); ++i, c = getchar()) {
num[i] = (char)c;
}
if (c != EOF) ungetc(c, stdin);
if (isdigit(c) || !num[0])
return NULL;
struct ast* ast = malloc(sizeof(*ast));
ast->op = 0;
strcpy(ast->num, num);
return ast;
}
struct ast* parse_exp(void) {
if (getchar() != '(') return NULL;
struct ast* left = parse();
if (!left) return NULL;
int op = getchar();
if (op != '+' && op != '-' && op != '*' && op != '\\')
return NULL;
struct ast* right = parse();
if (!right) return NULL;
if (getchar() != ')') return NULL;
struct ast* exp = malloc(sizeof(*exp));
exp->left = left;
exp->op = (char)op;
exp->right = right;
return exp;
}
void print_sml(struct ast* ast) {
assert(ast);
if (ast->op) {
print_sml(ast->right);
print_sml(ast->left);
switch (ast->op) {
case '+':
puts("add");
break;
case '-':
puts("sub");
break;
case '*':
puts("mul");
break;
case '\\':
puts("div");
}
} else {
printf("push %s\n", ast->num);
}
}
void destroy_ast(struct ast* ast) {
assert(ast);
if (ast->op) {
destroy_ast(ast->right);
destroy_ast(ast->left);
}
free(ast);
}
|
C
|
#include<stdio.h>
#include<string.h>
/*
int main(void)
{
struct {
int yil;
int ay;
int gun;
} dogum_gunu;
printf("Dogum gununzu ");
printf("gun ay yil gg aa yyyy olarak giriniz: ");
scanf("%d %d %d", &dogum_gunu.gun, &dogum_gunu.ay, &dogum_gunu.yil);
printf("Dogum gununuz: %d/%d/%d", dogum_gunu.gun, dogum_gunu.ay, dogum_gunu.yil);
return 0;
}
*/
/*
int main(void)
{
struct {
int yil;
int ay;
int gun;
} siz, kiz_kardes, erkek_kardes;
printf("Dogum gununuzu gg aa yyyy seklinde giriniz: ");
scanf("%d %d %d", &siz.gun, &siz.ay, &siz.yil);
printf("Kiz kardesinizin dogum gununu giriniz: ");
scanf("%d %d %d", &kiz_kardes.gun, &kiz_kardes.ay, &kiz_kardes.yil);
printf("Erkek kardesinizin dogum gununu giriniz: ");
scanf("%d %d %d", &erkek_kardes.gun, &erkek_kardes.ay, &erkek_kardes.yil);
printf("Sizin dogum gununuz: %d %d %d \n", siz.gun, siz.ay, siz.yil);
printf("Kiz kardesinizin dogum gunu: %d %d %d \n", kiz_kardes.gun, kiz_kardes.ay, kiz_kardes.yil);
printf("Erkek kardesinizin dogum gunu: %d %d %d", erkek_kardes.gun, erkek_kardes.ay, erkek_kardes.yil);
return 0;
}
*/
/*
int main(void)
{
struct {
char isim[40];
int boy;
struct
{
int ay;
int yil;
int gun;
}dogum_bilgileri;
} kisi;
printf("Adiniz: ");
scanf("%s", &kisi.isim);
printf("Boyunuz: ");
scanf("%d", &kisi.boy);
printf("Dogum tarihi: ");
scanf("%d %d %d", &kisi.dogum_bilgileri.gun, &kisi.dogum_bilgileri.ay, &kisi.dogum_bilgileri.yil);
printf("Girilen bilgiler: \n");
printf("Adi: %s \n", kisi.isim);
printf("Boyu %d \n", kisi.boy);
printf("Dogum Tarihi: %d %d %d", kisi.dogum_bilgileri.gun, kisi.dogum_bilgileri.ay, kisi.dogum_bilgileri.yil);
return 0;
}
*/
/*
int main(void)
{
struct sahis_bilgileri
{
char isim[40];
int boy;
};
struct sahis_bilgileri kisi_1;
struct sahis_bilgileri kisi_2;
strcpy(kisi_1.isim, "ERKAN");
kisi_1.boy = 173;
strcpy(kisi_2.isim, "ELIF");
kisi_2.boy= 163;
printf("Erkan ile Elifin boy farki: %d", kisi_1.boy - kisi_2.boy);
return 0;
}
*/
int main(void)
{
struct sahis_bilgileri
{
char isim[40];
int boy;
} kisi_1 = { "Erkan", 173 }, kisi_2 = { "Elif", 163 };
printf("Erkan ile Elifin boy farki: %d", kisi_1.boy - kisi_2.boy);
return 0;
}
|
C
|
#include <stdio.h>
#include "5-7.h"
#include "5-7.h"
int main()
{
matrix a, b;
if (mat_alloc(&a, 3, 3)) {
printf("allocation error\n");
exit(-1);
}
if (mat_alloc(&b, 3, 1)) {
printf("allocation error\n");
exit(-1);
}
mat_elem(a, 1, 1) = 1;
mat_elem(a, 1, 2) = 3;
mat_elem(a, 1, 3) = 4;
mat_elem(a, 2, 1) = 2;
mat_elem(a, 2, 2) = 6; //6
mat_elem(a, 2, 3) = 1; //1
mat_elem(a, 3, 1) = 3;
mat_elem(a, 3, 2) = 2; //2
mat_elem(a, 3, 3) = 1; //1
mat_elem(b, 1, 1) = 1;
mat_elem(b, 2, 1) = 9;
mat_elem(b, 3, 1) = 7;
if ( mat_solve(&b, a, b) ) {
printf("Cannot solve\n");
exit(-1);
}
printf("Answer is:\n");
mat_print(b);
if ( mat_inverse(&a, a) ) {
printf("Cannot make inverse matrix\n");
exit(-1);
}
printf("Inverse matrix is:\n");
mat_print(a);
mat_free(&a);
mat_free(&b);
return 0;
}
/*
int main(){
int i, j;
matrix mat, matt, mat1;
mat_alloc(&mat, 3, 3);
mat_alloc(&matt, 3, 2);
mat_alloc(&mat1, 3, 2);
for(i=0; i < mat.row; i++){
for(j=0; j < mat.col; j++){
mat.element[i][j] = j + i * mat.col;
}
}
for(i=0; i < matt.row; i++){
for(j=0; j < matt.col; j++){
matt.element[i][j] = j + i * matt.col;
}
}
mat.element[0][0] = 1;
mat.element[0][1] = -1;
mat.element[0][2] = 1;
matt.element[0][0] = -5;
matt.element[0][1] = -5;
mat.element[1][0] = 2;
mat.element[1][1] = 1;
mat.element[1][2] = -3;
matt.element[1][0] = 19;
matt.element[1][1] = 19;
mat.element[2][0] = 3;
mat.element[2][1] = 2;
mat.element[2][2] = -1;
matt.element[2][0] = 16;
matt.element[2][1] = 16;
//mat_copy(&mat1, mat);
//mat_add(&mat1, mat, matt);
//mat_sub(&mat1, mat, matt);
//mat_mul(&mat1, mat, matt);
//mat_muls(&mat1, mat, 3);
mat_solve(&mat1, mat, matt);
//mat_mul(&matt, mat, matt);
//mat_unit(&mat);
//printf("%d \n", mat_compare(mat, matt));
mat_print(mat1);
mat_free(&mat1);
mat_free(&matt);
mat_free(&mat);
return 0;
}
*/
|
C
|
#include "memo.h"
void *create_arr_1d(int n, int type_size) {
void *arr;
arr = (void *)malloc(n * type_size);
return arr;
}
void delete_arr_1d(void *arr) {
free(arr);
}
void **create_arr_2d(int nr, int nc, int type_size) {
void **mat;
mat = malloc(nr * sizeof(void *));
mat[0] = (void *)malloc(nr * nc * type_size);
for(int i = 1; i < nr; i++) {
mat[i] = mat[i - 1] + nc * type_size;
}
return mat;
}
void delete_arr_2d(void **mat, int nr) {
free(mat[0]);
free(mat);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* struct.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dverbyts <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/01/19 16:31:40 by dverbyts #+# #+# */
/* Updated: 2017/01/19 16:31:42 by dverbyts ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
t_trm ft_lstnew(t_trm array, int const x[4], int const y[4], char l)
{
int z;
z = 0;
while (z < 4)
{
array.x[z] = x[z];
array.y[z] = y[z];
z++;
}
array.letter = l;
return (array);
}
void correct_cords(int *x, int *y)
{
while (x[0] != 0 && x[1] != 0 && x[2] != 0 && x[3] != 0)
{
x[0] = x[0] - 1;
x[1] = x[1] - 1;
x[2] = x[2] - 1;
x[3] = x[3] - 1;
}
while (y[0] != 0 && y[1] != 0 && y[2] != 0 && y[3] != 0)
{
y[0] = y[0] - 1;
y[1] = y[1] - 1;
y[2] = y[2] - 1;
y[3] = y[3] - 1;
}
return ;
}
t_trm read_cords(t_trm array, char *buf, char l, int z)
{
int x[4];
int y[4];
int xk;
int yk;
xk = 0;
yk = 0;
while (*buf)
{
if (*buf == '#')
{
x[z] = xk;
y[z++] = yk;
}
if (*buf++ == '\n')
{
xk = -1;
yk++;
}
xk++;
}
correct_cords(x, y);
return (ft_lstnew(array, x, y, l));
}
t_trm *make_lists(char *buf)
{
char **sors;
char letter;
int z;
t_trm *array;
if (!(array = (t_trm *)malloc(sizeof(t_trm) * (ft_strlen(buf) / 21 + 1))))
return (0);
sors = split_ttrmns(buf);
z = 0;
letter = 'A';
while (sors[z] && z < 26)
{
array[z] = read_cords(array[z], sors[z], letter, 0);
z++;
letter++;
}
map_free(sors, 0);
return (array);
}
|
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 */
/* Type definitions */
/* Variables and functions */
int ENOMEM ;
char** calloc (int,int) ;
int setpath (char**,char*) ;
char* strchr (char*,char) ;
__attribute__((used)) static int
setmultipath(char ***what, char *val)
{
char *s, *v;
int count, error, idx;
count = 0;
v = val;
do {
count++;
s = strchr(v, ',');
v = (s == NULL) ? NULL : s + 1;
} while (v != NULL);
*what = calloc(count + 1, sizeof(char *));
if (*what == NULL)
return (ENOMEM);
for (idx = 0; idx < count; idx++) {
s = strchr(val, ',');
if (s != NULL)
*s++ = '\0';
error = setpath(*what + idx, val);
if (error)
return (error);
val = s;
}
return (0);
}
|
C
|
#include <stdio.h>
#include <string.h>
union un{
int a;
int b;
char c;
};
int main(){
union un x;
x.a=-7;
printf("%d\n", a.a);
x.b=10;
printf("%d\n", x.b);
x.c='c';
printf("%c\n", x.c);
printf("\n%d %d %c", x.a, x.b, x.c);
}
|
C
|
#include <stdio.h>
void funcPrint(char *pstring);
int main(void){
funcPrint("hola mundo Cruel");
return 0;
}
void funcPrint(char *pstring){
printf("%s\n",pstring);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* exit_func.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fhuang <fhuang@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/09/15 18:39:04 by fhuang #+# #+# */
/* Updated: 2016/09/22 16:41:03 by fhuang ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_select.h"
extern int g_fd;
void exit_error(char *msg)
{
ft_putstr_fd(msg, 2);
exit(EXIT_FAILURE);
}
static int count_selected(t_elem *lst)
{
int n;
t_elem *ptr;
n = 0;
ptr = lst;
while (ptr->next != lst)
{
if (ptr->selected == 1)
n++;
ptr = ptr->next;
}
if (ptr->selected == 1)
n++;
return (n);
}
void exit_result(t_elem *lst)
{
t_elem *ptr;
int selected;
if (lst == NULL || (selected = count_selected(lst)) == 0)
return ;
ptr = lst;
while (selected && ptr->next != lst)
{
if (ptr->selected == 1)
{
selected--;
ft_putstr_fd(ptr->name, 1);
selected ? ft_putchar_fd(' ', 1) : 0;
}
ptr = ptr->next;
}
if (ptr->selected == 1)
ft_putstr_fd(ptr->name, 1);
ft_putchar_fd('\n', 1);
}
void exit_free(t_env *e)
{
t_elem *ptr;
t_elem *tmp;
if (e->lst == NULL)
return ;
ptr = e->lst;
while (ptr->next != e->lst)
{
tmp = ptr;
ptr = ptr->next;
free(tmp->name);
free(tmp);
tmp = NULL;
}
tmp = ptr;
ptr = ptr->next;
free(tmp->name);
free(tmp);
tmp = NULL;
e->list_len = 0;
}
|
C
|
/*
Tommy Frometa
tfrometa@albany.edu
*/
/*
This file has the main functionalities of the project. It handles many errors,
gets input from the user and process it, and call functions accordinly.
*/
#include "shellFunctions.h"
#include "input.h"
//(main)
int main(int argc, char* argv[]) {
//Checking for wrong number of arguments
if (argc > 2 || argc < 1) {
fprintf(stderr, wrongArgumentNumberError, argv[0]); fflush(stderr);
exit(1);
}
//Open the given file (if any).
int fd;
if ((fd = open(argv[1], O_RDONLY)) == NULL) {
fprintf(stderr, "File %s could not be opened.", argv[1]); fflush(stderr);
exit(1);
}
//Redirect stdin with the file priviously opened.
if (argc == 2) {
if (dup2(fd, STDIN_FILENO) == -1) {
fprintf(stderr, "dup2 failed."); fflush(stderr);
exit(1);
}
}
//A bunch of self explanaroty variables.
char* line;
int forkValue;
int status;
char** arguments;
arguments = malloc(5);
arguments[4] = NULL;
char* listPath = malloc(256);
char* createPath = malloc(256);
char* cwd = malloc(256);
getcwd(cwd, 257);
strcpy(listPath, cwd);
strcpy(createPath, cwd);
strcat(listPath, "/list");
strcat(createPath, "/create");
//Main finctionalities. Get input and calls other methods accordingly.
while (1) {
//Prompt user for imput and process it.
printf("command? ");
if((line = getLine(stdin, argc)) == '\0'){
printf("Tommy\n"); fflush(stdout);
break;
}
if (strcmp(line, "\n") == 0) {
continue;
}
arguments = parseLine(line);
//Call the apporpiate function with the right number of arguments.
//list
if (strcmp("list", arguments[0]) == 0) {
forkValue = fork();
if (forkValue == 0) {
execvp(listPath, arguments);
}
else {
wait(&status);
if (status != 0) {
fprintf(stderr, commandFailedError, arguments[0]); fflush(stderr);
}
}
}
//create
else if (strcmp("create", arguments[0]) == 0) {
forkValue = fork();
if (forkValue == 0) {
execvp(createPath, arguments);
}
else {
wait(&status);
if (status != 0) {
fprintf(stderr, commandFailedError, arguments[0]); fflush(stderr);
}
}
}
//wd
else if (strcmp("wd", arguments[0]) == 0) {
wd();
}
//chwd
else if (strcmp("chwd", arguments[0]) == 0) {
if (arguments[1] == NULL) {
fprintf(stderr, "No arguments passed to %s.\n", arguments[0]); fflush(stderr);
continue;
}
if (chwd(arguments[1]) != 0) {
fprintf(stderr, commandFailedError, arguments[0]); fflush(stderr);
}
}
//quit
else if (strcmp("quit", arguments[0]) == 0) {
quit();
}
//anything else.
else {
fprintf(stderr, invalidCommandError, arguments[0]); fflush(stderr);
}
printf("\n");
}
return 0;
}
|
C
|
#include "graphics.h"
#include <math.h>
int main(void) {
int i;
for (i = 0; i < 6; i++) {
drawLine(50, 50 + (i * 25), 350, 50 + (i * 25));
}
drawRect(50, 50, 300, 250);
drawRect(150, 250, 100, 100);
for (i = 0;i <5;i++){
drawLine(50+(i*60),50,50+(i*60),175);
}
drawString("CS Department",150,240);
return 0;
}
|
C
|
// Function to find 2nd min and max elements of an array
#include <stdio.h>
void maxmin(int array[20], int n)
{
int i,j,swap,position,max2,min2;
for(i=0;i<(n-1);i++)
{
position = i;
for(j=i+1; j<n ;j++) {
if(array[position]>array[j])
position = j;
}
if(position!=i)
{
swap = array[i];
array[i] = array[position];
array[position] = swap;
}
}
printf("The second minimum is=%d\nThe second maximum is=%d\n",array[1],array[n-2]);
}
void main()
{
int a[20],n,i;
printf("Enter size of an array:\n");
scanf("%d",&n);
printf("Enter array:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
maxmin(a,n);
}
|
C
|
//**************************************************************************** /
// */
// #' ,#, # # #. .`# #==, .*. + + + */
// ~~~CREATED~~~ # # # # # # # *.* # # # *._.* + */
// ~~~~~BY~~~~~~ #. .# # # # ## # # # ,# ,' ', + */
// ~<<jonmd87>>~ ### '#' # # # # #==* *.* + */
// */
//**************************************************************************** /
//
//
// Требуется содать функцию которая читает строки и прекращает чтение
// на десятой строке включительно или при появлении символа EOF,
// в зависимости от того, какое из этих событий произойдет первым.
// Функция должна предложить пользователю меню с пятью вариантами:
// 1) печать исходного списка строк
// 2) печать строк в виде упорядоченной последовательности в кодировке ASCII
// 3) печать строк в порядке возрастания их длины
// 4) печать строк в порядке возрастания длины первого слова строки
// 5) выход из программы.
// Меню должно выводиться на экран после выполнения каждой операции,
// указанной меню, пока пользователь не выберет вариант выхода из
// программы. Разумеется, программа должна выполнять все
// указанные в меню задачи.
//
//
#include <unistd.h>
#include <stdio.h>
#define NUM_OF_CH 100 // the number of charachters
#define LIMIT 10
void read_str(char **str);
void menu();
int choose_variant();
int ft_strlen(char *str, char ch);
int ft_chcmp(const char c1, const char c2);
void display(char **str);
void sort_by_ascii(char **str);
void sort_by_leight(char **str, char ch);
void ft_putstr(char *str);
void ft_putchar(char ch);
int main()
{
char arr[LIMIT][NUM_OF_CH];
char *pnt[LIMIT];
int choose;
int ind;
ind = 0;
ft_putstr("This program will displays text in select mode");
ft_putchar('\n');
while (ind < LIMIT)
{
pnt[ind] = &arr[ind];
ind++;
}
read_str(pnt);
while ((choose = choose_variant()) != 5)
{
if (choose < 5 && choose > 0)
{
switch(choose)
{
case 1:
display(pnt);
putchar('\n');
break;
case 2:
sort_by_ascii(pnt);
display(pnt);
putchar('\n');
break;
case 3:
sort_by_leight(pnt, '\n');
display(pnt);
putchar('\n');
break;
case 4:
sort_by_leight(pnt, ' ');
display(pnt);
putchar('\n');
break;
}
}
while (getchar() != '\n');
read_str(pnt);
}
if (choose == 5)
ft_putstr("GOOD BUY");
else
ft_putstr("ERROR");
return (0);
}
void read_str(char **str)
{
int i;
i = 0;
puts("please, enter some text");
while (i < LIMIT && fgets(str[i], NUM_OF_CH, stdin) != NULL && str[i][0] != '\n')
{
//del_new_str(str[i]);
i++;
}
if (i > 0)
puts("ok, lets start!\nchoose mode");
else
puts("nothing turned in");
menu();
}
void menu()
{
ft_putstr("please,select mode");
ft_putchar('\n');
ft_putstr("1) original");
ft_putstr(" ");
ft_putstr("3) order for the length of the line");
ft_putchar('\n');
ft_putstr("2) ordered by ASCII");
ft_putstr(" ");
ft_putstr("4) in order the length of the first words");
ft_putchar('\n');
ft_putstr(" ");
ft_putstr("5) exit");
ft_putchar('\n');
}
int choose_variant()
{
int select;
int rembr;
rembr = 1;
while (scanf("%i", &select) < 1 || select > 5)
{
if (rembr == 5)
{
rembr = 0;
menu();
}
else
ft_putstr("only [1] [2] [3] [4] [5]");
rembr++;
ft_putchar('\n');
}
return (select);
}
int ft_chcmp(const char c1, const char c2)
{
return (c1 - c2);
}
void display(char **str)
{
int i;
i = 0;
while (str[i] != NULL && str[i][0] != '\n')
{
ft_putstr(str[i]);
i++;
}
}
void sort_by_ascii(char **str)
{
int i;
int n;
char *temp;
i = 0;
while (str[i][0] != '\n')
{
n = i + 1;
while (str[n][0] != '\n')
{
if (ft_chcmp(str[i][0],str[n][0]) > 0)
{
temp = str[i];
str[i] = str[n];
str[n] = temp;
}
n++;
}
i++;
}
}
void sort_by_leight(char **str, char ch)
{
int i;
int n;
char *temp;
i = 0;
while (str[i][0] != '\n')
{
n = i + 1;
while (str[n][0] != '\n')
{
if (ft_strlen(str[i], ch) > ft_strlen(str[n], ch))
{
temp = str[i];
str[i] = str[n];
str[n] = temp;
}
n++;
}
i++;
}
}
void ft_putstr(char *str)
{
while (*str)
{
ft_putchar(*str);
str++;
}
}
void ft_putchar(char ch)
{
write(1, &ch, 1);
}
int ft_strlen(char *str, char ch)
{
int val;
val = 0;
while (str[val] != ch)
val++;
return (val);
}
|
C
|
/*
* Filename: preprocessor2.c
* Created Date: Sunday, June 3rd 2018, 9:37:12 am
* Author: vrushb bayas
* @description
* Accept one string and two characters replcae first charater with second character in the string
* Copyright (c) 2018 Your Company
*/
#include <stdio.h>
#include <string.h>
//function declaration
char *replace(char *, char *, char *);
//Entery point function
int main(int argc, char *argv[])
{
char *string;
char *first, *second;
char *newStr;
if (argc <= 1)
{
printf("Enter argument from command line\n");
return -1;
}
string = argv[1];
first = argv[2];
second = argv[3];
newStr = replace(string, first, second);
printf("%s\n", newStr);
return 0;
}
char *replace(char *str, char *first, char *second)
{
int i = 0;
while (str[i] != '\0')
{
if (str[i] == *first)
{
str[i] = *second;
i++;
}
i++;
}
return str;
}
|
C
|
#ifndef ROM_MANAGEMENT_H
#define ROM_MANAGEMENT_H
#include <stdint.h>
/* Size of the ROM eeprom used on a WD hard disk drive. */
#define ROM_IMAGE_SIZE 256 * 1024
#define ROM_IMAGE_BLOCK_SIZE 64 * 1024
/* Maximum number of rom block headers found at the start of a rom image. */
#define NUMBER_OF_HEADERS 9
#define FLAG_UNENCRYPTED 0x04
#define SERIALISE_LINES_PER_BLOCK 12
/*
* Structure used to describe a block of executable firmware code.
* Source:
* https://forum.hddguru.com/viewtopic.php?f=13&t=20324 - checksum
* http://forum.hddguru.com/viewtopic.php?f=13&t=20324&start=40 - structure
* http://www.onicos.com/staff/iz/formats/lzh.html - compression algorithm
* http://www.fileformat.info/format/lzh/corion.htm - compression algorithm
*/
typedef struct __attribute__((packed)) {
uint8_t block_nr; /* Number of the block in the table of block structures */
uint8_t flag; /* Compression flag */
uint8_t unk1; /* ? */
uint8_t unk2; /* ? */
uint32_t length_plus_cs; /* Length of the block plus the checksum*/
uint32_t size; /* Length of the rom block*/
uint32_t start_address; /* Offset of the block address in flash */
/* Physical addr where decompresed blocks have to be stored */
uint32_t load_address;
uint32_t execution_address; /* Execution address */
uint32_t unk3; /* ? */
uint32_t fstw_plus_cs; /* 8-bit Checksum of the block */
} rom_block;
/* Dumps the rom image from a wd hard disk drive. */
int dump_rom_image(char *hard_disk_dev_file, char *out_file);
/* Upload the rom image to a wd hard disk drive. */
int upload_rom_image(char *hard_disk_dev_file, char *in_file);
/* Unpacks a packed rom image. */
int unpack_rom_image(char *rom_image);
/* Packs a rom image based with the name specified by out_file based on
the init file specified by rom_image. */
int pack_rom_image(char *rom_image, char *out_file);
/* Replaces an instruction at memory_address with new_instruction in the rom
image specified by the rom_image init file. */
int modify_instruction(char *rom_image, uint32_t memory_adress,
uint32_t new_instruction, uint32_t instruction_byte_size);
/* Display information about the blocks found in a rom image. */
int display_rom_info(char *rom_image);
#endif
|
C
|
#include <string.h>
#include <openssl/md5.h>
#include <mpi.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define BUFF_SIZE 50 // Максимальная длина обрабатываемой строки
#define ALPH_SIZE 100
#define BENCHMARK
// #define SYNC
int alphabet_length, wanted_length;
char alphabet[ALPH_SIZE];
int thf[BUFF_SIZE]; // Индексный массив
unsigned char md5_wanted[MD5_DIGEST_LENGTH]; // Хеш искомой функции
int perm_running = 0;
#ifndef BENCHMARK
int wanted_rank;
#endif
#ifdef SYNC
int sync = 2;
#endif
int chunk;
int key_found_loc = 0;
int key_found_reduce = 0;
int commsize, rank;
// Перевод посимвольно хэш-строки 32х8 бит в хэш-код 32х4 бит
void md5str_to_md5(unsigned char dest_md5[], char* src_str)
{
if (strlen(src_str) > 31)
for(int i = 0, j = 0; i < MD5_DIGEST_LENGTH; i++, j+=2)
{
if (src_str[j] >= '0' && src_str[j] <= '9')
dest_md5[i] = (src_str[j] - 48) << 4;
else
if (src_str[j] >= 'a' && src_str[j] <= 'f')
dest_md5[i] = (src_str[j] - 87) << 4;
if (src_str[j+1] >= '0' && src_str[j+1] <= '9')
dest_md5[i] += ((src_str[j+1] - 48) << 4) >> 4;
else
if (src_str[j+1] >= 'a' && src_str[j+1] <= 'f')
dest_md5[i] += ((src_str[j+1] - 87) << 4) >> 4;
}
}
// Вывод хеша
void print(unsigned char *str) {
for (int i = 0; i < MD5_DIGEST_LENGTH; i++)
printf("%02x", str[i]);
}
// Сравниваем хеши. Нашли или нет
int compare_hash(const unsigned char *a) {
for (int i = 0; i < MD5_DIGEST_LENGTH; i++)
if (a[i] != md5_wanted[i]) return -1;
return 0;
}
short int parse_alphabet(char* str)
{
int len = strlen(str);
alphabet_length = 0;
for(int i = 0; i < len; i++)
{
if( str[i] == '-' && i && i - len + 1)
{
if(str[i+2] == ',' || str[i+2] == '\0' ) {
int temp = str[i+1] - str[i-1];
if (temp < 0) temp *= -1;
alphabet_length += temp;
i+=2;
}
else
return 1;
} else {
alphabet_length++;
}
}
alphabet[alphabet_length] = '\0';
int counter = 0;
for(int i = 0; i < len; i++)
{
if( str[i] == '-' && i && i - len + 1)
{
if(str[i+2] == ',' || str[i+2] == '\0' ) {
// a-z,A-Z
char first = str[i-1];
char last = str[i+1];
while(first < last) {
alphabet[counter++] = ++first;
}
while(first > last) {
alphabet[counter++] = --first;
}
i+=2;
}
} else {
alphabet[counter++] = str[i];
}
}
return 0;
}
unsigned short recursive_permutations(unsigned short curr_len, unsigned short leaf_reached) {
if (curr_len != wanted_length) {
unsigned short i, lb;
float chunk_resize;
if (leaf_reached)
lb = 0;
else {
chunk_resize = chunk / pow(alphabet_length, wanted_length - curr_len -1);
lb = (unsigned short)floor(rank * chunk_resize);
lb = lb % alphabet_length;
}
// if (rank == 0)
//printf("new len = %d, rank = %d, chunk = %d, resize = %f, lb = %d\n", curr_len, rank, chunk, chunk_resize, lb);
if (rank != commsize - 1)
{
for(i = lb; i < alphabet_length && perm_running < chunk; i++)
{
thf[curr_len] = i;
if (curr_len + 1 != wanted_length)
leaf_reached = recursive_permutations(curr_len + 1, leaf_reached);
else
leaf_reached = recursive_permutations(curr_len + 1, 0);
if (leaf_reached == 2) {
return 2;
}
}
} else {
for(i = lb; i < alphabet_length; i++)
{
thf[curr_len] = i;
if (curr_len + 1 != wanted_length)
leaf_reached = recursive_permutations(curr_len + 1, leaf_reached);
else
leaf_reached = recursive_permutations(curr_len + 1, 0);
if (leaf_reached == 2) {
return 2;
}
}
}
return leaf_reached;
} else {
perm_running++; //счетчик перебранных вариантов
char current_line[wanted_length + 1];
unsigned char current_key[MD5_DIGEST_LENGTH];
//Заполнение текущей строки
unsigned short i;
for (i = 0; i < wanted_length; i++) {
current_line[i] = alphabet[thf[i]];
}
current_line[i] = '\0';
// Вывод паролей одного или нескольких процессов на экран, если не используются замеры времени
#ifndef BENCHMARK
if (rank == wanted_rank)
printf("rank %3d, pwd = %s, perm = %d\n", rank, current_line, perm_running);
else if (wanted_rank < 0)
printf("rank %3d, pwd = %s, perm = %d\n", rank, current_line, perm_running);
#endif
// Хэширование новой строки символов
MD5((const unsigned char *) current_line,
strlen(current_line),
(current_key)
);
// Сравнение полученного и исходного хэшей
if (compare_hash(current_key) == 0) {
// Если коллизия:
#ifndef BENCHMARK
print(current_key);
printf(" <= collision with \"%s\", rank = %d, perm = %d / %d\n", current_line, rank, perm_running, chunk);
#else
printf("\"%s\"\n", current_line);
#endif
// Поднятие флага после первой найденой коллизии
key_found_loc = 1;
}
#ifdef SYNC
// Синхронизация потоков по номеру пермутации:
if ( !(perm_running % sync) && (perm_running < chunk) ){
MPI_Barrier(MPI_COMM_WORLD);
MPI_Allreduce(&key_found_loc, &key_found_reduce, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD );
// printf("rank = %d, perm = %d, key_found_reduce = %d, key_found_loc = %d\n", rank, perm_running, key_found_reduce, key_found_loc);
if (key_found_reduce) {
printf("Exiting process, rank %d, perm %d\n", rank, perm_running);
return 2;
}
}
#endif
}
return 1;
}
int main(int argc, char **argv) {
MPI_Init(NULL,NULL);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &commsize);
if (!rank){
printf("\nHello, human! Let's break this password! :-)\n\n");
#ifndef BENCHMARK
if (argc > 5 || argc < 4) {
printf("Format: \"Alphabet\" \"MD5 Hash\" \"Word lenght\" \"Output Rank with number N (negative to output all; none to disable)\"\n");
MPI_Abort(MPI_COMM_WORLD, 1);
} else if (argc == 4){
wanted_rank = ~(1 << 31);
} else wanted_rank = atoi(argv[4]);
#else
if (argc != 4 ) {
printf("Format: \"Alphabet\" \"MD5 Hash\" \"Word lenght\" \n");
MPI_Abort(MPI_COMM_WORLD, 1);
}
#endif
if(parse_alphabet(argv[1])) {
printf("Invalid alphabet sectioning!\
\nSection should look like this: a-z,\
\n(multiple sections in a row are allowed, commas aren't included into alphabet)\n");
MPI_Abort(MPI_COMM_WORLD, 1);
return 1;
}
md5str_to_md5(md5_wanted, argv[2]); // Нахождение 128 битного хэша по входной 256 битной строке
wanted_length = atoi(argv[3]); // Длина искомой строки
for(int i = 1; i < commsize; i++)
{
MPI_Send(&alphabet_length, 1, MPI_INT, i, 0, MPI_COMM_WORLD);
MPI_Send(alphabet, alphabet_length, MPI_CHAR, i, 0, MPI_COMM_WORLD);
MPI_Send(&md5_wanted, MD5_DIGEST_LENGTH , MPI_CHAR, i, 0, MPI_COMM_WORLD);
MPI_Send(&wanted_length, 1, MPI_INT, i, 0, MPI_COMM_WORLD);
#ifndef BENCHMARK
MPI_Send(&wanted_rank, 1, MPI_INT, i, 0, MPI_COMM_WORLD);
#endif
}
} else {
MPI_Recv(&alphabet_length, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
//printf("\nAlph len = %d", alphabet_length);
MPI_Recv(alphabet, alphabet_length, MPI_CHAR, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
MPI_Recv(&md5_wanted, MD5_DIGEST_LENGTH, MPI_CHAR, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
MPI_Recv(&wanted_length, 1, MPI_INT, 0, 0 , MPI_COMM_WORLD, MPI_STATUS_IGNORE);
#ifndef BENCHMARK
MPI_Recv(&wanted_rank, 1, MPI_INT, 0, 0 , MPI_COMM_WORLD, MPI_STATUS_IGNORE);
#endif
}
int max_wanted_length = wanted_length;
chunk = pow(alphabet_length, max_wanted_length) / commsize;
if (!rank) {
printf("Alphabet: %s, length: %d\n", alphabet, alphabet_length);
printf("md5 to bruteforce: ");
print(md5_wanted);
printf("\n");
printf("Max word length : %d\n", max_wanted_length);
printf("N processes : %d\n", commsize);
printf("Permutations expected:\n");
int total_perms = 0;
for (int i = 1; i <= max_wanted_length; i++)
{
int n = (int)pow(alphabet_length, i);
printf(" word length %-2d\n\tall : %d\n\tper process : %d\n",i, n, n / commsize);
total_perms += n;
}
printf(" Total\n\tall : %d\n\tper process : %d\n", total_perms, total_perms / commsize);
printf("Max chunk: %d\n", chunk);
#ifdef SYNC
printf("Sync each %d permutations\n", sync);
#endif
printf("\nCollisions : \n\n");
}
// Вызываем функцию перебора,
// увеличивая длину искомой строки на 1
wanted_length = 1;
int perm_sum = 0;
int rank_iter = 0; // Итератор для цикла по ранкам процессов для случая пропусков вычислений
// Работа алгоритма пропусков процессов:
// хранение номера последнего использованного процесса 'rank_iter' позволяет загружать работой
// всё новые и новые неиспользованные процессы, равномерно загружая процессы В ПРЕДЕЛАХ алгоритма пропусков.
// Количество пропущенных итераций не учитывается в других секциях программы для оптимизации загрузки процессов.
#ifdef BENCHMARK
MPI_Barrier(MPI_COMM_WORLD);
double time, time_sum;
#endif
// Основной цикл программы:
do {
#ifdef BENCHMARK
time = MPI_Wtime();
#endif
perm_running = 0;
chunk = pow(alphabet_length, wanted_length) / commsize;
if (chunk != 0) {
recursive_permutations(0,0);
} else {
// Случай пропуска вычислений процессами:
chunk = 1;
int count = 0;
int perms_curr = pow(alphabet_length, wanted_length);
while (count++ < perms_curr){
if (rank == rank_iter) recursive_permutations(0,0);
rank_iter++;
if (rank_iter == commsize) rank_iter = 0;
}
}
#ifdef BENCHMARK
time = MPI_Wtime() - time;
time_sum += time;
#endif
perm_sum += perm_running; // Суммарное количество пермутаций носит лишь информативный характер
//printf("rank = %d, PR = %d, PS = %d\n", rank, perm_running, perm_sum);
} while
#ifdef SYNC
(!key_found_reduce && (wanted_length++ < max_wanted_length));
#else
(wanted_length++ < max_wanted_length);
#endif
#ifdef BENCHMARK
printf("Execution time on process %d: %lf\n", rank, time_sum);
#endif
MPI_Allreduce(&key_found_loc, &key_found_reduce, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD );
// printf("rank = %d, perm = %d, key_found_reduce = %d, key_found_loc = %d\n", rank, perm_running, key_found_reduce, key_found_loc);
if (!rank) {
if(!key_found_reduce)
printf("\nCollisions not found\n");
printf("\nPermutations:\n");
}
MPI_Barrier(MPI_COMM_WORLD);
printf("rank %-3d : %d (last) / %d (all)\n", rank, perm_running, perm_sum );
MPI_Finalize();
return 0;
}
|
C
|
/*
* bolt.c
*
* Created: 24.02.2014 09:59:36
* Author: JanGerd
*/
#include "drivers/bolt_drv.h"
static uint8_t bolts;
void bolt_drv_init(void){
BOLTS_PxDIR |= (BOLT_1 | BOLT_2);
BOLTS_PxOUT |= (BOLT_1 | BOLT_2);
bolts = (BOLT_1 | BOLT_2);
}
void bolts_up(unsigned char boltv){
boltv &= 0x03;
bolts |= boltv;
BOLTS_PxOUT |= boltv;
}
void bolts_down(unsigned char boltv){
boltv &= 0x03;
bolts &= ~boltv;
BOLTS_PxOUT &= ~boltv;
}
void bolts_toggle(unsigned char boltv){
boltv &= 0x03;
if(boltv & BOLT_1){
bolts ^= BOLT_1;
BOLTS_PxOUT ^= BOLT_1;
}
if(boltv & BOLT_2){
bolts ^= BOLT_2;
BOLTS_PxOUT ^= BOLT_2;
}
}
uint8_t get_bolts(void){
return 0x0F & bolts;
}
|
C
|
//Thomas Sanchez
//lab9
//05-08-20
// lab9 changes: PRODUCE MIPS CODE add strings
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include "ast.h"
#include "emit.h"
char * Cur_func;
static int GLABEL = 0;
char * genlabel()
{ char s[100];
char *s1;
sprintf(s,"_L%d",GLABEL++);
s1=strdup(s); // get heap memory for the label name
return (s1);
}
//pre: ptr to string type from yacc
//post: mips code to declare a string
void EmitStrings(ASTNode * p, FILE * fp){
if(p == NULL) return;
if((p->Type == myWRITE) && (p->name != NULL))
fprintf(fp, "%s:\t .asciiz\t%s\n", p->label, p->name);
EmitStrings(p->next, fp);
EmitStrings(p->s1, fp);
EmitStrings(p->s2, fp);
}// of emit strings
//post emits mips global varibles
void EMITGLOBALS(ASTNode * p, FILE * fp){
if(p == NULL) return;
if((p->Type == VARDEC) && (p->symbol->level == 0))
fprintf(fp, "%s:\t .space\t%d\n", p->name, p->symbol->mysize*WSIZE);
EMITGLOBALS(p->next, fp);
EMITGLOBALS(p->s1, fp);
// no global vardecs through s2
}// of emit globals
//helper function to make clean mips code
//take four params and print function
//precondition given three strings
void emit(FILE *fp, char *Label, char * command, char * comment){
if(strcmp("", Label) == 0) fprintf(fp, "\t%s\t\t%s\n",command,comment);
else
fprintf(fp, "%s:%s\t\t%s\n", Label,command,comment);
}// of emit
//precondition ptr to fundec
//post code written to mips
void emit_function_head(ASTNode * p, FILE * fp){
char s[100];
emit(fp,p->name,"","#start of function");
//global function var
Cur_func = p->name;
//make stack pointer move
sprintf(s,"\n\tsubu $a0, $sp, %d \n\tsw $sp, ($a0) \n\tsw $ra, 4($a0) \n\tmove $sp, $a0",p->value*WSIZE);
emit(fp,"", s,"#adjust stack pointer\n" );
}// of emit function head
//emit identifier prepares mips code for use of arrays and scalars, both local and global
void emit_identifier(ASTNode * p, FILE *fp){
char s[100];
if(p->symbol == NULL) return;
//check if VAR is global
if(p->symbol->level == 0){
if(p->s1 != NULL){
//array
sprintf(s, "la $t0, %s", p->name);
emit(fp, "", s, "#global array");
emit_expr(p->s1, fp);
sprintf(s, "sll $a0, $a0, %d", 2*WSIZE);
emit(fp, "", s ,"");
emit(fp, "", "add $a0, $a0, $t0", "");
//more
}
else{
//global scalar
sprintf(s, "la $a0, %s", p->name);
emit(fp, "", s, "#global indentifier");
}//of else scalar
}
else{//if local
if(p->s1 != NULL){
emit_expr(p->s1, fp);
sprintf(s, "sll $a0, $a0, %d", 2*WSIZE);
emit(fp, "", s ,"");
sprintf(s, "add $a0, $a0, %d", p->symbol->offset * WSIZE );
emit(fp, "", s, "");
emit(fp, "", "add $a0, $a0, $sp", "");
}// if array
else{
//add $a0, %d
sprintf(s, "add $a0, $sp, %d", p->symbol->offset * WSIZE);
emit(fp,"", s, "#identifier is a local scalar\n\n");
}
}
//check if VAr is scalar or array
//do two more
}//of emit identifier
//Precondition a ptr yo an expression "factor defined in the yacc language
//Post: mips that set $a0 to the value of ptr
void emit_expr(ASTNode * p, FILE * fp){
char s[100];
//base case(s)
switch(p->Type){
case myNUM:
sprintf(s, "li $a0, %d", p->value);
emit(fp,"",s, "# expression is a number");
return;
break; //for reading
case VAR:
emit_identifier(p, fp);
emit(fp, "", "lw $a0, ($a0)", "#fetch value");
return;
break; //for read
exit(1);
//case CALL:
//emit_call(p,fp);
// return;
}// of switch
if(p->Type != EXPR) return;
//expression is an expr deal with recursion
//evaluate s1
emit_expr(p->s1, fp);
// store s1 in p->symbol->offset
sprintf(s, "sw $a0 %d($sp)", p->symbol->offset *WSIZE);
emit(fp,"", s , "# store into offset");
if(p->s2 != NULL){
//evaluate s2
emit_expr(p->s2, fp);
//move a0 to a1
emit(fp,"", "move $a1, $a0", "");
}// of if s2 exsists
//laod a0 with p->symbol->offset
sprintf(s, "lw $a0 %d($sp)", p->symbol->offset *WSIZE);
emit(fp, "", s, "#load a0");
//perform calculations
switch(p->operator){
case PLUS:
emit(fp, "", "add $a0, $a0, $a1", "#expr ADD");
break;
case MINUS: emit(fp, "", "sub $a0, $a0, $a1", "#expr sub");
break;
case MULT: emit(fp, "", "mult $a0 $a1", "#expr mult");
emit(fp, "", "mflo $a0", "#expr mult");
break;
case DIV: emit(fp, "", "div $a0 $a1", "#expr mult");
emit(fp, "", "mflo $a0", "#expr mult");
break;
case MYAND:
emit(fp, "", "and $a0, $a0, $a1", "# and");
break;
case MYOR:
emit(fp, "", "or $a0, $a0, $a1", "#or");
break;
case myGE: printf(" >= \n");
emit(fp,"", "sge $a0, $a0, $a1", "#set greater o reqaul to" );
break;
case myLE: printf(" <= \n");
emit(fp,"", "sle $a0, $a0, $a1", "#set less thean or eqaul to" );
break;
case myNE:
emit(fp,"", "sne $a0, $a0, $a1", "#set not eqaul to" );
break;
case myEE:
emit(fp,"", "seq $a0, $a0, $a1", "#set eqaul to ");
break;
case GT: printf(" > \n");
emit(fp,"", "sgt $a0, $a0, $a1", "#set greater than");
break;
case LT: printf(" < \n");
//emit(fp, "", "sub $a0, $a0, $a1", "#expr sub");
emit(fp,"", "slt $a0, $a0, $a1", "#set less than");
break;
case MYNOT: printf(" not \n");
emit(fp, "", "sltiu $a0, $a0 1", "#not comparison");
break;
default: printf("unknow expression operator\n");
}//of operator switch
}// of emit expression
//precondition a ptr to a while factor from yacc
//post mipps code produced to run a while do statment
void emit_while(ASTNode * p, FILE * fp){
char s[100];
char *L1, *L2;
L1 = genlabel();
L2 = genlabel();
sprintf(s, "%s", L1);
emit(fp, s, "", "#loop start" );
emit_expr(p->s1, fp);
emit(fp, "", "li $t1, 0", "");
sprintf(s, "beq $a0, $t1, %s", L2);
emit(fp, "", s, "#if not true" );
EMITAST(p->s2, fp);
fprintf(fp, "\tj %s\n", L1);
sprintf(s, "%s", L2);
emit(fp, s, "nop", "#end of if section\n");
}// of emit while
void emit_for(ASTNode * p, FILE * fp){
char s[100];
char *L1, *L2;
L1 = genlabel();
L2 = genlabel();
emit_assignment(p->s1, fp);
sprintf(s, "%s", L1);
emit(fp, s, "", "#for loop" );
emit_expr(p->s2->s1, fp);
emit(fp, "", "li $t0, 0", "");
sprintf(s, "beq $a0, $t0, %s", L2);
emit(fp, "", s, "#if not true" );
EMITAST(p->s2->s2->s2, fp);
emit_expr(p->s2->s2->s1, fp);
fprintf(fp, "\tj %s\n", L1);
sprintf(s, "%s", L2);
emit(fp, s, "nop", "#end of for section\n");
}// of for loop
void emit_if(ASTNode * p, FILE * fp){
char s[100];
char *L1, *L2;
L1 = genlabel();
L2 = genlabel();
emit_expr(p->s1, fp);
emit(fp, "", "li $t0, 0", "");
sprintf(s, "beq $a0, $t0, %s", L1);
emit(fp, "", s, "#if not true" );
EMITAST(p->s2->s1, fp);
fprintf(fp, "\tj %s\n", L2);
sprintf(s, "%s", L1);
emit(fp, s, "", "#else section" );
EMITAST(p->s2->s2, fp);
sprintf(s, "%s", L2);
emit(fp, s, "nop", "#end of if section\n");
}//emit if
//precondition a ptr to assignment statment
//post: mips code storing value into indetifier
void emit_assignment(ASTNode *p, FILE *fp){
char s[100];
emit_identifier(p->s1, fp);
sprintf(s, "sw $a0, %d($sp)", p->symbol->offset *WSIZE);
emit(fp, "", s, "");
emit_expr(p->s2, fp);
sprintf(s, "lw $t0, %d($sp)", p->symbol->offset*WSIZE);
emit(fp, "", s , "");
emit(fp, "", "sw $a0, ($t0)", "");
}// of emit assignment
//precondition p is pointer to a VAR node
//post mips code such that $a0 is the address of where VAR is in memory
void emit_write(ASTNode * p,FILE * fp){
char s[100];
if(p->s1 != NULL){
emit_expr(p->s1,fp);
emit(fp,"", "li $v0 1", "# Print the number");
emit(fp, "", "syscall", "# system call\n");
}// of if
else{
emit(fp, "", "li $v0, 4", "");
sprintf(s, "la $a0, %s", p->label);
emit(fp, "", s , "");
emit(fp, "", "syscall", "");
emit(fp,"","","");
}// of else
}// of wmit write
//pre condition: ptr to READ
//pot condition: mips code to read from user and store in identifier
void emit_read(ASTNode * p,FILE * fp){
char s[100];
emit_identifier(p->s1, fp); //a0 is the address we want to store
emit(fp, "", "li $v0, 5", "#read num from input");
emit(fp, "", "syscall", "# system call\n\n");
emit(fp,"", "sw $v0, ($a0)", "#store the read into a mem location\n\n");
//we know $v0 has value read in
}//of emit read
//emit return
//to handle explicit and implicit function returns
//precondition ptr to return or null
//post mips return code
void emit_function_return(ASTNode * p, FILE *fp){
if(p != NULL){
//eval the the expr
emit_expr(p, fp); //this leaves $a0 with the result
}// if not null
//if it is null we do nothing with a0
emit(fp, "", "lw $ra, 4($sp)", "#restore RA");
emit(fp, "", "lw $sp, ($sp)", "#restore SP\n");
if(strcmp(Cur_func,"main") == 0){
//handle main returnd
emit(fp,"", "li $v0, 10", " #leave Main program");
emit(fp, "", "syscall", "#leave main");
emit(fp, "", "sw $v0 ($a0)", "#store the REad into a mem location");
}// of if amin
else{
//jump back to ra
}// of anyother function
}// of emit return
//pre: takes an ast tree
// post: outputs in mips code in fp
//
void EMITAST(ASTNode * p, FILE * fp){
if(p == NULL) return;
switch(p->Type){
case VARDEC: //nothing needed
break;
case FUNDEC: emit_function_head(p, fp);
EMITAST(p->s2, fp); //the block
emit_function_return(NULL, fp);
break;
case CMPSTMT: EMITAST(p->s2, fp);
break;
case myWRITE:
emit_write(p, fp);
break;
case myREAD:
emit_read(p, fp);
break;
case IFTHEN:
emit_if(p, fp);
break;
case myWHILE:
emit_while(p, fp);
break;
case ASSGINSTMT:
emit(fp, "", "", "");
emit_assignment(p, fp);
break;
case FORLOOP:
emit_for(p, fp);
break;
default: printf("Emit AST type not implemented\n");
}// of switch
EMITAST(p->next,fp);
}// of emitast
|
C
|
#include<stdio.h>
int main()
{
int n,i,j;
scanf("%d",&n);
int list[n],max[n];
for(i=0;i<n;i++)
{
scanf("%d",&list[i]);
max[i]=1;
}
for(i=1;i<n;i++)
{
for(j=0;j<i;j++)
{
if(list[j]<list[i]&&max[j]>=max[i])
max[i]=max[j]+1;
}
}
j=-1;
for(i=0;i<n;i++)
{
if(max[i]>j)
j=max[i];
}
printf("%d\n",j);
}
|
C
|
#include"graph.h"
void CreateGraph(Graph *pg)
{
int i = 0, j = 0;
while (i < MAXGRAPH)
{
pg->vertices[i] = '0';
i++;
}
for (i = 0; i < MAXGRAPH; i++){
for (j = 0; j < MAXGRAPH; j++)
pg->edges[i][j] = 0;
}
pg->size = 0;
} //end function CreateGraph
void ClearGraph(Graph *pg)
{
int i = 0, j = 0;
while (i < MAXGRAPH)
{
pg->vertices[i] = '0';
i++;
}
for (i = 0; i < MAXGRAPH; i++){
for (j = 0; j < MAXGRAPH; j++)
pg->edges[i][j] = 0;
}
pg->size = 0;
} //end function ClearGraph
void ClearRelations(Graph *pg)
{
int i, j;
for (i = 0; i < MAXGRAPH; i++)
{
for (j = 0; j < MAXGRAPH; j++)
pg->edges[i][j] = 0;
}
}
void AddEdge(GraphEntry src, GraphEntry dest, Graph *pg)
{
int i, j; // i referes to the position of the src and j referes to the position of the dest in the vertices array
for (i = 0; src != pg->vertices[i]; i++); // this loop loops on the vertices arry till it finds the (src) entry
for (j = 0; dest != pg->vertices[j]; j++); // this loop loops on the vertices array till it finds the (dest) entry
pg->edges[i][j] = 1;
pg->edges[j][i] = 1;
} // end function AddEdge
void DeleteEdge(GraphEntry src, GraphEntry dest, Graph *pg)
{
int i, j; // i referes to the position of the src and j referes to the position of the dest in the vertices array
for (i = 0; src != pg->vertices[i]; i++); // this loop loops on the vertices arry till it finds the (src) entry
for (j = 0; dest != pg->vertices[j]; j++); // this loop loops on the vertices arry till it finds the (dest) entry
pg->edges[i][j] = 0;
pg->edges[j][i] = 0;
} // end function DeleteEdge
void AddVertex (GraphEntry e, Graph *g)
{
int counter;
for (counter=0; g->vertices[counter] != '0' ; counter++);
// this loop loops on the intIndex array till it finds an empty place (0 in it)
g->vertices[counter] = e; // the entry is put in an empty place in the vertices array
g->size++;
} // end function AddVertex
void DeleteVertex(GraphEntry e, Graph *g)
{ int counter;
int i;
for (counter=0; g->vertices[counter]!=e; counter++); // this loop loops on the vertices array till it finds the place with the (e) entry in it
for (i = 0; i < MAXGRAPH; i++){
DeleteEdge(g->vertices[counter], g->vertices[i], g);
} // end for loop
g->vertices[counter] = '0'; // intIndex[counter] is set to integer 0 indicating that this position in the vertices array is empty
g->size--;
} // end function DeleteVertex
int GraphSize(Graph *pg)
{
return pg->size;
} //end function GraphSize
int GraphEmpty(Graph *pg)
{
return (pg->size == 0);
} //end function GraphEmpty
int GraphFull(Graph *pg)
{
return (pg->size == MAXGRAPH);
} //end function GraphFull
void TraverseGraph(Graph *pg, void(*Visit)(GraphEntry) )
{
int i; // i counter
for(i=0; i< pg->size; i++) // this loop passes the vertices on the function
(*Visit)(pg->vertices[i]);
} //end function TraverseGraph
int VertexExists (GraphEntry e , Graph *g)
{
int flag = 0;
int counter = 0;
while (counter < g->size ) // this loop loops on the vertices array untill the given GraphEntry is found
{
if (g->vertices[counter] == e) //the given GraphEntry is checked for validity for every loop
{flag = 1;
counter++;}
else
counter++;
}
return flag;
}// end of function VertixExists
void CreateAssistant(Assistant *pa)
{
int i;
for (i = 0; i < MAXGRAPH; i++){
pa->vertexconnected[i] = '0';
pa->vertexconnected2[i] = '0';
}
pa->elementCounter = 0;
pa->elementCounter2 = 0;
} //end function CreateAssistant
|
C
|
#include<stdio.h>
#include<math.h>
#define ERROR -1
int atoi(char *astr) {
int isvalid = 1;
char c;
int i = 0;
int out = 0;
int isminus = 0;
c = astr[0];
if (c == '-') {
isminus = 1;
i++;
}
while(c = astr[i++]){
if ((c > '9') || (c < '0')) {
isvalid = 0;
break;
}
}
i = (isvalid && isminus) ? 1 : 0;
if (isvalid){
while(c = astr[i++]){
out = out * 10 + (c - '0');
}
if (isminus)
out = -out;
}
else
out = ERROR;
return out;
}
int main(){
char a[] = "-1234";
int out = atoi(a);
printf("%d\n", out);
return 0;
}
|
C
|
#ifndef MXCHARSET_H
#define MXCHARSET_H
#include "MxCommon.h"
/**
* Decodes a code point from UTF-8.
*
* Converts the first character in a UTF-8 sequence into a Unicode code point.
*
* \param str an UTF-8 bytes sequence [IN]
* \param pwc address of a location to store the code point [OUT]
*
* \return the number of bytes occupied by the decoded code point
*
* \retval (size_t)-1 not a valid UTF-8 sequence
* \retval 0 null character (i.e. str points to an empty string)
* \retval 1 (non-null) ASCII character
* \retval 2-4 non-ASCII character
*/
MXSYSTEM_API size_t mxTowc(const char *str, uint32_t */*restrict*/ pwc);
/**
* Checks UTF-8 validity.
*
* Checks whether a null-terminated string is a valid UTF-8 bytes sequence.
*
* \param str string to check
*
* \retval str the string is a valid null-terminated UTF-8 sequence
* \retval NULL the string is not an UTF-8 sequence
*/
static inline const char *IsUTF8(const char *str)
{
size_t n;
uint32_t cp;
while ((n = mxTowc(str, &cp)) != 0)
if (likely(n != (size_t)-1))
str += n;
else
return NULL;
return str;
}
/**
* Removes non-UTF-8 sequences.
*
* Replaces invalid or <i>over-long</i> UTF-8 bytes sequences within a
* null-terminated string with question marks. This is so that the string can
* be printed at least partially.
*
* \warning Do not use this were correctness is critical. use IsUTF8() and
* handle the error case instead. This function is mainly for display or debug.
*
* \note Converting from Latin-1 to UTF-8 in place is not possible (the string
* size would be increased). So it is not attempted even if it would otherwise
* be less disruptive.
*
* \retval str the string is a valid null-terminated UTF-8 sequence
* (i.e. no changes were made)
* \retval NULL the string is not an UTF-8 sequence
*/
static inline char *EnsureUTF8(char *str)
{
char *ret = str;
size_t n;
uint32_t cp;
while ((n = mxTowc(str, &cp)) != 0)
if (likely(n != (size_t)-1))
str += n;
else
{
*str++ = '?';
ret = NULL;
}
return ret;
}
/* iconv wrappers (defined in src/extras/libc.c) */
#define MX_ICONV_ERR ((size_t) -1)
typedef void * MxIconv;
MXSYSTEM_API MxIconv mxIconvOpen(const char *, const char *) MX_USED;
MXSYSTEM_API size_t mxIconv(MxIconv, const char **, size_t *, char **, size_t *) MX_USED;
MXSYSTEM_API int mxIconvClose(MxIconv);
#include <stdarg.h>
MXSYSTEM_API int utf8_vfprintf(FILE *stream, const char *fmt, va_list ap);
MXSYSTEM_API int utf8_fprintf(FILE *, const char *, ...) MX_FORMAT(2, 3);
MXSYSTEM_API char * mxStrcasestr(const char *, const char *) MX_USED;
MXSYSTEM_API char * FromCharset(const char *charset, const void *data, size_t data_size) MX_USED;
MXSYSTEM_API void * ToCharset(const char *charset, const char *in, size_t *outsize) MX_USED;
#ifdef _WIN32
static inline char *FromWide(const wchar_t *wide)
{
size_t len = WideCharToMultiByte(CP_UTF8, 0, wide, -1, NULL, 0, NULL, NULL);
if (len == 0)
return NULL;
char *out = (char *)malloc(len);
if (likely(out))
WideCharToMultiByte(CP_UTF8, 0, wide, -1, out, len, NULL, NULL);
return out;
}
static inline wchar_t *ToWide(const char *utf8)
{
int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
if (len == 0)
return NULL;
wchar_t *out = (wchar_t *)malloc(len * sizeof(wchar_t));
if (likely(out))
MultiByteToWideChar(CP_UTF8, 0, utf8, -1, out, len);
return out;
}
static inline char *ToCodePage(unsigned cp, const char *utf8)
{
wchar_t *wide = ToWide(utf8);
if (wide == NULL)
return NULL;
size_t len = WideCharToMultiByte(cp, 0, wide, -1, NULL, 0, NULL, NULL);
if (len == 0) {
free(wide);
return NULL;
}
char *out = (char *)malloc(len);
if (likely(out != NULL))
WideCharToMultiByte(cp, 0, wide, -1, out, len, NULL, NULL);
free(wide);
return out;
}
static inline char *FromCodePage(unsigned cp, const char *mb)
{
int len = MultiByteToWideChar(cp, 0, mb, -1, NULL, 0);
if (len == 0)
return NULL;
wchar_t *wide = (wchar_t *)malloc(len * sizeof(wchar_t));
if (unlikely(wide == NULL))
return NULL;
MultiByteToWideChar(cp, 0, mb, -1, wide, len);
char *utf8 = FromWide(wide);
free(wide);
return utf8;
}
static inline char *FromANSI(const char *ansi)
{
return FromCodePage(GetACP(), ansi);
}
static inline char *ToANSI(const char *utf8)
{
return ToCodePage(GetACP(), utf8);
}
# ifdef UNICODE
# define FromT FromWide
# define ToT ToWide
# else
# define FromT FromANSI
# define ToT ToANSI
# endif
# define FromLocale FromANSI
# define ToLocale ToANSI
# define LocaleFree(s) free((char *)(s))
# define FromLocaleDup FromANSI
# define ToLocaleDup ToANSI
#elif defined(__OS2__)
static inline char *FromLocale(const char *locale)
{
return locale ? FromCharset((char *)"", locale, strlen(locale)) : NULL;
}
static inline char *ToLocale(const char *utf8)
{
size_t outsize;
return utf8 ? (char *)ToCharset("", utf8, &outsize) : NULL;
}
static inline void LocaleFree(const char *str)
{
free((char *)str);
}
static inline char *FromLocaleDup(const char *locale)
{
return FromCharset("", locale, strlen(locale));
}
static inline char *ToLocaleDup(const char *utf8)
{
size_t outsize;
return (char *)ToCharset("", utf8, &outsize);
}
#else
# define FromLocale(l) (l)
# define ToLocale(u) (u)
# define LocaleFree(s) ((void)(s))
# define FromLocaleDup strdup
# define ToLocaleDup strdup
#endif
/**
* Converts a nul-terminated string from ISO-8859-1 to UTF-8.
*/
static inline char *FromLatin1(const char *latin)
{
char *str = (char *)malloc(2 * strlen(latin) + 1), *utf8 = str;
unsigned char c;
if (str == NULL)
return NULL;
while ((c = *(latin++)) != '\0')
{
if (c >= 0x80)
{
*(utf8++) = 0xC0 | (c >> 6);
*(utf8++) = 0x80 | (c & 0x3F);
}
else
*(utf8++) = c;
}
*(utf8++) = '\0';
utf8 = (char *)realloc(str, utf8 - str);
return utf8 ? utf8 : str;
}
/** @} */
MXSYSTEM_API double us_strtod(const char *, char **) MX_USED;
MXSYSTEM_API float us_strtof(const char *, char **) MX_USED;
MXSYSTEM_API double us_atof(const char *) MX_USED;
MXSYSTEM_API int us_vasprintf(char **, const char *, va_list);
MXSYSTEM_API int us_asprintf(char **, const char *, ...) MX_USED;
#endif
|
C
|
#pragma once
#include <type/size_t.h>
extern size_t strlen(const char* str);
extern char *strcpy(char *s1, const char *s2);
extern int strcmp(char* str1, char* str2);
extern char * strcat(char *dst, const char * src);
extern void* memcpy(void *dst, const void *src, size_t count);
extern void* memset(void *dst, char val, size_t count);
extern unsigned short* memsetw(unsigned short *dst, unsigned short val, size_t count);
|
C
|
/*
* Garrett Low
* basic window - practice raylib
*/
#include "raylib.h"
int main(void) {
const int width = 800;
const int height = 450;
InitWindow(width, height, "GRL - basic window");
SetTargetFPS(60);
while (!WindowShouldClose()) {
BeginDrawing();
ClearBackground(RAYWHITE);
DrawText("Hello World", 190, 200, 20, LIGHTGRAY);
EndDrawing();
}
CloseWindow();
return 0;
}
|
C
|
#include "definitions.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "read_files.h"
#include "profiles.h"
#include "exit_program.h"
#include <string.h>
#include "login.h"
#include "forgot_password.h"
#include "new_acc.h"
#include <conio.h>
#include "definitions_2.h"
#include "commands.h"
#include "read_files_2.h"
void read_asterkis(char * target, int length)
{
char c;
int i;
for(i=0; i<length; i++)
{
c=getch();
if(c=='\n')
{
putch(c);
break;
}
putch('*');
target[i]=c;
}
target[i] = '\0';
}
void print_sep()
{
printf("\n\n===============================================================================\n\n");
}
void print_commands()
{
printf("\"profile\" - show your profile\n");
printf("\"status\" - update your current status\n");
printf("\"checkStatus <friend_username>\" - check the current status of a specific friend whom username is entered in the place of <friend_username>\n");
printf("\"checkRequests\" - check incoming friend requests.\n");
printf("\"printFriends\" - print the list of your friends(usernames)\n");
printf("\"search\" - search SocioPath network for a username\n");
printf("\"request <username>\" - send a friend request to a given username\n");
printf("\"unfriend <friend_username>\" - unfriend the entered friend\n");
printf("\"printNetowrk\" - print your social netowrk\n");
printf("\"#\" - log out and return to the first App screen\n");
printf("\"$\" - exit the app\n");
}
void logged_in(Account * acc_head, Profile ** prof_Array, int arr_len, Profile * current_user)
{
char command[65];//Should be enough
printf("Hello %s, Welcome to your profile!\n", current_user->username);
profile(acc_head, prof_Array, current_user, arr_len);
Command:printf("\nWhat would you like to do next?\n");
print_commands();
printf("Input:");
scanf ("%[^\n]%*c", command);
//command[65] = '\0';//In case someone tries to outsmart the system EXCEPTION
if(strcmp(command,"#")==0)
return;
read_commands(acc_head, prof_Array, current_user, command, arr_len);
goto Command;
}
void new_account(Account ** acc_head, Profile *** Array,int *arr_len)//Needs diet, THIS FUNCTION NEED TO CREATE NEW PROFILE FOR THE ACCOUNT
{
Profile * new_p;
Account * new_acc;
char username[51];
char Answer[513];
char password[9];
char password_2[9];
int RanNum;
printf("Hello dear guest\n");
printf("Please choose a username\n");
User:printf("Input:");
scanf ("%[^\n]%*c", username);
if(is_username_valid(username)==0)
{
printf("\nInvalid username, Try again\n");
goto User;
}
if(find_username(username, *acc_head)!=NULL)
{
printf("\nWe are truly sorry, but the username you chose is already taken\nPlease choose other\n");
goto User;
}
printf("\nHello %s\n", username);
printf("Please type a password\n");
Pass:printf("Input:");
read_asterkis(password, 8);
if(pass_valid(password)==0)
{
printf("\nInvalid password, Try again\n\n");
goto Pass;
}
if(strlen(password)!=8)
{
printf("\nThe length of a password must be 8 chars, Try again\n");
goto Pass;
}
printf("\n\nPlease type the password again\n");
printf("Input:");
read_asterkis(password_2, 8);
if(strcmp(password, password_2)!=0)
{
printf("\nThe password do not match, Type a new password\n");
goto Pass;
}
printf("\n\nQuestion:When did you perform your last air guitar jam?\n");
Question:printf("Input:");
scanf ("%[^\n]%*c", Answer);
if(is_ans_valid(Answer)==0)
{
printf("\nInvalid answer, only letters digits and spaces, try again\n");
goto Question;
}
new_acc = new_account_node(username, password, Answer);
add_account(acc_head, new_acc);
new_p = new_profile(username);
add_profile(new_p, Array, arr_len);
printf("The procedure was successful, thank you for choosing SocioPath");
print_sep();
}
void forgot_password(Account * acc_head, Account * user, Profile ** prof_Array, int arr_len)//add profile because get_out updates profile too
{
char answer[201];
char password[9];
int tries;
tries = 3;
while(tries>0)
{
printf("Please anwer the following question, you have %d chances\n", tries);
printf("\nQuestion:When did you perform your last air guitar jam?\nInput:");
//fgets(answer, 200, stdin);
scanf ("%[^\n]%*c", answer);
if (strcmp(answer, "$") == 0)
get_out(acc_head, prof_Array, arr_len);//prof_head
else if((strcmp(answer, "#") == 0))
{
print_sep();
return ;
}
if(compare_ans(user, answer))
{
printf("Correct, Hello %s\n", user->Username);
TryAgain:printf("Type your new password\nInput:");
//fgets(password, 8, stdin);
scanf ("%[^\n]%*c", password);
if(strlen(password)!=8 || pass_valid(password)==0 )
{
printf("\nInvalid password try again\n");
goto TryAgain;
}
change_pass(user, password);
printf("Your password was successfuly changed");
return;
}
printf("Wrong answer\n");
tries--;
}
printf("You only had 3 chances goodbye");
get_out(acc_head,prof_Array, arr_len);
}
void wrong_password(Account * acc_head, Account * user, Profile ** prof_Array, int arr_len) //NEEDS TO SEND PROFILE TO LOGGED_IN
{
char input[10];
printf("\nIncorrect password\n");
Incorrect: printf("Please type the password again, Or:\ntype # for the main men\ntype $ to exit SocioPath\ntype ! if you forgot your password\nInput: ");
//fgets(input, 10, stdin);
scanf ("%[^\n]%*c", input);
if (strcmp(input, "$") == 0)
get_out(acc_head, prof_Array,arr_len);//prof_head
else if((strcmp(input, "#") == 0))
{
return;
}
else if((strcmp(input, "!") == 0))
{
forgot_password(acc_head, user, prof_Array, arr_len);//add
return;
}
if(compare_password(user, input))
{ print_sep();
logged_in(acc_head, prof_Array, arr_len, find_profile(user->Username, prof_Array, arr_len));
return;
}
else
{
printf("Incorrect\n\n");
goto Incorrect;
}
}
void login(Account * acc_head, Profile ** prof_Array, int arr_len)//NEEDS TO SEND PROFILE TO LOGGED_IN
{
char input[100];// should be enough;
Account * user;
char * helper;
int user_found, pass_corrent;
printf("Please enter your username and password and in the format username::password\n");
printf("to go back to the first screen: #\nTo exit the program:$\n\n");
Input:printf("Input:");
//fgets(input, 100, stdin);
scanf ("%[^\n]%*c", input);
if (strcmp(input, "$") == 0)
get_out(acc_head, prof_Array, arr_len);
else if((strcmp(input, "#") == 0))
{
print_sep();
return;
}
else
{
helper = separation(input);
if(helper==NULL)//If something wrong with the input
{
printf("Error:Wrong format try again\n");
goto Input;
}
else//everything ok
{
*helper = '\0';
user = find_username(input, acc_head);
if(user!=NULL)//User found
{
if(compare_password(user, helper+2))//If pass correct
{
print_sep();
logged_in(acc_head, prof_Array, arr_len, find_profile(user->Username, prof_Array, arr_len));
print_sep();
return;
}
else
{ //Pass incorrect
wrong_password(acc_head, user, prof_Array, arr_len );
print_sep();
return;
}
}
else//User was not found
{
printf("There is no such user");
print_sep();
return;
}
}
}
}
void main_menu(Account * acc_head, Profile ** prof_Array, int arr_len)//needs to update each get_out and send profile array to new account and login
{
FILE * fp;
char option;
Enter: printf("Hello dear guest and welcome to SocioPath\n");
printf("What would you like to do next\n1.Login\n2.Create new account\n3. Exit\n");
Input:printf("Input :");
option = getch();
switch (option)
{
case '1': //login
print_sep();
login(acc_head,prof_Array,arr_len );//prof_array
fp = fopen("profile.txt", "w");
if (fp==NULL)
{
printf("Error");
return;
}
write_prof(prof_Array, fp, arr_len);
fclose(fp);
goto Enter;
case '2':
print_sep();
new_account(&acc_head, &prof_Array,&arr_len );//prof_array
goto Enter;
case '3':
get_out(acc_head, prof_Array,arr_len);////prof_array
default:
printf("Invalid input, try again\n");
goto Input;
}
}
int main()//needs to load profile.txt
{
Account * acc_head=NULL;
Profile ** prof_Array=NULL;
FILE * fp;
char c;
int arr_len=0;
fp = fopen("validation.txt", "r");
if (fp==NULL)
{
printf("Error");
return 0;
}
if((c=fgetc(fp))!=-1)
{
rewind(fp);
read_validation(fp, &acc_head);
}
fclose(fp);
fp = fopen("profile.txt", "r");//
if (fp==NULL)
{
printf("Error");
return 0;
}
if((c=fgetc(fp))!=-1)//
{
rewind(fp);
arr_len=read_profiles(fp, &prof_Array);
}
fclose(fp);
fclose(fp);
main_menu(acc_head, prof_Array, arr_len);
return 0;
}
|
C
|
struct foo1
{
struct bar1
{
int x;
};
int y;
};
union foo2
{
struct bar2
{
int x;
};
int y;
};
int main()
{
struct foo1 s;
union foo2 u;
s.y=1;
s.x=2;
u.y=1;
u.x=2;
return 0;
}
|
C
|
#include <stdio.h>
void main()
{
int n, temp;
printf("Usage of continue statement : ");
scanf("%d %d", &n, &temp);
for(int i = 0; i< n; i++) {
if (i == temp) continue;
printf("%d ", i);
}
printf("\n");
printf("Usage of break statement : ");
scanf("%d %d", &n, &temp);
for(int i = 0; i< n; i++) {
if (i == temp) break;
printf("%d ", i);
}
printf("\n");
printf("Usage of goto statement : ");
scanf("%d %d", &n, &temp);
for(int i = 0; i< n; i++) {
if (i == temp) goto label;
printf("%d ", i);
}
printf("\n");
label : printf("Loop break at %d", temp);
printf("\n");
}
|
C
|
#ifndef _COORD_H_
#define _COORD_H_
#include <stdio.h>
#include <unistd.h>
/*
* Definitions des constantes
*/
#define COORD_VIDE coord_vide()
/*
* Definition des structures
*/
typedef struct coord_s
{
int x ; /* abscisse case : # colonne */
int y ; /* ordonnee case : # ligne */
off_t pos ; /* position dans le fichier */
} coord_t ;
extern coord_t coord_vide() ;
/*
* Primitives de coord
*/
extern int coord_x_get( const coord_t coord ) ;
extern int coord_x_set( coord_t * const coord , const int x ) ;
extern int coord_y_get( const coord_t coord ) ;
extern int coord_y_set( coord_t * const coord , const int y ) ;
extern off_t coord_pos_get( const coord_t coord ) ;
extern int coord_pos_set( coord_t * const coord , const off_t pos ) ;
extern int coord_set( coord_t * const coord ,
const int x ,
const int y ,
const off_t pos ) ;
/*
* Affichage d'une coord
*/
extern void coord_printf( const coord_t coord );
/* Ecriture dans un fichier */
extern int coord_write( const int fd , /* Descripteur fichier */
const coord_t * const coord ) ;
#endif
|
C
|
#include <stdio.h>
int main(){
int i;
int sum=0;
for(i=1;i<=100;i+=2){
sum+=i;
}
//printf("%d\n",(1+99)*50/2);
printf("%d\n",sum);
return 0;
}
|
C
|
/*
** resources.c for in /Bomberman/bourda_j
**
** Made by BOURDALE Jules
** Login <bourda_j@etna-alternance.net>
**
*/
#include "./resources.h"
/**
* @brief Set the resource root dir to automatic load all the resources
*
* @warning Supported only on POSIX OS (MacOS / Linux)
*
* @note This must be called before EGB_Init()
*
* @param dirname The resources root dirname
*
* @return status Return 0 if the dirname is valid and availible, overwise return 1
*/
int EGB_Set_Resources_RootDir(char *dirname)
{
#ifdef _WIN32
log_error("[RESOURCES] Resources dir scan are not supported on Windows yet.");
return 1;
#endif
struct stat sb;
if (stat(dirname, &sb) == 0 && S_ISDIR(sb.st_mode)) {
log_debug("RESOURCES DIR OK");
EGB_ResourcesManager(EGB_Resources_Manager_Set_Dir, dirname);
return 0;
}
log_error("[RESOURCES] Unable to open resources dir (%s)", dirname);
return 1;
}
/**
* @brief Set the fontsize for a resource. Only availible for Font files
*
* @param resource_path The font resource path
* @param size font size
*
* @return status 0 = OK, 1 = KO
*/
int EGB_Resource_SetFontSize(char *resource_path, int size)
{
log_debug("resource path : %s, size : %d", resource_path, size);
return 1;
}
/**
* @brief Return the SDL resource (SDL_Texture, TTF_Font...) associated to the resource path
*
* @note For a root dir `./resources/` and a file `./resources/myImg.png`,
* the resource_path will be `myImg.png`
*
* @param resource_path The resource path
*
* @return A generic pointer on your ressource
*/
void *EGB_Get_Resource(const char* resource_path)
{
EGB_Resource_List *manager;
EGB_Resource *resources_iterator;
manager = EGB_ResourcesManager(EGB_Manager_Retrieve);
resources_iterator = manager->first;
while (resources_iterator && strcmp(resources_iterator->resource_path, resource_path) != 0) {
resources_iterator = resources_iterator->next;
}
if (resources_iterator) {
return resources_iterator->resource;
}
return NULL;
}
|
C
|
#include <unistd.h>
int ft_putchar(char c)
{
write(1, &c, 1);
return 0;
}
void ft_print_alphabet()
{
int i = 0;
char alphabet[] = "zyxwvutsrqponmlkjihgfedcba";
while (alphabet[i] != '\0')
{
char x = alphabet[i];
ft_putchar(x);
++i;
}
}
int main()
{
ft_print_alphabet();
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int n,i,m;
printf("Enter the number\n");
scanf("%d",&n);
while(n!=0)
{
m=n%10;
n=n/10;
if(m%2!=0)
printf("%d",m);
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct Node
{
struct Node *left,*right;
int num;
};
struct Node *start;
struct stackNode
{
struct Node *ptr;
struct stackNode *next;
};
struct stackNode *stackStart;
void push(struct Node *elem)
{
struct stackNode *t;
t=(struct stackNode *)malloc(sizeof(struct stackNode));
t->ptr=elem;
t->next=stackStart;
stackStart=t;
}
struct Node * pop()
{
struct stackNode *t;
struct Node *elem;
t=stackStart;
elem=t->ptr;
stackStart=stackStart->next;
free(t);
return elem;
}
int isEmpty()
{
return stackStart==NULL; // if stackStart==NULL it will return true else it will return false
}
int insert(int num)
{
struct Node *t,*j;
if(start==NULL)
{
t=(struct Node *)malloc(sizeof(struct Node));
t->num=num;
t->left=NULL;
t->right=NULL;
start=t;
return 1;
}
j=start;
while(1)
{
if(num==j->num) return 0;
if(num<j->num)
{
if(j->left==NULL)
{
t=(struct Node *)malloc(sizeof(struct Node));
t->num=num;
t->right=NULL;
t->left=NULL;
j->left=t;
break;
}
else
{
j=j->left;
}
}
else
{
if(j->right==NULL)
{
t=(struct Node *)malloc(sizeof(struct Node));
t->num=num;
t->left=NULL;
t->right=NULL;
j->right=t;
break;
}
else
{
j=j->right;
}
}
}
return 1;
}
void traverseInorderWithoutRecursion()
{
struct Node *t,*j;
if(start==NULL)
{
printf("No elements in BST");
return;
}
else
{
for(j=start;j!=NULL;j=j->left) push(j);
while(!isEmpty()) // loop will execute until stack is not empty
{
t=pop();
printf("%d\n",t->num);
if(t->right!=NULL)
{
for(j=t->right;j!=NULL;j=j->left) push(j);
}
}
}
}
int main()
{
int ch,success,data;
start=NULL;
while(1)
{
printf("1. Insert number into BST\n");
printf("2. Inorder traversal of BST\n");
printf("3. Exit\n");
printf("Enter your choice:");
scanf("%d",&ch);
if(ch==1)
{
printf("Enter data to insert:");
scanf("%d",&data);
success=insert(data);
if(success==0) printf("Cannot insert in BST data already exist\n");
else printf("%d inserted in BST",data);
}
if(ch==2)
{
traverseInorderWithoutRecursion();
}
if(ch==3) break;
}
return 0;
}
|
C
|
#include <syslog.h>
#include <sys/resource.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/sysinfo.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <time.h>
#define MB 1024*1024
#include <stdio.h>
#include <stddef.h>
/* a ub4 is an unsigned 4-byte quantity */
typedef unsigned long int ub4;
/* external results */
ub4 randrsl[256], randcnt;
/* internal state */
static ub4 mm[256];
static ub4 aa = 0, bb = 0, cc = 0;
void isaac()
{
register ub4 i, x, y;
cc = cc + 1; /* cc just gets incremented once per 256 results */
bb = bb + cc; /* then combined with bb */
for (i = 0; i < 256; ++i)
{
x = mm[i];
switch (i % 4)
{
case 0: aa = aa ^ (aa << 13); break;
case 1: aa = aa ^ (aa >> 6); break;
case 2: aa = aa ^ (aa << 2); break;
case 3: aa = aa ^ (aa >> 16); break;
}
aa = mm[(i + 128) % 256] + aa;
mm[i] = y = mm[(x >> 2) % 256] + aa + bb;
randrsl[i] = bb = mm[(y >> 10) % 256] + x;
/* Note that bits 2..9 are chosen from x but 10..17 are chosen
from y. The only important thing here is that 2..9 and 10..17
don't overlap. 2..9 and 10..17 were then chosen for speed in
the optimized version (rand.c) */
/* See http://burtleburtle.net/bob/rand/isaac.html
for further explanations and analysis. */
}
}
/* if (flag!=0), then use the contents of randrsl[] to initialize mm[]. */
#define mix(a,b,c,d,e,f,g,h) \
{ \
a^=b<<11; d+=a; b+=c; \
b^=c>>2; e+=b; c+=d; \
c^=d<<8; f+=c; d+=e; \
d^=e>>16; g+=d; e+=f; \
e^=f<<10; h+=e; f+=g; \
f^=g>>4; a+=f; g+=h; \
g^=h<<8; b+=g; h+=a; \
h^=a>>9; c+=h; a+=b; \
}
void randinit(flag)
int flag;
{
int i;
ub4 a, b, c, d, e, f, g, h;
aa = bb = cc = 0;
a = b = c = d = e = f = g = h = 0x9e3779b9; /* the golden ratio */
for (i = 0; i < 4; ++i) /* scramble it */
{
mix(a, b, c, d, e, f, g, h);
}
for (i = 0; i < 256; i += 8) /* fill in mm[] with messy stuff */
{
if (flag) /* use all the information in the seed */
{
a += randrsl[i]; b += randrsl[i + 1]; c += randrsl[i + 2]; d += randrsl[i + 3];
e += randrsl[i + 4]; f += randrsl[i + 5]; g += randrsl[i + 6]; h += randrsl[i + 7];
}
mix(a, b, c, d, e, f, g, h);
mm[i] = a; mm[i + 1] = b; mm[i + 2] = c; mm[i + 3] = d;
mm[i + 4] = e; mm[i + 5] = f; mm[i + 6] = g; mm[i + 7] = h;
}
if (flag)
{ /* do a second pass to make all of the seed affect all of mm */
for (i = 0; i < 256; i += 8)
{
a += mm[i]; b += mm[i + 1]; c += mm[i + 2]; d += mm[i + 3];
e += mm[i + 4]; f += mm[i + 5]; g += mm[i + 6]; h += mm[i + 7];
mix(a, b, c, d, e, f, g, h);
mm[i] = a; mm[i + 1] = b; mm[i + 2] = c; mm[i + 3] = d;
mm[i + 4] = e; mm[i + 5] = f; mm[i + 6] = g; mm[i + 7] = h;
}
}
isaac(); /* fill in the first set of results */
randcnt = 256; /* prepare to use the first set of results */
}
void sig_handler(int signo)
{
if(signo == SIGTERM)
{
syslog(LOG_INFO, "SIGTERM has been caught! Exiting...");
if(remove("run/daemon.pid") != 0)
{
syslog(LOG_ERR, "Failed to remove the pid file. Error number is %d", errno);
exit(1);
}
exit(0);
}
}
void handle_signals()
{
if(signal(SIGTERM, sig_handler) == SIG_ERR)
{
syslog(LOG_ERR, "Error! Can't catch SIGTERM");
exit(1);
}
}
void daemonise()
{
pid_t pid, sid;
FILE *pid_fp;
syslog(LOG_INFO, "Starting daemonisation.");
//First fork
pid = fork();
if(pid < 0)
{
syslog(LOG_ERR, "Error occured in the first fork while daemonising. Error number is %d", errno);
exit(1);
}
if(pid > 0)
{
syslog(LOG_INFO, "First fork successful (Parent)");
exit(0);
}
syslog(LOG_INFO, "First fork successful (Child)");
//Create a new session
sid = setsid();
if(sid < 0)
{
syslog(LOG_ERR, "Error occured in making a new session while daemonising. Error number is %d", errno);
exit(1);
}
syslog(LOG_INFO, "New session was created successfuly!");
//Second fork
pid = fork();
if(pid < 0)
{
syslog(LOG_ERR, "Error occured in the second fork while daemonising. Error number is %d", errno);
exit(1);
}
if(pid > 0)
{
syslog(LOG_INFO, "Second fork successful (Parent)");
exit(0);
}
syslog(LOG_INFO, "Second fork successful (Child)");
pid = getpid();
//Change working directory to Home directory
if(chdir(getenv("HOME")) == -1)
{
syslog(LOG_ERR, "Failed to change working directory while daemonising. Error number is %d", errno);
exit(1);
}
//Grant all permisions for all files and directories created by the daemon
umask(0);
//Redirect std IO
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
if(open("/dev/null",O_RDONLY) == -1)
{
syslog(LOG_ERR, "Failed to reopen stdin while daemonising. Error number is %d", errno);
exit(1);
}
if(open("/dev/null",O_WRONLY) == -1)
{
syslog(LOG_ERR, "Failed to reopen stdout while daemonising. Error number is %d", errno);
exit(1);
}
if(open("/dev/null",O_RDWR) == -1)
{
syslog(LOG_ERR, "Failed to reopen stderr while daemonising. Error number is %d", errno);
exit(1);
}
//Create a pid file
mkdir("run/", 0777);
pid_fp = fopen("run/daemon.pid", "w");
if(pid_fp == NULL)
{
syslog(LOG_ERR, "Failed to create a pid file while daemonising. Error number is %d", errno);
exit(1);
}
if(fprintf(pid_fp, "%d\n", pid) < 0)
{
syslog(LOG_ERR, "Failed to write pid to pid file while daemonising. Error number is %d, trying to remove file", errno);
fclose(pid_fp);
if(remove("run/daemon.pid") != 0)
{
syslog(LOG_ERR, "Failed to remove pid file. Error number is %d", errno);
}
exit(1);
}
fclose(pid_fp);
}
int sizeOfFile(FILE *buffer)
{
int size, curPos;
curPos = ftell(buffer);
fseek(buffer, 0, SEEK_END);
size = ftell(buffer);
fseek(buffer, curPos, SEEK_SET);
return size;
}
void rndgnt()
{
ub4 i, j;
aa = bb = cc = (ub4)0;
for (i = 0; i < 256; ++i) mm[i] = randrsl[i] = (ub4)0;
randinit(1);
for (i = 0; i < 2; ++i)
{
isaac();
}
}
void fillData(int size, FILE *buffer)
{
syslog(LOG_INFO, "fillData()");
struct sysinfo sys_info;
time_t rawtime;
int k = 0, num = 0;
ub4 j;
while (sizeOfFile(buffer) < size)
{
rndgnt();
sysinfo(&sys_info);
for(j = 0; j < 256; ++j)
{
time(&rawtime);
ub4 result = randrsl[j] ^ rawtime ^ sys_info.freeram ^ sys_info.bufferram ^ sys_info.freeswap;
fwrite(&result,sizeof(ub4),1,buffer);
}
//fwrite(&num, sizeof(int), 1, buffer);
}
}
// сделать функцию для подсчета размера
void randomize()
{
FILE *buffer;
int size;
syslog(LOG_INFO, "random");
chdir(getenv("HOME"));
if(mkdir("random", S_IRWXU | S_IRWXG | S_IRWXO))
{
syslog(LOG_INFO, "dir is already create");
}
if((buffer = fopen("random/buffer", "r")) == NULL)
{
syslog(LOG_INFO, "not exist buffer file, create new file");
buffer = fopen("random/buffer", "a");
size = sizeOfFile(buffer);
syslog(LOG_INFO, "size of empty file is %i byte", size);
fillData(5*1024*1024, buffer);
}
else
{
syslog(LOG_INFO, "exist buffer file");
buffer = fopen("random/buffer", "a");
//fseek(buffer, 0 , SEEK_END);
//size = ftell(buffer);
size = sizeOfFile(buffer);
syslog(LOG_INFO, "size is %i", size);
if (size < 5*1024*1024)
{
fillData(5 * 1024*1024, buffer);
syslog(LOG_INFO, "size is less than 5 mb");
}
else
{
syslog(LOG_INFO, "size is more than 5 mb, do nothing");
//do nothing
}
fclose(buffer);
}
}
int main(int argc,char *argv[])
{
pid_t pid;
int fd, len;
FILE *pid_fp;
char pid_buf[16];
if (argc == 2)
{
//syslog(LOG_INFO, "2 arg");
if(!strcmp(argv[1], "start"))
{
//syslog(LOG_INFO, "start");
chdir(getenv("HOME"));
if((pid_fp = fopen("run/daemon.pid", "r")) == NULL)
{
//syslog(LOG_INFO, "create daemon.pid");
daemonise();
handle_signals();
}
else
{
//syslog(LOG_INFO, "daemon.pid is exist");
fclose(pid_fp);
exit(0);
}
}
if(!strcmp(argv[1], "stop"))
{
//syslog(LOG_INFO, "Stop");
chdir(getenv("HOME"));
if((pid_fp = fopen("run/daemon.pid", "r")) == NULL)
{
//syslog(LOG_INFO, "already killed");
exit(0);
}
else
{
//syslog(LOG_INFO, "find pid");
fscanf(pid_fp, "%i", &pid);
//len = read(fd, pid_buf, 16);
//pid_buf[len] = 0;
//pid = atoi(pid_buf);
//syslog(LOG_INFO, "pid is %i", pid );
kill(pid, SIGTERM);
fclose(pid_fp);
exit(0);
}
}
}
else
{
exit(0);
}
while(1)
{
randomize();
sleep(5);
}
return 0;
}
|
C
|
#include <stdio.h>
int main(void)
{
double heading;
printf("Enter a compass heading (0.0-360.0 degree)> ");
scanf("%lf",&heading);
if (heading<0.0)
printf("Error--negative heading (%.1f): must be between 0 and 360\n",heading);
else if (heading<90.0)
printf("The bearing is north %.1f degrees east\n",heading);
else if (heading<180.0)
printf("The bearing is north %.1f degrees west\n",180.0-heading);
else if (heading<270.0)
printf("The bearing is south %.1f degrees west\n",heading-180.0);
else if (heading<=360.0)
printf("The bearing is south %.1f degrees east\n",360.0-heading);
else
printf("Error--heading > 360 (%.1f): must be between 0 and 360\n",heading);
return 0;
}
|
C
|
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sqlite3.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <stdint.h>
#include "terminal-code.h"
#include "db.h"
int init_tty(int fd);
/**
* Run this program and pass the location of the serial file descriptor as an argument
* On linux, this is likely /dev/ttyACM0
* On OSX, this may be similar to /dev/cu.usbmodem1D1131
*/
int main(int argc, char **argv) {
/*
* Read the device path from input,
* or default to /dev/ttyACM0
*/
if (argc == 2) {
device = argv[1];
} else {
device = "/dev/tty.usbmodem1411";
}
printf("Connecting to %s\n", device);
/*
* Need the following flags to open:
* O_RDWR: to read from/write to the devices
* O_NOCTTY: Do not become the process's controlling terminal
* O_NDELAY: Open the resource in nonblocking mode
*/
printf("fd\n");
fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
perror("Error opening serial");
return -1;
}
printf("config\n");
/* Configure settings on the serial port */
if (init_tty(fd) == -1) {
perror("init");
close(fd);
return -1;
}
printf("flush\n");
/* Flush whatever is remaining in the buffer */
tcflush(fd, TCIFLUSH);
get_date();
/*int pid = fork();
if (pid < 0){ // error
perror("Error forking process...quitting!\n");
return -1;
}
if (pid == 0){
printf("Child\n");
child_work();
//Prints when child process has exited
printf("Aborting child\n");
}else{
printf("Parent\n");
child_pid = pid;
parent_work();
//Prints when parent process has exited
printf("Leaving parent\n");
}*/
printf("Program is done!\n");
parent_work();
close(hist_fd);
close(fd);
return -1;
}
int mmap_file(){
const char *text = "0";
/* Open a file for writing.
* - Creating the file if it doesn't exist.
* - Truncating it to 0 size if it already exists. (not really needed)
*
* Note: "O_WRONLY" mode is not sufficient when mmaping.
*/
const char *filepath = "histogramiscool";
hist_fd = open(filepath, O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600);
if (hist_fd == -1){
perror("Error opening file for writing");
exit(EXIT_FAILURE);
}
//Stretch the file size to the size of the (mmapped) array of char
size_t textsize = strlen(text) + 1; // + \0 null character
if (lseek(hist_fd, textsize-1, SEEK_SET) == -1){
close(hist_fd);
perror("Error calling lseek() to 'stretch' the file");
exit(EXIT_FAILURE);
}
if (write(hist_fd, "", 1) == -1){
close(hist_fd);
perror("Error writing last byte of the file");
exit(EXIT_FAILURE);
}
// Now the file is ready to be mmapped.
int* histo;
histo = mmap(0, textsize, PROT_READ | PROT_WRITE, MAP_SHARED, hist_fd, 0);
if (histo == MAP_FAILED){
close(hist_fd);
perror("Error mmapping the file");
exit(EXIT_FAILURE);
}
// Write it now to disk
if (msync(histo, textsize, MS_SYNC) == -1)
{
perror("Could not sync the file to disk");
}
return 0;
}
int parent_read_ar(){
cstruct = malloc(sizeof(struct data_coll));
cstruct->_BPM = 0;
cstruct->_hr = 0;
cstruct->_min = 0;
cstruct->_temp = 0;
int found_end = 0; //if ending byte if read
unsigned char beginbyte = 0x7e;
unsigned char endbyte = 0x7f;
char check = 0x00; //used for reading values from Arduino
int index = 0;
int value = 0;
char begin = 'z'; //tells Arduino to send info
data_array[0] = 0;
data_array[1] = 0;
data_array[2] = 0;
data_array[3] = 0;
value = write(fd, &begin, 1);
if (value == -1){
perror("write");
close(fd);
return -1;
}else if (value == 0) {
fprintf(stderr, "No data written\n");
close(fd);
return -1;
}
value = read(fd, &check, 1);
if(value == -1){
perror("read");
close(fd);
return -1;
}else if(value == 0){
fprintf(stderr, "No data returned\n");
close(fd);
return -1;
}
if(check == beginbyte){
check = 0x00;
//printf("writing to arduino...");
//Tells Arduino to start sending info
value = write(fd, &begin, 1);
printf("(%d) %s\n", value, &begin);
if (count == -1) {
//perror("write");
close(fd);
return -1;
} else if (count == 0) {
//fprintf(stderr, "No data written\n");
close(fd);
return -1;
}
sleep(1);
do{
//printf("reading from arduino...");
value = read(fd, &check, 1);
//printf("(%d) %s\n", value, &check);
if(check == endbyte){
found_end = 1;
}else{
data_array[index] += check;
index++;
check = 0x00;
}
}while(!found_end);
cstruct->_BPM = data_array[0];
cstruct->_hr = data_array[1];
cstruct->_min = data_array[2];
cstruct->_temp = data_array[3];
add_to_gram();
data_array[0] = 0;
data_array[1] = 0;
data_array[2] = 0;
data_array[3] = 0;
index = 0;
value = 0;
}else{ printf("not beginning: %s\n", &check); }
return 0;
}
//Takes state of RTC from Arduino
int get_date(){
char incoming;
char dbyte = 'd';
int i = 0;
int endthis = 0;
unsigned char bbyte = 0x7e;
unsigned char ebyte = 0x7f;
time_array[0] = 0;
time_array[1] = 0;
time_array[2] = 0;
count = write(fd, &dbyte, 1);
sleep(1);
count = read(fd, &incoming, 1);
if(incoming == bbyte){
while(!endthis){
count = read(fd, &incoming, 1);
if(incoming == ebyte){
endthis = 1;
}else{
time_array[i] += incoming;
i++;
}
}
month = time_array[0];
day = time_array[1];
year = time_array[2];
}else{
printf("Could not set date! Try again...\n");
return -1;
}
return 0;
}
/*int callback(void *arg, int argc, char** argv, char** colName){
int i;
for(i=0;i<argc;i++){
printf("%s = %s\t", colName[i], argv[i] ? : "NULL");
}
printf("\n");
return 0;
}*/
int child_work(){
c2a = malloc(sizeof(struct command_ar*));
while(c2a->command != 'e'){
char* query;
int rc,m;
printf("Enter command: \n");
printf("d:date\nn:environment\nx:hist X\np:pause\na:rate\ng:regression X\nc:reset\nr:resume\nt:stat X\ns:show X\n");
c2a->command = getchar();
puts(&c2a->command);
//Pause for given time then resumes
if(c2a->command == 'p'){
count = write(fd, &c2a->command, 1);
//sleep(1000*3000);
//prints given value to display and console
}else if(c2a->command == 's'){
char x;
x = getchar();
count = write(fd, &c2a->command, 1);
sleep(1);
count = write(fd, &x, 1);
//sleep(1000);
printf("Desired bpm value: ");
puts(&x);
//resumes default data collection
}else if(c2a->command == 'r'){
count = write(fd, &c2a->command, 1);
//Prints current sensor value
}else if(c2a->command == 'n'){
printf("Current temprature: %d\n", c_temp);
//Prints current heart rate value
}else if(c2a->command == 'a'){
printf("Last recorded heart rate: %d\n", c_BPM);
//Prints state of RTC
}else if(c2a->command == 'd'){
printf("%d %d,%d %d:%d\n", day, month, year, c_hr, c_min);
// Prints our linear regression formula
}else if(c2a->command == 'g'){
asprintf(&query, "SELECT ((SUM(B.bpm)*SUM(T.temps*T.temps)-SUM(T.temps)*SUM(T.temps*B.bpm))/(COUNT(B.bpm)*SUM(T.temps*T.temps))-(SUM(T.temps)*SUM(T.temps))) FROM Beats B, Temps T WHERE hour = %d AND minute >= %d;",cstruct->_hr,cstruct->_min);
printf("Linear Regression: Y = ");
rc = handle_selects(db, query);
if(rc != SQLITE_ROW) printf("Trouble executing regression statement\n");
printf("X + ");
asprintf(&query, "SELECT ((Count(B.bpm)*SUM(B.bpm*T.temps)-SUM(T.temps)*SUM(B.bpm))/(COUNT(B.bpm)*SUM(T.temps*T.temps))-(SUM(T.temps)*SUM(T.temps))) FROM Beats B, Temps T WHERE hour = %d AND minute >= %d;",cstruct->_hr,cstruct->_min);
rc = handle_selects(db, query);
if(rc != SQLITE_ROW) printf("Trouble executing regression statement\n");
free(query);
//Prints desired statistic of both sensor and hr values
}else if(c2a->command == 't'){
int stat;
printf("Choose a number for a statistic...\n1: reading count\n2: mean\n3: median\n4: mode\n5: std dev\n");
scanf("%d\n", &stat);
if(stat == 1){ // count
asprintf(&query, "SELECT count(*) AS num_beats FROM Beats WHERE hour = %d AND minute >= %d;",cstruct->_hr,cstruct->_min);
printf("Beats count: ");
rc = handle_selects(db, query);
if(rc != SQLITE_ROW) printf("Trouble executing count statement\n");
asprintf(&query, "SELECT count(*) AS num_temps FROM Temp WHERE hour = %d AND minute >= %d;",cstruct->_hr,cstruct->_min);
printf("Temperature count: ");
rc = handle_selects(db, query);
if(rc != SQLITE_ROW) printf("Trouble executing count statement\n");
free(query);
}else if(stat == 2){ // mean
asprintf(&query, "SELECT AVG(*) AS mean_beats FROM Beats WHERE hour = %d AND minute >= %d;",cstruct->_hr,cstruct->_min);
printf("Beats mean: ");
rc = handle_selects(db, query);
if(rc != SQLITE_ROW) printf("Trouble executing mean statement\n");
asprintf(&query, "SELECT AVG(*) AS mean_temps FROM Temp WHERE hour = %d AND minute >= %d;",cstruct->_hr,cstruct->_min);
printf("Temperature mean: ");
rc = handle_selects(db, query);
if(rc != SQLITE_ROW) printf("Trouble executing mean statement\n");
free(query);
}else if(stat == 3){ // median
asprintf(&query, "SELECT bpm FROM Beats WHERE hour = %d AND minute >= %d ORDER BY ASC Limit 1 OFFSET (SELECT COUNT(*) FROM Beats) /2;",cstruct->_hr,cstruct->_min);
printf("Median of Beats: ");
rc = handle_selects(db, query);
if(rc != SQLITE_ROW) printf("Trouble executing median statement\n");
asprintf(&query, "SELECT temps FROM Temp WHERE hour = %d AND minute >= %d ORDER BY ASC Limit 1 OFFEST (SELECT COUNT(*) FROM Temps) /2;",cstruct->_hr,cstruct->_min);
printf("Median of Temperature: ");
rc = handle_selects(db, query);
if(rc != SQLITE_ROW) printf("Trouble executing median statement\n");
free(query);
}else if(stat == 4){ // mode
asprintf(&query, "SELECT bpm FROM Beats WHERE hour = %d AND minute >= %d GROUP BY bpm ORDER BY COUNT(*) DESC Limit 1;",cstruct->_hr,cstruct->_min);
printf("Beats Mode: ");
rc = handle_selects(db, query);
if(rc != SQLITE_ROW) printf("Trouble executing mode statement\n");
asprintf(&query, "SELECT temps FROM Temp WHERE hour = %d AND minute >= %d GROUP BY bpm ORDER BY COUNT(*) DESC Limit 1;",cstruct->_hr,cstruct->_min);
printf("Temperature Mode: ");
rc = handle_selects(db, query);
if(rc != SQLITE_ROW) printf("Trouble executing mode statement\n");
free(query);
}else if(stat == 5){ // standard deviation
printf("Beats Standard Deviation\n");
printf("-----------");
printf("The Square root of ");
asprintf(&query, "SELECT SUM(bpm-AVG(bpm))/COUNT(bpm) as stdev FROM Beats WHERE hour = %d AND minute >= %d;",cstruct->_hr,cstruct->_min);
rc = handle_selects(db, query);
if(rc != SQLITE_ROW) printf("Trouble executing std dev statement\n");
printf("Temperature std dev\n");
printf("-----------");
printf("The Square root of ");
asprintf(&query, "SELECT SUM(temps-AVG(temps))/COUNT(temps) as stdev FROM Temp WHERE hour = %d AND minute >= %d;",cstruct->_hr,cstruct->_min);
rc = handle_selects(db,query);
if(rc != SQLITE_ROW) printf("Trouble executing std dev statement\n");
free(query);
}
}
c2a->command = 0x00;
}//end of while loop
return 0;
}
int parent_work(){
int rc, status;
char* query;
//create database or access existing db
db = open_db("temp_bpm.db");//rc = sqlite3_open("temp_bpm.db", &db);
if(db == NULL){
perror("Error opening database\n");
_exit(-1);
}
//create tables
asprintf(&query, "CREATE TABLE IF NOT EXISTS Beats(bpm INTEGER NOT NULL, minute INTEGER NOT NULL, hour INTEGER NOT NULL);");
rc = create_tables(db, query);
if(rc != SQLITE_DONE){
perror("Error creating beats table\n");
_exit(-1);
}
asprintf(&query, "CREATE TABLE IF NOT EXISTS Temp(degrees INTEGER NOT NULL, minute INTEGER NOT NULL, hour INTEGER NOT NULL);");
rc = create_tables(db, query);
if(rc != SQLITE_DONE){
perror("Error creating temp tables\n");
_exit(-1);
}
//create histogram file
mmap_file();
sleep(1000*500); //.5 seconds
//Continues until child quits
cstruct = malloc(sizeof(struct data_coll*));
while(1){//waitpid(child_pid, &status, WNOHANG) == 0){
parent_read_ar();
set_vals();
query_beats();
query_temp();
}
return 0;
}
int set_vals(){
c_BPM = cstruct->_BPM;
c_hr = cstruct->_hr;
c_temp = cstruct->_temp;
c_min = cstruct->_min;
return 0;
}
int add_to_gram(){
int x_time = (cstruct->_hr*4)+(cstruct->_min%15);
int y_bts = cstruct->_BPM - 40;
//add to histogram mmaped file
**histogram[x_time][y_bts] = cstruct->_BPM;
return 0;
}
int query_temp(){
int rc;
char *query = NULL;
asprintf(&query, "insert into Temp(degrees, minute, hour) values (%d,%d,%d);",cstruct->_temp,cstruct->_min,cstruct->_hr);
rc = input_info(db, query); // step executes the statement
if (rc != SQLITE_DONE) { // Error
printf("ERROR inserting temperature data");
return -1;
}
free(query);
return 0;
}
int query_beats(){
int rc;
char* query = NULL;
asprintf(&query, "insert into Beats(bpm, minute, hour) values(%d,%d,%d);",cstruct->_BPM,cstruct->_min,cstruct->_hr);
rc = input_info(db, query); // step executes the statement
if (rc != SQLITE_DONE) { // Error
printf("ERROR inserting beats data");
return -1;
}
free(query);
return 0;
}
int init_tty(int fd) {
struct termios tty;
/*
* Configure the serial port.
* First, get a reference to options for the tty
* Then, set the baud rate to 9600 (same as on Arduino)
*/
memset(&tty, 0, sizeof(tty));
if (tcgetattr(fd, &tty) == -1) {
perror("tcgetattr");
return -1;
}
if (cfsetospeed(&tty, (speed_t)B9600) == -1) {
perror("ctsetospeed");
return -1;
}
if (cfsetispeed(&tty, (speed_t)B9600) == -1) {
perror("ctsetispeed");
return -1;
}
// 8 bits, no parity, no stop bits
tty.c_cflag &= ~PARENB;
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
// No flow control
tty.c_cflag &= ~CRTSCTS;
// Set local mode and enable the receiver
tty.c_cflag |= (CLOCAL | CREAD);
// Disable software flow control
tty.c_iflag &= ~(IXON | IXOFF | IXANY);
// Make raw
tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
tty.c_oflag &= ~OPOST;
// Infinite timeout and return from read() with >1 byte available
tty.c_cc[VMIN] = 0;
tty.c_cc[VTIME] = 0;
// Update options for the port
if (tcsetattr(fd, TCSANOW, &tty) == -1) {
perror("tcsetattr");
return -1;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void first()
{
int
size = 0,
i, j;
printf("Введите размер квадрата\n");
scanf("%d", &size);
for (i = 0; i < size; i++)
{
for (j = 0; j < size; j++)
{
if (i==0 || i==size-1)
printf("*");
else if (j==0 || j==size-1)
printf("*");
else printf(" ");
}
printf("\n");
}
}
void second()
{
int
number = 0,
result = 0,
i;
printf("Введите число в двоичной СС\n");
scanf("%d", &number);
for(i = 0; number != 0; i++)
{
result += number % 10 * pow(2, i);
number /= 10;
}
printf("%d", result);
}
void third() // По невнимательности сделал до 99999.99
{
double
sum = 0,
rub, kop;
int
*array = NULL,
size = 0, i,
kop_int, rub_int;
printf("Введите 0 < число < 99999.99 \n");
scanf("%lf", &sum);
kop = modf(sum, &rub);
kop_int = (int) ceil((kop * 100));
rub_int = (int) rub;
if (rub_int == 0)
{
printf("Ноль рублей");
}
else {
for (i = 0; rub_int != 0; i++) {
array = (int *) realloc(array, (i + 1) * sizeof(int));
array[i] = rub_int % 10;
rub_int /= 10;
printf("%d", array[i]);
size++;
}
printf("\n");
for (i = size - 1; i >= 0; i--) {
if (array[i - 1] == 1 && (i == size || i == 0 || i == 4) ||
array[i + 1] == 1 && (i == size || i == 0 || i == 4)) {
switch (array[i]) {
case 0:;
break;
case 1:
printf("Одиннадцать");
break;
case 2:
printf("Двенадцать");
break;
case 3:
printf("Тринадцать");
break;
case 4:
printf("Четырнадцать");
break;
case 5:
printf("Пятнадцать");
break;
case 6:
printf("Шестнадцать");
break;
case 7:
printf("Семнадцать");
break;
case 8:
printf("Восемнадцать");
break;
case 9:
printf("Девятнадцать");
break;
default:break;
}
i--;
}
if (i == 2) {
switch (array[i]) {
case 0:;
break;
case 1:
printf("Сто");
break;
case 2:
printf("Двести");
break;
case 3:
printf("Триста");
break;
case 4:
printf("Четыреста");
break;
case 5:
printf("Пятьсот");
break;
case 6:
printf("Шестьсот");
break;
case 7:
printf("Семьсот");
break;
case 8:
printf("Восемьсот");
break;
case 9:
printf("Девятьсот");
break;
default:break;
}
}
if (i == 1 || i == 4) {
switch (array[i]) {
case 0:;
break;
case 1:
if (array[i - 1] == 0) {
printf("Десять");
i--;
}
break;
case 2:
printf("Двадцать");
break;
case 3:
printf("Тридцать");
break;
case 4:
printf("Сорок");
break;
case 5:
printf("Пятьдесят");
break;
case 6:
printf("Шестьдесят");
break;
case 7:
printf("Семьдесят");
break;
case 8:
printf("Восемьдесят");
break;
case 9:
printf("Девяносто");
break;
default:break;
}
}
if ((i == 0 || i == size || i == 3) && (array[i - 1] != 1) && (array[i + 1] != 1)) {
switch (array[i]) {
case 0:;
break;
case 1:
if (i == 3) printf("Одна тысяча"); else printf("Один");
break;
case 2:
if (i == 3) printf("Две тысячи"); else printf("Два");
break;
case 3:
printf("Три");
break;
case 4:
printf("Четыре");
break;
case 5:
printf("Пять");
break;
case 6:
printf("Шесть");
break;
case 7:
printf("Семь");
break;
case 8:
printf("Восемь");
break;
case 9:
printf("Девять");
break;
default:break;
}
if (i == 3 && array[i] != 1 && array[i] != 2 || i == 4) {
printf(" Тысяч");
}
}
printf(" ");
}
if (array[0] == 1)
printf("Рубль");
else if (array[0] > 0 && array[0] < 5)
printf("Рубля");
else printf("Рублей");
}
if (kop_int == 100)
kop_int--;
printf(" %d ", kop_int);
if (kop_int < 10)
printf(0);
if (kop_int % 10 == 1)
printf("Копейка");
else if (kop_int % 10 > 0 && kop_int % 10 < 5)
printf("Копейки");
else printf("Копеек");
}
int fac(int num) {
if (num < 2)
return 1;
else return num * fac(num - 1);
}
void fourth() {
int i = 0;
double eps = 0, result = 2, instance = 10;
scanf("%lf", &eps);
printf("%d", fac(1));
for (i = 2; instance >= eps; i++)
{
instance = 1.0/fac(i);
result += instance;
}
printf("%lf", result);
}
void main()
{
int number;
printf("Введите номер задачи\n");
scanf("%d", &number);
printf("Задача %d\n", number);
if(number == 1) first();
else if(number == 2) second();
else if(number == 3) third();
else if(number == 4) fourth();
}
|
C
|
#include "./inc/main.h"
/**
* @defgroup privRs232Vars Private Main RS-232 Variables
*/
volatile int RX_INT_count = 0;
char test_buffer_PC[60];
char *putPC_ptr, *getPC_ptr;
bool put_status_PC, get_status_PC;
bool AC2PC_RX_flag = FALSE;
/**@}*/
/*
* main.c
*/
int main(void) {
WDTCTL = WDTPW | WDTHOLD; // Stop watchdog timer
return 0;
}
/**
* A wrapper for __delay_cycles() which allows the developer to create a **synchronous** delay
* of a number in microseconds.
*
* @note This should not be used in conjunction with functions that rely on ISRs!
*
* @param[in] delayConstant One of the constants defined in Delay Timings.
*/
extern void Delay(unsigned int delayConstant) {
switch(delayConstant) {
case DELAY_100:
__delay_cycles(DELAY_100);
break;
case DELAY_500:
__delay_cycles(DELAY_500);
break;
case DELAY_1000:
__delay_cycles(DELAY_1000);
break;
case DELAY_FOREVER: // If DELAY_FOREVER is passed in, don't do anything!
break;
default: // If an unknown value is given, then don't perform the delay.
/** @note As this is necessary for the IO init function, the printf
* was removed.
* @note __delay_cycles() requires a constant value; it cannot have
* a variable parameter passed to it. Therefore, the default case
* does nothing.*/
break;
}
}
/*
* Initialize I/O port directions and states
* - Drive unused pins as outputs to avoid floating inputs
* - XT1 setup for ACLK and XT2 setup for MCLK
*/
void io_init( void )
{
/*Port 1 Initialization*/
P1OUT = 0x00; /*Set outputs to ground*/
P1DIR = LED0 | LED1 | P1_UNUSED; /*Setup output pins*/
P1OUT = LED0 | LED1; /*Turn on LEDs*/
// P1SEL = BUTTON1 | BUTTON2 | CAN_INTn0 | CAN_INTn1; /*Set as interrupt pins*/
/*Generate an interrupt on a negative edge transition (high to low)*/
P1IES = BUTTON1 | BUTTON2 | CAN_INTn0 | CAN_INTn1;
P1IFG = 0x00; /*Clears all interrupt flags on Port 1*/
Delay(DELAY_100);
// P1IE = BUTTON1 | BUTTON2 | CAN_INTn0 | CAN_INTn1; /*Enable Interrupts*/
/*Port 2 Initialization*/
P2OUT = 0x00; /*Set outputs to ground*/
P2DIR = ADC_CSn | ADC_RESETn | P2_UNUSED; /*Setup output pins*/
// P2SEL = ADC_RDYn | DRIVER_SW1 | DRIVER_SW2 | DRIVER_SW3; /*Set as interrupt pins*/
/*Generate an interrupt on a negative edge transition (high to low)*/
P2IES = ADC_RDYn | DRIVER_SW1 | DRIVER_SW2 | DRIVER_SW3;
P2IFG = 0x00; /*Clears all interrupt flags on Port 2*/
Delay(DELAY_100);
// P2IE = ADC_RDYn | DRIVER_SW1 | DRIVER_SW2 | DRIVER_SW3; /*Enable Interrupts*/
/*Port 3 Initialization*/
P3OUT = 0x00; /*Set outputs to ground*/
P3DIR = ADC_DIN | ADC_SCLK | TX_EXT | CAN_SCLK2 | P3_UNUSED; /*Setup output pins*/
P3SEL = ADC_DIN | ADC_DOUT |ADC_SCLK | TX_EXT | RX_EXT | CAN_SCLK2; /*Setup pins for secondary function*/
Delay(DELAY_100);
/*Port 4 Initialization*/
P4OUT = 0x00; /*Set outputs to ground*/
P4DIR = LED2 | LED3 | LED4 | LED5 | P4_UNUSED; /*Setup output pins*/
P4OUT = ~(LED2 | LED3 | LED4 | LED5); /*Turn on LEDs*/
Delay(DELAY_100);
/*Port 5 Initialization*/
P5OUT = 0x00; /*Set outputs to ground*/
P5DIR = XT2OUT | CAN_RSTn2 | CAN_CSn2 | CAN_SI2 | P5_UNUSED; /*Setup output pins*/
P5OUT = CAN_CSn2 | CAN_SI2;
P3OUT = CAN_SCLK2;
P5SEL = XT2IN | XT2OUT | CAN_CSn2 | CAN_SI2 | CAN_SO2; /*Setup pins for secondary function*/
P5OUT = CAN_RSTn2; /*Send a reset signal*/
P5OUT &= ~P8_UNUSED;
Delay(DELAY_100);
/*Port 6 Initialization*/
P6OUT = 0x00; /*Set outputs to ground*/
P6DIR = P6_UNUSED; /*Setup output pins*/
/*Port 7 Initialization*/
P7OUT = 0x00; /*Set outputs to ground*/
P7DIR = XT1OUT | P7_UNUSED; /*Setup output pins*/
P7SEL = XT1IN | XT1OUT; /*Setup pins for secondary function*/
Delay(DELAY_100);
/*Port 8 Initialization*/
P8OUT = 0x00; /*Set outputs to ground*/
P8DIR = P8_UNUSED; /*Setup output pins*/
/*Port 9 Initialization*/
P9OUT = 0x00; /*Set outputs to ground*/
P9DIR = P9_UNUSED; /*Setup output pins*/
/*Port 10 Initialization*/
P10OUT = 0x00; /*Set outputs to ground*/
P10DIR = CAN_SCLK | CAN_CSn | CAN_RSTn | CAN_SI | P10_UNUSED; /*Setup output pins*/
P10OUT = CAN_CSn | CAN_SI | CAN_SCLK;
P10SEL = CAN_SCLK | CAN_CSn | CAN_SI | CAN_SO;
P10OUT = CAN_RSTn; /*Send a reset signal*/
P10OUT &= ~P10_UNUSED;
Delay(DELAY_100);
/*Port 11 Initialization*/
P11OUT = 0x00; /*Set outputs to ground*/
P11DIR = P11_UNUSED; /*Setup output pins*/
/*Port J Initialization*/
PJOUT = 0x00;
PJDIR = 0x0F; /*set to output as per user's guide*/
}
void timerA_init(void)
{
/*Set up Watch Crystal and TIMER A*/
TA0CCR0 = 255;
/*The TACCRO initializes the value of Timer A to count up to before setting CCIFG flag
(255 for 1/128 sec) (8191 1/4 sec) (16383 1/2 sec) (32767 1 sec) tick time*/
TA0CCTL0 = 0x0010; /*Enables CCIFG to cause an interrupt*/
TA0CTL = 0x0110; /*Set Timer A to ALCK, Start Timer A, Up mode, Timer-A interrupt enabled*/
}
/*
* Interrupts
*/
/*
* BPS2PC Interrupt Service Routine
*/
#pragma vector=USCI_A3_VECTOR
__interrupt void USCI_A3_ISR(void)
{
extern char *putPC_ptr, *getPC_ptr;
extern bool put_status_PC, get_status_PC, AC2PC_RX_flag;
char ch;
switch(__even_in_range(UCA3IV,16))
{
case 0: // Vector 0 - no interrupt
break;
case 2: // Data Received - UCRXIFG
ch = UCA3RXBUF;
*getPC_ptr++ = ch;
if (ch == 0x0D){
*getPC_ptr = 0;
getPC_ptr = &test_buffer_PC[0];
AC2PC_RX_flag = TRUE;
get_status_PC = FALSE;
}
else
{
get_status_PC = TRUE;
}
break;
case 4: // TX Buffer Empty - UCTXIFG
ch = *putPC_ptr++;
if (ch == '\0')
{
UCA3IE &= ~UCTXIE;
put_status_PC = FALSE;
}
else
{
UCA3TXBUF = ch;
}
break;
default:
break;
}
}
/*
* Timer A interrupts
*/
#pragma vector = TIMERA0_VECTOR
__interrupt void TIMERA_ISR(void)
{
TA0CCTL0 &= 0xFFFE; /*Clear Flags*/
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_DEPRECATE
#include "helpers.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*POLE S TYPMI VOJAKOV, KTORYCH SI MOZE HRAC VOLIT*/
extern Vojak TypyVojakov[] = {
{"Sermiar", 3,3,4,"warrior"},
{"Lukostrelec", 4,4,3,"rogue"},
{"Kopijnik", 5,3,3,"tank"},
{"Rytier", 5,3,3,"warrior" },
{"Vlajkonos", 3,2,6,"priest"},
{"Kusostrelec", 3,5,3,"rogue"},
{"Jazdec", 4,3,4,"warrior"},
{"Obrneny jazdec",7,2,4,"tank"},
{"Mag", 4,4,3,"priest"}
};
/*FUNKCIA NA ZOBRAZENIE TABULKY S TYPMI VOJAKOV*/
void vypisTypyVojakov() {
printf(" ID| MENO | HP|ATT|DEF| CLASS|\n");
printf("-------------------------------------------\n");
for (int i = 0; i < SIZEOFTYPESOFSOLDIERS; i++) {
printf("%2.i | ",i+1);
printf("%*s ",14,TypyVojakov[i].meno);
printf("|");
printf("%2.i ", TypyVojakov[i].hp);
printf("|");
printf("%2.i ", TypyVojakov[i].att);
printf("|");
printf("%2.i", TypyVojakov[i].def);
printf(" | ");
printf("%*s ", 7, TypyVojakov[i].role);
printf("|\n");
}
}
void vypisVojiskoHraca(Armada armadaHraca) {
printf(" ID| MENO | HP|ATT|DEF| CLASS|\n");
printf("-------------------------------------------\n");
for (int i = 0; i < SIZEOFPLAYERARMY; i++) {
if (armadaHraca.vojisko[i].hp > 0) {
printf("%2.i | ", i + 1);
printf("%*s ", 14, armadaHraca.vojisko[i].meno);
printf("|");
printf("%2.i ", armadaHraca.vojisko[i].hp);
printf("|");
printf("%2.i ", armadaHraca.vojisko[i].att);
printf("|");
printf("%2.i", armadaHraca.vojisko[i].def);
printf(" | ");
printf("%*s ", 7, armadaHraca.vojisko[i].role);
printf("|\n");
}
}
}
void vypisKonkretnehoVojaka(Armada armadaHraca, int index) {
printf(" ID| MENO | HP|ATT|DEF| CLASS|\n");
printf("-------------------------------------------\n");
printf("%2.i | ", index + 1);
printf("%*s ", 14, armadaHraca.vojisko[index].meno);
printf("|");
printf("%2.i ", armadaHraca.vojisko[index].hp);
printf("|");
printf("%2.i ", armadaHraca.vojisko[index].att);
printf("|");
printf("%2.i", armadaHraca.vojisko[index].def);
printf(" | ");
printf("%*s ", 7, TypyVojakov[index].role);
printf("|\n");
}
void zapisVojakaDoArmady(Armada *armadaHraca, int typVojaka, int pocet) {
armadaHraca->vojisko[pocet].meno = TypyVojakov[typVojaka].meno;
armadaHraca->vojisko[pocet].hp = TypyVojakov[typVojaka].hp;
armadaHraca->vojisko[pocet].att = TypyVojakov[typVojaka].att;
armadaHraca->vojisko[pocet].def = TypyVojakov[typVojaka].def;
armadaHraca->vojisko[pocet].role = TypyVojakov[typVojaka].role;
}
void vypisTipyKuRoliam() {
printf("|-----------------------------------------------------------------------------------------|\n");
printf("| Priest - po boji dvoch vojakov nahodne vylieci/prida zivot niekomu z team-u |\n");
printf("| Tank - po narocnom boji (5+tahov) si zvysi obranu o jedna |\n");
printf("| Rogue - pokial su v team-e aspon 2 rogue, tak po kazdom boji sa jednemu zvysi atk o 1 |\n");
printf("| Warrior - ked nastupi warrior do boja, zvysi si atk alebo def o 1 (vybrane nahodne) |\n");
printf("|-----------------------------------------------------------------------------------------|\n");
}
int nacitajVstup(int a, int b) {
int vstup;
do {
vstup = getchar();
vstup -= '0';
} while (vstup<a||vstup>b);
getchar();
return vstup-1;
}
void vyberVojiska(Armada *armadaHraca) {
int volba;
for (int i = 0; i < SIZEOFPLAYERARMY; i++) {
volba = nacitajVstup(1, SIZEOFTYPESOFSOLDIERS);
printf("%s zverbovany do tvojej armady\n", TypyVojakov[volba].meno);
zapisVojakaDoArmady(armadaHraca, volba, i);
armadaHraca->pocet += 1;
}
CLEAR_SCREEN();
}
void inicializaciaHraca(Hrac *hrac) {
printf("---------HRAC %s---------\nProsim, zadaj svoje meno (aspon 3 znaky): ",hrac->meno);
do {
fgets(hrac->meno, 30, stdin);
hrac->meno[strlen(hrac->meno) - 1] = '\0';
} while (strlen(hrac->meno) < 3);
printf("\nVitaj, %s!\n", hrac->meno);
getchar();
CLEAR_SCREEN();
}
void inicializaciaVojska(Hrac *hrac) {
//VYBER VOJISKA HRACA A
printf("---------VOJISKO HRACA %s---------\n", hrac->meno);
vypisTypyVojakov();
vypisTipyKuRoliam();
printf("\n%s, vyber si %i vojakov:\n",hrac->meno,SIZEOFPLAYERARMY);
vyberVojiska(hrac->armadaHraca);
printf("---------VOJISKO HRACA %s---------\n", hrac->meno);
vypisVojiskoHraca(*hrac->armadaHraca);
getchar();
CLEAR_SCREEN();
}
|
C
|
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/jiffies.h>
#include <linux/utsname.h>
void get_time(void);
void getSystemInfo(void);
typedef struct{
int ID;
char *NAME;
int AGE;
}Student;
int i;
int countS=-1;
Student arrStudent[10];
Student createStudent(int id, char *nombre, int edad){
Student newStudent;
newStudent.ID=id;
newStudent.NAME=nombre;
newStudent.AGE=edad;
countS=countS+1;
return newStudent;
}
void addStudent(Student x){
arrStudent[countS]=x;
}
void listStudents(void){
int i;
for(i=0;i<=countS;i++){
printk("Student: %s\n Name: %s\n\tID: %d\n\tAge: %d\n"," ",arrStudent[i].NAME, arrStudent[i].ID, arrStudent[i].AGE);
}
}
//////////////////////////////////////////////////////////////
/* This function is called when the module is loaded. */
int simple_init(void)
{
printk(KERN_INFO "Loading Module\n");
//simple_uptime();
//simple_systeminfo();
addStudent(createStudent(122,"Arturo",23));
listStudents();
return 0;
}
void simple_uptime(void){
printk("Uptime: %d sec \n", (jiffies_to_msecs(get_jiffies_64())/1000));
}
void simple_systeminfo(void){
struct new_utsname *a= utsname();
printk("Sysname: %s\n", a->sysname);
printk("Nodename: %s\n", a->nodename);
printk("Realease: %s\n", a->release);
printk("Version: %s\n", a->version);
printk("Machine: %s\n", a->machine);
}
/* This function is called when the module is removed. */
void simple_exit(void) {
printk(KERN_INFO "Removing Module\n");
}
/* Macros for registering module entry and exit points. */
module_init( simple_init );
module_exit( simple_exit );
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Simple Module");
MODULE_AUTHOR("SGG");
|
C
|
/*
To compile:
gcc -O3 -o mandelbrot mandelbrot.c -lm
To create an image with 4096 x 4096 pixels (last argument will be used to set number of threads):
./mandelbrot 4096 4096 1
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int writeMandelbrot(const char *fileName, int width, int height, float *img, int minI, int maxI);
#define MXITER 2048
typedef struct {
double r;
double i;
}complex_t;
// return iterations before z leaves mandelbrot set for given c
int testpoint(complex_t c){
int iter;
complex_t z;
double temp;
z = c;
for(iter=0; iter<MXITER; iter++){
temp = (z.r*z.r) - (z.i*z.i) + c.r;
z.i = z.r*z.i*2. + c.i;
z.r = temp;
if((z.r*z.r+z.i*z.i)>4.0){
return iter;
}
}
return iter;
}
// perform Mandelbrot iteration on a grid of numbers in the complex plane
// record the iteration counts in the count array
void mandelbrot(int Nre, int Nim, complex_t cmin, complex_t dc, float *count){
for(int n=0;n<Nim;++n){
for(int m=0;m<Nre;++m){
complex_t c;
c.r = cmin.r + dc.r*m;
c.i = cmin.i + dc.i*n;
count[m+n*Nre] = (float) testpoint(c);
}
}
}
int main(int argc, char **argv){
// to create a 4096x4096 pixel image [ last argument is placeholder for number of threads ]
// usage: ./mandelbrot 4096 4096 32
int Nre = atoi(argv[1]);
int Nim = atoi(argv[2]);
int Nthreads = atoi(argv[3]);
// storage for the iteration counts
float *count = (float*) malloc(Nre*Nim*sizeof(float));
// Parameters for a bounding box for "c" that generates an interesting image
const float centRe = -.759856, centIm= .125547;
const float diam = 0.151579;
complex_t cmin;
complex_t cmax;
complex_t dc;
cmin.r = centRe - 0.5*diam;
cmax.r = centRe + 0.5*diam;
cmin.i = centIm - 0.5*diam;
cmax.i = centIm + 0.5*diam;
//set step sizes
dc.r = (cmax.r-cmin.r)/(Nre-1);
dc.i = (cmax.i-cmin.i)/(Nim-1);
// replace with omp wtime
clock_t start = clock(); //start time in CPU cycles
// compute mandelbrot set
mandelbrot(Nre, Nim, cmin, dc, count);
// replace with omp wtime
clock_t end = clock(); //start time in CPU cycles
// print elapsed time
printf("elapsed = %f\n", ((double)(end-start))/CLOCKS_PER_SEC);
// output mandelbrot to png format image
printf("Printing mandelbrot.ppm...");
writeMandelbrot("mandelbrot.ppm", Nre, Nim, count, 0, 80);
free(count);
exit(0);
return 0;
}
/* Output data as PPM file */
void saveppm(const char *filename, unsigned char *img, int width, int height){
/* FILE pointer */
FILE *f;
/* Open file for writing */
f = fopen(filename, "wb");
/* PPM header info, including the size of the image */
fprintf(f, "P6 %d %d %d\n", width, height, 255);
/* Write the image data to the file - remember 3 byte per pixel */
fwrite(img, 3, width*height, f);
/* Make sure you close the file */
fclose(f);
}
int writeMandelbrot(const char *fileName, int width, int height, float *img, int minI, int maxI){
int n, m;
unsigned char *rgb = (unsigned char*) calloc(3*width*height, sizeof(unsigned char));
for(n=0;n<height;++n){
for(m=0;m<width;++m){
int id = m+n*width;
int I = (int) (768*sqrt((double)(img[id]-minI)/(maxI-minI)));
// change this to change palette
if(I<256) rgb[3*id+2] = 255-I;
else if(I<512) rgb[3*id+1] = 511-I;
else if(I<768) rgb[3*id+0] = 767-I;
else if(I<1024) rgb[3*id+0] = 1023-I;
else if(I<1536) rgb[3*id+1] = 1535-I;
else if(I<2048) rgb[3*id+2] = 2047-I;
}
}
saveppm(fileName, rgb, width, height);
free(rgb);
}
|
C
|
#include<stdio.h> //Binary Search
#include<stdlib.h>
#define size 10
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void sort(int *a)
{
for(int i=0;i<size-1;i++)
{
for(int j=0;j<size-i-1;j++)
{
if(a[j]>a[j+1])
swap(&a[j],&a[j+1]);
}
}
}
int binary_search(int *a, int val)
{
int i=0;
int j=size-1;
int key;
int flag=-1;
while (j>=i)
{
key=(i+j)/2;
if(a[key]>val)
{
j=key-1;
}
else if(a[key]<val)
{
i=key+1;
}
else if (a[key]==val)
{
flag++;
break;
}
}
if(flag!=-1)
return(key);
else
return(-1);
}
int main()
{
int arr[size], val,pos;
for(int i=0;i<size;i++)
arr[i]=rand();
printf("Array: \n");
for(int i=0;i<size;i++)
{
printf("%d\t",arr[i]);
}
sort(arr);
printf("\nArray: \n");
for(int i=0;i<size;i++)
{
printf("%d\t",arr[i]);
}
printf("\n\nEnter the value you want to search: ");
scanf("%d",&val);
pos=binary_search(arr,val);
if(pos!=-1)
printf("\nFound at: %d",pos);
else
printf("\nValue Not Found");
}
|
C
|
#include <stdio.h>
#include "student.h"
void getList(Student astu[],int number);
int save(Student astu[],int number);
int main()
{
int number = 0;
printf("ѧ\n");
scanf("%d", &number);
Student *astu = (Student *)malloc(number * sizeof(int));
//Student astu[number];//c99ֱӿ֣֧C99ַֻʽǵҪͷڴ
getList(astu, number);
if (save(astu, number)) {
printf("success save\n");
}
else {
printf("save failed");
}
free( astu);
return 0;
}
void getList(Student astu[], int number)
{
char format[STR_LEN];
sprintf(format, "%%%ds\n", STR_LEN - 1);//%%ָҪһ%,%dDZʽ\
sҲҪ-->"%19s",ⲻλòҪʹ
int i;
for (i = 0; i < number; i++) {
printf("%dѧ\n", i+1);
printf("\t");
scanf("%s", astu[i].name);
printf("\tԱ(Ů102):");
scanf("%d", &astu[i].gender);
printf("\t䣺");
scanf("%d", &astu[i].age);
}
}
int save(Student astu[], int number)
{
int ret = 0;
FILE*fp = fopen("studebt.data", "w");
if (fp) {
ret = fwrite(astu,sizeof(Student),number,fp);
fclose(fp);
return ret == number;
}
}
|
C
|
/*
** EPITECH PROJECT, 2018
** bootstrap
** File description:
** server2
*/
#include "server.h"
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
void close_socket(server_t *server)
{
client_t *current;
client_t *tmp;
if (!server)
return;
current = server->current;
while (current != 0){
tmp = current;
current = current->next;
tmp->cdel(tmp);
}
if (server->fd != -1)
close(server->fd);
if (server->type == HOST)
free(server->list);
free(server);
}
int create_socket(server_t *server, char *root, enum SERVER_TYPE type)
{
int opt = 1;
server->pe = getprotobyname("TCP");
if (!server->pe)
return (-1);
printf("Creating the socket\n");
server->fd = socket(AF_INET, SOCK_STREAM, server->pe->p_proto);
if (server->fd == -1)
return (-1);
else if (type == HOST && setsockopt(server->fd, SOL_SOCKET, SO_REUSEADDR
, (char *)&opt, sizeof(opt)) == -1)
return (-1);
printf("Socket created\n");
server->type = type;
if (type == HOST){
server->list = get_list();
server->root = root;
}
return (server->fd);
}
int set_port(server_t *server, unsigned int port, const char *ip)
{
int result;
if (!server || server->fd == -1)
return (1);
server->s_in.sin_family = AF_INET;
server->s_in.sin_port = htons(port);
server->s_in.sin_addr.s_addr = inet_addr(ip);
printf("Setting the port...\n");
result = bind(server->fd
, (struct sockaddr *)&server->s_in, sizeof(server->s_in));
if (result == -1)
return (1);
printf("The port has been set\n");
return (0);
}
server_t *init_server(void)
{
server_t *server;
server = malloc(sizeof(server_t));
if (!server)
return (0);
server->cnew = &create_socket;
server->cdel = &close_socket;
server->start = &start_server;
server->set_port = &set_port;
server->last = 0;
server->current = 0;
server->root = 0;
server->parent = 0;
return (server);
}
|
C
|
#include "IA.h"
int theIAchoice(int lin,int col,int Array[lin][col],int level)
{
int i;
int place;
int choice = rand()%2;
int err = rand()%100;
int err2 = rand()%300;
for(i=0;i<col;i++)
{
if(Array[lin-1][i] == 10)
place = i;
}
if(level == 1)
{
if(Array[lin-2][place] != 0)
{
if(choice == 0)
{
if(place > 0)
{
if(Array[lin-2][place-1] == 0)
{
Array[lin-1][place-1] = 10;
Array[lin-1][place] = 0;
}
}
else
if(Array[lin-2][place+1] == 0)
{
Array[lin-1][place+1] = 10;
Array[lin-1][place] = 0;
}
}
if(choice == 1)
{
if(place < col-1)
{
if(Array[lin-2][place+1] == 0)
{
Array[lin-1][place+1] = 10;
Array[lin-1][place] = 0;
}
}
else
if(Array[lin-2][place-1] == 0)
{
Array[lin-1][place-1] = 10;
Array[lin-1][place] = 0;
}
}
for(i=0;i<col;i++)
{
if(Array[lin-1][i] == 10)
place = i;
}
if(err==25)
{
if(place < col-1)
{
Array[lin-1][place+1] = 10;
Array[lin-1][place] = 0;
}
else
if(place > 0)
{
Array[lin-1][place-1] = 10;
Array[lin-1][place] = 0;
}
}
}
return 0;
}
if(level == 2)
{
if(Array[lin-2][place] != 0)
{
if(choice == 0)
{
if(place > 0)
{
if(Array[lin-2][place-1] == 0)
{
Array[lin-1][place-1] = 10;
Array[lin-1][place] = 0;
}
}
else
if(Array[lin-2][place+1] == 0)
{
Array[lin-1][place+1] = 10;
Array[lin-1][place] = 0;
}
}
if(choice == 1)
{
if(place < col-1)
{
if(Array[lin-2][place+1] == 0)
{
Array[lin-1][place+1] = 10;
Array[lin-1][place] = 0;
}
}
else
if(Array[lin-2][place-1] == 0)
{
Array[lin-1][place-1] = 10;
Array[lin-1][place] = 0;
}
}
for(i=0;i<col;i++)
{
if(Array[lin-1][i] == 10)
place = i;
}
if(err2==50)
{
if(place < col-1)
{
Array[lin-1][place+1] = 10;
Array[lin-1][place] = 0;
}
else
if(place > 0)
{
Array[lin-1][place-1] = 10;
Array[lin-1][place] = 0;
}
}
return 2;
}
}
if(level >= 3)
{
if(Array[lin-2][place] != 0)
{
if(choice == 0)
{
if(place > 0)
{
if(Array[lin-2][place-1] == 0)
{
Array[lin-1][place-1] = 10;
Array[lin-1][place] = 0;
}
}
else
if(Array[lin-2][place+1] == 0)
{
Array[lin-1][place+1] = 10;
Array[lin-1][place] = 0;
}
}
if(choice == 1)
{
if(place < col-1)
{
if(Array[lin-2][place+1] == 0)
{
Array[lin-1][place+1] = 10;
Array[lin-1][place] = 0;
}
}
else
if(Array[lin-2][place-1] == 0)
{
Array[lin-1][place-1] = 10;
Array[lin-1][place] = 0;
}
}
}
}
//return (int) (((((((((15+rand()%15)/2.)*0.666)+2)*666)/25)*level)-choice)/777); //pourquoi pas...
// pas de retour suite à un accord avec le fantôme dans la machine (The Gost in the Shell)
}/*Ghost In The Shell*/
|
C
|
/*
* Starter producer/consumer program using a shared buffer.
*
*/
#include <pthread.h>
#include <stdio.h>
#include <time.h>
int main(int argc, char *argv[]);
void * producer(void * arg);
void * consumer(void * arg);
void thread_sleep(unsigned int ms);
#define BUFSLOTS 10
/*
* Structure used to hold data between producer and consumer.
*/
struct data {
int value; /* Value to be passed to consumer */
int consumer_sleep; /* Time (in ms) for consumer to sleep */
int line; /* Line number in input file */
int print_code; /* Output code; see below */
int quit; /* Nonzero if consumer should exit ("value" ignored) */
};
/*
* The shared buffer itself.
*/
static struct data buffer[BUFSLOTS];
/*
* TODO:
*
* You will need to add new variables here.
*
*/
/*
* TODO:
*
* Sample conditions and mutexes. You will need to customize these.
*
*/
static pthread_cond_t sample_condition = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int main(int argc, char * argv[])
{
pthread_t consumer_tid;
/*
* Make sure output appears right away.
*/
setlinebuf(stdout);
/*
* Create a thread for the consumer.
*/
if (pthread_create(&consumer_tid, NULL, consumer, NULL) != 0) {
fprintf(stderr, "Couldn't create consumer thread\n");
return 1;
}
/*
* We will call the producer directly. (Alternatively, we could
* spawn a thread for the producer, but then we would have to join
* it.)
*/
producer(NULL);
/*
* The producer has terminated. Clean up the consumer, which might
* not have terminated yet.
*/
if (pthread_join(consumer_tid, NULL) != 0) {
fprintf(stderr, "Couldn't join with consumer thread\n");
return 1;
}
return 0;
}
void * producer(void * arg)
{
unsigned int consumer_sleep; /* Space for reading in data */
int line = 0; /* Line number in input */
int print_code; /* Space for reading in data */
unsigned int producer_sleep; /* Space for reading in data */
int value; /* Space for reading in data */
while (scanf("%d%u%u%d", &value, &producer_sleep, &consumer_sleep, &print_code) == 4) {
line++;
thread_sleep(producer_sleep);
/*
* TODO: Add your code here.
*/
/*
* After sending values to the consumer, print what was asked.
*/
if (print_code == 1 || print_code == 3)
printf("Produced %d from input line %d\n", value, line);
}
/*
* TODO: Add code to terminate the consumer.
*/
return NULL;
}
void * consumer(void * arg)
{
/*
* TODO: Write the consumer here.
*/
return NULL;
}
void thread_sleep(unsigned int ms)
{
struct timespec sleep_time;
if (ms == 0)
return;
/*
* TODO:
*
* These assignment statements are dummies. You will need to write
* correct values. Remember that tv_nsec cannot exceed one billion!
*/
sleep_time.tv_sec = 0;
sleep_time.tv_nsec = 250000000;
nanosleep(&sleep_time, NULL);
}
|
C
|
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//test edit
string secretMessage;
int code;
//another test edit
int main(int argc, string argv[])
{
if(argc == 2)
{
code = atoi(argv[1]);
printf("The code is %i\n", code);
secretMessage = get_string("What is your secret message?");
for (int i = 0, n = strlen(secretMessage); i < n; i++)
{
if(isalpha(secretMessage[i]))
{
if(isupper(secretMessage[i]))
{
printf("%c", (((secretMessage[i] + code) - 65) % 26) + 65);
}
if(islower(secretMessage[i]))
{
printf("%c", (((secretMessage[i] + code) - 97) % 26) + 97);
}
}
else
printf("%c", secretMessage[i]);
}
printf("\n");
return 0;
}
else
{
printf("Please specify the code when running the program as a command line argument.\n");
return 1;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]){
int x,y,z,m;
x=atoi(argv[1]);
y=atoi(argv[2]);
z=atoi(argv[3]);
m = z;
if (y<z) {
if(x<y)
m=y;
else if (x<z)
m=y;
} else {
if (x>y)
m=y;
else if (x>z)
m = x;
}
printf("Middle number is: %d\n",m);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <wctype.h>
void read_file(char* file_name, char* options){
int character_count = 0;
int whitespace_count = 1;
int linebreak_count = 0;
FILE *file_to_read = NULL;
if( file_name == NULL ) {
printf( "read_file: invalid file_name" );
return;
}
if( options == NULL ) {
printf( "read_file: invalid options" );
return;
}
fopen(file_name,"r");
if (file_to_read == NULL){
printf("You tried to open %s, which doesn't exist", file_name);
exit(1);
}
//int size = sizeof()/sizeof(char);
int i;
char c;
//for (i = 0; i<=size; i++){
while(c !=EOF){
c = fgetc(file_to_read);
if (c == ' ' || c == '-') {
whitespace_count = whitespace_count +1;
}
else if(c == '\n'){
linebreak_count++;
}
else if(isalpha(c)){
character_count++;
}
else if(c == EOF){
break;
}
}
int size = sizeof(options)/sizeof(char);
for (i = 0; i<=size; i++){
if(options[i] == NULL){
break;
}
else if(options[i] == 'w'){
printf("%s => %d \n", file_name, whitespace_count);
}
else if(options[i] == 'l'){
printf("%s => %d \n", file_name, linebreak_count);
}
}
if(options[0] == 'n'){
printf("%s => %d\t %d\t %d \n", file_name, linebreak_count, whitespace_count, character_count);
}
}
int main(int argc, char **argv) {
char input [256];
char options[255];
int i;
for(i=0; i <= argc; i++){
if (argv[i] == NULL){
break;
}
else if (strcmp(argv[i],"-l")==0){
options[i] = 'l';
}
else if (strcmp(argv[i],"-w")== 0){
options[i] = 'w';
}
}
if(argv[2] == NULL){
options[0] = 'n';
}
//printf("%s", argv[2]);
read_file(argv[1], options);
}
|
C
|
/*
* libsc - Relational memory management
*
* Copyright 2011 Nathaniel McCallum <nathaniel@themccallums.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "common.h"
static bool dest = false;
static void
destr(void *mem)
{
dest = true;
}
int
main(int argc, const char **argv)
{
myStruct *top, *tmp;
/* Test standard parentage, allocation and destructor */
assert(top = sc_new(NULL, myStruct));
assert(sc_size_children(top) == 0);
assert(tmp = sc_new0(top, myStruct));
assert(sc_size_children(top) == 1);
assert(sc_size_parents(tmp) == 1);
sc_destructor_set(tmp, destr);
assert(dest == false);
sc_decref(top, tmp);
assert(dest == true);
assert(sc_size_children(top) == 0);
/* Check aligned allocation */
tmp = sc_memalign0(top, 4096, sizeof(myStruct), NULL);
assert(tmp);
assert(((uintptr_t) tmp) % 4096 == 0);
assert(sc_size_children(top) == 1);
assert(sc_size_parents(tmp) == 1);
assert(_sc_resizea0((void**) &tmp, sizeof(myStruct), 3, 4096));
assert(((uintptr_t) tmp) % 4096 == 0);
assert(sc_size_children(top) == 1);
assert(sc_size_parents(tmp) == 1);
sc_decref(top, tmp);
assert(sc_size_children(top) == 0);
/* Test incref and decref */
assert(sc_size_parents(top) == 1);
sc_incref(NULL, top);
assert(sc_size_parents(top) == 2);
sc_decref(NULL, top);
assert(sc_size_parents(top) == 1);
/* Test steal */
assert(tmp = sc_new(top, myStruct));
assert(sc_size_children(top) == 1);
assert(sc_size_parents(tmp) == 1);
assert(sc_steal_old(NULL, tmp, top));
assert(sc_size_children(top) == 0);
assert(sc_size_parents(tmp) == 1);
assert(sc_steal(top, tmp));
assert(sc_size_children(top) == 1);
assert(sc_size_parents(tmp) == 1);
sc_decref(top, tmp);
sc_decref(NULL, top);
return 0;
}
|
C
|
#include <stdio.h>
main() {
int c;
int is_space = 0;
while((c = getchar()) != EOF) {
if(c == ' ' && !is_space) {
is_space = 1;
putchar(c);
}else if(c!= ' ') {
is_space = 0;
putchar(c);
}
}
}
|
C
|
// subshell.c
// author: Jann Horn
// source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1712
#define _GNU_SOURCE
#include <unistd.h>
#include <grp.h>
#include <err.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sched.h>
#include <sys/wait.h>
int main() {
int sync_pipe[2];
char dummy;
if (socketpair(AF_UNIX, SOCK_STREAM, 0, sync_pipe)) err(1, "pipe");
pid_t child = fork();
if (child == -1) err(1, "fork");
if (child == 0) {
close(sync_pipe[1]);
if (unshare(CLONE_NEWUSER)) err(1, "unshare userns");
if (write(sync_pipe[0], "X", 1) != 1) err(1, "write to sock");
if (read(sync_pipe[0], &dummy, 1) != 1) err(1, "read from sock");
execl("/bin/bash", "bash", NULL);
err(1, "exec");
}
close(sync_pipe[0]);
if (read(sync_pipe[1], &dummy, 1) != 1) err(1, "read from sock");
char pbuf[100];
sprintf(pbuf, "/proc/%d", (int)child);
if (chdir(pbuf)) err(1, "chdir");
const char *id_mapping = "0 0 1\n1 1 1\n2 2 1\n3 3 1\n4 4 1\n5 5 995\n";
int uid_map = open("uid_map", O_WRONLY);
if (uid_map == -1) err(1, "open uid map");
if (write(uid_map, id_mapping, strlen(id_mapping)) != strlen(id_mapping)) err(1, "write uid map");
close(uid_map);
int gid_map = open("gid_map", O_WRONLY);
if (gid_map == -1) err(1, "open gid map");
if (write(gid_map, id_mapping, strlen(id_mapping)) != strlen(id_mapping)) err(1, "write gid map");
close(gid_map);
if (write(sync_pipe[1], "X", 1) != 1) err(1, "write to sock");
int status;
if (wait(&status) != child) err(1, "wait");
return 0;
}
|
C
|
#include <stdio.h>
int main(void)
{
int c, v, i, x, j, menor, maior=0, n[999999]={0}, m[3];
scanf("%d%d", &c, &v);
for(i = 0; i < c; i++)
for(j = 0; j < v; j++)
{
scanf("%d", &x);
n[i] += x;
}
for(i = 0; i < c; i++)
if(n[maior] < n[i])
maior = i;
for(j = 0; j < 3; j++)
{
for(i = 0; i < c; i++)
{
if(i == 0)
menor = maior;
if(n[i] < n[menor] && n[i] != -1)
menor = i;
}
m[j] = menor;
n[menor] = -1;
}
for(i = 0; i < 3; i++)
printf("%d\n", m[i] + 1);
return 0;
}
|
C
|
#include "dog.h"
/**
* _strcpy - copy pointers
* @dest: destination
* @src: string to copy
* Return: the pointer to dest
*/
char *_strcpy(char *dest, char *src)
{
int i;
for (i = 0; src[i] != 0; i++)
{
dest[i] = src[i];
}
dest[i] = '\0';
return (dest);
}
/**
* _strlen - Count the maximum number of a array
* @s: Input Array
*
* Return: counter
*/
int _strlen(char *s)
{
int cont;
cont = 0;
while (s[cont])
{
cont++;
}
return (cont);
}
/**
* new_dog - create a new dog
* @name: name of the dog
* @age: age of the dog
* @owner: owner of the dog
*
* Return: a dog woff
*/
dog_t *new_dog(char *name, float age, char *owner)
{
struct dog *dog_t;
char *n;
char *o;
int i, j;
dog_t = malloc(sizeof(struct dog));
if (dog_t == NULL)
{
return (NULL);
}
i = _strlen(name);
j = _strlen(owner);
n = malloc(i + 1);
if (n == NULL)
{
free(dog_t);
return (NULL);
}
o = malloc(j + 1);
if (o == NULL)
{
free(dog_t);
free(n);
return (NULL);
}
n = _strcpy(n, name);
o = _strcpy(o, owner);
dog_t->name = n;
dog_t->age = age;
dog_t->owner = o;
return (dog_t);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "parse.h"
#include "helpers.h"
static Parser* newParser(int argumentsCount, char** arguments) {
Parser* parser = calloc(1, sizeof(Parser));
if (argumentsCount == 2 && stringsEqual(arguments[1], ARGUMENT_SWITCH_DEBUG))
parser->debugMode = true;
else if (argumentsCount > 1)
forceExitDueToArguments();
return parser;
}
static void freeParser(Parser* parser) {
free(parser);
}
static void setEventListener(Parser* parser, OnEventListener* listener) {
parser->listener = listener;
}
static void setOnParseResultCallback(Parser* parser, OnParseResultCallback callback)
{
parser->parseResultCallback = callback;
}
static ParseResult executeCommandEnterDescription(Parser* parser, char* name, char* description) {
DataEnterDescription data;
data.diseaseDescription = description;
data.name = name;
if (parser->listener)
return parser->listener->OnEnterDescription(parser->listener, &data);
return PARSE_RESULT_IGNORED;
}
static ParseResult parseCommandEnterDescription(Parser* parser) {
char* name = readSingleWord();
char* disease = readLine();
ParseResult result = executeCommandEnterDescription(parser, name, disease);
free(name);
free(disease);
return result;
}
static ParseResult executeCommandCopyDescription(Parser* parser, char* sourceName, char* destinationName) {
DataCopyDescription data;
data.sourceName = sourceName;
data.destinationName = destinationName;
if (parser->listener)
return parser->listener->OnCopyDescription(parser->listener, &data);
return PARSE_RESULT_IGNORED;
}
static ParseResult parseCommandCopyDescription(Parser* parser) {
char* destinationName = readSingleWord();
char* sourceName = readSingleWord();
ParseResult result = executeCommandCopyDescription(parser, sourceName, destinationName);
free(sourceName);
free(destinationName);
return result;
}
static ParseResult executeCommandChangeDescription(Parser* parser, char* name, int index, char* diseaseDescription) {
DataChangeDescription data;
data.name = name;
data.indexOfDisease = index;
data.diseaseDescription = diseaseDescription;
if (parser->listener)
return parser->listener->OnChangeDescription(parser->listener, &data);
return PARSE_RESULT_IGNORED;
}
static ParseResult parseCommandChangeDescription(Parser* parser) {
char* name = readSingleWord();
int index = readInt();
char* diseaseDescription = readLine();
ParseResult result = executeCommandChangeDescription(parser, name, index, diseaseDescription);
free(name);
free(diseaseDescription);
return result;
}
static ParseResult executeCommandPrintDescription(Parser* parser, char* name, int index) {
DataPrintDescription data;
data.name = name;
data.indexOfDisease = index;
if (parser->listener)
return parser->listener->OnPrintDescription(parser->listener, &data);
return PARSE_RESULT_IGNORED;
}
static ParseResult parseCommandPrintDescription(Parser* parser) {
char* name = readSingleWord();
int index = readInt();
ParseResult result = executeCommandPrintDescription(parser, name, index);
free(name);
return result;
}
static ParseResult executeCommandDeletePatientData(Parser* parser, char* name) {
DataDeletePatientData data;
data.name = name;
if (parser->listener)
return parser->listener->OnDeletePatientData(parser->listener, &data);
return PARSE_RESULT_IGNORED;
}
static ParseResult parseCommandDeletePatientData(Parser* parser) {
char* name = readSingleWord();
ParseResult result = executeCommandDeletePatientData(parser, name);
free(name);
return result;
}
static ParseResult parseCommand(Parser* parser, char* command) {
if (stringsEqual(NEW_DISEASE_ENTER_DESCRIPTION, command))
return parseCommandEnterDescription(parser);
else if (stringsEqual(NEW_DISEASE_COPY_DESCRIPTION, command))
return parseCommandCopyDescription(parser);
else if (stringsEqual(PRINT_DESCRIPTION, command))
return parseCommandPrintDescription(parser);
else if (stringsEqual(CHANGE_DESCRIPTION, command))
return parseCommandChangeDescription(parser);
else // if (stringsEqual(DELETE_PATIENT_DATA, command))
return parseCommandDeletePatientData(parser);
}
static bool isDebugMode(Parser* parser) {
return parser->debugMode;
}
static void callCallback(Parser* parser, ParseResult result) {
if (parser->parseResultCallback)
parser->parseResultCallback(parser, result);
}
static ParseResult parse(Parser* parser) {
ParseResult result = PARSE_RESULT_EOF;
char input[MAX_COMMAND_LENGTH];
if (scanf("%s", input) != EOF) {
result = parseCommand(parser, input);
callCallback(parser, result);
}
return result;
}
static void runParser(Parser* parser) {
ParseResult result;
do {
result = Parsers.parse(parser);
} while (result != PARSE_RESULT_EOF);
}
const struct parsers Parsers = {
.new = newParser,
.free = freeParser,
.parse = parse,
.setEventListener = setEventListener,
.setOnParseResultCallback = setOnParseResultCallback,
.isDebugMode = isDebugMode,
.runParser = runParser
};
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<stdbool.h>
#include<limits.h>
typedef long long ll;
enum{ P =(ll)1e9 + 7 };
enum{ N = 22 };
enum{ M = 11 };
enum{ K = 4 };
enum{ milion=(ll) 1e6};
ll p[N][M][K];
ll pref[N][1 << M][M * K];
enum{ inv1e6 = 142857001};
ll spow(ll a, ll b){
ll r = 1;
while (b) {
if (b % 2) {
r = r * a % P;
}
a = a * a % P;
b /= 2;
}
return r;
}
ll inv(ll a){
return spow(a, P - 2);
}
int main(){
ll n, m;
scanf("%lld %lld", &n, &m);
for(ll k =(1); k <=(3); ++k){
for(ll step = 0;step <(m); ++step){
for(ll i =(1); i <=(n); ++i){
scanf("%lld", &p[i][step][k]);
}
}
}
for(ll i =(1); i <=(n); ++i){
for(ll mask = 0;mask <(1 << m); ++mask){
int dp[3*m+2]; memset(dp, 0, sizeof(dp));
dp[0] = 1;
for(ll step = 0;step <(m); ++step){
if (mask & (1 << step)){
int ndp[3*m+2]; memset(ndp, 0, sizeof(ndp));
for(ll prv = 0;prv <(3 * m + 2); ++prv){
if(dp[prv] == 0)
continue;
for(ll k =(1); k <=(3); ++k){
ll nxt = prv + k;
ndp[nxt] = (ndp[nxt] + dp[prv] * p[i][step][k]) % P;
}
}
memcpy(&dp, &ndp, sizeof(dp));
}
}
for(ll val = 0;val <(3 * m + 2); ++val){
pref[i][mask][val] = dp[val];
if (val)
pref[i][mask][val] += pref[i][mask][val - 1];
pref[i][mask][val] %= P;
}
}
}
ll res = 0;
ll all_ways = spow(milion, m);
for(ll val = 0;val <(3 * m + 2); ++val){
int dpSz = 1<<m;
int dp[dpSz]; memset(dp, 0, sizeof(dp));
dp[0] = 1;
for(ll i =1; i <=n; ++i){
int ndp[1 << m]; memset(ndp, 0, sizeof(ndp));
for(ll cur_mask = 0;cur_mask <(1 << m); ++cur_mask){
ll complement = (1 << m) - 1 - cur_mask;
for (ll prv = complement; ; prv = (prv - 1) & complement){
ndp[cur_mask + prv] = (ndp[cur_mask + prv] + dp[prv] * pref[i][cur_mask][val]) % P;
if (prv == 0)
break;
}
}
memcpy(&dp, &ndp, sizeof(dp));
}
res += (all_ways - dp[dpSz-1] + P);
res %= P;
}
printf("%lld\n", res % P * spow(inv1e6, m) % P);
return 0;
}
|
C
|
#include <stdlib.h>
#include "mod_core.h"
#include "mod_http.h"
#include "mod_rtsp.h"
/*
typedef struct net_module {
(void)(*process_request)(int fd);
}
*/
typedef struct module_node {
int port;
net_module *module;
struct module_node *next;
} module_node;
static module_node *header = NULL, *tail = NULL;
void register_all_modules() {
//read a config xml file.
//This file will record the port:module;
}
net_module* register_module(int port) {
//load shared lib
module_node *node = (module_node *)calloc(sizeof(char), sizeof(module_node));
net_module *module = (net_module *)calloc(sizeof(char), sizeof(net_module));
if( port == 1234 )
create_http(module);
else if( port == 8554 )
create_rtsp(module);
node->port = port;
node->module = module;
node->next = NULL;
if( !header ) {
header = tail = node;
} else {
tail->next = node;
tail = node;
}
return module;
}
void modules_init(conf *_conf) {
module_node *_header = header;
while( _header ) {
if( ((socket_conf *)_conf)->port == _header->port )
_header->module->module_init(_conf);
_header = _header->next;
}
}
void module_init(int port, conf *_conf) {
}
void dipatche(int fd) {
}
void modules_start() {
module_node *_header = header;
while( _header ) {
if( fork() == 0 ) {
_header->module->module_start();
}
_header = _header->next;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * dna_strand(const char * dna)
{
if (dna == NULL || strlen(dna) == 0)
return NULL;
int length = strlen(dna);
printf("size: %d\n", length);
char * complement = malloc( sizeof(char) * length);
int i;
for (i = 0; i != length; i++) {
if (dna[i] == 'A') {
complement[i] = 'T';
} else if (dna[i] == 'T') {
complement[i] = 'A';
} else if (dna[i] == 'C') {
complement[i] = 'G';
} else {
complement[i] = 'C';
}
}
while (i > length - 1) {
complement[i] = '\0';
i--;
}
return complement;
}
int main(void)
{
char * strand = "GTAT";
dna_strand(strand);
return 0;
}
|
C
|
#include<stdio.h>
int main(){ int i; for(i = -4; i <= 86; i += 18) printf("%d\n", i); }
|
C
|
/* array.h - Foundation library - Public Domain - 2013 Mattias Jansson
*
* This library provides a cross-platform foundation library in C11 providing basic support
* data types and functions to write applications and games in a platform-independent fashion.
* The latest source code is always available at
*
* https://github.com/mjansson/foundation_lib
*
* This library is put in the public domain; you can redistribute it and/or modify it without
* any restrictions.
*/
#pragma once
/*! \file array.h
\brief Simple resizable array of integral/POD types
Simple resizable array of integral/POD types. All functions are "unsafe" (not range checked)
unless marked as "_safe". It is safe to pass null pointers to all methods as a null pointer is
considered a valid array (array storage will be allocated and assigned as needed).
Note that all public APIs are defines as macros. Some calls might evaluate argument expressions
multiple times.
Arrays are not inherently thread safe. Synchronization in a multithreaded use case must be done
by caller.
Example usage:
<code>int** arr = 0;
array_push( arr, 10 ); //arr is now allocated and arr[0] now equals 10
array_pop( arr ); //arr size is now 0, arr still allocated
array_deallocate( arr ); //arr is now deallocated and arr now equals null</code>
Adapted and extended from stb_arr at http://nothings.org/stb.h */
#include <foundation/platform.h>
#include <foundation/types.h>
#include <foundation/math.h>
#include <foundation/memory.h>
/*! Deallocate array memory and reset array pointer to zero. Value of expression
is a null pointer.
\param array Array pointer */
#define array_deallocate(array) /*lint -e{522}*/ \
(_array_verify(array) ? (memory_deallocate(_array_raw(array)), ((array) = 0)) : 0)
/*! Get capacity of array in number of elements. Capacity indicates the size of the allocated
memory block (maximum size of array).
\param array Array pointer */
#define array_capacity(array) (_array_verify(array) ? _array_rawcapacity_const(array) : 0)
/*! Reserve storage for given number of elements. Never reduces storage and does not affect
number of currently stored elements.
\param array Array pointer
\param capacity New capacity */
#define array_reserve(array, capacity) \
((void)_array_maybegrowfixed(array, (int)(capacity) - (int)array_capacity(array)))
/*! Get number of currently stored elements.
\param array Array pointer */
#define array_count(array) (_array_verify(array) ? _array_rawsize_const(array) : 0)
#define array_size(array) array_count(array)
/*! Add or remove elements without initialization, if size is positive or negative respectively.
Sets new size to array_size(array)+count and allocates new storage if new size is larger than
array capacity. Value of expression is the new size of the array.
\param array Array pointer
\param count Number of elements to grow/shrink */
#define array_grow(array, count) ((void)_array_resize(array, (size_t)((ssize_t)array_size(array) + (ssize_t)count)))
/*! Resize to given absolute size without initialization. Sets new size to count and allocate
new storage if new size is larger than array capacity.
\param array Array pointer
\param count New size */
#define array_resize(array, count) ((void)_array_resize(array, count))
/*! Set size to 0. Does not affect capacity or resize array storage buffer.
\param array Array pointer */
#define array_clear(array) (_array_verify(array) ? (_array_rawsize(array) = 0) : 0)
/*! Copy content of one array to another, setting new destination array size to source array
size and allocating more storage if new destination size is larger than destination array
capacity. Value of the expression is the size of the destination array after copy.
\param dst Destination array
\param src Source array */
#define array_copy(dst, src) \
((_array_verify(src) && _array_elementsize(src) == _array_elementsize(dst) && \
_array_maybegrowfixed((dst), (_array_rawsize_const(src) - (_array_verify(dst) ? (_array_rawsize(dst)) : 0)))) ? \
(memcpy((dst), (src), (_array_rawsize_const(src)) * _array_elementsize(src)), \
(_array_rawsize(dst) = _array_rawsize_const(src))) : \
array_clear(dst))
/*! Add element at end of array with assignment. Value of expression is new array pointer.
\param array Array pointer
\param element New element */
#define array_push(array, element) /*lint -e522*/ \
(_array_maybegrow(array, 1) ? (((array)[_array_rawsize(array)++] = (element)), (array)) : (array))
/*! Add element at end of array copying data with memcpy. Value of expression
is new array pointer.
\param array Array pointer
\param elementptr Pointer to new element */
#define array_push_memcpy(array, elementptr) /*lint -e{506,522}*/ \
(_array_maybegrow(array, 1) ? \
(memcpy((array) + _array_rawsize(array)++, (elementptr), sizeof(*(array))), (array)) : \
(array))
/*! Add element at given position in array with assignment. Position is NOT range checked.
Existing elements are moved using memmove. Value of expression is new array pointer.
\param array Array pointer
\param pos Position
\param element New element */
#define array_insert(array, pos, element) \
(_array_maybegrow(array, 1) ? (memmove((array) + (pos) + 1, (array) + (pos), \
_array_elementsize(array) * (_array_rawsize(array)++ - (pos))), \
(array)[(pos)] = (element), (array)) : \
(array))
/*! Add element at given position in array, copy data using memcpy. Position is NOT range
checked. Existing elements are moved using memmove. Value of expression is new array pointer.
\param array Array pointer
\param pos Position
\param elementptr Pointer to new element */
#define array_insert_memcpy(array, pos, elementptr) \
(_array_maybegrow(array, 1) ? (memmove((array) + (pos) + 1, (array) + (pos), \
_array_elementsize(array) * (_array_rawsize(array)++ - (pos))), \
memcpy((array) + (pos), (elementptr), sizeof(*(array))), (array)) : \
(array))
/*! Add element at given position in array with assignment. Position IS range checked and
clamped to array size. Existing elements are moved using memmove.
\param array Array pointer
\param pos Position
\param element New element */
#define array_insert_safe(array, pos, element) \
do { \
uint32_t _arr_size = array_size(array); \
uint32_t _clamped_pos = ((uint32_t)(pos)&0x80000000U) ? 0 : math_min((uint32_t)(pos), _arr_size); \
array_insert(array, _clamped_pos, element); \
} while (0)
/*! Add element at given position in array, copy data using memcpy. Position IS range
checked and clamped to array size. Existing elements are moved using memmove.
\param array Array pointer
\param pos Position
\param elementptr Pointer to new element */
#define array_insert_memcpy_safe(array, pos, elementptr) \
do { \
uint32_t _arr_size = array_size(array); \
uint32_t _clamped_pos = ((uint32_t)(pos)&0x80000000U) ? 0 : math_min((uint32_t)(pos), _arr_size); \
array_insert_memcpy(array, _clamped_pos, elementptr); \
} while (0)
/*! Remove last element. Array size is NOT validated, will cause undefined behaviour if
called on an empty array.
\param array Array pointer */
#define array_pop(array) (_array_verify(array) ? --_array_rawsize(array) : 0)
/*! Remove last element. Array size IS validated, safe to call on an empty array.
\param array Array pointer */
#define array_pop_safe(array) (_array_verify(array) && (_array_rawsize(array) > 0) ? --_array_rawsize(array) : 0)
/*! Erase element at given position without preserving order, swap-with-last using assignment.
Position is NOT ranged checked.
\param array Array pointer
\param pos Position */
#define array_erase(array, pos) \
(_array_verify(array) ? *((array) + (pos)) = *((array) + (_array_rawsize(array) - 1)), --_array_rawsize(array) : 0)
/*! Erase element at given position without preserving order, swap-with-last by copy data
using memcpy. Position is NOT ranged checked.
\param array Array pointer
\param pos Position */
#define array_erase_memcpy(array, pos) \
(_array_verify(array) ? \
(((uint32_t)(pos) != (_array_rawsize(array) - 1) ? \
memcpy((array) + (pos), (array) + (_array_rawsize(array) - 1), _array_elementsize(array)) : \
0), \
--_array_rawsize(array)) : \
0)
/*! Erase element at given position without preserving order, swap-with-last using assignment.
Position IS ranged checked.
\param array Array pointer
\param pos Position */
#define array_erase_safe(array, pos) \
(_array_verify(array) && _array_verify_index(array, pos) ? array_erase(array, pos) : 0)
/*! Erase element at given position without preserving order, swap-with-last by copy data
using memcpy. Position IS ranged checked.
\param array Array pointer
\param pos Position */
#define array_erase_memcpy_safe(array, pos) \
(_array_verify(array) && _array_verify_index(array, pos) ? array_erase_memcpy(array, pos) : 0)
/*! Erase element at given position and preserve order by memmove remaining elements in array.
Position is NOT ranged checked.
\param array Array pointer
\param pos Position */
#define array_erase_ordered(array, pos) \
(_array_verify(array) ? (memmove((array) + (pos), (array) + (pos) + 1, \
(_array_rawsize(array) - (pos)-1U) * _array_elementsize(array)), \
--_array_rawsize(array)) : \
0)
/*! Erase element at given position and preserve order by memmove remaining elements in array.
Position IS ranged checked.
\param array Array pointer
\param pos Position */
#define array_erase_ordered_safe(array, pos) \
(_array_verify(array) && _array_verify_index(array, pos) ? array_erase_ordered(array, (uint32_t)pos) : 0)
/*! Erase a range of elements at given position and preserve order by memmove remaining elements
in array. Position and number of elements are NOT ranged checked
\param array Array pointer
\param pos Starting position
\param count Number of elements to erase */
#define array_erase_ordered_range(array, pos, count) \
(_array_verify(array) && (/*lint -e506 */ (count) > 0) ? \
memmove((array) + (pos), (array) + (pos) + (count), \
(_array_rawsize(array) - (pos) - (count)) * _array_elementsize(array)), \
(_array_rawsize(array) -= (count)) : 0)
/*! Erase a range of elements at given position and preserve order by memmove remaining elements
in array. Position and number of elements ARE ranged checked
\param array Array pointer
\param pos Starting position
\param count Number of elements to erase */
#define array_erase_ordered_range_safe(array, pos, count) \
do { \
uint32_t _arr_size = array_size(array); \
uint32_t _clamped_start = ((uint32_t)(pos)&0x80000000U) ? 0 : math_min((uint32_t)(pos), _arr_size); \
uint32_t _clamped_end = \
((uint32_t)((pos) + (count)) & 0x80000000U) ? 0 : math_min((uint32_t)((pos) + (count)), _arr_size); \
if (_clamped_end > _clamped_start) \
array_erase_ordered_range(array, _clamped_start, _clamped_end - _clamped_start); \
} while (0)
// **** Internal implementation details below, not for direct use ****
/*! \internal Header size set to 16 bytes in order to align main array memory */
#define _array_header_size 4UL
#if BUILD_DEBUG
#define _array_verify(a) ((a) && internal_array_verifyfn((const void* const*)&(a)))
#else
#define _array_verify(a) (a)
#endif
/*! \internal Access the raw array header area */
#define _array_raw(a) ((uint32_t*)(a)-_array_header_size)
#define _array_rawcapacity(a) _array_raw(a)[0]
#define _array_rawsize(a) _array_raw(a)[1]
#define _array_rawelementsize(a) _array_raw(a)[3]
#define _array_raw_const(a) ((const uint32_t*)(a)-_array_header_size)
#define _array_rawcapacity_const(a) _array_raw_const(a)[0]
#define _array_rawsize_const(a) _array_raw_const(a)[1]
#define _array_elementsize(a) ((size_t)(pointer_diff(&(a)[1], &(a)[0])))
#define _array_needgrow(a, n) /*lint -e506 */ \
(((n) > 0) && (!_array_verify(a) || (_array_rawsize_const(a) + (uint)(n)) > _array_rawcapacity_const(a)))
#define _array_maybegrow(a, n) (_array_needgrow(a, (n)) ? _array_grow(a, n, 2) : (a))
#define _array_maybegrowfixed(a, n) (_array_needgrow(a, (n)) ? _array_grow(a, (uint)(n), 1) : (a))
#define _array_grow(a, n, f) (internal_array_growfn((void**)&(a), (uint)(n), (f), _array_elementsize(a)))
#define _array_resize(a, n) (internal_array_resizefn((void**)&(a), (uint)(n), _array_elementsize(a)))
#define _array_verify_index(a, n) ((uint32_t)(n) < _array_rawsize(a))
/*! \internal Array memory allocation function. This will reallocate array storage with the given
parameters, resulting in a total size of(factor * previous_capacity + increment) elements,
with each element size given by itemsize.
\param arr Pointer to array
\param count Number of elements to increment storage with
\param factor Factor to multiply previous capacity with
\param itemsize Size of a single item
\return New array pointer */
FOUNDATION_API void*
internal_array_growfn(void** arr, size_t count, size_t factor, size_t itemsize);
/*! \internal Array resize function. This will reallocate array storage if needed
\param arr Pointer to array
\param count Number of elements to resize to
\param itemsize Size of a single item
\return New array pointer */
FOUNDATION_API void*
internal_array_resizefn(void** arr, size_t count, size_t itemsize);
/*! \internal Verify array integrity. Will cause an assert if array is not valid.
\param arr Pointer to array
\return Array if valid, null if invalid */
FOUNDATION_API const void*
internal_array_verifyfn(const void* const* arr);
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* Functions to swap byte order from little endian to big endian. Required
* because Kindle is big endian, but x86 is little endian.*/
#define ByteSwap16(n) \
( ((((unsigned int) n) << 8) & 0xFF00) | \
((((unsigned int) n) >> 8) & 0x00FF) )
#define ByteSwap32(n) \
( ((((unsigned long) n) << 24) & 0xFF000000) | \
((((unsigned long) n) << 8) & 0x00FF0000) | \
((((unsigned long) n) >> 8) & 0x0000FF00) | \
((((unsigned long) n) >> 24) & 0x000000FF) )
/* Stores a Kindle bookmark entry */
typedef struct bookmark
{
int page;
char *pageNumber;
struct bookmark *next;
} bookmark;
/* Allocate and initialize a bookmark */
bookmark* makeBookmark(int, char*);
/* Copies linked list of bookmarks to the specified file */
int addBookmarks(bookmark*, FILE *);
/* Displays the usage string. */
int usage(void);
int main(int argc, char** argv)
{
int bookmarkCount = 0;
int lastPage = 1;
FILE *input;
FILE *output;
bookmark *head;
bookmark *current;
if (argc != 3)
{
usage();
return 0;
}
input = fopen(argv[1], "r");
if (input != NULL)
{
char line[512];
while (fgets(line, sizeof(line), input) != NULL)
{
if (line[strlen(line)-1] == '\n')
line[strlen(line)-1] = 0;
if (bookmarkCount++ == 0)
{
head = makeBookmark(bookmarkCount, line);
current = head;
}
else
{
current->next = makeBookmark(bookmarkCount, line);
current = current->next;
}
printf("%s\n", line);
}
}
else
{
perror(argv[1]);
return 0;
}
unsigned char header[] = {0xDE, 0xAD, 0xCA, 0xBB, 0x01};
unsigned char spacer = 0x00;
unsigned int lastReadPage = ByteSwap32(1);
bookmarkCount = ByteSwap32(bookmarkCount);
output = fopen(argv[2], "wb");
fprintf(output, "%s", header);
fwrite(&lastReadPage, 1, sizeof(lastReadPage), output);
fwrite(&bookmarkCount, 1, sizeof(bookmarkCount), output);
fwrite(&spacer, 1, sizeof(spacer), output);
addBookmarks(head, output);
fclose(output);
return 0;
}
bookmark* makeBookmark(int page, char* pageNumber)
{
bookmark* bMark;
bMark = (bookmark*) malloc(sizeof(bookmark));
bMark->page = page;
bMark->pageNumber = (char*) malloc(strlen(pageNumber) + 1);
strcpy(bMark->pageNumber, pageNumber);
bMark->next = NULL;
return bMark;
}
int addBookmarks(bookmark *head, FILE *outFile)
{
short int numChars;
unsigned int pageNum = ByteSwap32(head->page);
fwrite(&pageNum, 1, sizeof(pageNum), outFile);
numChars = strlen(head->pageNumber);
numChars = ByteSwap16(numChars);
fwrite(&numChars, 1, sizeof(numChars), outFile);
fprintf(outFile, "%s", head->pageNumber);
if (head->next != NULL)
{
addBookmarks(head->next, outFile);
}
return 1;
}
int usage(void)
{
printf("Usage: makecontents input output\n");
return 0;
}
|
C
|
/**
* _atoi - Convert string to an integer.
* @s: Pointer to a character string.
*
* Return: void.
*/
int _atoi(char *s)
{
int sign;
unsigned int num;
char *temp;
temp = s;
num = 0;
sign = 1;
while (*temp != '\0' && (*temp < '0' || *temp > '9'))
{
if (*temp == '-')
sign *= -1;
temp++;
}
if (*temp != '\0')
{
do {
num = num * 10 + (*temp - '0');
temp++;
} while (*temp >= '0' && *temp <= '9');
}
return (num * sign);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
//#define BitIsSET '*'
//#define BitIsSET '#'
#define BitIsSET '@'
//#define BitIsSET ' ' /* special invers Darstellung */
int main(int argc, char *argv[])
{
int width,new_width;
int height;
int anz;
int hexwert;
int ii, kk;
int blanks;
int hh;
int line, row;
int lines;
char origbuf[256];
char *linebuf;
char filename[256];
char asc_table[100][130];
char *end_line;
char BitSetChar;
char BitClearChar;
char *tx;
FILE *outfile;
if (argc != 2) {
fprintf(stderr,"Count of arguments: %d\r\n",argc-1);
fprintf(stderr,"Argument 1: file to be converted\r\n");
exit(0);
}
stdin = fopen(argv[1],"r");
if (stdin == (FILE *)NULL) {
fprintf(stderr,"File %s can not be opened!\r\n",argv[1]);
exit(-1);
}
width = 0;
sscanf(argv[1],"%d",&width);
if (width < 4) {
fprintf(stderr,"Width can not be located from file name %s !\r\n",argv[1]);
exit(-1);
}
hh = 0;
if ((argv[1][1] == 'x') || (argv[1][1] == 'X')) hh = 2;
if ((argv[1][2] == 'x') || (argv[1][2] == 'X')) hh = 3;
sscanf(&argv[1][hh],"%d",&height);
if ((hh == 0)|| (height < 5)) {
fprintf(stderr,"Height can not be located from file name %s !\r\n",argv[1]);
exit(-1);
}
fprintf(stderr,"Width = %d\r\n", width);
fprintf(stderr,"Height = %d\r\n", height);
hh = strlen(argv[1]);
while (hh > 1) {
hh--;
if (argv[1][hh] == '.') argv[1][hh] = (char)0;
}
sprintf(filename,"%s.asc",argv[1]);
fprintf(stderr,"Create file: %s\r\n", filename);
outfile = fopen(filename, "w+");
if (outfile == (FILE *)NULL) {
fprintf(stderr,"File %s can not be created!\r\n",filename);
exit(-1);
}
/* Test-Ausgabe */
// for (kk=0x20; kk<255; kk++) {
// if ((kk%16) == 0) fprintf(stderr,"\r\n");
// fprintf(stderr,"%c",kk);
// }
// fprintf(stderr,"\r\n");
anz = width;
anz *= ((height + 7) / 8);
lines = 0;
while (fgets(origbuf,256,stdin) != NULL)
{
lines++;
for(ii=0;ii<256;ii++) {
if (origbuf[ii] == '\n') origbuf[ii] = (char)0;
if (origbuf[ii] == '\r') origbuf[ii] = (char)0;
}
/* remove leading Blanks */
for (blanks=0;blanks<20;blanks++) {
if (origbuf[blanks] != ' ') break;
}
linebuf = &origbuf[blanks];
if (linebuf[0] == 0) {
linebuf[1] = 0;
linebuf[20] = 0;
linebuf[22] = 0;
}
if ( ((linebuf[0] == '{') && (linebuf[1] == '0')) ||
((linebuf[1] == ' ') && (linebuf[2] == '{') && (linebuf[3] == '0')) ||
((strncmp(&linebuf[0],"#define PIX_",12) == 0) && (linebuf[21] == '{') && (linebuf[22] == '0')) ||
((strncmp(&linebuf[2],"#define PIX_",12) == 0) && (linebuf[23] == '{') && (linebuf[24] == '0')) ) {
if ( (linebuf[0] == '{') ) tx = &linebuf[1];
if ( (linebuf[1] == ' ') && (linebuf[2] == '{') ) tx = &linebuf[3]; /* probably diff output "< {" "> {" */
if ( (linebuf[20] == ' ') && (linebuf[21] == '{') ) {
/* probably #define style */
/* #define PIX_a_stroke {0x.... */
/* 012345678901234567890123 */
tx = &linebuf[22];
}
if ( (linebuf[22] == ' ') && (linebuf[23] == '{') ) {
/* probably #define style */
/* < #define PIX_a_stroke {0x.... */
/* 01234567890123456789012345 */
tx = &linebuf[24];
}
if ( (strncmp(linebuf,"#define PIX_",12) == 0) ||
(strncmp(&linebuf[2],"#define PIX_",12) == 0) ) {
fprintf(outfile,"%s\r\n",&linebuf[0]);
}
for (ii=0;ii<235;ii++) {
if (tx[ii] == '}') {
/* end of byte list found */
anz = ((ii +2) / 5);
new_width = anz / ((height + 7) / 8);
if (new_width != width) {
// fprintf(outfile,"// **** new width = %d\r\n",new_width);
width = new_width;
}
break;
}
} /* end for ii */
// init the table
for (ii=0;ii<100;ii++) {
for (kk=0;kk<height;kk++) asc_table[ii][kk] = '.';
asc_table[ii][width] = (char)0;
}
BitSetChar = BitIsSET;
BitClearChar = '.';
ii = 0;
end_line = &linebuf[strlen(linebuf)];
while (ii<anz ) {
line = (ii / width) * 8;
if ((tx[0] == '0') && ((tx[1] == 'x') || (tx[1] == 'X'))) {
sscanf( tx,"%x,", &hexwert);
row = (ii % width);
if ((hexwert & 0x01) != 0) {
asc_table[line][row] = BitSetChar;
} else {
asc_table[line][row] = BitClearChar;
}
if ((hexwert & 0x02) != 0) {
asc_table[line+1][row] = BitSetChar;
} else {
asc_table[line+1][row] = BitClearChar;
}
if ((hexwert & 0x04) != 0) {
asc_table[line+2][row] = BitSetChar;
} else {
asc_table[line+2][row] = BitClearChar;
}
if ((hexwert & 0x08) != 0) {
asc_table[line+3][row] = BitSetChar;
} else {
asc_table[line+3][row] = BitClearChar;
}
if ((hexwert & 0x10) != 0) {
asc_table[line+4][row] = BitSetChar;
} else {
asc_table[line+4][row] = BitClearChar;
}
if ((hexwert & 0x20) != 0) {
asc_table[line+5][row] = BitSetChar;
} else {
asc_table[line+5][row] = BitClearChar;
}
if ((hexwert & 0x40) != 0) {
asc_table[line+6][row] = BitSetChar;
} else {
asc_table[line+6][row] = BitClearChar;
}
if ((hexwert & 0x80) != 0) {
asc_table[line+7][row] = BitSetChar;
} else {
asc_table[line+7][row] = BitClearChar;
}
tx += 5;
ii++;
} else { /* no "0x" */
if ((tx[0] == '/') && (tx[1] == '*')) {
BitClearChar = ' ';
BitSetChar = 'O';
}
if ((tx[0] == '*') && (tx[1] == '/')) {
BitSetChar = BitIsSET;
BitClearChar = '.';
}
tx++;
if (tx[0] == '}') {
fprintf(stderr,"Warning } is found at line %d!\r\n",lines);
break;
}
if (tx >= end_line) {
// read new line
if (fgets(origbuf,256,stdin) != NULL) {
lines++;
for(kk=0;kk<256;kk++) {
if (origbuf[kk] == '\n') origbuf[kk] = (char)0;
if (origbuf[kk] == '\r') origbuf[kk] = (char)0;
}
/* remove leading Blanks */
for (blanks=0;blanks<20;blanks++) {
if (origbuf[blanks] != ' ') break;
}
linebuf = &origbuf[blanks];
end_line = &linebuf[strlen(linebuf)];
tx = &linebuf[0];
}
}
} /* no "0x" */
} /* end while(ii<anz) */
if ( tx[2] != 0 ) fprintf(outfile,"%s\r\n",&tx[2]);
fprintf(outfile," ");
for (kk=0; kk<width; kk++) {
if ( ((kk % 8) == 0) && (kk != 0) ) {
fprintf(outfile,"+");
} else {
fprintf(outfile,"-");
}
} /* end for kk */
fprintf(outfile," \r\n");
for (kk=0; kk<height; kk++) {
// Zeile aufbereiten
if ((kk % 8) == 0) {
fprintf(outfile,"+");
} else {
fprintf(outfile,"|");
}
// fprintf(outfile,"%s",&asc_table[kk][0]);
int ll;
ll = 0;
while (asc_table[kk][ll] != 0) {
#if BitIsSET == ' '
if (asc_table[kk][ll] == BitIsSET ) {
fprintf(outfile,"\033[0;7m%c\033[0m",asc_table[kk][ll]);
} else {
fprintf(outfile,"%c",asc_table[kk][ll]);
}
#else
fprintf(outfile,"%c",asc_table[kk][ll]);
#endif
ll++;
} /* end while */
if ((kk % 8) == 0) {
fprintf(outfile,"+\r\n");
} else {
fprintf(outfile,"|\r\n");
}
} /* end for kk */
fprintf(outfile," ");
for (kk=0; kk<width; kk++) {
if ( ((kk % 8) == 0) && (kk != 0) ) {
fprintf(outfile,"+");
} else {
fprintf(outfile,"-");
}
} /* end for kk */
// fprintf(outfile," l=%d\r\n",lines);
fprintf(outfile," \r\n");
} else { /* linebuf != "{0" */
fprintf(outfile,"%s\r\n", origbuf);
}
}
fclose(outfile);
return(0);
}
|
C
|
#include <stdio.h>
int reverseNum(int n)
{
int revNum = 0;
revNum = (n % 10) * 100;
revNum += ((n / 10) % 10) * 10;
revNum += (n / 100);
return revNum;
}
int main(void)
{
int a, b;
scanf("%d %d", &a, &b);
a = reverseNum(a);
b = reverseNum(b);
if (a > b)
printf("%d", a);
else
printf("%d", b);
return 0;
}
|
C
|
#include "fraction.h"
#include "math.h"
#include <stdio.h>
#include <stdlib.h>
Fraction add ( Fraction a, Fraction b ) {
return (Fraction) { a.num * b.den + a.den * b.num, a.den * b.den };
}
Fraction multiply ( Fraction a, Fraction b ) {
return (Fraction) { a.num * b.num, a.den * b.den };
}
Fraction reduce ( Fraction a ) {
int num = a.num;
int den = a.den;
bool isNegtive = false;
if (den == 0 && num == 0) return (Fraction) { num, den };
if (den == 0) return (Fraction) { 1, den };
if (num == 0) return (Fraction) { num, 1 };
if ((num < 0 && den > 0) || (num > 0 && den < 0)) isNegtive = true;
num = abs(num);
den = abs(den);
for (int i = 2; i <= num && i <= den; i++) {
if (num % i == 0 && den % i == 0) {
num = num / i;
den = den / i;
i = 1;
}
}
if (isNegtive) return (Fraction) { -num, den };
return (Fraction) { num, den };
}
|
C
|
/*
* File: MatrixMath.c
* Author: Stephanie Lin
*
* Created on April 19, 2019, 2:21 PM
*/
#include <stdio.h>
#include <stdlib.h>
#include "MatrixMath.h"
/*
*
*/
static float MatrixDeterminant2x2(float mat[2][2]) {
float a;
float b;
float c;
// Does cross multiplication of 2x2 matrix
a = (mat[0][0] * mat[1][1]);
b = (mat[0][1] * mat[1][0]);
c = a - b;
return c;
}
void MatrixPrint(float mat[3][3]) {
printf("\nOutput of MatrixPrint():\n");
printf("_________________\n");
printf("\n%0.2f %0.2f %0.2f\n%0.2f %0.2f %0.2f\n%0.2f %0.2f %0.2f\n",
mat[0][0], mat[0][1], mat[0][2],
mat[1][0], mat[1][1], mat[1][2],
mat[2][0], mat[2][1], mat[2][2]);
printf("-----------------\n");
printf("\nExpected output of MatrixPrint():\n");
printf("_________________\n");
printf("\n%0.2f %0.2f %0.2f\n%0.2f %0.2f %0.2f\n%0.2f %0.2f %0.2f\n",
1.00,2.00,6.00,4.00,5.00,6.00,7.00,8.00,9.00);
printf("-----------------\n");
}
int MatrixEquals(float mat1[3][3], float mat2[3][3]) {
int not_equal = 1;
int r;
int c;
float abs;
for (r = 0; r < 3; r++) {
for (c = 0; c < 3; c++) {
if ((mat1[r][c] - mat2[r][c]) <= 0) { //checks if difference is negative
abs = (mat1[r][c] - mat2[r][c]) * -1;
if (FP_DELTA >= abs) { //checks if error is less that FP_DELTA
not_equal = 0; //sets flag for matrix equal so far
} else {
not_equal = 1;
break;
}
} else if (((mat1[r][c] - mat2[r][c]) > 0)) { //checks if difference is positive
not_equal = 1;
break;
} else if (not_equal == 1) {
break;
} else {
not_equal = 1;
}
if (not_equal == 1) {
break;
}
}
if (not_equal == 1) {
break;
}
}
if (not_equal == 0) {
return 1;
} else {
return 0;
}
}
void MatrixAdd(float mat1[3][3], float mat2[3][3], float result[3][3]) {
int r;
int c;
for (r = 0; r < 3; r++) {
for (c = 0; c < 3; c++) {
result[r][c] = (mat1[r][c] + mat2[r][c]);
}
}
}
void MatrixMultiply(float mat1[3][3], float mat2[3][3], float result[3][3]) {
int r;
int c;
int i;
int j;
int k;
float cell = 0;
for (r = 0; r < 3; r++) {
for (j = 0; j < 3; j++) {
for (c = 0, i = 0; c < 3, i < 3; c++, i++) {
//multiplies row and column and add to itself each time
cell += (mat1[r][c] * mat2[i][j]);
}
result[r][j] = cell;
cell = 0;
}
}
}
void MatrixScalarAdd(float x, float mat[3][3], float result[3][3]) {
int r;
int c;
for (r = 0; r < 3; r++) {
for (c = 0; c < 3; c++) {
result[r][c] = (mat[r][c] + x);
}
}
}
void MatrixScalarMultiply(float x, float mat[3][3], float result[3][3]) {
int r;
int c;
for (r = 0; r < 3; r++) {
for (c = 0; c < 3; c++) {
result[r][c] = (mat[r][c] * x);
}
}
}
float MatrixTrace(float mat[3][3]) {
int r;
int c;
float result;
result = 0;
for (r = 0; r < 3; r++) {
for (c = 0; c < 3; c++) {
if (r == c) {
//if at diagonal, then will add to itself
result += mat[r][c];
}
}
}
return result;
}
void MatrixTranspose(float mat[3][3], float result[3][3]) {
int r;
int c;
int i;
int j;
for (r = 0; r < 3; r++) {
for (c = 0; c < 3; c++) {
if (r != c) {
//swaps cells so information doesn't get lost
result[c][r] = mat[r][c];
result[r][c] = mat[c][r];
} else {
//if at diagonal information remains the same
result[r][c] = mat[r][c];
}
}
}
}
void MatrixSubmatrix(int i, int j, float mat[3][3], float result[2][2]) {
int r;
int c;
int r2;
int c2;
r2 = 0;
c2 = 0;
for (r = 0; r < 3; r++) {
for (c = 0; c < 3; c++) {
if ((r != i - 1) && (c != j - 1)) {
//checks if i and j is equal to r and c. if so, skips those cells
result[r2][c2] = mat[r][c];
c2++;
} else {
}
}
}
}
float MatrixDeterminant(float mat[3][3]) {
float result[2][2];
float det;
float det1;
float det2;
float det3;
float determinant1;
float determinant2;
float determinant3;
//calculating determinant of each submatrix to calculate 3x3 determinant
MatrixSubmatrix(1, 1, mat, result);
det1 = MatrixDeterminant2x2(result);
determinant1 = mat[0][0] * det1;
MatrixSubmatrix(1, 2, mat, result);
det2 = MatrixDeterminant2x2(result);
determinant2 = mat[0][1] * det2;
MatrixSubmatrix(1, 3, mat, result);
det3 = MatrixDeterminant2x2(result);
determinant3 = mat[0][2] * det3;
det = determinant1 - determinant2 + determinant3;
return det;
}
void MatrixInverse(float mat[3][3], float result[3][3]) {
int r;
int c;
float det;
float result1[3][3];
float two[2][2];
float divdet;
det = MatrixDeterminant(mat);
MatrixTranspose(mat, result1);
MatrixSubmatrix(1, 1, result1, two);
result[0][0] = MatrixDeterminant2x2(two);
MatrixSubmatrix(1, 2, result1, two);
result[0][1] = -(MatrixDeterminant2x2(two));
MatrixSubmatrix(1, 3, result1, two);
result[0][2] = MatrixDeterminant2x2(two);
MatrixSubmatrix(2, 1, result1, two);
result[1][0] = -(MatrixDeterminant2x2(two));
MatrixSubmatrix(2, 2, result1, two);
result[1][1] = MatrixDeterminant2x2(two);
MatrixSubmatrix(2, 3, result1, two);
result[1][2] = -(MatrixDeterminant2x2(two));
MatrixSubmatrix(3, 1, result1, two);
result[2][0] = MatrixDeterminant2x2(two);
MatrixSubmatrix(3, 2, result1, two);
result[2][1] = -(MatrixDeterminant2x2(two));
MatrixSubmatrix(3, 3, result1, two);
result[2][2] = MatrixDeterminant2x2(two);
if (det == 0) {
} else {
divdet = (1 / det);
MatrixScalarMultiply(divdet, result, result1);
}
}
|
C
|
#include "path_planning.h"
//to get pos in node array based on x, y
// pos = y * 30 + x
//to get x, y in terms of pos
// y = pos / 30
// x = pos % 30
//note that when accessing, for example, current_map->map[i][j]
//is equivalent to (word) current_map[i][j]
void bfs(maze_map* current_map, int* target_point) {
int target_x = target_point[0];
int target_y = target_point[1];
int current_bot_x = 0; // in MIPS, modify this to get data from interrupt IO
int current_bot_y = 0; // see above
refresh_pp();
int queue[MAXIMUM_NODE_NUM]; //at most 900!
int queue_ptr = -1;
int ava_spot_ptr = 1;
queue[0] = current_bot_y * 30 + current_bot_x;
visited_mark[queue[0]] = 1;
//prv_pos[queue[0]] = -1;
//we dont need this line bc it's inited to be so
while (1) {
++queue_ptr;
// printf("queue_ptr: %d\n", queue_ptr);
// if queue > end_ptr, we should end. but technically that should not happen.
int current_node = queue[queue_ptr];
//printf("current_node: %d\n", current_node);
//printf("Current_node: %d\n", current_node);
// if (visited_mark[current_node]) {
// continue;
// }
int node_x = current_node % 30;
int node_y = current_node / 30;
//printf("cur x: %d\ncur y: %d\n", node_x, node_y);
if (node_x == target_x && node_y == target_y) {
//finished! Recurse and get traveled path
int cur_pos = current_node;
int cnt = 0;
while (cur_pos != -1) {
command_buffer[cnt++] = cur_pos;
cur_pos = prv_pos[cur_pos];
}
// now cnt = length of command
int i = 0;
for (; i < cnt / 2; ++i) {
int temp = command_buffer[i];
command_buffer[i] = command_buffer[cnt - i - 1];
command_buffer[cnt - i - 1] = temp;
}
i = 0;
for (; i < cnt - 1; ++i) {
int cur_pos = command_buffer[i];
int next_pos = command_buffer[i + 1];
if (next_pos == cur_pos + 30)
command_buffer[i] = SOUTH; //move south
if (next_pos == cur_pos - 30)
command_buffer[i] = NORTH;
if (next_pos == cur_pos + 1)
command_buffer[i] = EAST;
if (next_pos == cur_pos - 1)
command_buffer[i] = WEST;
}
command_buffer[i] = -1;
return;
}
//add subsequent nodes to queue and update their prv positions
//east
if (current_map->map[node_y][node_x].e_open) {
int next_pos = node_y * 30 + node_x + 1;
//printf("E pos: %d\n", next_pos);
if (next_pos / 30 == node_y && !(visited_mark[next_pos])) {
visited_mark[next_pos] = 1; //mark
queue[ava_spot_ptr++] = next_pos;
prv_pos[next_pos] = current_node;
}
}
if (current_map->map[node_y][node_x].w_open) {
int next_pos = node_y* 30 + node_x - 1;
if (next_pos / 30 == node_y && !(visited_mark[next_pos])) {
visited_mark[next_pos] = 1;
queue[ava_spot_ptr++] = next_pos;
prv_pos[next_pos] = current_node;
}
}
if (current_map->map[node_y][node_x].n_open) {
int next_pos = node_y * 30 + node_x - 30;
if (next_pos >= 0 && !(visited_mark[next_pos])) {
visited_mark[next_pos] = 1;
queue[ava_spot_ptr++] = next_pos;
prv_pos[next_pos] = current_node;
}
}
if (current_map->map[node_y][node_x].s_open) {
int next_pos = node_y * 30 + node_x + 30;
if (next_pos < MAXIMUM_NODE_NUM && !(visited_mark[next_pos])) {
visited_mark[next_pos] = 1;
queue[ava_spot_ptr++] = next_pos;
prv_pos[next_pos] = current_node;
//printf("Setting prv_pos[%d] = %d\n", next_pos, current_node);
}
}
}
}
|
C
|
/*
* conv.c
*
* Created on: May 1, 2013
* Author: Rafat Hussain
*/
#include "conv.h"
int factorf(int M) {
int N;
N = M;
while (N%7 == 0){
N = N/7;
}
while (N%3 == 0){
N = N/3;
}
while (N%5 == 0){
N = N/5;
}
while (N%2 == 0){
N = N/2;
}
return N;
}
int findnext(int M) {
int N;
N = M;
while (factorf(N) != 1) {
++N;
}
return N;
}
int findnexte(int M) {
int N;
N = M;
while (factorf(N) != 1 || N%2 != 0) {
++N;
}
return N;
}
conv_object conv_init(int N, int L) {
conv_object obj = NULL;
int conv_len;
conv_len = N + L - 1;
obj = (conv_object) malloc (sizeof(struct conv_set));
//obj->clen = npow2(conv_len);
//obj->clen = conv_len;
obj->clen = findnexte(conv_len);
obj->ilen1 = N;
obj->ilen2 = L;
obj->fobj = fft_real_init(obj->clen,1);
obj->iobj = fft_real_init(obj->clen,-1);
return obj;
}
void conv_directx(fft_type *inp1,int N, fft_type *inp2, int L,fft_type *oup){
int M,k,n;
M = N + L - 1;
for (k = 0; k < M;++k) {
oup[k] = 0.0;
for ( n = 0; n < N; ++n) {
if ( (k-n) >= 0 && (k-n) < L ) {
oup[k]+= inp1[n] * inp2[k-n];
}
}
}
}
void conv_direct(fft_type *inp1,int N, fft_type *inp2, int L,fft_type *oup) {
int M,k,m,i;
fft_type t1,tmin;
M = N + L -1;
i = 0;
if (N >= L) {
for (k = 0; k < L; k++) {
oup[k] = 0.0;
for (m = 0; m <= k;m++) {
oup[k]+= inp1[m] * inp2[k-m];
}
}
for (k = L; k < M; k++) {
oup[k] = 0.0;
i++;
t1 = L + i;
tmin = MIN(t1,N);
for (m = i; m < tmin;m++) {
oup[k]+= inp1[m] * inp2[k-m];
}
}
} else {
for (k = 0; k < N; k++) {
oup[k] = 0.0;
for (m = 0; m <= k;m++) {
oup[k]+= inp2[m] * inp1[k-m];
}
}
for (k = N; k < M; k++) {
oup[k] = 0.0;
i++;
t1 = N + i;
tmin = MIN(t1,L);
for (m = i; m < tmin;m++) {
oup[k]+= inp2[m] * inp1[k-m];
}
}
}
}
void conv_fft(const conv_object obj,fft_type *inp1,fft_type *inp2,fft_type *oup) {
int i,N,L1,L2,ls;
fft_type* a;
fft_type* b;
fft_data* c;
fft_data* ao;
fft_data* bo;
fft_type* co;
N = obj->clen;
L1 = obj->ilen1;
L2 = obj->ilen2;
ls = L1 + L2 - 1;
a = (fft_type*) malloc (sizeof(fft_data) * N);
b = (fft_type*) malloc (sizeof(fft_data) * N);
c = (fft_data*) malloc (sizeof(fft_data) * N);
ao = (fft_data*) malloc (sizeof(fft_data) * N);
bo = (fft_data*) malloc (sizeof(fft_data) * N);
co = (fft_type*) malloc (sizeof(fft_data) * N);
for (i = 0; i < N;i++) {
if (i < L1) {
a[i] = inp1[i];
} else {
a[i] = 0.0;
}
if (i < L2) {
b[i] = inp2[i];
} else {
b[i] = 0.0;
}
}
fft_r2c_exec(obj->fobj,a,ao);
fft_r2c_exec(obj->fobj,b,bo);
for (i = 0; i < N;i++) {
c[i].re = ao[i].re * bo[i].re - ao[i].im * bo[i].im;
c[i].im = ao[i].im * bo[i].re + ao[i].re * bo[i].im;
}
fft_c2r_exec(obj->iobj,c,co);
for (i = 0; i < ls;i++) {
oup[i] = co[i]/N;
}
free(a);
free(b);
free(c);
free(ao);
free(bo);
free(co);
}
void free_conv(conv_object object) {
free(object);
}
|
C
|
#include "lab6.h"
int main(void)
{
// Declare all variables
Student * students;
students = createArray();
if (students != NULL)
{
// Print out the result
printf("The average GPA of %d students is %.2f.\n\n", getNumberOfStudents(students), getAverageOfGPA(students));
freeArray(students);
}
else
{
printf("ERROR: Fail to create a Student array.\n");
return -1; //this only happens if the file cant be opened
}
return 0;
}
|
C
|
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <unistd.h>
#include <string.h>
int main() {
int threads = 16;
int msg_size = 2048*64;
size_t size = threads * msg_size;
int fd = open("/tmp/testmmap", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
ftruncate(fd, size + 4096);
volatile char *buf = (char*)mmap(NULL, 4096 + size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
char *src = (char*)malloc(size);
for (size_t i = 0; i < threads; i++) {
buf[i] = 1;
}
for (size_t i = 0; i < size; i++) {
src[i] = i;
}
#pragma omp parallel for
for (size_t i = 0; i < threads; i++) {
size_t off = i * size/threads;
for (int j = 0; j < 1e3; j++) {
memset(src+off, (char)i, size/threads);
while (buf[i] == 0) {
}
memcpy(buf+(off+4096), src+off, size/threads);
buf[i] = 0;
}
}
return 0;
}
|
C
|
//string length
#include<stdio.h>
#include<string.h>
int main()
{
char str[50];
int i=0;
printf("Enter the string:\n");
gets(str);
while(str[i]!='\0')
{
i++;
}
printf("string length is %d\n",i);
}
|
C
|
/* Ex05_01.c */
// if 문 써보기
#include <stdio.h>
int main(void)
{
int score;
printf("점수를 입력하세요. : ");
scanf("%d", &score);
if( score < 60 ) {
printf("%d점은 불합격입니다.\n", score);
}
if ( score >= 60 ) {
printf("%d점은 합격입니다.\n", score);
}
return 0;
}
|
C
|
/******************************************************************************
* File: TimeDaemon.cc
* Aufgabe: the daemon code
* Autor: M. Thaler, ZHW
* Datum: Februar 2000 (Rev. 8/2004, Rev. 3/2008)
* History: 29/03/2008 M. Thaler: single connection socket server
******************************************************************************/
//*****************************************************************************
// system includes
//*****************************************************************************
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/un.h>
#include <netdb.h>
#include <time.h>
//*****************************************************************************
// local includes
//*****************************************************************************
#include "TimeDaemon.h"
#include "TimeDaemonDefs.h"
#include "IPsockCom.h"
//*****************************************************************************
// Function: TimeDeamon
// Parameter: data: expects here pointer to string
//*****************************************************************************
void TimeDaemon(void *data) {
TimeData tData;
char buffer[COM_BUF_SIZE];
struct tm MyTime;
time_t ActualTime;
int sfd, cfd;
printf("%s\n", (char *)data);
// start server
sfd = StartTimeServer(TIME_PORT);
if (sfd < 0) {
perror("could not start socket server");
exit(-1);
}
while (1) {
cfd = WaitForClient(sfd, buffer);
if ((strcmp(buffer, REQUEST_STRING) == 0) && (cfd >= 0)) {
time(&ActualTime);
MyTime = *localtime(&ActualTime);
tData.hours = MyTime.tm_hour;
tData.minutes = MyTime.tm_min;
tData.seconds = MyTime.tm_sec;
tData.day = MyTime.tm_mday;
tData.month = MyTime.tm_mon + 1;
tData.year = MyTime.tm_year + 1900;
write(cfd, (char *)(&tData), sizeof(tData));
}
}
// if we should somehow come here (how ?)
close(sfd);
exit(0);
}
//*****************************************************************************
|
C
|
#include <pic.h>
void eeprom_str_write(unsigned char *ptr, unsigned char address, unsigned char length)
{
unsigned char i=0;
while(i!=length)
{
eeprom_write(address+i,*(ptr+i));
i++;
}
}
void eeprom_str_read(unsigned char *ptr, unsigned char address, unsigned char length)
{
unsigned char i=0;
while(i!=length)
{
*(ptr+i)=eeprom_read(address+i);
i++;
}
}
|
C
|
#include "kernel_stats.h"
double get_current_time() {
struct timeval tp;
struct timezone tzp;
gettimeofday(&tp,&tzp);
return ((double) tp.tv_sec + (double) tp.tv_usec * 1.e-6 );
}
void print_timestep(uint8_t type, double collected_time) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if(rank == 0)
switch(type) {
case PRINT_INIT:
printf("Init time,%f\n", collected_time - init_time);
break;
case PRINT_STATS:
printf("Iteration,%i,%f,%f\n", current_iteration, collected_time - init_time, collected_time - begin_time);
}
}
void init_timestep_() {
current_iteration = 0;
init_time = get_current_time();
}
void end_timestep_() {
double end_time = get_current_time();
print_timestep(PRINT_STATS, end_time);
if(early_stop && current_iteration == STOP_IN)
MPI_Abort(MPI_COMM_WORLD, 0);
}
void begin_timestep_() {
if(current_iteration == 0) {
double current_time = get_current_time();
print_timestep(PRINT_INIT, current_time);
}
current_iteration++;
begin_time = get_current_time();
}
int get_iteration_() {
return current_iteration;
}
|
C
|
#include "burger.h"
bool interrupt = false; /* Flag which will be set to true when the threads should terminate themselves */
/* Define the counter for available burgers in the rack */
uint8_t burger_count;
int main ()
{
//uint8_t burger_count = 0;
char s[1000];
FILE *fptr;
if ((fptr = fopen("test_cases.txt", "r")) == NULL)
{
printf("Error! File cannot be opened.");
exit(1);
}
while(fgets(s,sizeof(s),fptr))
{
//burger_count = 0;
int num_of_tests;
fscanf(fptr,"%d",&num_of_tests);
printf("Number of test cases :: %d\n",num_of_tests);
while (num_of_tests--)
{
burger_count = 0;
printf("Burger Count :: %d\n",burger_count);
//burger_count = 0;
fscanf(fptr,"%d",&COOK_COUNT);
printf("Enter cook count :: %d\n",COOK_COUNT);
fscanf(fptr,"%d",&CASHIER_COUNT);
printf("Enter cashier count :: %d\n",CASHIER_COUNT);
fscanf(fptr,"%d",&CUSTOMER_COUNT);
printf("Enter customer count :: %d\n",CUSTOMER_COUNT);
fscanf(fptr,"%d",&RACK_HOLDER_SIZE);
printf("Enter rack holder size :: %d\n",RACK_HOLDER_SIZE);
fscanf(fptr,"%d",&WAITING_TIME);
printf("Enter waiting time :: %d\n",WAITING_TIME);
burger_threads();
}
}
fclose(fptr);
/*
int num_of_tests;
printf("Number of test cases :: ");
scanf("%d",&num_of_tests);
while (num_of_tests--)
{
printf("Enter cook count :: ");
scanf("%d",&COOK_COUNT);
printf("Enter cashier count :: ");
scanf("%d",&CASHIER_COUNT);
printf("Enter customer count :: ");
scanf("%d",&CUSTOMER_COUNT);
printf("Enter rack holder size :: ");
scanf("%d",&RACK_HOLDER_SIZE);
printf("Enter waiting time :: ");
scanf("%d",&WAITING_TIME);
burger_threads();
}
*/
}
|
C
|
/*
* CCD.c
*
* Created on: 2013-12-2
* Author: lvniqi
* Email: lvniqi@gmail.com
*/
/*
棡ʹʱdzСģ
ʹǰʼ
Ҫ ֤ݲ!
ͬʱ ֹ
*/
#ifndef LINKLIST_H_
#define LINKLIST_H_
#include <pthread.h>
#include <stdbool.h>
#include <string.h>
#include<stdlib.h>
#include<stdio.h>
#include "Sequeue.h"
#define DEBUG
/***************************************/
typedef struct _socks{
int udp;
int tcp;
int address;
}socks;
typedef struct _socksfd_node socksfd_node;
struct _socksfd_node
{
socks dataspace;
socksfd_node *next;
};
typedef struct{
socksfd_node* begin;
pthread_rwlock_t lock;//ַ
}socksfd;
/*****************************************/
/*ڵͷʼ*/
#define Socksfd_Init(sl) \
{ \
(sl)->begin = 0;\
pthread_rwlock_init(&((sl)->lock), NULL);\
}
/*õг*/
extern int socksfd_GetLen(socksfd* sl);
/*ӽڵ*/
extern int Socksfd_Add(socksfd* sl,int ip,int tcp,int udp);
/*ɾڵ*/
extern bool Socksfd_Delete(socksfd* sl,int ip);
/*ʾ*/
extern void Socksfd_Print(socksfd *sl);
/*ص*/
extern void Socksfd_RunFuc(socksfd *sl,void(*func)(socks*));
#endif
|
C
|
#include <stdio.h>
#include <cs50.h>
string cardType(long num)
{
int firstNumber, i = 1;
do
{
firstNumber = num%10;
num = num / 10;
i++;
}
while(num / 10 != 0);
if(firstNumber == 3 && i == 15)
{
return "AMEX";
}
else if(firstNumber == 4 && (i == 13 || i == 16))
{
return "VISA";
}
else if(firstNumber == 5 && i == 16)
{
return "MASTERCARD";
}
else
{
return "INVALID";
}
}
int main(void)
{
long number = get_long("Number : ");
string type = cardType(number);
int sum = 0, sum1 = 0, sum2 = 0, i = 1;
do
{
int rem = 0;
rem = number%10;
if(i % 2 == 0)
{
rem = rem * 2;
if(rem / 10 == 0)
{
sum2 = sum2 + rem;
}
else
{
do
{
int digit = 0;
digit = rem % 10;
sum2 = sum2 + digit;
rem = rem / 10;
}
while(rem != 0);
}
}
else
{
sum1 = sum1 + rem;
}
number = number / 10;
i++;
}
while(number != 0);
sum = sum1 + sum2;
if(sum % 10 == 0)
{
printf("%s\n", type);
}
else
{
printf("INVALID\n");
}
}
|
C
|
/* receivemq.c */
/* message queue example */
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#define BUFSIZE 16
#define QKEY (key_t)0111
struct msgq_data {
long type;
char text[BUFSIZE];
} ;
struct msgq_data recv_data;
int main()
{
int qid, len;
if ((qid = msgget(QKEY, IPC_CREAT | 0666))
== -1) {
perror ("msgget failed");
exit (1);
}
if ((len=msgrcv(qid, &recv_data, BUFSIZE, 0,
0)) == -1) {
perror ("msgrcv failed");
exit (1);
}
printf("received from message queue: %s\n",
recv_data.text);
if (msgctl(qid, IPC_RMID, 0) == -1) {
perror ("msgctl failed");
exit (1);
}
}
|
C
|
//
// main.c
// tree
//
// Created by 김지우 on 2021/05/25.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct TreeNode {
int data;
struct TreeNode *left, *right;
} TreeNode;
TreeNode* CreateTree(void){
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node -> left = NULL;
node -> right = NULL;
return node;
}
void Lchild(TreeNode* par, TreeNode* chi){
if (par->left != NULL) free(par->left);
par->left = chi;
}
void Rchild(TreeNode* par, TreeNode* chi){
if (par->right != NULL) free(par->right);
par -> right = chi;
}
void SetData (TreeNode* node, int Data){
node->data = Data;
}
void ShowNodeData(int data){
if (0<=data && data<=9) printf("%d ",data);
else printf("%c ",data);
}
TreeNode* ExpTree(char exp[]);
int Evaluate(TreeNode* root);
void PreorderTraverse(TreeNode* root);
void InorderTraverse(TreeNode* root);
void PostorderTraverse(TreeNode* root);
void Levelorder (TreeNode* root);
//----------main----------
int main() {
char exp[50];
printf("수식을 입력하세요(공백 없이 입력) : ");
gets(exp);
TreeNode* Tree = ExpTree(exp);
printf("전위 순회 : ");
PreorderTraverse(Tree);
printf("\n");
printf("중위 순회 : ");
InorderTraverse(Tree);
printf("\n");
printf("후위 순회 : ");
PostorderTraverse(Tree);
printf("\n");
printf("레벨 순회 : ");
Levelorder (Tree);
printf("\n");
printf("계산 결과 : %d \n", Evaluate(Tree));
return 0;
}
//----------evaluate----------
#define True 1
#define False 0
typedef int Bool;
typedef struct {
int stackArr[10];
int top;
}Stack;
Stack* Create(void) {
Stack* tempstack;
tempstack = malloc(sizeof(Stack));
tempstack->top = -1;
return tempstack;
}
Bool isEmpty(Stack* pstack) {
if (pstack->top == -1)
return True;
else
return False;
}
Bool isFull(Stack* pstack) {
if (pstack->top == 50 - 1)
return True;
else
return False;
}
void Spush(Stack* pstack, int Data) {
pstack->stackArr[++pstack->top] = Data;
}
int Spop(Stack* pstack) {
return pstack->stackArr[pstack->top--];
}
int peek(Stack* pstack) {
if (isEmpty(pstack)) {
printf("Stack is empty. \n");
exit(1);
}
else
return pstack->stackArr[pstack->top];
}
TreeNode* stack[50];
int top = -1;
void push(TreeNode* data) {
if (top< 49 && data != NULL) stack[++top] = data;
}
TreeNode* pop() {
TreeNode* node;
if (top >=0) node = stack[top--];
return node;
}
int pri(char ch) {
switch (ch) {
case '+': case '-':
return 1;
case '*': case '/':
return 2;
}
return -1;
}
TreeNode* ExpTree(char exp[]){
TreeNode* node;
int len = (int)strlen(exp);
int i;
Stack* s = Create();
int j = 0;
char ch;
char str[10];
for (i = 0; i < len; i++) {
ch = exp[i];
switch (ch) {
case '+': case '-': case '*': case '/':
while (!isEmpty(s) && pri(ch) <= pri(peek(s)))
str[j++] = Spop(s);
Spush(s, ch);
break;
default:
if (ch >= '0' && ch <= '9') {
str[j++] = ch;
break;
}
}
}
while (!isEmpty(s))
str[j++] = Spop(s);
for (i=0; i<len; i++){
node = CreateTree();
if(isdigit(str[i]))SetData(node, str[i]-'0');
else {
Rchild(node, pop());
Lchild(node, pop());
SetData(node, str[i]);
}
push(node);
}
return pop();
}
void PreorderTraverse(TreeNode* root) {
if(root == NULL) return;
ShowNodeData(root->data);
PreorderTraverse(root->left);
PreorderTraverse(root->right);
}
void InorderTraverse(TreeNode* root) {
if(root == NULL) return;
InorderTraverse(root->left);
ShowNodeData(root->data);
InorderTraverse(root->right);
}
void PostorderTraverse(TreeNode* root) {
if(root == NULL) return;
PostorderTraverse(root->left);
PostorderTraverse(root->right);
ShowNodeData(root->data);
}
int front =0, rear =0;
TreeNode* Queue[20];
void addQ(TreeNode* node) {
Queue[++rear] = node;
}
TreeNode* delQ() {
return Queue[++front];
}
void Levelorder (TreeNode* root) {
if(root == NULL) return;
addQ(root);
while(1){
root = delQ();
if (root != NULL){
ShowNodeData(root->data);
if(root->left != NULL) addQ(root->left);
if(root->right != NULL) addQ(root->right);
}
else break;
}
}
int Evaluate(TreeNode* root) {
if (root == NULL) return 0;
if (root->left == NULL && root->right ==NULL) return root->data;
else {
int op1 = Evaluate(root->left);
int op2 = Evaluate(root->right);
switch (root->data) {
case '+': printf("%d + %d\n",op1,op2); return op1+op2;
case '-': printf("%d - %d\n",op1,op2);return op1-op2;
case '*': printf("%d * %d\n",op1,op2);return op1*op2;
case '/': printf("%d / %d\n",op1,op2);return op1/op2;
}
}
return 0;
}
|
C
|
#include <stdio.h>
int factorial(int num){
int result = 1;
for (int i = 1; i <= num; i++){
result = result* i;
}
return result;
};
int fibo(int num){
if(num==0)
return 0;
if(num==1)
return 1;
return fibo(num-1)+fibo(num-2);
};
int fibonacci(int num){
int fibo = 0;
for (int i = 1; i <= num; ++i){
fibo = fibo+i;
printf("%d\n",fibo);
}
return 0;
};
int print_all_odd(int num){
for(int i=1; i<=num; i+=2){
printf("%d\t",i);
}
return 0;
};
int print_all_even(int num){
for(int i=2; i<=num; i+=2){
printf("%d\t",i);
}
return 0;
};
int all_odd_print(int num1,int num2){
for (int i = num1; i < num2; i++) {
if(i%2==1)
printf("%d\t", i);
};
return 0;
};
int all_even_print(int num1,int num2){
for (int i = num1; i < num2; i++) {
if(i%2==0)
printf("%d\t", i);
};
return 0;
};
int every_Nth_num(int n,int num1,int num2){
for (int i = num1; i <= num2; i+=n) {
printf("%d\t", i);
};
return 0;
};
int print_all_odd_rev(int num){
for(int i=num; i>=1; i--){
if(i%2==1)
printf("%d\t",i);
}
return 0;
};
int print_all_even_rev(int num){
for(int i=num; i>=2; i--){
if(i%2==0)
printf("%d\t",i);
}
return 0;
};
int multi_table(int num, int upto){
for (int i = 1; i <= upto; ++i){
printf("%d * %d = %d\n",num, i, num*i );
}
return 0;
};
int sum_of_n(int num){
int sum=0;
for (int i = 0; i <= num; i++) {
sum = sum+i;
}
return sum;
};
int product_of_n(int num){
int sum=1;
for (int i = 1; i <= num; i++) {
sum=sum*i;
};
return sum;
};
int sum_of_any_num(int num1,int num2){
int sum=0;
for (int i = num1; i <= num2; i++) {
sum = sum+i;
};
return sum;
};
int product_of_any_num(int num1,int num2){
int sum=1;
for (int i = num1; i <= num2; i++) {
sum = sum*i;
};
return sum;
};
int sum_of_all_odd(int num1,int num2){
int sum = 0;
for (int i = num1; i <= num2; i++) {
if(i%2==1)
sum = sum+i;
};
return sum;
};
int sum_of_all_even(int num1,int num2){
int sum = 0;
for (int i = num1; i <= num2; i++) {
if(i%2==0)
sum = sum+i;
};
return sum;
};
|
C
|
#include <stdio.h>
int main(void)
{
int i, n;
int binary[32] = {0};
// 최대 32 자리 이므로 binary 배열 32개를 만들어주고
printf("숫자를 입력하세요 : ");
scanf("%d", &n);
for( i = 0 ; i < 32 && n > 0 ; i++ ){
// n을 계속 2로 나눠준 값을 저장하기 때문에
// n이 0 보다 작아지면 변환이 끝난것 이기 때문에
// i가 32보다 작고 n 이 0보다 클때만 for문을 반복해준다.
binary[i] = n % 2;
// i번째 자리에 2진수 변환 값을 넣어준다.
n /= 2;
}
for( i = 31 ; i >= 0 ; i--)
// 변환은 i번 째 부터 이지만
// 2진수를 읽는 방식은 역순이므로
// 31 부터 0 까지 역순으로 출력시켜준다.
{
printf("%d",binary[i]);
}
printf("\n");
}
|
C
|
#include <stdio.h>
int main (void)
{
printf ("MMMMMMMMM\n");
printf (" M \n");
printf (" M \n");
printf (" M \n");
printf (" M \n");
printf (" M \n");
printf (" M \n");
printf (" M \n");
printf ("MMMMMMMMM\n");
printf (" \n");
printf ("A \n");
printf (" A \n");
printf (" A A \n");
printf (" A A \n");
printf (" A A\n");
printf (" A A \n");
printf (" A A \n");
printf (" A \n");
printf ("A \n");
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_nl.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: wstygg <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/04/07 15:30:06 by wstygg #+# #+# */
/* Updated: 2020/04/21 12:16:37 by wstygg ### ########.fr */
/* */
/* ************************************************************************** */
#include "conf.h"
static int fn_free(t_get_next_line *gnl, const int fd, char **lp)
{
if (gnl->line_count != 0)
free(gnl->line);
if (lp[fd] != 0)
{
free(lp[fd]);
lp[fd] = 0;
}
return (-1);
}
static int fn_while(t_get_next_line *gnl)
{
gnl->interval = gnl->lp_cmp == 0 ? gnl->count : gnl->lp_cmp - gnl->buffer;
if (gnl->interval == 0 && gnl->line_count != 0)
return (0);
gnl->lp_prev = (char *)ft_malloc(gnl->interval + gnl->line_count + 1);
if (gnl->lp_prev == 0)
{
gnl->count = -1;
return (0);
}
if (gnl->interval != 0)
{
if (gnl->line_count != 0)
{
ft_memcpy(gnl->lp_prev, gnl->line, gnl->line_count);
free(gnl->line);
}
memcpy(gnl->lp_prev + gnl->line_count, gnl->buffer, gnl->interval);
gnl->line_count += gnl->interval;
}
gnl->line = gnl->lp_prev;
return (1);
}
static int fn_exit(t_get_next_line *gnl, const int fd, char **line,
char **lp)
{
gnl->interval++;
if (gnl->lp_cmp != 0 && (size_t)gnl->count > gnl->interval)
{
gnl->tmp = gnl->count - gnl->interval;
gnl->lp_cmp = ft_malloc(gnl->tmp + sizeof(size_t));
if (gnl->lp_cmp == 0)
return (fn_free(gnl, fd, lp));
if (lp[fd] != 0)
free(lp[fd]);
lp[fd] = gnl->lp_cmp;
*((size_t *)gnl->lp_cmp) = gnl->tmp;
gnl->lp_cmp += sizeof(size_t);
ft_memcpy(gnl->lp_cmp, &gnl->buffer[gnl->interval], gnl->tmp);
}
else if (lp[fd] != 0)
{
free(lp[fd]);
lp[fd] = 0;
}
gnl->line[gnl->line_count] = 0;
*line = gnl->line;
return (1);
}
int get_nl(const int fd, char **line)
{
static char *lp[0x400];
t_get_next_line gnl;
if (line == 0 || (unsigned)fd > 0x400)
return (-1);
gnl.line_count = 0;
if (lp[fd] != 0)
{
gnl.count = *((size_t *)lp[fd]);
ft_memcpy(gnl.buffer, lp[fd] + sizeof(size_t), gnl.count);
}
else
gnl.count = read(fd, gnl.buffer, BUFF_SIZE);
while (gnl.count > 0)
{
gnl.lp_cmp = ft_memchr(gnl.buffer, '\n', gnl.count);
if (fn_while(&gnl) == 0 || gnl.lp_cmp != 0)
break ;
gnl.count = read(fd, gnl.buffer, BUFF_SIZE);
}
if (gnl.count < 0)
return (fn_free(&gnl, fd, lp));
if (gnl.count == 0 && gnl.line_count == 0)
return (0);
return (fn_exit(&gnl, fd, line, lp));
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h> //For using malloc
#include "modifiedDay1.h"
#include "day3.h"
node* parseTree(char post_exp[])
{
int max = strlen(post_exp);
int stackPointer = -1;
node* stack[max+1];
for(int i = 0; i < max; i++)
{
switch(post_exp[i])
{
case 'V':
case '^':
case '>': {
node* right_child = top(stack, max, stackPointer);
pop(stack, max, &stackPointer);
node* left_child = top(stack, max, stackPointer);
pop(stack, max, &stackPointer);
node *value = (node *)malloc(sizeof(node));
value->ch = post_exp[i];
value->left = left_child;
value->right = right_child;
push(stack, max, &stackPointer, value);
break;
}
case '~': {
node* right_child = top(stack, max, stackPointer);
pop(stack, max, &stackPointer);
node *value = (node *)malloc(sizeof(node));
value->ch = post_exp[i];
value->left = NULL;
value->right = right_child;
push(stack, max, &stackPointer, value);
break;
} //Special case for negation - create right child only
default: {
node* value = (node *)malloc(sizeof(node));
value->ch = post_exp[i];
value->left = NULL;
value->right = NULL;
push(stack, max, &stackPointer, value);
break;
} //Takes care of operands
}
}
return top(stack, max, stackPointer); //Return root node
}
void inorder(node *root)
{
if(root == NULL)
return;
switch(root->ch) //If root node is operator, open a bracket
{
case '~':
case 'V':
case '^':
case '>': {
printf("(");
break;
}
default: {
break;
}
}
inorder(root->left);
printf("%c", root->ch);
inorder(root->right);
switch(root->ch) //Once operands have been printed and functions have recursed back to operator node, close bracket
{
case '~':
case 'V':
case '^':
case '>': {
printf(")");
break;
}
default: {
break;
}
}
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_2__ TYPE_1__ ;
/* Type definitions */
typedef size_t USHORT ;
typedef scalar_t__ ULONG ;
struct TYPE_2__ {scalar_t__ cy; scalar_t__ y; } ;
/* Variables and functions */
int /*<<< orphan*/ ClrLine (scalar_t__) ;
int /*<<< orphan*/ Home (size_t) ;
TYPE_1__* wWindow ;
void Clear(USHORT Window)
{
ULONG j;
for(j=0;j<wWindow[Window].cy;j++)
{
ClrLine(wWindow[Window].y+j);
}
Home(Window);
}
|
C
|
#include "libmx.h"
// Function works with NULL terminated array
void mx_print_strarr(char **arr, const char *delim)
{
if (arr != NULL || delim != NULL || *arr != NULL)
{
for (int i = 0; arr[i] != NULL; i++)
{
mx_printstr(arr[i]);
if (arr[i + 1] != NULL)
mx_printstr(delim);
}
write(1, "\n", 1);
}
}
// int main() {
// char *arr[6] = {"Hello", "darkness", "my", "old", "friend", NULL};
// mx_print_strarr(arr, "--->");
// return 0;
// }
|
C
|
/**
*--------------------------------------------------------------------\n
* HSLU T&A Hochschule Luzern Technik+Architektur \n
*--------------------------------------------------------------------\n
*
* \brief terminal with command line parser
* \file
* \author Christian Jost, christian.jost@hslu.ch
* \date 30.11.2012
*
* \b Language: Ansi-C \n\n
* \b Target: MC-Car \n
*
* \par Description:
*
* $Id: term.c 547 2013-12-01 18:41:02Z zajost $
*--------------------------------------------------------------------
*/
#include "platform.h"
#include "term.h"
#include <string.h>
#include "sci.h"
#include "util.h"
#include "pid.h"
#include "linesens.h"
void termWriteNum16s(int16 value)
{
char str[8];
utilNum16sToStr(str, sizeof(str), value);
sci1Write(str);
sci2Write(str);
}
void termWriteNum16u(uint16 value)
{
char str[8];
utilNum16uToStr(str, sizeof(str), value);
sci1Write(str);
sci2Write(str);
}
void termWriteSubString(char *str, uint8 start, uint8 length)
{
str += start;
while(length-- > 0)
{
sci1WriteChar(*(str++));
sci2WriteChar(*(str++));
}
}
void termWriteLine(char *str)
{
sci1WriteLine(str);
sci2WriteLine(str);
}
void termWrite(char *str)
{
sci1Write(str);
sci2Write(str);
}
void termWriteChar(char ch)
{
sci1WriteChar(ch);
sci2WriteChar(ch);
}
void termParseCommand(char *cmd)
{
uint8 subCmdLength = 0;
tError result = EC_INVALID_CMD;
if (strcmp(cmd, "help") == 0)
{
termWriteLine(NULL);
termWriteLine(">>> MC-Car terminal <<<");
termWriteLine("valid commands are:");
termWriteLine(" pid help");
termWriteLine(" ls help");
result = EC_SUCCESS;
}
else if (strncmp(cmd, "pid ", sizeof("pid")) == 0)
{
subCmdLength = sizeof("pid ") - 1;
result = pidParseCommand(cmd + sizeof("pid"));
}
else if (strncmp(cmd, "ls ", sizeof("ls")) == 0)
{
subCmdLength = sizeof("ls ") - 1;
result = lsParseCommand(cmd + sizeof("ls"));
}
if (result != EC_SUCCESS)
{
termWrite(cmd);
termWriteLine(": command not found!");
termWrite("Enter '");
termWriteSubString(cmd, 0, subCmdLength);
termWriteLine("help' for a list of valid commands.");
}
}
void termDoWork(void)
{
char cmd[64];
if (sci1HasLineReceived())
{
(void)sci1ReadLine(cmd, sizeof(cmd));
termParseCommand(cmd);
}
if (sci2HasLineReceived())
{
(void)sci2ReadLine(cmd, sizeof(cmd));
termParseCommand(cmd);
}
}
void termInit(void)
{
termWriteLine("MC-Car ready :-)");
}
|
C
|
#include "integral_channels_for_pedestrians.h"
#include <math.h>
#include <string.h>
#include "utility.h"
#include "image_processing.h"
#include "color_converting.h"
#include "angle_bin_compute.h"
#include "helpers/utility_data_structure.h"
static float angleBinVectors[NUMBER_BINS][2];
static void initAngleBinCompute(void)
{
const float angle_quantum = MY_PI / (NUMBER_BINS);
unsigned int binIndex = 0;
float theta = 0; // theta is in the center of the angle bin
for (binIndex = 0; binIndex < NUMBER_BINS; binIndex += 1, theta += angle_quantum)
{
angleBinVectors[binIndex][0] = (float)cos(theta);
angleBinVectors[binIndex][1] = (float)sin(theta);
}
}
// calling convention is the same of atan2
static int angleBinCompute(const int y, const int x)
{
// no need to explicitly handle the case y and x == 0,
// this correspond to zero gradient areas, thus whatever the bin, the histograms will not be modified
int i = 0;
int index = 0;
float maxDotProduct = (float)fabs(x * angleBinVectors[0][0] + y * angleBinVectors[0][1]);
float dotProduct = 0;
for (i = 1; i < NUMBER_BINS; i += 1)
{
dotProduct = (float)fabs(x * angleBinVectors[i][0] + y * angleBinVectors[i][1]);
if (dotProduct > maxDotProduct)
{
maxDotProduct = dotProduct;
index = i;
}
}
return index;
}
static void computeShrinkedChannel(const unsigned char *grayImage, const Size inputSize, const Size channelSize, const int shrinkingFactor, unsigned char *dstImage)
{
const int factor = shrinkingFactor * shrinkingFactor;
const int maxInputY = inputSize.y - 1;
const int maxInputX = inputSize.x - 1;
int row = 0;
int col = 0;
int sum = 0;
unsigned char *rowDst = NULL;
const unsigned char* rowSrc = NULL;
int inputX = 0;
int inputY = 0;
int x = 0;
int y = 0;
int tempX = 0;
int tempY = 0;
for (row = 0; row < channelSize.y; row++)
{
rowDst = dstImage + row * channelSize.x;
for (col = 0; col < channelSize.x; col++)
{
sum = 0;
inputY = row * shrinkingFactor;
inputX = col * shrinkingFactor;
for (y = 0; y < shrinkingFactor; y += 1)
{
tempY = Pedestrian_MIN(inputY + y, maxInputY);
rowSrc = grayImage + tempY * inputSize.x;
for (x = 0; x < shrinkingFactor; x += 1)
{
tempX = Pedestrian_MIN(inputX + x, maxInputX);
sum += *(rowSrc + tempX);
}
}
sum /= factor; //rescale back to [0, 255]
rowDst[col] = (unsigned char)sum;
}
}
}
static void computeHOGchannels(const unsigned char *grayImage, Size inputSize, unsigned char *inputChannels[NUMBER_CHANNELS])
{
//6 gradient orientations channels, 1 gradient magnitude channel
const int count = inputSize.y * inputSize.x;
int index = 0;
short *derivativeDx = NULL;
short *derivativeDy = NULL;
#if OPENMP == 0 && MY_NEON == 0
short dx = 0;
short dy = 0;
int squareMagnitude = 0;
int magnitude = 0;
unsigned char magnitudeU8 = 0;
int angleIndex = 0;
#endif
#if MY_NEON == 1
short *copyDerivativeDx = NULL;
short *copyDerivativeDy = NULL;
short dx = 0;
short dy = 0;
int squareMagnitude = 0;
int magnitude = 0;
unsigned char magnitudeU8 = 0;
int angleIndex = 0;
float32x4_t squareMagnitude1;
uint32x4_t squareMagnitude_int;
int16x4_t dx0;
int32x4_t dx1;
int16x4_t dy0;
int32x4_t dy1;
int32x4_t squareMagnitude0;
#endif
derivativeDx = (short*)my_calloc(count, sizeof(short));
derivativeDy = (short*)my_calloc(count, sizeof(short));
computeDerivativeX(grayImage, inputSize.x, inputSize.y, derivativeDx);
computeDerivativeY(grayImage, inputSize.x, inputSize.y, derivativeDy);
#if OPENMP == 0 && MY_NEON == 0
for (index = 0; index < count; index += 1)
{
dx = derivativeDx[index];
dy = derivativeDy[index];
squareMagnitude = dx * dx + dy * dy;
magnitude = (int)sqrtf(squareMagnitude * 0.5f);
#if DEBUG == 1
assert(magnitude < 256);
#endif
magnitudeU8 = (unsigned char)magnitude;
//Using atan2 runs at 58 Hz,
//while angleBinComputer runs at 62 Hz
angleIndex = angleBinCompute(dy, dx);
*(inputChannels[angleIndex] + index) = magnitudeU8;
*(inputChannels[NUMBER_BINS] + index) = magnitudeU8;
}
#elif MY_NEON == 1
copyDerivativeDx = derivativeDx;
copyDerivativeDy = derivativeDy;
for (index = 0; index < count - 3; index += 4)
{
dx0 = vld1_s16(copyDerivativeDx);
dx1 = vmovl_s16(dx0);
dy0 = vld1_s16(copyDerivativeDy);
dy1 = vmovl_s16(dy0);
squareMagnitude0 = vmulq_s32(dx1, dx1);
squareMagnitude0 = vmlaq_s32(squareMagnitude0, dy1, dy1);
squareMagnitude0 = vshrq_n_s32(squareMagnitude0, 1);
squareMagnitude1 = vcvtq_f32_s32(squareMagnitude0);
squareMagnitude1 = vrsqrteq_f32(squareMagnitude1);
squareMagnitude1 = vrecpeq_f32(squareMagnitude1);
squareMagnitude_int = vcvtq_u32_f32(squareMagnitude1);
vst1q_u32(inputChannels[NUMBER_BINS] + index, squareMagnitude_int);
angleIndex = angleBinCompute(copyDerivativeDy[0], copyDerivativeDx[0]);
*(inputChannels[angleIndex] + index) = (unsigned char)vgetq_lane_u32(squareMagnitude_int, 0);
angleIndex = angleBinCompute(copyDerivativeDy[1], copyDerivativeDx[1]);
*(inputChannels[angleIndex] + index + 1) = (unsigned char)vgetq_lane_u32(squareMagnitude_int, 1);
angleIndex = angleBinCompute(copyDerivativeDy[2], copyDerivativeDx[2]);
*(inputChannels[angleIndex] + index + 2) = (unsigned char)vgetq_lane_u32(squareMagnitude_int, 2);
angleIndex = angleBinCompute(copyDerivativeDy[3], copyDerivativeDx[3]);
*(inputChannels[angleIndex] + index + 3) = (unsigned char)vgetq_lane_u32(squareMagnitude_int, 3);
copyDerivativeDx += 4;
copyDerivativeDy += 4;
}
for (; index < count; index += 1)
{
dx = *copyDerivativeDx;
dy = *copyDerivativeDy;
squareMagnitude = dx * dx + dy * dy;
//magnitude = (int)fastSqrt(squareMagnitude * 0.5f);
magnitude = (int)sqrtf(squareMagnitude >> 1);
magnitudeU8 = (unsigned char)magnitude;
//Using atan2 runs at 58 Hz,
//while angleBinComputer runs at 62 Hz
angleIndex = angleBinCompute(dy, dx);
*(inputChannels[angleIndex] + index) = magnitudeU8;
*(inputChannels[NUMBER_BINS] + index) = magnitudeU8;
copyDerivativeDx++;
copyDerivativeDy++;
}
#else
#pragma omp parallel for
for (index = 0; index < count; index += 1)
{
const short dx = derivativeDx[index];
const short dy = derivativeDy[index];
const int squareMagnitude = dx * dx + dy * dy;
const int magnitude = (int)sqrtf(squareMagnitude * 0.5f);
#if DEBUG == 1
assert(magnitude < 256);
#endif
const unsigned char magnitudeU8 = (unsigned char)magnitude;
//Using atan2 runs at 58 Hz,
//while angleBinComputer runs at 62 Hz
const int angleIndex = angleBinCompute(dy, dx);
*(inputChannels[angleIndex] + index) = magnitudeU8;
*(inputChannels[NUMBER_BINS] + index) = magnitudeU8;
}
#endif
my_free(derivativeDx);
my_free(derivativeDy);
derivativeDx = NULL;
derivativeDy = NULL;
}
static void computeLUVchannels(const ElementRGB *rgbImage, Size inputSize, unsigned char *inputChannels[NUMBER_CHANNELS])
{
const int count = inputSize.y * inputSize.x;
int index = 0;
unsigned char *inputChannelL = inputChannels[7];
unsigned char *inputChannelU = inputChannels[8];
unsigned char *inputChannelV = inputChannels[9];
#if OPENMP == 0
ElementLUV luv;
for (index = 0; index < count; index += 1)
{
luv = getPixelRgbToLuv(rgbImage[index]);
inputChannelL[index] = luv.l;
inputChannelU[index] = luv.u;
inputChannelV[index] = luv.v;
}
#else
#pragma omp parallel for
for (index = 0; index < count; index += 1)
{
const ElementLUV luv = getPixelRgbToLuv(rgbImage[index]);
inputChannelL[index] = luv.l;
inputChannelU[index] = luv.u;
inputChannelV[index] = luv.v;
}
#endif
}
static void resizeChannels(unsigned char * const inputChannels[NUMBER_CHANNELS], const Size inputSize,
const Size channelSize, unsigned char *channels[NUMBER_CHANNELS])
{
int channelIndex = 0;
#if OPENMP == 1
#pragma omp parallel for
#endif
for (channelIndex = 0; channelIndex < NUMBER_CHANNELS; channelIndex += 1)
{
computeShrinkedChannel(inputChannels[channelIndex], inputSize, channelSize, SHRINKING_FACTOR, channels[channelIndex]);
}
}
static void integrateChannels(unsigned char* const channels[NUMBER_CHANNELS], const Size channelSize, unsigned int *integralChannels[NUMBER_CHANNELS])
{
int channelIndex = 0;
for (channelIndex = 0; channelIndex < NUMBER_CHANNELS; channelIndex += 1)
{
//for some strange reason explicitly defining this reference is needed to get the code compiling
integrate(channels[channelIndex], channelSize.x, channelSize.y, integralChannels[channelIndex]);
}
}
Size getChannelSize(const Size inputSize, const int shrinkingFactor)
{
Size channelSize;
//shrinkingFactor/2 to round-up
if (shrinkingFactor == 4)
{
channelSize.x = (((inputSize.x + 1) / 2) + 1) / 2;
channelSize.y = (((inputSize.y + 1) / 2) + 1) / 2;
}
else if (shrinkingFactor == 2)
{
channelSize.x = (inputSize.x + 1) / 2;
channelSize.y = (inputSize.y + 1) / 2;
}
else
{
channelSize = inputSize;
}
return channelSize;
}
void initComputeIntegralChannel(void)
{
//compute hog channels
initAngleBinCompute();
//compute LUV channels
initLUVLookupTable();
}
void computeIntegralChannel(const ElementRGB *rgbImage, const Size inputSize, unsigned int *integralChannels[NUMBER_CHANNELS])
{
#if DEBUG == 1
assert(rgbImage != NULL);
assert(integralChannels != NULL);
#endif
const Size channelSize = getChannelSize(inputSize, SHRINKING_FACTOR);
unsigned char* grayImage = NULL;
unsigned char *channels[NUMBER_CHANNELS];
unsigned char *inputChannels[NUMBER_CHANNELS];
unsigned int index = 0;
#if TEST_TIME == 1
unsigned int startTime = 0;
#endif
for (index = 0; index < NUMBER_CHANNELS; index++)
{
//allocate the channel images
//since hogInputChannels[angleIndex][y][x] does not set the value for all hog channels,
//we need to set them all to zero
inputChannels[index] = (unsigned char*)my_calloc(inputSize.y * inputSize.x, sizeof(unsigned char));
channels[index] = (unsigned char *)my_calloc(channelSize.y * channelSize.x, sizeof(unsigned char));
memset(inputChannels[index], 0, inputSize.y * inputSize.x * sizeof(unsigned char));
memset(channels[index], 0, channelSize.y * channelSize.x * sizeof(unsigned char));
}
#if TEST_TIME == 1
startTime = my_gettime();
#endif
grayImage = (unsigned char*)my_calloc(inputSize.y * inputSize.x, sizeof(unsigned char));
rgbToGray(rgbImage, inputSize.x, inputSize.y, grayImage);
#if TEST_TIME == 1
my_printf("gray cost time:%d ms\n", my_gettime() - startTime);
#endif
#if TEST_TIME == 1
startTime = my_gettime();
#endif
computeHOGchannels(grayImage, inputSize, inputChannels);
#if TEST_TIME == 1
my_printf("HOG cost time:%d ms\n", my_gettime() - startTime);
#endif
#if TEST_TIME == 1
startTime = my_gettime();
#endif
computeLUVchannels(rgbImage, inputSize, inputChannels);
#if TEST_TIME == 1
my_printf("LUV cost time:%d ms\n", my_gettime() - startTime);
#endif
#if TEST_TIME == 1
startTime = my_gettime();
#endif
resizeChannels(inputChannels, inputSize, channelSize, channels);
#if TEST_TIME == 1
my_printf("resize cost time:%d ms\n", my_gettime() - startTime);
#endif
#if TEST_TIME == 1
startTime = my_gettime();
#endif
integrateChannels(channels, channelSize, integralChannels);
#if TEST_TIME == 1
my_printf("integrate cost time:%d ms\n", my_gettime() - startTime);
#endif
my_free(grayImage);
grayImage = NULL;
for (index = 0; index < NUMBER_CHANNELS; index++)
{
my_free(inputChannels[index]);
my_free(channels[index]);
inputChannels[index] = NULL;
channels[index] = NULL;
}
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct SYMBOLTABLE
{
char name[10];
int addr;
int val;
}SYMBOLTABLE;
SYMBOLTABLE st[10];
int lc=1;
int i,p,r,c,d,q,n,sym_ptr=1;
char b1[10],b2[10],b3[10],b4[10],b5[10],b6[10],b7[10],buffer[80];
char IS[][6]={"STOP","ADD","SUB","MULT","MOVER","MOVEM","COMP","BC","DIV","READ","PRINT"};
char DL[][3]={"DC","DS"};
char AD[][7]={"START","END","ORIGIN","EQU","LTORG"};
char CC[][4]={"LT","LE","EQ","GT","GE","ANY"};
char RT[][5]={"AREG","BREG","CREG","DREG"};
int optab(char *s)
{
int i;
for(i=0;i<11;i++)
{
if(strcmp(IS[i],s)==0)
return i;
}
return -1;
}
int adtab(char *s)
{
int i;
for(i=0;i<5;i++)
{
if(strcmp(AD[i],s)==0)
return i+1;
}
return -1;
}
int regtab(char *s)
{
int i;
for(i=0;i<4;i++)
{
if(strcmp(RT[i],s)==0)
return i+1;
}
return -1;
}
int condtab(char *s)
{
int i;
for(i=0;i<6;i++)
{
if(strcmp(CC[i],s)==0)
return i+1;
}
return -1;
}
int dltab(char *s)
{
int i;
for(i=0;i<2;i++)
{
if(strcmp(DL[i],s)==0)
return i+1;
}
return -1;
}
int symtab(char *a)
{
int i;
for(i=1;i<sym_ptr;i++)
{
if(strcmp(st[i].name,a)==0)
return i;
}
return -1;
}
void passone()
{
char a[20];
printf("Enter the filename: ");
scanf("%s",a);
FILE *fin,*fout;
fin=fopen(a,"r");
if(!fin)
{
perror("Error");
}
fout=fopen("output.txt","w");
while(fgets(buffer,80,fin))
{
fprintf(fout,"\n");
n=sscanf(buffer,"%s%s%s%s%s",b1,b2,b3,b4,b5);
switch(n)
{
case 1: //STOP or END
{
i=optab(b1); //stop
if(i==0)
{
fprintf(fout,"(IS, %02d )",i);
fprintf(fout,"\t\t\t\t\t\t\t%d",lc++);
}
i=adtab(b1); //end
if(i==2)
fprintf(fout,"(AD, %02d )",i);
}
break;
case 2: //Start or Read or Print
{
i=optab(b1); //Read or Print
if(i==9|i==10)
{
fprintf(fout,"(IS, %02d )",i);
p=symtab(b2);
if(p==-1)
{
strcpy(st[sym_ptr].name,b2);
fprintf(fout,"(S, %02d )",sym_ptr);
sym_ptr++;
}
else
fprintf(fout,"(S, %02d )",p);
fprintf(fout,"\t\t\t\t\t%d",lc++);
}
i=adtab(b1);
if(i==1)
{
fprintf(fout,"(AD, %02d )",i);
fprintf(fout,"(C, %s )",b2);
lc=atoi(b2);
}
}
break;
case 3: {
i=optab(b1); //from IS[1] to IS[8]
if((i>=1 && i<=6) || (i==8))
{
fprintf(fout,"(IS, %02d )",i);
r=regtab(b2);
fprintf(fout,"(RT, %02d )",r);
p=symtab(b3);
if(p==-1)
{
strcpy(st[sym_ptr].name,b3);
fprintf(fout,"(S, %02d )",sym_ptr);
sym_ptr++;
}
else
fprintf(fout,"(S, %02d )",p);
fprintf(fout,"\t\t\t%d",lc++);
}
if(i==7)
{
fprintf(fout,"(IS, %02d )",i);
c=condtab(b2);
fprintf(fout,"(CC, %02d )",c);
p=symtab(b3);
if(p==-1)
{
strcpy(st[sym_ptr].name,b3);
fprintf(fout,"(S, %02d )",sym_ptr);
sym_ptr++;
}
else
fprintf(fout,"(S, %02d )",p);
fprintf(fout,"\t\t\t%d",lc++);
}
if(strcmp(b2,"DC")==0)
d=1;
if(strcmp(b2,"DS")==0)
d=2;
if(d==1|d==2)
{
fprintf(fout,"(DL, %02d )",d);
p=symtab(b1);
if(p==-1)
{
strcpy(st[sym_ptr].name,b1);
fprintf(fout,"(S, %02d )",sym_ptr);
st[sym_ptr].addr=lc;
sym_ptr++;
}
else
{
st[p].addr=lc+1;
fprintf(fout,"(S, %02d )",p);
}
fprintf(fout,"(C, %02d )",atoi(b3));
fprintf(fout,"\t\t\t%d",lc++);
}
}
break;
case 4: {
i=optab(b2);
fprintf(fout,"(IS, %02d )",i);
r=regtab(b3);
fprintf(fout,"(RT, %02d )",r);
q=symtab(b4);
if(q==-1)
{
strcpy(st[sym_ptr].name,b1);
fprintf(fout,"(S, %02d )",sym_ptr);
sym_ptr++;
}
else
{
fprintf(fout,"(S, %02d )",q);
}
p=symtab(b1);
strcpy(st[sym_ptr].name,b1);
st[sym_ptr].addr=lc+1;
sym_ptr++;
fprintf(fout,"\t\t\t%d",lc++);
}
break;
}
}
fclose(fin);
fclose(fout);
}
void passtwo()
{
FILE *fin,*fout;
fin=fopen("output.txt","r");
if(!fin)
{
perror("Error");
}
fout=fopen("final.txt","w");
lc=0;
int a,b,c,addr;
while(fgets(buffer,80,fin))
{
a=0,b=0,c=0;
n=sscanf(buffer,"%s%s%s%s%s%s%s",b1,b2,b3,b4,b5,b6,b7);
if(lc==0)
{
if((strcmp(b1,"(AD,")==0) && (strcmp(b2,"01")==0))
{
lc=atoi(b4);
fprintf(fout,"\n");
}
}
else if(strcmp(b1,"(IS,")==0)
{
if(strcmp(b2,"00")==0)
fprintf(fout,"%d\t00\t00\t00",lc++);
else
{
a=atoi(b2);
b=atoi(b4);
c=atoi(b6);
if(strcmp(b2,"09")==0 | strcmp(b2,"10")==0)
{
addr = st[b].addr;
fprintf(fout,"%d\t%d\t00\t%d",lc++,a,addr);
}
else
{
addr = st[c].addr;
fprintf(fout,"%d\t%02d\t%d\t%d",lc++,a,b,addr);
}
}
}
else if(strcmp(b1,"(DL,")==0)
{
if(strcmp(b2,"02")==0)
fprintf(fout,"%d",lc++);
else if(strcmp(b2,"01")==0)
fprintf(fout,"%d\t00\t00\t001",lc++);
}
fprintf(fout,"\n");
}
fclose(fin);
fclose(fout);
}
int main()
{
passone();
passtwo();
//printf("%d\n",lc);
printf("\nSymbol table-\n");
for(i=1;i<sym_ptr;i++)
printf("%d\t%s\t%d\n",i,st[i].name,st[i].addr);
return 0;
}
|
C
|
#ifndef UPEM_MORPHING_QUADRILATERAL
#define UPEM_MORPHING_QUADRILATERAL
/**
* File: quadrilateral.h
* Operations on quadrilaterals formed by adjacent triangles pairs.
*
* Author:
* Pacien TRAN-GIRARD
*/
#include <stdbool.h>
#include "common/geom.h"
#include "morpher/trianglemap.h"
/**
* Function: quadrilateral_flip_diagonal
* Flips the diagonal of a quadrilateral formed by two triangles sharing a common edge,
* using a positive rotation-like transform inverting both references.
* This transforms keeps the positive orientation of the vertices.
* Pointers to surrounding triangles are updated accordingly.
*
* Parameters:
* *t1 - the first triangle
* *t2 - the second triangle
*/
void quadrilateral_flip_diagonal(TriangleMap *t1, TriangleMap *t2);
/**
* Function: quadrilateral_is_delaunay
* Tells whether the quadrilateral formed by the two supplied adjacent triangle forms a Delaunay triangulation.
*
* Parameters:
* *t1 - first triangle
* *t2 - second triangle adjacent to the first one
*
* Returns:
* T(t1 and t2 are a Delaunay triangulation in the quadrilateral formed by the twos)
*/
bool quadrilateral_is_delaunay(TriangleMap *t1, TriangleMap *t2);
#endif
|
C
|
////////////////////////////////////////////////////////////////////////////////
//
// File : crud_client.c
// Description : This is the client side of the CRUD communication protocol.
//
// Author : Patrick McDaniel
// Last Modified : Thu Oct 30 06:59:59 EDT 2014
//
// Include Files
// Project Include Files
#include <crud_network.h>
#include <cmpsc311_log.h>
#include <cmpsc311_util.h>
// Global variables
int crud_network_shutdown = 0; // Flag indicating shutdown
unsigned char *crud_network_address = NULL; // Address of CRUD server
unsigned short crud_network_port = 0; // Port of CRUD server
//
// Functions
////////////////////////////////////////////////////////////////////////////////
//
// Function : crud_client_operation
// Description : This the client operation that sends a request to the CRUD
// server. It will:
//
// 1) if INIT make a connection to the server
// 2) send any request to the server, returning results
// 3) if CLOSE, will close the connection
//
// Inputs : op - the request opcode for the command
// buf - the block to be read/written from (READ/WRITE)
// Outputs : the response structure encoded as needed
CrudResponse crud_client_operation(CrudRequest op, void *buf) {
}
|
C
|
#include <stdio.h>
int jia(int v1, int v2) {
return v1 + v2;
}
int jian(int v1, int v2) {
return v1 - v2;
}
int dynamicFunc(int v1, int v2, int (*funcP)(int, int)) {
return funcP(v1, v2);
}
void testFuncPointer() {
printf("10+5=%d\n", dynamicFunc(10, 5, jia));
printf("10-5=%d\n", dynamicFunc(10, 5, jian));
}
|
C
|
/**
* Author: Lanqing Ye
* Date: 2019-08-25
*/
/*
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
*/
int countPrimes(int n){
if(n<=2) return 0;
int num = 0;
int i,j;
for(i = 2;i<n;i++){
int tmp=(int)sqrt(i);
for(j=2;j<=tmp;j++){
if(i%j==0)
break;
}
if(j>tmp) num++;
}
return num;
}
|
C
|
/*
* 파일명: foo.c
* 내용: InFoo 함수를 정의한다.
* InFoo 함수는 두 정수를 매개변수로 받아, 덧셈 결과를 반환한다.
*/
#include "libfooboobar.h"
int InFoo(int num1, int num2) {
printf("You are in Foo!!!\n");
printf("Foo returns the results of addition.\n");
return num1 + num2;
}
|
C
|
#include<stdio.h>
#include<conio.h>
int main()
{
int i,num,n=0,p=0,z=0;
printf("Enter the number of elements:\n");
scanf("%d",&num);
int a[num];
srand(time(NULL));
for(i=0;i<num;i++)
{
a[i]=rand() % 100-50;
}
printf("Array elements are:\n");
for(i=0;i<num;i++)
{
printf("a[%d]=> %d\n",i,a[i]);
if(a[i]<0)
n++;
else if(a[i]==0)
z++;
else
p++;
}
printf("\n n==> +v=%d",p);
printf("\n n0==> =%d",z);
printf("\n n==> -v=%d",n);
return 0;
}
|
C
|
#include <stdio.h>
int main(){
int vetor[4];
vetor[0] = 'a';
vetor[1] = 6;
vetor[2] = 'H';
vetor[3] = 39;
int i;
for(i=0; i<4; i++){
printf("(int) (int) %d\n", vetor[i]);
}
for(i=0; i<4; i++){
printf("(char) (int) %c\n", vetor[i]);
}
char vet[4];
vet[0] = 'a';
vet[1] = 6;
vet[2] = 'H';
vet[3] = 39;
for(i=0; i<4; i++){
printf("(int) (char) %d\n", vet[i]);
}
for(i=0; i<4; i++){
printf("(char) (char) %c\n", vet[i]);
}
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#if 0
void cout_multiplication_table(int x) {
for (int i = 1; i <= x; i++) {
for (int j = 1; j <= i; j++) {
printf("%02d*%02d=%3d ", j, i, j * i);
}
printf("\n");
}
}
int main() {
int i;
printf("912");
scanf("%d", &i);
cout_multiplication_table(i);
system("pause");
return 0;
}
#endif
#if 0
void swap(int* x, int* y) {
int c = 0;
c = *x;
*x = *y;
*y = c;
}
int main() {
int a = 10;
int b = 20;
printf("ӡǰ%d %d\n",a,b);
swap(&a, &b);
printf("ӡ%d %d",a,b);
system("pause");
return 0;
}
#endif
#if 0
int is_leapyear(int x) {
if (((x % 4 == 0) && (x % 100 != 0))|| (x % 400 == 0)) {
return 1;
}
else {
return 0;
}
}
int main(){
for (int i = 1000; i <= 2000; i++) {
if (1 == is_leapyear(i)) {
printf("%d \n",i);
}
}
system("pause");
return 0;
}
#endif
#if 0
int is_prime(int x) {
for (int j = 2; j <= (x / 2) + 1; j++) {
if (x % j == 0) {
return 0;
}
}
return 1;
}
int main() {
int count = 0;
for (int i = 100; i <= 200;i++) {
if (1 == is_prime(i)) {
count++;
printf("%d ",i);
}
}
printf("\n%d ", count);
}
#endif
#if 0
int main() {
int arr[100] = {0};
for (int i = 0; i < 100; i++) {
arr[i] = i*2;
}
int a = 0; //ʼԪ
int i = 1; //(ʶ)
int left = 0;//±
int right= sizeof(arr) / sizeof(arr[0]);//±
int index = (right+left)/2;//м±꣨Աֵ
printf("һ֣");
scanf("%d",&a);
while (i) {
if (a > arr[index]) {//Ƿм
left=index; //±м
index= (right + left) / 2;//¼м±
if ((left + 1 == right) && (a > arr[left] && a < arr[right])) {//жϸǷ
printf("");
i = 0;
}
}
else if(a < arr[index]) {
right = index;
index = (right + left) / 2;
if ((left + 1 == right) && (a > arr[left] && a < arr[right])) {
printf("");
i = 0;
}
}
else {//a=arr[index],ҵǰ֣±Ϊindex
printf("± %d:", index);
i = 0;
}
}
}
#endif
#if 0
//˷ھ
int main() {
for (int i = 1; i < 10; i++) {//
for (int j = 1; j <= i; j++) {//
printf("%d*%d=%d\t", j, i, j * i);//ӡ˷ھ
}
printf("\n");//ÿнҪ
}
}
#endif
#if 0
//ʮֵ
//scanfijʼ
int main(){
printf("10");
int max = 0;//ʼ
int arr[10] = { 0 };//ʼǰ
for (int i = 0; i < 10; i++){//Ϊǰ鸳ֵ
scanf("%d", &arr[i]);
}
for (int i = 0; i < 10; i++) {//˳Ҫ
if (arr[i] > max) {
max = arr[i];
}
}
printf("\nthe max number:%d ", max);
}
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MTHASH(v) ((((long) v) >> 8) & 0xffff)
#define MEMTSTSZ (1 << 18)
#define MTHASHSZ (1 << 16)
#define MTBTLEN 5
struct memtst {
long *mem;
long n;
long bt[MTBTLEN];
int freed;
};
static struct memtst *memtst; /* memtst records */
static int memtst_n; /* number of items in memtst[] */
static int memtst_sz = MEMTSTSZ;
static int *memtst_tail; /* hash table list tails */
static int *memtst_prev; /* hash table list previous items */
static int memtst_mcnt, memtst_fcnt; /* malloc() and free() count */
static long memtst_mmax; /* maximum memory used */
static long memtst_mcur; /* allocated memory */
static long memtst_mtot; /* total memory allocated */
static int memtst_full(void)
{
return memtst_n == memtst_sz;
}
static char *memtst_show(long *bt)
{
static char s[100];
snprintf(s, sizeof(s), "%8p %8p %8p %8p %8p",
bt[0], bt[1], bt[2], bt[3], bt[4]);
return s;
}
static void memtst_summary(void)
{
int i;
fprintf(stderr, "memtst %d %d %ld", memtst_mcnt, memtst_fcnt, memtst_mtot);
if (memtst_full()) {
fprintf(stderr, "\nmemtst: increase MEMTSTSZ\n");
return;
}
fprintf(stderr, " %ld\n", memtst_mmax);
for (i = 0; i < memtst_n; i++) {
struct memtst *mt = &memtst[i];
if (!mt->freed)
fprintf(stderr, "memtstleak %8p %8ld %s\n",
mt->mem, mt->n, memtst_show(mt->bt));
}
}
static void memtst_init(void)
{
memtst = malloc(memtst_sz * sizeof(memtst[0]));
memtst_prev = malloc(memtst_sz * sizeof(memtst_prev[0]));
memtst_tail = malloc(MTHASHSZ * sizeof(memtst_tail[0]));
memset(memtst_tail, 0xff, MTHASHSZ * sizeof(memtst_tail[0]));
atexit(memtst_summary);
}
static void memtst_put(void *mem, int n, long *bt)
{
struct memtst *mt;
if (!memtst)
memtst_init();
if (memtst_full())
return;
mt = &memtst[memtst_n];
mt->mem = mem;
mt->n = n;
memcpy(mt->bt, bt, sizeof(mt->bt));
memtst_prev[memtst_n] = memtst_tail[MTHASH(mem)];
memtst_tail[MTHASH(mem)] = memtst_n;
memtst_n++;
}
static struct memtst *memtst_get(void *mem)
{
int idx;
if (!memtst)
return NULL;
idx = memtst_tail[MTHASH(mem)];
while (idx >= 0) {
struct memtst *mt = &memtst[idx];
if (!mt->freed && mt->mem == mem)
return mt;
idx = memtst_prev[idx];
}
return NULL;
}
long memtst_back(int n);
static void memtst_bt(long *bt)
{
bt[0] = memtst_back(1);
bt[1] = memtst_back(2);
bt[2] = memtst_back(3);
bt[3] = memtst_back(4);
bt[4] = memtst_back(5);
}
static void memtst_mcheck(void *v, long n, long *bt)
{
if (!v)
fprintf(stderr, "memtstfail %8ld %s\n", n, memtst_show(bt));
else
memtst_put(v, n, bt);
if (v) {
memtst_mcnt++;
memtst_mcur += n;
memtst_mtot += n;
}
if (memtst_mcur > memtst_mmax)
memtst_mmax = memtst_mcur;
}
void *memtst_malloc(long n)
{
void *v = malloc(n);
long bt[MTBTLEN];
memtst_bt(bt);
memtst_mcheck(v, n, bt);
return v;
}
static void memtst_fcheck(void *v, long *bt)
{
struct memtst *mt;
memtst_fcnt++;
mt = memtst_get(v);
if (!mt && !memtst_full()) {
fprintf(stderr, "memtstfree %8p %s\n", v, memtst_show(bt));
return;
}
if (mt)
memtst_mcur -= mt->n;
if (mt)
mt->freed = 1;
}
void memtst_free(void *v)
{
long bt[MTBTLEN];
if (v) {
memtst_bt(bt);
memtst_fcheck(v, bt);
free(v);
}
}
void *memtst_calloc(long n, long sz)
{
void *r = calloc(n, sz);
long bt[MTBTLEN];
memtst_bt(bt);
memtst_mcheck(r, n * sz, bt);
return r;
}
void *memtst_realloc(void *v, long sz)
{
void *r = realloc(v, sz);
long bt[MTBTLEN];
memtst_bt(bt);
memtst_mcheck(r, sz, bt);
if (v)
memtst_fcheck(v, bt);
return r;
}
|
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 */
/* Type definitions */
struct stat {scalar_t__ st_blocks; scalar_t__ st_blksize; scalar_t__ STAT_NANOSECONDS_ACCESS_TIME; scalar_t__ st_atime; scalar_t__ st_rdev; scalar_t__ st_gid; scalar_t__ st_uid; scalar_t__ st_nlink; scalar_t__ st_mode; } ;
typedef int /*<<< orphan*/ HCFILE ;
/* Variables and functions */
scalar_t__ fstat (int /*<<< orphan*/ ,struct stat*) ;
int /*<<< orphan*/ hc_fclose (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ hc_fileno (int /*<<< orphan*/ *) ;
int hc_fopen (int /*<<< orphan*/ *,char*,char*) ;
scalar_t__ memcmp (struct stat*,struct stat*,int) ;
bool hc_same_files (char *file1, char *file2)
{
if ((file1 != NULL) && (file2 != NULL))
{
struct stat tmpstat_file1;
struct stat tmpstat_file2;
int do_check = 0;
HCFILE fp;
if (hc_fopen (&fp, file1, "r") == true)
{
if (fstat (hc_fileno (&fp), &tmpstat_file1))
{
hc_fclose (&fp);
return false;
}
hc_fclose (&fp);
do_check++;
}
if (hc_fopen (&fp, file2, "r") == true)
{
if (fstat (hc_fileno (&fp), &tmpstat_file2))
{
hc_fclose (&fp);
return false;
}
hc_fclose (&fp);
do_check++;
}
if (do_check == 2)
{
tmpstat_file1.st_mode = 0;
tmpstat_file1.st_nlink = 0;
tmpstat_file1.st_uid = 0;
tmpstat_file1.st_gid = 0;
tmpstat_file1.st_rdev = 0;
tmpstat_file1.st_atime = 0;
#if defined (STAT_NANOSECONDS_ACCESS_TIME)
tmpstat_file1.STAT_NANOSECONDS_ACCESS_TIME = 0;
#endif
#if defined (_POSIX)
tmpstat_file1.st_blksize = 0;
tmpstat_file1.st_blocks = 0;
#endif
tmpstat_file2.st_mode = 0;
tmpstat_file2.st_nlink = 0;
tmpstat_file2.st_uid = 0;
tmpstat_file2.st_gid = 0;
tmpstat_file2.st_rdev = 0;
tmpstat_file2.st_atime = 0;
#if defined (STAT_NANOSECONDS_ACCESS_TIME)
tmpstat_file2.STAT_NANOSECONDS_ACCESS_TIME = 0;
#endif
#if defined (_POSIX)
tmpstat_file2.st_blksize = 0;
tmpstat_file2.st_blocks = 0;
#endif
if (memcmp (&tmpstat_file1, &tmpstat_file2, sizeof (struct stat)) == 0)
{
return true;
}
}
}
return false;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.