language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
void titulo(){
/*Contem o Titulo do jogo "PROMPT FIGHT"*/
printf(" \xC9\xCD\xCD\xBB \xC9\xCD\xCD\xBB \xC9\xCD\xCB\xCD\xBB \xC9\xCD\xCD\xBB \xCD\xCD\xCB\xCD\xCD \t\t\xC9\xCD\xCD\xCD \xFE \xC9\xCD\xCD\xCD\xCD \xBA \xBA \xCD\xCD\xCB\xCD\xCD");
printf("\n \xCC\xCD\xCD\xBC \xBA \xBA \xBA \xBA \xBA \xCC\xCD\xCD\xBC \xBA \t\t\xCC\xCD\xCD\xCD \xBA \xBA \xCD\xBB \xCC\xCD\xCD\xB9 \xBA");
printf("\n \xBA \t\xC8\xCD\xCD\xBC \xBA \xBA \xBA \xBA \xBA \t\t\xBA \xBA \xC8\xCD\xCD\xCD\xBC \xBA \xBA \xBA");
}
int menu(int sis){
/*Contem o menu principal do jogo*/
char tecla = 0;
int slctvert = 1, a = 254, b = 255, c = 255;
system("color 08");
while(1){
clear(sis);
titulo();
printf("\n\n\n\n\n\n\n\t\t\t\t\xC9\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xBB\n");
printf("\t\t\t\t\xBA %c Iniciar \xBA\n", a);
printf("\t\t\t\t\xBA %c Instrucoes \xBA\n", b);
printf("\t\t\t\t\xBA %c Sair \xBA\n", c);
printf("\t\t\t\t\xC8\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xBC\n\n");
fflush(stdin);
tecla = getch();
if (tecla == down && slctvert < 3)
{
slctvert++;
Beep(500, 250);
}
if (tecla == up && slctvert > 1)
{
slctvert--;
Beep(500, 250);
}
if (slctvert == 1)
{
a = 254; //Quadrado
b = 255;
c = 255;
}
if (slctvert == 2)
{
a = 255;
b = 254; //Quadrado
c = 255;
}
if (slctvert == 3)
{
a = 255;
b = 255;
c = 254; //Quadrado
}
if (tecla == enter && slctvert < 3)
{
Beep(400, 250);
return slctvert;
}
if (tecla == enter && slctvert == 3)
{
return 3;
}
}
}
void os(int *sistema){
/*Coleta qual o sistema operacional o usuario esta utilizando*/
printf("\n\n\n\n\n\n");
printf("\t\t | Indique qual o seu Sistema Operacional |\n\n");
printf("\t\t\t (1) Windows\n");
printf("\t\t\t (2) Mac Os\n");
printf("\t\t\t (3) Linux\n");
printf("\t\t\t\t: ");
scanf("%d", sistema);
}
void aviso(int sistema){
/*Informa o usuario os comando para se utilizar o jogo*/
clear(sistema);
color(sistema, 4);
printf("\n\n\n\n\t\t\t\tAtencao!\n\n");
printf(" Para navegar nos menus use os direcionais para | Cima | e para | Baixo |.\n");
printf(" Para selecionar use a tecla | Enter |.\n");
printf("\n\n\n\n\t Pressione uma tecla para continuar\n");
Beep(500,800);
getch();
color(sistema, 8);
}
int classe(classes *heroeclass, atrib heroe[], int sis, int n){
/*Contem o menu de selecao dos personagens e insercao dos atributos*/
char tecla;
int slctvert = 0, a = 254, b = 255, c = 255;
while(1){
clear(sis);
switch(slctvert){
case 0: // MAGO
printf(" Selecione o Her\xA2i %d **\n", n+1);
printf(" \xC9\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xBB\t\t\t * *\n");
printf(" \xBA %c Mago \xBA\t\t\t * *\n", a);
printf(" \xBA %c Arqueiro \xBA\t\t\t * *\n", b);
printf(" \xBA %c An\xC6o \xBA\t\t\t * *\n", c);
printf(" \xC8\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xBC\t\t ***** *****\n");
printf("\t\t\t * *\n");
printf("\t\t\t * -------------- *\n");
printf("\t\t\t ******************** \n");
printf("\t\t\t * * \n");
printf("\t\t\t * (0) (0) * \n");
printf("\t\t\t * ( * \n");
printf("\t\t\t * * \n");
printf("\t\t\t * -__- * \n");
printf("\t\t\t * *|| ||* * \n");
printf("\t\t\t * |||||| *\n");
printf("\t\t\t * |||| *\n");
printf("\t\t\t * || *\n");
printf(" ESC para voltar\n");
break;
case 1: // ARQUEIRO
printf(" Selecione o Her\xA2i %d ****\n", n+1);
printf(" \xC9\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xBB\t\t\t * *\n");
printf(" \xBA %c Mago \xBA\t\t * *\n", a);
printf(" \xBA %c Arqueiro \xBA\t\t * *\n", b);
printf(" \xBA %c An\xC6o \xBA\t\t * *\n", c);
printf(" \xC8\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xBC\t\t * *\n");
printf("\t\t\t * ********** *\n");
printf("\t\t\t * * * *\n");
printf("\t\t\t * * * *\n");
printf("\t\t\t * * (0) (0) * *\n");
printf("\t\t\t * * < * *\n");
printf("\t\t\t * * * *\n");
printf("\t\t\t * * ____ * *\n");
printf("\t\t\t * * * *\n");
printf("\t\t\t * * * *\n");
printf("\t\t\t ** * * **\n");
printf("\t\t\t * * * *\n");
printf("\t\t\t * ** *\n");
printf(" ESC para voltar\n");
break;
case 2: // ANÃO
printf(" Selecione o Her\xA2i %d ***\n", n+1);
printf(" \xC9\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xBB\t\t\t * *\n");
printf(" \xBA %c Mago \xBA\t\t * *\n", a);
printf(" \xBA %c Arqueiro \xBA\t\t * *\n", b);
printf(" \xBA %c An\xC6o \xBA\t\t * *** *\n", c);
printf(" \xC8\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xBC\t\t * * * *\n");
printf("\t\t\t * * * *\n");
printf("\t\t\t * * * *\n");
printf("\t\t\t * * ```\\ /``` * *\n");
printf("\t\t\t * * (0)| |(0) * *\n");
printf("\t\t\t * * ( ) * *\n");
printf("\t\t\t * * ```` ```` * *\n");
printf("\t\t\t **** `` ___ `` ****\n");
printf("\t\t\t * `` `` *\n");
printf("\t\t\t *|||||||||||||||||||||||*\n");
printf("\t\t\t * ||||||||||||||||||||||| *\n");
printf("\t\t\t * ||||||||||||||||||||||| *\n");
printf("\t\t\t * ||||||||||||||||||||| *\n");
printf("\t\t * ||||||||||||||||| *\n");
printf(" ESC para voltar\n");
break;
}
fflush(stdin);
tecla = getch();
if (tecla == down && slctvert < 2)
{
slctvert++;
Beep(500, 250);
}
if (tecla == up && slctvert > 0)
{
slctvert--;
Beep(500, 250);
}
if (slctvert == 0)
{
a = 254; //Quadrado
b = 255;
c = 255;
}
if (slctvert == 1)
{
a = 255;
b = 254; //Quadrado
c = 255;
}
if (slctvert == 2)
{
a = 255;
b = 255;
c = 254; //Quadrado
}
if (tecla == enter)
{
*heroeclass = slctvert;
Beep(400, 250);
coletadados(heroe, n, slctvert);
return 5;
}
if (tecla == esc && n == 0)
{
Beep(380, 300);
return 1;
}
if (tecla == esc && n == 1)
{
Beep(380, 300);
return 0;
}
}
}
void luta(classes *heroe1class, classes *heroe2class, int dano, int atacante){ /*Chama a animacao de combate de acordo com as classes*/
if (*heroe1class == MAGE && *heroe2class == MAGE)
{
magevsmage(dano, atacante);
}
if (*heroe1class == ARCHER && *heroe2class == ARCHER)
{
archervsarcher(dano, atacante);
}
if (*heroe1class == DWARF && *heroe2class == DWARF)
{
dwarfvsdwarf(dano, atacante);
}
if (*heroe1class == MAGE && *heroe2class == ARCHER)
{
magevsarcher(dano, atacante);
}
if (*heroe1class == ARCHER && *heroe2class == MAGE)
{
archervsmage(dano, atacante);
}
if (*heroe1class == MAGE && *heroe2class == DWARF)
{
magevsdwarf(dano, atacante);
}
if (*heroe1class == DWARF && *heroe2class == MAGE)
{
dwarfvsmage(dano, atacante);
}
if (*heroe1class == ARCHER && *heroe2class == DWARF)
{
archervsdwarf(dano, atacante);
}
if (*heroe1class == DWARF && *heroe2class == ARCHER)
{
dwarfvsarcher(dano, atacante);
}
}
void contagem(){
int i;
for (i = 3; i > 0; i--)
{
system("cls");
printf("\n\n\n\n\n\n\n\n\n\t\t\t\t\t%d\n", i);
Sleep(1000);
}
system("cls");
printf("\n\n\n\n\n\n\n\n\n\t\t\t\t\tLutar!!!\n");
Sleep(1000);
}
|
C
|
#include "turn_angle_detection.h"
#include "ev3api.h"
#include "common_definition.h"
#define STEER EV3_PORT_C
#define DRIVE_L EV3_PORT_A
#define DRIVE_R EV3_PORT_B
#define IR EV3_PORT_3
#define TOUCH EV3_PORT_2
/***********************************************
* ŝ̉]px̌m
***********************************************/
//RXgN^
turn_angle_structure* turn_angle_constructor(){
//setting sensor value of radius to 0
ev3_motor_reset_counts(DRIVE_R); //right motor
ev3_motor_reset_counts(DRIVE_L); //left motor
return turn_angle_structure_make();
}
//]pxmp̍\̍쐬
turn_angle_structure *turn_angle_structure_make(void) {
turn_angle_structure *new_turn_angle_structure =
(turn_angle_structure*)malloc(sizeof(turn_angle_structure));
new_turn_angle_structure->right_motor_current_angle = ev3_motor_get_counts(DRIVE_R);
new_turn_angle_structure->left_motor_current_angle = ev3_motor_get_counts(DRIVE_L);
new_turn_angle_structure->right_motor_old_angle = 0;
new_turn_angle_structure->left_motor_old_angle = 0;
new_turn_angle_structure->right_motor_rotation_angle = 0;
new_turn_angle_structure->left_motor_rotation_angle = 0;
new_turn_angle_structure->wheel_across = 8.0;
new_turn_angle_structure->between_wheels = 12.0;
new_turn_angle_structure->moving_distance = 0;
new_turn_angle_structure->turning_angle = 0;
new_turn_angle_structure->old_angle = 0;
new_turn_angle_structure->current_angle = 0;
new_turn_angle_structure->original_right_motor_angle = 0;
new_turn_angle_structure->original_left_motor_angle = 0;
return new_turn_angle_structure;
}
//\̊J
void turn_angle_structure_free(turn_angle_structure *tas) {
free(tas);
}
//\̕ϐ̍XVA]px̌vZ
float turn_angle_detection(turn_angle_structure *tas){
//rotation angle of right wheel
tas->old_angle = tas->current_angle;
tas->right_motor_old_angle = tas->right_motor_current_angle;
tas->right_motor_current_angle = ev3_motor_get_counts(DRIVE_R) - tas->original_right_motor_angle;
tas->right_motor_rotation_angle =
tas->right_motor_current_angle - tas->right_motor_old_angle;
//rotation angle of left wheel
tas->left_motor_old_angle = tas->left_motor_current_angle;
tas->left_motor_current_angle = ev3_motor_get_counts(DRIVE_L) - tas->original_left_motor_angle;
tas->left_motor_rotation_angle =
tas->left_motor_current_angle - tas->left_motor_old_angle;
//moving distance and turning angle
tas->turning_angle =
tas->wheel_across/2 * (tas->right_motor_rotation_angle - tas->left_motor_rotation_angle)
/ tas->between_wheels;
//updating of coordinates
tas->current_angle = tas->old_angle + tas->turning_angle;
return tas->current_angle;
}
|
C
|
#define WIN32_LEAN_AND_MEAN
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <winsock2.h>
#include <conio.h>
#include <winbase.h>
#include <malloc.h>
int sockfd;
#define MAX_BUFF_SIZE 1000
void main(void){
struct sockaddr_in server,local;
int retval,fromlen;
char *Buffer;
const char serverip[] = "192.168.1.5";
WSADATA wsaData;
unsigned short port = 5001;
fromlen = sizeof(local);
memset(&server,0,sizeof(server));
Buffer = (char *)malloc(MAX_BUFF_SIZE);
server.sin_family = AF_INET;
server.sin_addr.S_un.S_addr = inet_addr(serverip);
server.sin_port = htons(port);
if (WSAStartup(0x202,&wsaData) == SOCKET_ERROR){
printf("WSAStartup failed with error %d\n",WSAGetLastError());
WSACleanup();
exit(1);
}
sockfd = socket(AF_INET,SOCK_DGRAM,0);
retval =0;
printf("Type x to exit\n");
while(1){
printf("\n:");
gets(Buffer);
if(Buffer[0] == 'x')break;
strcat(Buffer,"\r\n");
retval = sendto(sockfd, Buffer, strlen(Buffer), 0, (struct sockaddr *)&server, sizeof(struct sockaddr));
if (retval <0){
fprintf(stderr,"sendto() failed: error %d\n",WSAGetLastError());
WSACleanup();
closesocket(sockfd);
exit(1);
}
fromlen = sizeof(struct sockaddr);
retval = recvfrom(sockfd, Buffer, MAX_BUFF_SIZE, 0, (struct sockaddr *)&local, &fromlen);
if (retval <0){
fprintf(stderr,"recvfrom() failed: error %d\n",WSAGetLastError());
WSACleanup();
closesocket(sockfd);
exit(1);
}
Buffer[retval-1]=0;
printf("%d>%s",retval,Buffer);
};//end while 1
closesocket(sockfd);
}
|
C
|
#include "getLine.h"
int getLine(char *buffer, int n, FILE *stream)
{
char c;
int i = 0;
while (1)
{
c = getc(stream);
// if not at end of stream
if (!charIsEndOfString(c))
{
// then if at end of buffer
if (i == (int)n-1)
{
// null-terminate buffer and consume to end of stream
buffer[i] = '\0';
while (!charIsEndOfString(c)) { c = getc(stream); }
return -1; // return error code
}
else
{
// else add char and keep going
buffer[i] = c;
i++;
}
}
// if at end of string
else
{
// end string and return its length
buffer[i] = '\0';
return i;
}
}
}
static int charIsEndOfString(char c)
{
return (c == '\n') || (c == '\0') || (c == EOF);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
Takes character array and size of it. Prints character of array followed by newline.
*/
void print_state(char *state, int size) {
printf("%s\n", state);
}
/*
Takes character array and updates the state of the array
*/
void update_state(char *state, int size) {
// make a copy of the current state
char state_cp[size];
// strncpy(state_cp, state, size);
// state_cp[size-1] = '\0';
for (int i=0; i < size; i++) {
state_cp[i] = state[i];
}
for (int i=1; i < size - 1; i++) {
if (state_cp[i-1] == state_cp[i+1]) {
// modify the original state character array pointer directly
state[i] = '.';
} else if (state_cp[i-1] != state_cp[i+1]) {
state[i] = 'X';
}
}
}
|
C
|
#include "infer_types.gen.c"
internal
Node *alloc_node(BlockGraph *block, enum uop uop) {
Node *result = alloc(&block->node_pool, sizeof(Node));
result->uop = uop;
return result;
}
typedef struct {
BlockGraphPtrArray blocks;
BlockGraph *main;
b32 optimise;
TypePool *type_pool;
Pool block_pool;
} ProgramGraph;
internal
void delete_constant(BlockGraph *block, Node *node) {
if (block->constants == node) {
block->constants = node->next_constant;
} else {
Node *constant = block->constants;
while (constant) {
if (constant->next_constant == node) {
constant->next_constant = node->next_constant;
break;
}
constant = constant->next_constant;
}
}
if (node->uop == UOP_BLOCK_CONSTANT) {
array_remove(&block->references, node->block);
}
release(&block->node_pool, node);
}
internal
InLink *in_link(Node *node, u32 index) {
InLinkChunk *chunk = &node->in;
while (index >= array_count(chunk->links)) {
index -= array_count(chunk->links);
chunk = chunk->next;
}
return &chunk->links[index];
}
internal
OutLink *out_link(Node *node, u32 index) {
OutLinkChunk *chunk = &node->out;
while (index >= array_count(chunk->links)) {
index -= array_count(chunk->links);
chunk = chunk->next;
}
return &chunk->links[index];
}
internal
InLink *add_in_link(BlockGraph *block, Node *node) {
InLinkChunk *chunk = &node->in;
u32 index = node->in_count++;
while (index >= array_count(chunk->links)) {
index -= array_count(chunk->links);
if (chunk->next == NULL) {
chunk->next = alloc(&block->in_link_pool, sizeof(InLink));
}
chunk = chunk->next;
}
return &chunk->links[index];
}
internal
OutLink *add_out_link(BlockGraph *block, Node *node) {
OutLinkChunk *chunk = &node->out;
u32 index = node->out_count++;
while (index >= array_count(chunk->links)) {
index -= array_count(chunk->links);
if (chunk->next == NULL) {
chunk->next = alloc(&block->out_link_pool, sizeof(InLink));
}
chunk = chunk->next;
}
return &chunk->links[index];
}
typedef struct {
Node *node;
u32 slot;
Type *type;
} Link;
// Can't return arrays in C.
typedef struct {
Link l[2];
} Link2;
typedef struct {
Link l[3];
} Link3;
typedef struct {
Link l[5];
} Link5;
internal inline
Link init_block_graph(ProgramGraph *program, BlockGraph *block, Type *input_type) {
block->id = (u32)program->blocks.size;
array_push(&program->blocks, block);
block->input.out_count = 1;
OUT0(&block->input).type = input_type;
return (Link){&block->input, 0, input_type};
}
internal inline
void finish_block_graph(BlockGraph *block, Link last) {
OutLink *out = out_link(last.node, last.slot);
out->node = &block->output;
out->slot = 0;
block->output.uop = UOP_END;
block->output.in_count = 1;
IN0(&block->output).node = last.node;
IN0(&block->output).slot = last.slot;
}
void collect_mapping(TypePtrMap *mapping, Type *type1, Type *type2, u64 traversal) {
type1 = deref(type1);
if (type1->seen == traversal) {
return;
}
type1->seen = traversal;
type2 = deref(type2);
if (type1 == type2) {
return;
}
if (IS_VAR(type1)) {
type_ptr_map_put(mapping, type1, type2);
} else {
if (type1->symbol == SYMBOL_UNIT || type1->symbol == SYMBOL_NUMBER || type1->symbol == SYMBOL_BOOL) {
return;
}
collect_mapping(mapping, type1->child1, type2->child1, traversal);
if (!IS_SEALED(type1->symbol)) {
collect_mapping(mapping, type1->child2, type2->child2, traversal);
}
}
}
// TODO Maybe use modified version of Tarjan's SCC algorithm as per
// http://stackoverflow.com/questions/28924321/copying-part-of-a-graph
internal
Type *apply_mapping(TypePtrMap *mapping, Type *type, TypePool *pool) {
type = deref(type);
TypePtrMapGetResult map_result = type_ptr_map_get(mapping, type);
if (map_result.found) {
return map_result.value;
}
if (IS_VAR(type) ||
type->symbol == SYMBOL_UNIT ||
type->symbol == SYMBOL_NUMBER ||
type->symbol == SYMBOL_BOOL) {
type_ptr_map_put_bucket(mapping, type, type, map_result.bucket);
return type;
}
Type *new = alloc_type(pool);
type_ptr_map_put_bucket(mapping, type, new, map_result.bucket);
new->symbol = type->symbol;
new->next = new;
new->child1 = NULL; // Set as term
new->child1 = apply_mapping(mapping, type->child1, pool);
if (!IS_SEALED(type->symbol)) {
new->child2 = apply_mapping(mapping, type->child2, pool);
}
return new;
}
internal
Link append_block(BlockGraph *block1, Link link, BlockGraph *block2, TypePtrMap *mapping, TypePool *type_pool) {
u64 traversal = global_traversal++;
NodePtrArray worklist = {};
array_push(&worklist, OUT0(&block2->input).node);
for (Node *constant = block2->constants; constant; constant = constant->next_constant) {
array_push(&worklist, constant);
}
block2->input.seen = traversal;
Link result = {};
while (worklist.size > 0) {
Node *node = array_pop(&worklist);
if (node->seen == traversal) {
continue;
}
b32 ready = true;
for (u32 i = 0; i < node->in_count; i++) {
if (in_link(node, i)->node->seen != traversal) {
ready = false;
}
}
if (!ready) {
continue;
}
node->seen = traversal;
if (node->uop == UOP_END) {
OutLink *out = out_link(IN0(node).node->copy, IN0(node).slot);
result.node = IN0(node).node->copy;
result.slot = IN0(node).slot;
result.type = out->type;
continue;
}
node->copy = alloc_node(block1, node->uop);
if (node->uop == UOP_BLOCK_CONSTANT) {
array_push(&block1->references, node->block);
}
// XXX we don't account for constants on sums
node->copy->text = node->text;
for (u32 i = 0; i < node->in_count; i++) {
InLink *in = in_link(node, i);
InLink *in_copy = add_in_link(block1, node->copy);
if (in->node->uop == UOP_START) {
in_copy->node = link.node;
in_copy->slot = link.slot;
} else {
in_copy->node = in->node->copy;
in_copy->slot = in->slot;
}
OutLink *out_copy = out_link(in_copy->node, in_copy->slot);
out_copy->node = node->copy;
out_copy->slot = i;
}
for (u32 i = 0; i < node->out_count; i++) {
OutLink *out = out_link(node, i);
OutLink *out_copy = add_out_link(block1, node->copy);
array_push(&worklist, out->node);
out_copy->type = apply_mapping(mapping, out->type, type_pool);
}
if (is_constant(node->uop)) {
node->copy->next_constant = block1->constants;
block1->constants = node->copy;
}
}
array_free(&worklist);
assert(result.node);
return result;
}
#define assert_product(type) assert(!IS_VAR(type) && (type)->symbol == SYMBOL_PRODUCT)
#define assert_sum(type) assert(!IS_VAR(type) && (type)->symbol == SYMBOL_SUM)
#define assert_block(type) assert(!IS_VAR(type) && ((type)->symbol & POLYMORPHIC_MASK) == SYMBOL_BLOCK)
#define child1(type) deref((type)->child1)
#define child2(type) deref((type)->child2)
// We need this to construct pairs for some of the optimisations
internal Link append_node21(ProgramGraph *program, BlockGraph *block, u8 uop, Link link1, Link link2,
Type *type, Type *extra_type1, Type *extra_type2);
internal inline
Link append_node01(ProgramGraph *program, BlockGraph *block, u8 uop, Type *type) {
Node *result = alloc_node(block, uop);
result->next_constant = block->constants;
block->constants = result;
OUT0(result).type = type;
result->out_count = 1;
return (Link){result, 0, type};
}
internal inline
Node *append_node10(BlockGraph *block, u8 uop, Link link) {
Node *result = alloc_node(block, uop);
IN0(result) = (InLink){link.node, link.slot};
OutLink *out = out_link(link.node, link.slot);
out->node = result;
out->slot = 0;
result->in_count = 1;
return result;
}
internal inline
Link append_node11(ProgramGraph *program, BlockGraph *block, u8 uop, Link link, Type *type) {
if (program->optimise) {
// We ignore assertion errors at this stage. It'll be more
// convenient to catch them in future passes
u8 prevuop = link.node->uop;
if ((uop == UOP_ASSERT_COPYABLE || uop == UOP_ASSERT_DROPPABLE) && is_constant(prevuop)) {
return link;
}
if (uop == UOP_ASSERT_NONZERO && prevuop == UOP_NUMBER_CONSTANT) {
// XXX This is bogus, but it doesn't matter because it
// will be replaced by exact rationals soon anyway.
if (link.node->number > 0.00000000001f || link.node->number < -0.00000000001f) {
return link;
}
}
if (uop == UOP_QUOTE && prevuop == UOP_BLOCK_CONSTANT) {
BlockGraph *quote_source = link.node->block;
BlockGraph *quoted = quote_source->quoted;
if (!quoted) {
assert_block(type);
Type *input_type = child1(type);
Type *output_type = child2(type);
assert_product(output_type);
quoted = alloc(&program->block_pool, sizeof(BlockGraph));
Link input = init_block_graph(program, quoted, input_type);
Link constant = append_node01(program, quoted, UOP_BLOCK_CONSTANT,
child1(output_type));
constant.node->block = link.node->block;
Link output = append_node21(program, quoted, UOP_PAIR, constant, input,
output_type, NULL, NULL);
finish_block_graph(quoted, output);
link.node->block->quoted = quoted;
}
array_remove(&block->references, quote_source);
array_push(&block->references, quoted);
link.node->block = quoted;
link.type = type;
OUT0(link.node).type = type;
return link;
}
}
Node *result = append_node10(block, uop, link);
OUT0(result).type = type;
result->out_count = 1;
return (Link){result, 0, type};
}
internal inline
Link2 append_node12(ProgramGraph *program, BlockGraph *block,
u8 uop,
Link link,
Type *type1, Type *type2) {
if (program->optimise) {
if (uop == UOP_UNPAIR && link.node->uop == UOP_PAIR) {
out_link(IN0(link.node).node, IN0(link.node).slot)->node = NULL;
out_link(IN1(link.node).node, IN1(link.node).slot)->node = NULL;
return (Link2){{
{IN0(link.node).node, IN0(link.node).slot, type1},
{IN1(link.node).node, IN1(link.node).slot, type2},
}};
}
if (uop == UOP_COPY) {
if (is_constant(link.node->uop)) {
Link copy = append_node01(program, block, link.node->uop, link.type);
copy.node->text = link.node->text;
if (link.node->uop == UOP_BLOCK_CONSTANT) {
array_push(&block->references, link.node->block);
}
return (Link2){{link, copy}};
}
if (does_implicit_copies(link.node->uop)) {
OutLink *copy = add_out_link(block, link.node);
copy->type = type2;
return (Link2){{link, {link.node, link.node->out_count - 1, type2}}};
}
}
}
Node *result = append_node10(block, uop, link);
OUT0(result).type = type1;
OUT1(result).type = type2;
result->out_count = 2;
return (Link2){{{result, 0, type1}, {result, 1, type2}}};
}
internal inline
Link3 append_node13(ProgramGraph *program, BlockGraph *block,
u8 uop,
Link link,
Type *type1, Type *type2, Type *type3) {
if (program->optimise) {
if (uop == UOP_UNSUM && link.node->uop == UOP_SUM) {
out_link(IN0(link.node).node, IN0(link.node).slot)->node = NULL;
out_link(IN1(link.node).node, IN1(link.node).slot)->node = NULL;
out_link(IN2(link.node).node, IN2(link.node).slot)->node = NULL;
return (Link3){{
{IN0(link.node).node, IN0(link.node).slot, type1},
{IN1(link.node).node, IN1(link.node).slot, type2},
{IN2(link.node).node, IN2(link.node).slot, type2},
}};
}
}
Node *result = append_node10(block, uop, link);
OUT0(result).type = type1;
OUT1(result).type = type2;
OUT2(result).type = type3;
result->out_count = 3;
return (Link3){{{result, 0, type1}, {result, 1, type2}, {result, 2, type3}}};
}
internal inline
Node *append_node20(BlockGraph *block, u8 uop, Link link1, Link link2) {
Node *result = alloc_node(block, uop);
IN0(result).node = link1.node;
IN1(result).node = link2.node;
IN0(result).slot = link1.slot;
IN1(result).slot = link2.slot;
OutLink *out1 = out_link(link1.node, link1.slot);
OutLink *out2 = out_link(link2.node, link2.slot);
out1->node = result;
out2->node = result;
out1->slot = 0;
out2->slot = 1;
result->in_count = 2;
return result;
}
internal inline
Link append_node21(ProgramGraph *program, BlockGraph *block,
u8 uop,
Link link1, Link link2,
Type *type, Type *extra_type1, Type *extra_type2) {
if (program->optimise) {
if (uop == UOP_AND) {
if (link1.node->uop == UOP_BOOL_CONSTANT && link1.node->boolean) {
delete_constant(block, link1.node);
return link2;
}
if (link2.node->uop == UOP_BOOL_CONSTANT && link2.node->boolean) {
delete_constant(block, link2.node);
return link1;
}
if (link1.node->uop == UOP_BOOL_CONSTANT && !link1.node->boolean) {
append_node10(block, UOP_DROP, link2);
return link1;
}
if (link2.node->uop == UOP_BOOL_CONSTANT && !link2.node->boolean) {
append_node10(block, UOP_DROP, link1);
return link2;
}
}
// TODO Should compose have a variable number of inputs?
if (uop == UOP_COMPOSE &&
link1.node->uop == UOP_BLOCK_CONSTANT &&
link2.node->uop == UOP_BLOCK_CONSTANT) {
BlockGraph *block1 = link1.node->block;
BlockGraph *block2 = link2.node->block;
BlockGraphMapGetResult map_result = block_graph_map_get(&block1->compositions, block2);
BlockGraph *composed = map_result.value;
if (!map_result.found) {
assert_block(type);
Type *input_type = child1(type);
InLink *in1 = &IN0(&block1->output);
InLink *in2 = &IN0(&block2->output);
u64 traversal = global_traversal++;
TypePtrMap mapping = {};
collect_mapping(&mapping, OUT0(&block1->input).type, input_type, traversal);
collect_mapping(&mapping, out_link(in1->node, in1->slot)->type, extra_type1, traversal);
collect_mapping(&mapping, OUT0(&block2->input).type, extra_type2, traversal);
collect_mapping(&mapping, out_link(in2->node, in2->slot)->type, child2(type), traversal);
composed = alloc(&program->block_pool, sizeof(BlockGraph));
input_type = apply_mapping(&mapping, input_type, program->type_pool);
Link link = init_block_graph(program, composed, input_type);
link = append_block(composed, link, block1, &mapping, program->type_pool);
link = append_block(composed, link, block2, &mapping, program->type_pool);
finish_block_graph(composed, link);
block_graph_map_put_bucket(&block1->compositions, block2, composed,
map_result.bucket);
}
array_remove(&block->references, link1.node->block);
array_push(&block->references, composed);
link1.node->block = composed;
link1.type = type;
OUT0(link1.node).type = type;
delete_constant(block, link2.node);
return link1;
}
}
Node *result = append_node20(block, uop, link1, link2);
OUT0(result).type = type;
result->out_count = 1;
return (Link){result, 0, type};
}
internal inline
Link2 append_node22(ProgramGraph *program, BlockGraph *block,
u8 uop,
Link link1, Link link2,
Type *type1, Type *type2) {
Node *result = append_node20(block, uop, link1, link2);
OUT0(result).type = type1;
OUT1(result).type = type2;
result->out_count = 2;
return (Link2){{{result, 0, type1}, {result, 1, type2}}};
}
internal inline
Node *append_node30(BlockGraph *block, u8 uop, Link link1, Link link2, Link link3) {
Node *result = alloc_node(block, uop);
IN0(result).node = link1.node;
IN1(result).node = link2.node;
IN2(result).node = link3.node;
IN0(result).slot = link1.slot;
IN1(result).slot = link2.slot;
IN2(result).slot = link3.slot;
OutLink *out1 = out_link(link1.node, link1.slot);
OutLink *out2 = out_link(link2.node, link2.slot);
OutLink *out3 = out_link(link3.node, link3.slot);
out1->node = result;
out2->node = result;
out3->node = result;
out1->slot = 0;
out2->slot = 1;
out3->slot = 2;
result->in_count = 3;
return result;
}
internal inline
Link append_node31(ProgramGraph *program, BlockGraph *graph,
u8 uop,
Link link1, Link link2, Link link3,
Type *type) {
Node *result = append_node30(graph, uop, link1, link2, link3);
OUT0(result).type = type;
result->out_count = 1;
return (Link){result, 0, type};
}
internal inline
Link2 unpair_(ProgramGraph *program, BlockGraph *graph, Link link) {
assert_product(link.type);
return append_node12(program, graph, UOP_UNPAIR, link, child1(link.type), child2(link.type));
}
internal inline
Link3 unpair2_(ProgramGraph *program, BlockGraph *graph, Link link) {
Link2 outer = unpair_(program, graph, link);
Link2 inner = unpair_(program, graph, outer.l[1]);
return (Link3){{outer.l[0], inner.l[0], inner.l[1]}};
}
internal inline
Link pair2_(ProgramGraph *program, BlockGraph *graph,
Link link1, Link link2, Link link3,
Type *type) {
assert_product(type);
Link right = append_node21(program, graph, UOP_PAIR, link2, link3, child2(type), NULL, NULL);
return append_node21(program, graph, UOP_PAIR, link1, right, type, NULL, NULL);
}
internal inline
Link3 unsum_(ProgramGraph *program, BlockGraph *graph, Link link) {
assert_sum(link.type);
return append_node13(program, graph, UOP_UNSUM, link,
child1(link.type), child2(link.type), program->type_pool->boolean);
}
internal inline
Link5 unsum2_(ProgramGraph *program, BlockGraph *graph, Link link) {
Link3 outer = unsum_(program, graph, link);
Link3 inner = unsum_(program, graph, outer.l[1]);
return (Link5){{outer.l[0], inner.l[0], inner.l[1], outer.l[2], inner.l[2]}};
}
internal inline
Link sum2_(ProgramGraph *program, BlockGraph *graph,
Link link1, Link link2, Link link3, Link link4, Link link5,
Type *type) {
assert_sum(type);
Link right = append_node31(program, graph, UOP_SUM, link2, link3, link5, child2(type));
return append_node31(program, graph, UOP_SUM, link1, right, link4, type);
}
internal
void build_graph(ProgramGraph *program, Block *block) {
if (block->size == 0) {
return;
}
Type *bool_type = program->type_pool->boolean;
BlockGraph *bgraph = &block->graph;
#define append01(uop, type) append_node01(program, bgraph, (uop), (type))
#define append10(uop, link) append_node10(bgraph, (uop), (link))
#define append11(uop, link, type) append_node11(program, bgraph, (uop), (link), (type))
#define append12(uop, link, type1, type2) append_node12(program, bgraph, (uop), (link), (type1), (type2))
#define append20(uop, link1, link2) append_node20(bgraph, (uop), (link1), (link2))
#define append21(uop, link1, link2, type) \
append_node21(program, bgraph, (uop), (link1), (link2), (type), NULL, NULL)
#define append22(uop, link1, link2, type1, type2) \
append_node22(program, bgraph, (uop), (link1), (link2), (type1), (type2))
#define append31(uop, link1, link2, link3, type) \
append_node31(program, bgraph, (uop), (link1), (link2), (link3), (type))
#define unpair(link) unpair_(program, bgraph, (link))
#define unpair2(link) unpair2_(program, bgraph, (link))
#define pair(link1, link2, type) append21(UOP_PAIR, (link1), (link2), (type))
#define pair2(link1, link2, link3, type) \
pair2_(program, bgraph, (link1), (link2), (link3), (type))
#define unsum(link) unsum_(program, bgraph, (link))
#define unsum2(link) unsum2_(program, bgraph, (link))
#define sum(link1, link2, link3, type) append31(UOP_SUM, (link1), (link2), (link3), (type))
#define sum2(link1, link2, link3, link4, link5, type) \
sum2_(program, bgraph, (link1), (link2), (link3), (link4), (link5), (type))
#define and(link1, link2) append21(UOP_AND, (link1), (link2), bool_type)
#define or(link1, link2) append21(UOP_OR, (link1), (link2), bool_type)
#define not(link) append11(UOP_NOT, (link), bool_type)
#define compose(link1, link2, type, extra_type1, extra_type2) \
append_node21(program, bgraph, UOP_COMPOSE, (link1), (link2), (type), (extra_type1), (extra_type2))
Link last = init_block_graph(program, bgraph, deref(block->types[0]));
AOStackFrame *frame = NULL;
for (usize i = 0, extra_type_index = 0, frame_index = 0, block_index = 0, text_index = 0, sealer_index = 0;
i < block->size;
i++) {
u8 op = block->opcodes[i];
Type *output_type = deref(block->types[i + 1]);
switch (op) {
case OP_FRAME_PUSH: frame = block->frames[frame_index++]; break;
case OP_FRAME_POP: frame = frame->next; break;
case OP_SEAL:
{
last = append11(UOP_SEAL, last, output_type);
// Only set the seal if the node wasn't optimised away
if (last.node->uop == UOP_SEAL && last.node->seal == NULL) {
last.node->seal = block->sealers[sealer_index++];
}
break;
}
case OP_UNSEAL:
{
last = append11(UOP_UNSEAL, last, output_type);
// Only set the seal if the node wasn't optimised away
if (last.node->uop == UOP_UNSEAL && last.node->seal == NULL) {
last.node->seal = block->sealers[sealer_index++];
}
break;
}
case OP_ASSERT_EQUAL:
{
Link3 input = unpair2(last);
Link2 assert_equal = append22(UOP_ASSERT_EQUAL,
input.l[0], input.l[1],
input.l[0].type, input.l[1].type);
last = pair2(assert_equal.l[0], assert_equal.l[1], input.l[2], output_type);
break;
}
case OP_DEBUG_PRINT_RAW:
{
last = append11(UOP_DEBUG_PRINT_RAW, last, output_type);
break;
}
case OP_DEBUG_PRINT_TEXT:
{
last = append11(UOP_DEBUG_PRINT_TEXT, last, output_type);
break;
}
case '[':
{
assert_product(output_type);
Link block_constant = append01(UOP_BLOCK_CONSTANT,
child1(output_type));
block_constant.node->block = &block->blocks[block_index++]->graph;
array_push(&bgraph->references, block_constant.node->block);
last = pair(block_constant, last, output_type);
break;
}
case '"':
{
assert_product(output_type);
Link text_constant = append01(UOP_TEXT_CONSTANT,
child1(output_type));
text_constant.node->text = block->texts[text_index++];
last = pair(text_constant, last, output_type);
break;
}
case 'l':
{
Link3 input = unpair2(last);
assert_product(output_type);
Link left = pair(input.l[0], input.l[1], child1(output_type));
last = pair(left, input.l[2], output_type);
break;
}
case 'r':
{
Link2 outer = unpair(last);
Link2 inner = unpair(outer.l[0]);
last = pair2(inner.l[0], inner.l[1], outer.l[1], output_type);
break;
}
case 'w':
{
Link3 input = unpair2(last);
last = pair2(input.l[1], input.l[0], input.l[2], output_type);
break;
}
case 'z':
{
Link3 input = unpair2(last);
Link2 inner = unpair(input.l[2]);
assert_product(output_type);
Type *type = child2(output_type);
assert_product(type);
Link new_inner = pair(input.l[1], inner.l[1], child2(type));
last = pair2(input.l[0], inner.l[0], new_inner, output_type);
break;
}
case 'v':
{
assert_product(output_type);
Link unit_constant = append01(UOP_UNIT_CONSTANT,
child2(output_type));
last = pair(last, unit_constant, output_type);
break;
}
case 'c':
{
Link2 input = unpair(last);
append10(UOP_DROP, input.l[1]);
last = input.l[0];
break;
}
case '%':
{
Link2 input = unpair(last);
Link to_drop = append11(UOP_ASSERT_DROPPABLE,
input.l[0], input.l[0].type);
append10(UOP_DROP, to_drop);
last = input.l[1];
break;
}
case '^':
{
Link2 input = unpair(last);
Link to_copy = append11(UOP_ASSERT_COPYABLE,
input.l[0], input.l[0].type);
Link2 copy = append12(UOP_COPY, to_copy,
to_copy.type, to_copy.type);
last = pair2(copy.l[0], copy.l[1], input.l[1], output_type);
break;
}
case '$':
{
Link3 input = unpair2(last);
assert_product(output_type);
Link apply = append21(UOP_APPLY,
input.l[0], input.l[1],
child1(output_type));
last = pair(apply, input.l[2], output_type);
break;
}
case 'o':
{
Link3 input = unpair2(last);
assert_product(output_type);
Link composed = compose(input.l[0], input.l[1],
child1(output_type),
block->extra_types[extra_type_index],
block->extra_types[extra_type_index + 1]);
extra_type_index += 2;
last = pair(composed, input.l[2], output_type);
break;
}
case '\'':
{
Link2 input = unpair(last);
assert_product(output_type);
Link quote = append11(UOP_QUOTE, input.l[0], child1(output_type));
last = pair(quote, input.l[1], output_type);
break;
}
case 'k':
{
Link2 input = unpair(last);
assert_product(output_type);
Link relevant = append11(UOP_MARK_RELEVANT,
input.l[0], child1(output_type));
last = pair(relevant, input.l[1], output_type);
break;
}
case 'f':
{
Link2 input = unpair(last);
assert_product(output_type);
Link affine = append11(UOP_MARK_AFFINE,
input.l[0], child1(output_type));
last = pair(affine, input.l[1], output_type);
break;
}
case '#':
{
assert_product(output_type);
Link zero_constant = append01(UOP_NUMBER_CONSTANT,
child1(output_type));
zero_constant.node->number = 0;
last = pair(zero_constant, last, output_type);
break;
}
case '0'...'9':
{
u32 digit = op - '0';
Link2 input = unpair(last);
if (input.l[0].node->uop == UOP_NUMBER_CONSTANT) {
input.l[0].node->number = input.l[0].node->number * 10 + digit;
break;
}
assert_product(output_type);
Type *number = child1(output_type);
Link ten_constant = append01(UOP_NUMBER_CONSTANT, number);
ten_constant.node->number = 10;
Link digit_constant = append01(UOP_NUMBER_CONSTANT, number);
digit_constant.node->number = digit;
Link mul_by_10 = append21(UOP_MULTIPLY,
input.l[0], ten_constant, number);
Link add_digit = append21(UOP_ADD,
mul_by_10, digit_constant, number);
last = pair(add_digit, input.l[1], output_type);
break;
}
case '+':
{
Link3 input = unpair2(last);
assert_product(output_type);
Link add = append21(UOP_ADD, input.l[0], input.l[1], child1(output_type));
last = pair(add, input.l[2], output_type);
break;
}
case '*':
{
Link3 input = unpair2(last);
assert_product(output_type);
Link multiply = append21(UOP_MULTIPLY,
input.l[0], input.l[1], child1(output_type));
last = pair(multiply, input.l[2], output_type);
break;
}
case '/':
{
Link2 input = unpair(last);
assert_product(output_type);
Type *number = child1(output_type);
Link checked_number = append11(UOP_ASSERT_NONZERO, input.l[0], number);
Link inverse = append11(UOP_INVERSE, checked_number, number);
last = pair(inverse, input.l[1], output_type);
break;
}
case '-':
{
Link2 input = unpair(last);
assert_product(output_type);
Link negate = append11(UOP_NEGATE, input.l[0], child1(output_type));
last = pair(negate, input.l[1], output_type);
break;
}
case 'Q':
{
Link3 input = unpair2(last);
assert_product(output_type);
Type *number = child1(output_type);
Link checked_number = append11(UOP_ASSERT_NONZERO, input.l[0], number);
Link2 divmod = append22(UOP_DIVMOD,
checked_number, input.l[1],
number, number);
last = pair2(divmod.l[0], divmod.l[1], input.l[2], output_type);
break;
}
// The condition equations are listed for the output
// nodes, in outside-in order. The variables a, b, c
// represent the conditions of the input nodes, in
// outside-in order (e.g. a is the condition of the
// outermost node in the input).
case 'L':
{
// Conditions:
// a || b
// a
Link2 input = unpair(last);
Link5 branches = unsum2(input.l[0]);
assert_product(output_type);
Type *type = child1(output_type);
Link2 cond_inner = append12(UOP_COPY, branches.l[3],
bool_type, bool_type);
assert_sum(type);
Link inner = sum(branches.l[0], branches.l[1], cond_inner.l[0],
child1(type));
Link cond_outer = or(cond_inner.l[1], branches.l[4]);
Link outer = sum(inner, branches.l[2], cond_outer, type);
last = pair(outer, input.l[1], output_type);
break;
}
case 'R':
{
// Conditions:
// a && b
// a && !b
Link2 input = unpair(last);
Link3 outer = unsum(input.l[0]);
Link3 inner = unsum(outer.l[0]);
Link2 cond_outer = append12(UOP_COPY, outer.l[2],
bool_type, bool_type);
Link2 cond_inner = append12(UOP_COPY, inner.l[2],
bool_type, bool_type);
assert_product(output_type);
Link new_outer = sum2(inner.l[0], inner.l[1], outer.l[1],
and(cond_outer.l[0], cond_inner.l[0]),
and(cond_outer.l[1], not(cond_inner.l[1])),
child1(output_type));
last = pair(new_outer, input.l[1], output_type);
break;
}
case 'W':
{
// Conditions:
// !a && b
// a
Link2 input = unpair(last);
Link5 branches = unsum2(input.l[0]);
Link2 cond_outer = append12(UOP_COPY, branches.l[3],
bool_type, bool_type);
assert_product(output_type);
Link new_branches = sum2(branches.l[1], branches.l[0], branches.l[2],
and(not(cond_outer.l[0]), branches.l[4]),
cond_outer.l[1],
child1(output_type));
last = pair(new_branches, input.l[1], output_type);
break;
}
case 'Z':
{
// Conditions:
// a
// !a && !b && c
// !a && b
Link2 input = unpair(last);
Link5 branches = unsum2(input.l[0]);
Link3 inner = unsum(branches.l[2]);
Link2 cond_outer = append12(UOP_COPY, branches.l[3],
bool_type, bool_type);
Link2 not_cond_outer = append12(UOP_COPY, not(cond_outer.l[0]),
bool_type, bool_type);
Link2 cond_middle = append12(UOP_COPY, branches.l[4],
bool_type, bool_type);
assert_product(output_type);
Type *type = child1(output_type);
assert_sum(type);
Type *type2 = child2(type);
assert_sum(type2);
Link new_inner = sum(branches.l[1], inner.l[1],
and(not_cond_outer.l[0], cond_middle.l[0]),
child2(type2));
Link new_branches = sum2(branches.l[0], branches.l[2], new_inner,
cond_outer.l[1],
and(not_cond_outer.l[1],
and(not(cond_middle.l[1]), inner.l[2])),
type);
last = pair(new_branches, input.l[1], output_type);
break;
}
case 'V':
{
Link2 input = unpair(last);
assert_product(output_type);
Type *type = child1(output_type);
assert_sum(type);
Link void_constant = append01(UOP_VOID_CONSTANT, child2(type));
Link bool_constant = append01(UOP_BOOL_CONSTANT, bool_type);
bool_constant.node->boolean = true;
Link branches = sum(input.l[0], void_constant, bool_constant, type);
last = pair(branches, input.l[1], output_type);
break;
}
case 'C':
{
Link2 input = unpair(last);
Link3 branches = unsum(input.l[0]);
append10(UOP_DROP, branches.l[1]);
append10(UOP_DROP, branches.l[2]);
last = pair(branches.l[0], input.l[1], output_type);
break;
}
case '?':
{
Link3 input = unpair2(last);
Link checked_block = append11(UOP_ASSERT_DROPPABLE,
input.l[0], input.l[0].type);
Link3 branches = unsum(input.l[1]);
assert_product(output_type);
Type *type = child1(output_type);
assert_sum(type);
Link applied_branch = append21(UOP_APPLY,
checked_block, branches.l[0],
child1(type));
Link new_branches = sum(applied_branch, branches.l[1], branches.l[2],
type);
last = pair(new_branches, input.l[2], output_type);
break;
}
case 'D':
{
Link3 input = unpair2(last);
Link3 branches = unsum(input.l[1]);
Link2 cond = append12(UOP_COPY, branches.l[2], bool_type, bool_type);
Link2 distrib = append22(UOP_DISTRIB, input.l[0], cond.l[0],
input.l[0].type, input.l[0].type);
assert_product(output_type);
Type *type = child1(output_type);
assert_sum(type);
Link left = pair(distrib.l[0], branches.l[0],
child1(type));
Link right = pair(distrib.l[1], branches.l[1],
child2(type));
Link new_branches = sum(left, right, cond.l[1], type);
last = pair(new_branches, input.l[2], output_type);
break;
}
case 'F':
{
Link2 input = unpair(last);
Link3 branches = unsum(input.l[0]);
Link2 cond = append12(UOP_COPY, branches.l[2], bool_type, bool_type);
Link2 left = unpair(branches.l[0]);
Link2 right = unpair(branches.l[1]);
assert_product(output_type);
Type *type = child2(output_type);
assert_product(type);
Link new_left = sum(left.l[0], right.l[0], cond.l[0],
child1(output_type));
Link new_right = sum(left.l[1], right.l[1], cond.l[1],
child1(type));
last = pair2(new_left, new_right, input.l[1], output_type);
break;
}
case 'M':
{
Link2 input = unpair(last);
Link3 branches = unsum(input.l[0]);
assert_product(output_type);
Link merge = append31(UOP_MERGE, branches.l[0], branches.l[1],
branches.l[2],
child1(output_type));
last = pair(merge, input.l[1], output_type);
break;
}
case 'K':
{
Link2 input = unpair(last);
Link3 branches = unsum(input.l[0]);
append20(UOP_ASSERT_VOID, branches.l[0], branches.l[2]);
last = pair(branches.l[1], input.l[1], output_type);
break;
}
case '>':
{
Link3 input = unpair2(last);
Node *greater = append_node20(bgraph, UOP_GREATER, input.l[1], input.l[0]);
Link g0 = {greater, 0, input.l[0].type};
Link g1 = {greater, 1, input.l[1].type};
Link g2 = {greater, 2, input.l[1].type};
Link g3 = {greater, 3, input.l[0].type};
Link g4 = {greater, 4, bool_type};
greater->out.next = alloc(&bgraph->out_link_pool, sizeof(OutLinkChunk));
OUT0(greater).type = g0.type;
OUT1(greater).type = g1.type;
OUT2(greater).type = g2.type;
OUT3(greater).type = g3.type;
OUT4(greater).type = g4.type;
greater->out_count = 5;
assert_product(output_type);
Type *type = child1(output_type);
assert_sum(type);
// We have truth on left in the graph IR
Link right = pair(g0, g1, child1(type));
Link left = pair(g2, g3, child2(type));
Link branches = sum(left, right, not(g4), type);
last = pair(branches, input.l[2], output_type);
break;
}
default:
{
assert(!"Received invalid opcode");
}
}
}
finish_block_graph(bgraph, last);
}
internal
ProgramGraph build_graphs(BlockPtrArray blocks, TypePool *type_pool, b32 optimise) {
ProgramGraph program = {};
program.type_pool = type_pool;
program.optimise = optimise;
foreach (block, blocks) {
build_graph(&program, *block);
}
program.main = &blocks.data[blocks.size - 1]->graph;
return program;
}
|
C
|
#include "sw_conf.h"
#include <stdint.h>
#include <stdbool.h>
#include "../src/gpio_driver.h"
#include "../unity.framework/src/unity.h"
static GPIO_Port_t portB;
static GPIO_Port_t portC;
static GPIO_Port_t portD;
void setUp()
{
GPIO_Init(&portB, &portC, &portD);
}
void test_GpioInitsToInputWithPullUp()
{
TEST_ASSERT_EQUAL(0b00000000, portB.dataDirection);
TEST_ASSERT_EQUAL(0b11111111, portB.output);
}
void test_ConfigSetsExpectedOutputFlag()
{
// PortB, 0 -> 4
pinConfig_t config;
config.pintype = PINTYPE_OUTPUT;
config.pullUpActive = false;
GPIO_ConfigurePin(12, config);
GPIO_ConfigurePin(13, config);
GPIO_ConfigurePin(14, config);
GPIO_ConfigurePin(15, config);
GPIO_ConfigurePin(16, config);
TEST_ASSERT_EQUAL(0b00011111, portB.dataDirection);
TEST_ASSERT_EQUAL(0b11100000, portB.output);
}
void test_OutOffBouncePinHasNoEffect()
{
// 16 == PORTB,4
pinConfig_t config;
config.pintype = PINTYPE_OUTPUT;
config.pullUpActive = false;
GPIO_ConfigurePin(40, config);
GPIO_ConfigurePin(35, config);
GPIO_ConfigurePin(-1, config);
GPIO_GetPin(40);
GPIO_GetPin(35);
GPIO_GetPin(-1);
GPIO_SetPin(40, false);
GPIO_SetPin(35, false);
GPIO_SetPin(-1, false);
TEST_ASSERT_EQUAL(0b00000000, portB.dataDirection);
TEST_ASSERT_EQUAL(0b11111111, portB.output);
TEST_ASSERT_EQUAL(0b00000000, portC.dataDirection);
TEST_ASSERT_EQUAL(0b11111111, portC.output);
TEST_ASSERT_EQUAL(0b00000000, portD.dataDirection);
TEST_ASSERT_EQUAL(0b11111111, portD.output);
}
void test_InvalidPinHasNoEffect()
{
// 16 == PORTB,4
pinConfig_t config;
config.pintype = PINTYPE_OUTPUT;
config.pullUpActive = false;
GPIO_ConfigurePin(20, config);
GPIO_ConfigurePin(6, config);
GPIO_GetPin(20);
GPIO_GetPin(6);
GPIO_SetPin(20, false);
GPIO_SetPin(6, false);
TEST_ASSERT_EQUAL(0b00000000, portB.dataDirection);
TEST_ASSERT_EQUAL(0b11111111, portB.output);
TEST_ASSERT_EQUAL(0b00000000, portC.dataDirection);
TEST_ASSERT_EQUAL(0b11111111, portC.output);
TEST_ASSERT_EQUAL(0b00000000, portD.dataDirection);
TEST_ASSERT_EQUAL(0b11111111, portD.output);
}
void test_PullUpCanBeDeactivated()
{
pinConfig_t config;
config.pintype = PINTYPE_INPUT;
config.pullUpActive = false;
GPIO_ConfigurePin(2, config);
TEST_ASSERT_EQUAL(0b00000000, portD.dataDirection);
TEST_ASSERT_EQUAL(0b11101111, portD.output);
}
void test_PullUpCanBeActivated()
{
// Disable PullUp first
pinConfig_t config;
config.pintype = PINTYPE_INPUT;
config.pullUpActive = false;
GPIO_ConfigurePin(2, config);
TEST_ASSERT_EQUAL(0b00000000, portD.dataDirection);
TEST_ASSERT_EQUAL(0b11101111, portD.output);
//Enable it
config.pintype = PINTYPE_INPUT;
config.pullUpActive = true;
GPIO_ConfigurePin(2, config);
TEST_ASSERT_EQUAL(0b00000000, portD.dataDirection);
TEST_ASSERT_EQUAL(0b11111111, portD.output);
}
void test_SetPinSetsOutput()
{
pinConfig_t config;
config.pintype = PINTYPE_OUTPUT;
config.pullUpActive = false;
GPIO_ConfigurePin(1, config);
GPIO_ConfigurePin(2, config);
GPIO_ConfigurePin(9, config);
GPIO_ConfigurePin(10, config);
GPIO_ConfigurePin(11, config);
GPIO_ConfigurePin(30, config);
GPIO_ConfigurePin(31, config);
GPIO_ConfigurePin(32, config);
TEST_ASSERT_EQUAL(0xFF, portD.dataDirection);
GPIO_SetPin(1, 1);
TEST_ASSERT_EQUAL(0b00001000, portD.output);
}
void test_SetPinClearsOutput()
{
pinConfig_t config;
config.pintype = PINTYPE_OUTPUT;
config.pullUpActive = false;
GPIO_ConfigurePin(1, config);
GPIO_ConfigurePin(2, config);
GPIO_ConfigurePin(9, config);
GPIO_ConfigurePin(10, config);
GPIO_ConfigurePin(11, config);
GPIO_ConfigurePin(30, config);
GPIO_ConfigurePin(31, config);
GPIO_ConfigurePin(32, config);
TEST_ASSERT_EQUAL(0xFF, portD.dataDirection);
GPIO_SetPin(1, 0);
TEST_ASSERT_EQUAL(0b00000000, portD.output);
}
void test_GetPinReturnsInputValue()
{
bool retVal;
pinConfig_t config;
config.pintype = PINTYPE_INPUT;
config.pullUpActive = false;
GPIO_ConfigurePin(1, config);
GPIO_ConfigurePin(2, config);
GPIO_ConfigurePin(9, config);
GPIO_ConfigurePin(10, config);
GPIO_ConfigurePin(11, config);
GPIO_ConfigurePin(30, config);
GPIO_ConfigurePin(31, config);
GPIO_ConfigurePin(32, config);
TEST_ASSERT_EQUAL(0, portD.dataDirection);
retVal = GPIO_GetPin(1);
TEST_ASSERT_FALSE(retVal);
portD.input |= (1 << 3);
retVal = GPIO_GetPin(1);
TEST_ASSERT_TRUE(retVal);
}
|
C
|
#include "LinerIR.h"
#include <assert.h>
Operand newOperand(){
return malloc(sizeof(struct Operand_));
}
InterCode newInterCode(){
return malloc(sizeof(struct InterCode_));
}
void printOperand(FILE* f, Operand operand){
if(operand == NULL) return;
switch(operand->kind){
case VARIABLE:
{
fprintf(f, "v%d", operand->no);
break;
}
case TEMP:
{
fprintf(f, "t%d", operand->no);
break;
}
case STRING:
{
fprintf(f, "%s", operand->str);
break;
}
case CONSTANT:
{
fprintf(f, "#%d", operand->no);
break;
}
case ADDRESS:
{
fprintf(stderr, "please implement me\n");
assert(0);
break;
}
default:
break;
}
}
InterCodes newInterCodes(){
InterCodes interCodes = malloc(sizeof(struct InterCodes_));
interCodes->code = newInterCode();
interCodes->prev = NULL;
interCodes->next = NULL;
return interCodes;
}
InterCodes genLabelCode(int label_no){
assert(label_no > 0);
InterCodes code_label = newInterCodes();
code_label->code = newInterCode();
code_label->code->kind = LABEL;
code_label->code->label.no = label_no;
return code_label;
}
InterCodes genGotoCode(int label_no){
InterCodes code_goto = newInterCodes();
code_goto->code = newInterCode();
code_goto->code->kind = GOTO;
code_goto->code->goto_.label_no = label_no;
return code_goto;
}
InterCodes tail(InterCodes code){
assert(code != NULL);
InterCodes code_tail = code;
while(code_tail->next != NULL)
code_tail = code_tail->next;
return code_tail;
}
InterCodes head(InterCodes code){
assert(code != NULL);
InterCodes code_head = code;
while(code_head->prev != NULL)
code_head = code_head->prev;
return code_head;
}
InterCodes mergeCode(InterCodes code1, InterCodes code2){
if(code1 == NULL) return code2;
if(code2 == NULL) return code1;
assert(code1 != NULL && code2 != NULL);
assert(code1 != code2);
InterCodes code1_tail = tail(code1);
InterCodes code2_head = head(code2);
assert(code1_tail != NULL && code2_head != NULL);
code1_tail->next = code2_head;
code2_head->prev = code1_tail;
InterCodes code = head(code1);
return code;
}
void printInterCodes(FILE* f, InterCodes interCodes){
if(interCodes == NULL) return;
InterCodes first = head(interCodes);
for(; first != NULL; first = first->next){
InterCode interCode = first->code;
switch(interCode->kind){
case ASSIGN:
{
printOperand(f, interCode->assign.left);
fprintf(f, " := ");
printOperand(f, interCode->assign.right);
fprintf(f, "\n");
break;
}
case ASSIGN_STAR:
{
printOperand(f, interCode->assign.left);
fprintf(f, " := *");
printOperand(f, interCode->assign.right);
fprintf(f, "\n");
break;
}
case ASSIGN_ADDR:
{
printOperand(f, interCode->assign.left);
fprintf(f, " := &");
printOperand(f, interCode->assign.right);
fprintf(f, "\n");
break;
}
case STAR_ASSIGN:
{
fprintf(f, "*");
printOperand(f, interCode->assign.left);
fprintf(f, " := ");
printOperand(f, interCode->assign.right);
fprintf(f, "\n");
break;
}
case PLUS_:
{
printOperand(f, interCode->binop.result);
fprintf(f, " := ");
printOperand(f, interCode->binop.op1);
fprintf(f, " + ");
printOperand(f, interCode->binop.op2);
fprintf(f, "\n");
break;
}
case MINUS_:
{
printOperand(f, interCode->binop.result);
fprintf(f, " := ");
printOperand(f, interCode->binop.op1);
fprintf(f, " - ");
printOperand(f, interCode->binop.op2);
fprintf(f, "\n");
break;
}
case MUL:
{
printOperand(f, interCode->binop.result);
fprintf(f, " := ");
printOperand(f, interCode->binop.op1);
fprintf(f, " * ");
printOperand(f, interCode->binop.op2);
fprintf(f, "\n");
break;
}
case DIV_:
{
printOperand(f, interCode->binop.result);
fprintf(f, " := ");
printOperand(f, interCode->binop.op1);
fprintf(f, " / ");
printOperand(f, interCode->binop.op2);
fprintf(f, "\n");
break;
}
case EMPTY:
{
break;
}
case FUNCDEC:
{
fprintf(f, "FUNCTION ");
printOperand(f, interCode->funcdec.op);
fprintf(f, " :\n");
break;
}
case FUNCCALL:
{
printOperand(f, interCode->funccall.left);
fprintf(f, " := CALL ");
printOperand(f, interCode->funccall.right);
fprintf(f, "\n");
break;
}
case FUNCCALLREAD:
{
fprintf(f, "READ ");
printOperand(f, interCode->funccallread.op);
fprintf(f, "\n");
break;
}
case FUNCCALLWRITE:
{
fprintf(f, "WRITE ");
printOperand(f, interCode->funccallwrite.op);
fprintf(f, "\n");
break;
}
case SPFUNCCALL:
{
break;
}
case ARG:
{
fprintf(f, "ARG ");
printOperand(f, interCode->arg.op);
fprintf(f, "\n");
break;
}
case LABEL:
{
fprintf(f, "LABEL label%d :\n",interCode->label.no);
break;
}
case COND:
{
fprintf(f, "IF ");
printOperand(f, interCode->cond.v1);
fprintf(f, " %s ", interCode->cond.op);
printOperand(f, interCode->cond.v2);
assert(interCode->cond.label_no > 0);
fprintf(f, " GOTO label%d\n", interCode->cond.label_no);
break;
}
case GOTO:
{
fprintf(f, "GOTO label%d\n",interCode->label.no);
break;
}
case RETURN_:
{
fprintf(f, "RETURN ");
printOperand(f, interCode->return_.op);
fprintf(f, "\n");
break;
}
case PARAM:
{
fprintf(f, "PARAM ");
printOperand(f, interCode->param.op);
fprintf(f, "\n");
break;
}
case DEC:
{
fprintf(f, "DEC ");
printOperand(f, interCode->dec.op);
fprintf(f, " %d\n", interCode->dec.size);
break;
}
case ADDR_ASSIGN:
{
printOperand(f, interCode->assign.left);
fprintf(f, " := &");
printOperand(f, interCode->assign.right);
fprintf(f, "\n");
break;
}
case ARRAY_ASSIGN:
{
break;
}
default:
break;
}
}
}
|
C
|
/**
* Copyright (C) 2021 jouyouyun <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* detach.c -- test usb detach by libusb-1.0
*
* compile: gcc -Wall -g detach.c `pkg-config --libs --cflags libusb-1.0`
*
* Written on 星期三, 7 四月 2021.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libusb-1.0/libusb.h>
libusb_context *ctx = NULL;
static void detach_device(const char *vendor, const char *product)
{
int ret = 0;
long int vid = 0, pid = 0;
vid = strtol(vendor, NULL, 16);
pid = strtol(product, NULL, 16);
printf("will detach device %lx:%lx\n", vid, pid);
libusb_device_handle *handler = libusb_open_device_with_vid_pid(ctx, vid, pid);
if (!handler) {
fprintf(stderr, "failed to open device(%lx:%lx):", vid, pid);
return;
}
ret = libusb_detach_kernel_driver(handler, 0);
if (ret != LIBUSB_SUCCESS) {
fprintf(stderr, "failed to detach device(%lx:%lx): %s\n", vid, pid, libusb_strerror(ret));
}
libusb_close(handler);
}
// Some USB devices of the same model may have the same vendor id and product id.
static void detach_device2(const char *vendor, const char *product)
{
int i = 0;
int ret = 0;
long int vid = 0, pid = 0;
struct libusb_device **devs = NULL;
struct libusb_device *dev = NULL;
struct libusb_device_handle *handler = NULL;
vid = strtol(vendor, NULL, 16);
pid = strtol(product, NULL, 16);
printf("will detach device %lx:%lx\n", vid, pid);
if ((ret = libusb_get_device_list(ctx, &devs)) < 0) {
fprintf(stderr, "failed to get device list: %s\n", libusb_strerror(ret));
return;
}
while ((dev = devs[i++]) != NULL) {
struct libusb_device_descriptor desc;
ret = libusb_get_device_descriptor(dev, &desc);
if (ret < 0) {
fprintf(stderr, "failed to get device descriptor: %s\n", libusb_strerror(ret));
goto out;
}
if (desc.idVendor != vid || desc.idProduct != pid) {
continue;
}
printf("found, detach device:\n");
ret = libusb_open(dev, &handler);
if (ret < 0) {
fprintf(stderr, "failed to open device: %s\n", libusb_strerror(ret));
continue;
}
ret = libusb_detach_kernel_driver(handler, 0);
if (ret < 0) {
fprintf(stderr, "failed to detach device: %s\n", libusb_strerror(ret));
}
libusb_close(handler);
handler = NULL;
}
out:
libusb_free_device_list(devs, 1);
return ;
}
#define DESC_MAX_BUF 256
static void list_device()
{
int i = 0;
int ret = 0;
unsigned char buf[DESC_MAX_BUF];
struct libusb_device **devs = NULL;
struct libusb_device *dev = NULL;
struct libusb_device_handle *handler = NULL;
printf("usb device list\n");
if ((ret = libusb_get_device_list(ctx, &devs)) < 0) {
fprintf(stderr, "failed to get device list: %s\n", libusb_strerror(ret));
return;
}
while ((dev = devs[i++]) != NULL) {
struct libusb_device_descriptor desc;
ret = libusb_get_device_descriptor(dev, &desc);
if (ret < 0) {
fprintf(stderr, "failed to get device descriptor: %s\n",
libusb_strerror(ret));
goto out;
}
ret = libusb_open(dev, &handler);
if (ret < 0) {
fprintf(stderr, "failed to open device: %s\n", libusb_strerror(ret));
continue;
}
printf("0x%x:0x%x\n", desc.idVendor, desc.idProduct);
libusb_get_string_descriptor_ascii(handler, ${2 : uint8_t desc_index}, buf,
DESC_MAX_BUF);
libusb_close(handler);
handler = NULL;
}
out:
libusb_free_device_list(devs, 1);
return;
printf("end usb device list\n");
}
int main(int argc, char *argv[])
{
if (argc != 3) {
fprintf(stderr, "Usage: %s <vendor id> <product id>", argv[0]);
return -1;
}
int ret = libusb_init(&ctx);
if (ret != LIBUSB_SUCCESS) {
fprintf(stderr, "failed to init: %s\n", libusb_strerror(ret));
return -1;
}
libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, LIBUSB_LOG_LEVEL_DEBUG);
//detach_device(argv[1], argv[2]);
detach_device2(argv[1], argv[2]);
libusb_exit(ctx);
return 0;
}
|
C
|
#include "lexer.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define _PARSER_C
#include "parser.h"
#undef _PARSER_C
static allocator_t *alloc = NULL;
list_t *keyValPairs();
void keyValPair(), *key(), *val(), *array();
/**
*
*/
json_t *JsonParse() {
json_t *json = malloc(sizeof(json_t));
if(getNextToken() == Tok_BraceOpen) {
do {
advance();
json->values = keyValPairs();
if(getNextToken() != Tok_BraceClose) {
printf("Missing closing }");
exit(1);
}
advance();
} while(getNextToken() == Tok_BraceOpen);
}
return json;
}
list_t *keyValPairs() {
if(alloc == NULL) {
alloc = AllocatorCreate(sizeof(struct Node), 256);
}
list_t *list = ListCreate(alloc);
char *k;
void *v;
keyValPair(&k, &v);
ListInsertBack(list, k, v);
while (getNextToken() == Tok_End) {
advance();
keyValPair(&k, &v);
ListInsertBack(list, k, v);
}
return list;
}
void keyValPair(char **k, void **v) {
*k = key();
if(getNextToken() != Tok_Separator) {
printf("Expected `:` \n");
exit(1);
}
advance();
*v = val();
}
void *key() {
if(getNextToken() != Tok_Key) {
printf("Unexpected character %c on line %d\n", LastChar, CurrentLine);
exit(1);
}
return strdup(buffer);
}
void *val() {
value_t *val = malloc(sizeof(value_t));
switch(getNextToken()) {
case Tok_String: {
val->type = STRING;
val->val = strdup(buffer);
return val;
}
case Tok_Bool: {
val->type = KYWRD;
val->val = strdup(buffer);
return val;
}
case Tok_Number: {
val->type = NUMBER;
val->val = strdup(buffer);
return val;
}
case Tok_ParenOpen: {
val->type = ARRAY;
val->val = array();
return val;
}
case Tok_BraceOpen: {
val->type = JSON;
val->val = JsonParse();
return val;
}
default: printf("Unexpefcted `%c` on line %d\n", LastChar, CurrentLine);exit(1);
}
}
void *array() {
list_t *l = ListCreate(alloc);
int i = 0;
advance();
while (1) {
ListInsertBack(l, 0, val());
token t = getNextToken();
if(t == Tok_End) {
advance();
} else if(t == Tok_ParenClose) {
break;
}
}
advance();
return l;
}
void JsonFree(json_t *json) {
ListDestroy(json->values);
free(json);
}
|
C
|
/******************************************************************************
* Projekt - Zaklady pocitacove grafiky - IZG
* [email protected]
*
* $Id:$
*/
#include "student.h"
#include "transform.h"
#include "fragment.h"
#include <memory.h>
#include <math.h>
/*****************************************************************************
* Globalni promenne a konstanty
*/
/* Typ/ID rendereru (nemenit) */
const int STUDENT_RENDERER = 1;
// v MAT_RED bola cervena zlozka nastavena na 0.8 - nastavit to tiez na 0.8 ci na 1.0?
const S_Material MAT_WHITE_AMBIENT = { 1.0, 1.0, 1.0, 1.0 };
const S_Material MAT_WHITE_DIFFUSE = { 1.0, 1.0, 1.0, 1.0 };
const S_Material MAT_WHITE_SPECULAR = { 1.0, 1.0, 1.0, 1.0 };
/*****************************************************************************
* Funkce vytvori vas renderer a nainicializuje jej
*/
S_Renderer * studrenCreate()
{
S_StudentRenderer * renderer = (S_StudentRenderer *)malloc(sizeof(S_StudentRenderer));
IZG_CHECK(renderer, "Cannot allocate enough memory");
/* inicializace default rendereru */
renderer->base.type = STUDENT_RENDERER;
renInit(&renderer->base);
/* nastaveni ukazatelu na upravene funkce */
/* napr. renderer->base.releaseFunc = studrenRelease; */
renderer->base.releaseFunc = studrenRelease;
renderer->base.projectTriangleFunc = studrenProjectTriangle;
/* inicializace nove pridanych casti */
renderer->width = 0;
renderer->height = 0;
//S_RGBA *p = loadBitmap(TEXTURE_FILENAME, &(renderer->width), &(renderer->height));
renderer->texture = loadBitmap(TEXTURE_FILENAME, &(renderer->width), &(renderer->height));
return (S_Renderer *)renderer;
}
/*****************************************************************************
* Funkce korektne zrusi renderer a uvolni pamet
*/
void studrenRelease(S_Renderer **ppRenderer)
{
S_StudentRenderer * renderer;
if( ppRenderer && *ppRenderer )
{
/* ukazatel na studentsky renderer */
renderer = (S_StudentRenderer *)(*ppRenderer);
/* pripadne uvolneni pameti */
free(renderer->texture);
/* fce default rendereru */
renRelease(ppRenderer);
}
}
/******************************************************************************
* Nova fce pro rasterizaci trojuhelniku s podporou texturovani
* Upravte tak, aby se trojuhelnik kreslil s texturami
* (doplnte i potrebne parametry funkce - texturovaci souradnice, ...)
* v1, v2, v3 - ukazatele na vrcholy trojuhelniku ve 3D pred projekci
* n1, n2, n3 - ukazatele na normaly ve vrcholech ve 3D pred projekci
* x1, y1, ... - vrcholy trojuhelniku po projekci do roviny obrazovky
*/
void studrenDrawTriangle(S_Renderer *pRenderer,
S_Coords *v1, S_Coords *v2, S_Coords *v3,
S_Coords *n1, S_Coords *n2, S_Coords *n3,
int x1, int y1,
int x2, int y2,
int x3, int y3,
S_Coords *t, double ha, double hb, double hc)
{
int minx, miny, maxx, maxy;
int a1, a2, a3, b1, b2, b3, c1, c2, c3;
int s1, s2, s3;
int x, y, e1, e2, e3;
double alpha, beta, gamma, w1, w2, w3, z, tX, tY;
S_RGBA col1, col2, col3, color, tColor;
IZG_ASSERT(pRenderer && v1 && v2 && v3 && n1 && n2 && n3);
/* vypocet barev ve vrcholech */
col1 = pRenderer->calcReflectanceFunc(pRenderer, v1, n1);
col2 = pRenderer->calcReflectanceFunc(pRenderer, v2, n2);
col3 = pRenderer->calcReflectanceFunc(pRenderer, v3, n3);
/* obalka trojuhleniku */
minx = MIN(x1, MIN(x2, x3));
maxx = MAX(x1, MAX(x2, x3));
miny = MIN(y1, MIN(y2, y3));
maxy = MAX(y1, MAX(y2, y3));
/* oriznuti podle rozmeru okna */
miny = MAX(miny, 0);
maxy = MIN(maxy, pRenderer->frame_h - 1);
minx = MAX(minx, 0);
maxx = MIN(maxx, pRenderer->frame_w - 1);
/* Pineduv alg. rasterizace troj.
hranova fce je obecna rovnice primky Ax + By + C = 0
primku prochazejici body (x1, y1) a (x2, y2) urcime jako
(y1 - y2)x + (x2 - x1)y + x1y2 - x2y1 = 0 */
/* normala primek - vektor kolmy k vektoru mezi dvema vrcholy, tedy (-dy, dx) */
a1 = y1 - y2;
a2 = y2 - y3;
a3 = y3 - y1;
b1 = x2 - x1;
b2 = x3 - x2;
b3 = x1 - x3;
/* koeficient C */
c1 = x1 * y2 - x2 * y1;
c2 = x2 * y3 - x3 * y2;
c3 = x3 * y1 - x1 * y3;
/* vypocet hranove fce (vzdalenost od primky) pro protejsi body */
s1 = a1 * x3 + b1 * y3 + c1;
s2 = a2 * x1 + b2 * y1 + c2;
s3 = a3 * x2 + b3 * y2 + c3;
if ( !s1 || !s2 || !s3 )
{
return;
}
/* normalizace, aby vzdalenost od primky byla kladna uvnitr trojuhelniku */
if( s1 < 0 )
{
a1 *= -1;
b1 *= -1;
c1 *= -1;
}
if( s2 < 0 )
{
a2 *= -1;
b2 *= -1;
c2 *= -1;
}
if( s3 < 0 )
{
a3 *= -1;
b3 *= -1;
c3 *= -1;
}
/* koeficienty pro barycentricke souradnice */
alpha = 1.0 / ABS(s2);
beta = 1.0 / ABS(s3);
gamma = 1.0 / ABS(s1);
/* vyplnovani... */
for( y = miny; y <= maxy; ++y )
{
/* inicilizace hranove fce v bode (minx, y) */
e1 = a1 * minx + b1 * y + c1;
e2 = a2 * minx + b2 * y + c2;
e3 = a3 * minx + b3 * y + c3;
for( x = minx; x <= maxx; ++x )
{
if( e1 >= 0 && e2 >= 0 && e3 >= 0 )
{
/* interpolace pomoci barycentrickych souradnic
e1, e2, e3 je aktualni vzdalenost bodu (x, y) od primek */
w1 = alpha * e2;
w2 = beta * e3;
w3 = gamma * e1;
/* interpolace z-souradnice */
z = w1 * v1->z + w2 * v2->z + w3 * v3->z;
/* Vypocet texturovacich suradnic bez perspektivnej korekcie
tX = w1 * t[0].x + w2 * t[1].x + w3 * t[2].x;
tY = w1 * t[0].y + w2 * t[1].y + w3 * t[2].y;
*/
/* Vypocet texturovacich suradnic s vyuzitim perspektivnej korekcie */
tX = (w1*t[0].x/ha + w2*t[1].x/hb + w3*t[2].x/hc)/(w1/ha + w2/hb + w3/hc);
tY = (w1*t[0].y/ha + w2*t[1].y/hb + w3*t[2].y/hc)/(w1/ha + w2/hb + w3/hc);
/* interpolace barvy */
color.red = ROUND2BYTE(w1 * col1.red + w2 * col2.red + w3 * col3.red);
color.green = ROUND2BYTE(w1 * col1.green + w2 * col2.green + w3 * col3.green);
color.blue = ROUND2BYTE(w1 * col1.blue + w2 * col2.blue + w3 * col3.blue);
/* Ziskanie farby z textury */
tColor = studrenTextureValue((S_StudentRenderer *) pRenderer, tX, tY);
/* Miesanie farieb */
color.red = (color.red * tColor.red)/256;
color.green = (color.green * tColor.green)/256;
color.blue = (color.blue * tColor.blue)/256;
color.alpha = 255;
/* vykresleni bodu */
if( z < DEPTH(pRenderer, x, y) )
{
PIXEL(pRenderer, x, y) = color;
DEPTH(pRenderer, x, y) = z;
}
}
/* hranova fce o pixel vedle */
e1 += a1;
e2 += a2;
e3 += a3;
}
}
}
/******************************************************************************
* Vykresli i-ty trojuhelnik n-teho klicoveho snimku modelu
* pomoci nove fce studrenDrawTriangle()
* Pred vykreslenim aplikuje na vrcholy a normaly trojuhelniku
* aktualne nastavene transformacni matice!
* Upravte tak, aby se model vykreslil interpolovane dle parametru n
* (cela cast n udava klicovy snimek, desetinna cast n parametr interpolace
* mezi snimkem n a n + 1)
* i - index trojuhelniku
* n - index klicoveho snimku (float pro pozdejsi interpolaci mezi snimky)
*/
void studrenProjectTriangle(S_Renderer *pRenderer, S_Model *pModel, int i, float n)
{
S_Coords aa, bb, cc; /* souradnice vrcholu po transformaci */
S_Coords n_aa, n_bb, n_cc;
S_Coords naa, nbb, ncc; /* normaly ve vrcholech po transformaci */
S_Coords n_naa, n_nbb, n_ncc;
S_Coords nn; /* normala trojuhelniku po transformaci */
S_Coords n_nn;
double ha, hb, hc;
double nFrac; /* desatinna cast n */
int u1, v1, u2, v2, u3, v3; /* souradnice vrcholu po projekci do roviny obrazovky */
S_Triangle * triangle;
int vertexOffset, normalOffset; /* offset pro vrcholy a normalove vektory trojuhelniku */
int n_vertexOffset, n_normalOffset;
int i0, i1, i2, in; /* indexy vrcholu a normaly pro i-ty trojuhelnik n-teho snimku */
int n_i0, n_i1, n_i2, n_in;
IZG_ASSERT(pRenderer && pModel && i >= 0 && i < trivecSize(pModel->triangles) && n >= 0 );
nFrac = n - (long) n;
/* z modelu si vytahneme i-ty trojuhelnik */
triangle = trivecGetPtr(pModel->triangles, i);
/* ziskame offset pro vrcholy n-teho snimku */
vertexOffset = (((int) n) % pModel->frames) * pModel->verticesPerFrame;
n_vertexOffset = (((int) (n + 1.0)) % pModel->frames) * pModel->verticesPerFrame;
/* ziskame offset pro normaly trojuhelniku n-teho snimku */
normalOffset = (((int) n) % pModel->frames) * pModel->triangles->size;
n_normalOffset = (((int) (n + 1.0)) % pModel->frames) * pModel->triangles->size;
/* indexy vrcholu pro i-ty trojuhelnik n-teho snimku - pricteni offsetu */
i0 = triangle->v[ 0 ] + vertexOffset;
i1 = triangle->v[ 1 ] + vertexOffset;
i2 = triangle->v[ 2 ] + vertexOffset;
n_i0 = triangle->v[ 0 ] + n_vertexOffset;
n_i1 = triangle->v[ 1 ] + n_vertexOffset;
n_i2 = triangle->v[ 2 ] + n_vertexOffset;
/* index normaloveho vektoru pro i-ty trojuhelnik n-teho snimku - pricteni offsetu */
in = triangle->n + normalOffset;
n_in = triangle->n + n_normalOffset;
/* transformace vrcholu matici model */
trTransformVertex(&aa, cvecGetPtr(pModel->vertices, i0));
trTransformVertex(&bb, cvecGetPtr(pModel->vertices, i1));
trTransformVertex(&cc, cvecGetPtr(pModel->vertices, i2));
trTransformVertex(&n_aa, cvecGetPtr(pModel->vertices, n_i0));
trTransformVertex(&n_bb, cvecGetPtr(pModel->vertices, n_i1));
trTransformVertex(&n_cc, cvecGetPtr(pModel->vertices, n_i2));
aa.x += (n_aa.x - aa.x) * nFrac;
aa.y += (n_aa.y - aa.y) * nFrac;
aa.z += (n_aa.z - aa.z) * nFrac;
bb.x += (n_bb.x - bb.x) * nFrac;
bb.y += (n_bb.y - bb.y) * nFrac;
bb.z += (n_bb.z - bb.z) * nFrac;
cc.x += (n_cc.x - cc.x) * nFrac;
cc.y += (n_cc.y - cc.y) * nFrac;
cc.z += (n_cc.z - cc.z) * nFrac;
/* promitneme vrcholy trojuhelniku na obrazovku */
ha = trProjectVertex(&u1, &v1, &aa);
hb = trProjectVertex(&u2, &v2, &bb);
hc = trProjectVertex(&u3, &v3, &cc);
/* pro osvetlovaci model transformujeme take normaly ve vrcholech */
trTransformVector(&naa, cvecGetPtr(pModel->normals, i0));
trTransformVector(&nbb, cvecGetPtr(pModel->normals, i1));
trTransformVector(&ncc, cvecGetPtr(pModel->normals, i2));
trTransformVector(&n_naa, cvecGetPtr(pModel->normals, n_i0));
trTransformVector(&n_nbb, cvecGetPtr(pModel->normals, n_i1));
trTransformVector(&n_ncc, cvecGetPtr(pModel->normals, n_i2));
naa.x += (n_naa.x - naa.x) * nFrac;
naa.y += (n_naa.y - naa.y) * nFrac;
naa.z += (n_naa.z - naa.z) * nFrac;
nbb.x += (n_nbb.x - nbb.x) * nFrac;
nbb.y += (n_nbb.y - nbb.y) * nFrac;
nbb.z += (n_nbb.z - nbb.z) * nFrac;
ncc.x += (n_ncc.x - ncc.x) * nFrac;
ncc.y += (n_ncc.y - ncc.y) * nFrac;
ncc.z += (n_ncc.z - ncc.z) * nFrac;
/* normalizace normal */
coordsNormalize(&naa);
coordsNormalize(&nbb);
coordsNormalize(&ncc);
/* transformace normaly trojuhelniku matici model */
trTransformVector(&nn, cvecGetPtr(pModel->trinormals, in));
trTransformVector(&n_nn, cvecGetPtr(pModel->trinormals, n_in));
nn.x += (n_nn.x - nn.x) * nFrac;
nn.y += (n_nn.y - nn.y) * nFrac;
nn.z += (n_nn.z - nn.z) * nFrac;
/* normalizace normaly */
coordsNormalize(&nn);
/* je troj. privraceny ke kamere, tudiz viditelny? */
if( !renCalcVisibility(pRenderer, &aa, &nn) )
{
/* odvracene troj. vubec nekreslime */
return;
}
/* rasterizace trojuhelniku */
studrenDrawTriangle(pRenderer,
&aa, &bb, &cc,
&naa, &nbb, &ncc,
u1, v1, u2, v2, u3, v3,
triangle->t, ha, hb, hc);
}
/******************************************************************************
* Vraci hodnotu v aktualne nastavene texture na zadanych
* texturovacich souradnicich u, v
* Pro urceni hodnoty pouziva bilinearni interpolaci
* Pro otestovani vraci ve vychozim stavu barevnou sachovnici dle uv souradnic
* u, v - texturovaci souradnice v intervalu 0..1, ktery odpovida sirce/vysce textury
*/
S_RGBA studrenTextureValue( S_StudentRenderer * pRenderer, double u, double v )
{
double uFil = u * pRenderer->height - 0.5;
int x = floor(uFil);
double uR = uFil - x;
double uRN = 1.0 - uR;
double vFil = v * pRenderer->width - 0.5;
int y = floor(vFil);
double vR = vFil - y;
double vRN = 1.0 - vR;
S_RGBA p0 = pRenderer->texture[(x*(pRenderer->width) + y)%(pRenderer->width*pRenderer->height)];
S_RGBA p1 = pRenderer->texture[(x*(pRenderer->width) + y + 1)%(pRenderer->width*pRenderer->height)];
S_RGBA p2 = pRenderer->texture[((x + 1) * (pRenderer->width) + y + 1)%(pRenderer->width*pRenderer->height)];
S_RGBA p3 = pRenderer->texture[((x + 1) * (pRenderer->width) + y)%(pRenderer->width*pRenderer->height)];
S_RGBA col;
col.red = (p0.red*uRN + p3.red*uR)*vRN + (p1.red*uRN + p2.red*uR)*vR;
col.green = (p0.green*uRN + p3.green*uR)*vRN + (p1.green*uRN + p2.green*uR)*vR;
col.blue = (p0.blue*uRN + p3.blue*uR)*vRN + (p1.blue*uRN + p2.blue*uR)*vR;
col.alpha = 255;
return col;
}
/******************************************************************************
******************************************************************************
* Funkce pro vyrenderovani sceny, tj. vykresleni modelu
* Upravte tak, aby se model vykreslil animovane
* (volani renderModel s aktualizovanym parametrem n)
*/
void renderStudentScene(S_Renderer *pRenderer, S_Model *pModel)
{
/* test existence frame bufferu a modelu */
IZG_ASSERT(pModel && pRenderer);
/* nastavit projekcni matici */
trProjectionPerspective(pRenderer->camera_dist, pRenderer->frame_w, pRenderer->frame_h);
/* vycistit model matici */
trLoadIdentity();
/* nejprve nastavime posuv cele sceny od/ke kamere */
trTranslate(0.0, 0.0, pRenderer->scene_move_z);
/* nejprve nastavime posuv cele sceny v rovine XY */
trTranslate(pRenderer->scene_move_x, pRenderer->scene_move_y, 0.0);
/* natoceni cele sceny - jen ve dvou smerech - mys je jen 2D... :( */
trRotateX(pRenderer->scene_rot_x);
trRotateY(pRenderer->scene_rot_y);
/* nastavime material */
renMatAmbient(pRenderer, &MAT_WHITE_AMBIENT);
renMatDiffuse(pRenderer, &MAT_WHITE_DIFFUSE);
renMatSpecular(pRenderer, &MAT_WHITE_SPECULAR);
/* a vykreslime nas model (ve vychozim stavu kreslime pouze snimek 0) */
renderModel(pRenderer, pModel, t);
}
/* Callback funkce volana pri tiknuti casovace
* ticks - pocet milisekund od inicializace */
void onTimer( int ticks )
{
/* uprava parametru pouzivaneho pro vyber klicoveho snimku
* a pro interpolaci mezi snimky */
t = (float) ticks / 100;
}
/*****************************************************************************
*****************************************************************************/
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"list.h"
#include"canciones.h"
int main(){
char archivo[20];
char nombre[41];
char artista[11];
char genero[11];
char lista[10];
char año[7];
Cancion* nuevo;
List * listaCanciones;
listaCanciones = createList();
int op;
while (op!=0)
{
printf("---------------------------------------------------\n");
printf("1.- Importar Canciones\n");
printf("2.- Exportar Canciones\n");
printf("3.- Agregar Cancion\n");
printf("4.- Buscar Cancion por Nombre\n");
printf("5.- Buscar Cancion por Artista\n");
printf("6.- Buscar Cancion por Genero\n");
printf("7.- Eliminar Cancion\n");
printf("8.- Mostrar nombres de las listas de reproducción\n");
printf("9.- Mostrar una lista de reproducción\n");
printf("10.- Mostrar todas las canciones\n");
printf("0.- Salir\n");
printf("---------------------------------------------------\n");
printf("Indica la opcion: ");
scanf("%d", &op);
printf("\n");
switch(op)
{
case 3:
printf("Agregar Cancion\n");
printf("Nombre de la Cancion: ");
getchar();
fgets(nombre, 41, stdin); //lee 41 caracteres hasta el salto de linea
printf("Artista: ");
fgets(artista,11, stdin);
printf("Genero: ");
fgets(genero,11, stdin);
printf("Año: ");
fgets(año,7,stdin);
printf("Lista: ");
fgets(lista,10, stdin);
agregarCancion(listaCanciones,nombre,artista,genero,lista,año);
break;
return 0;
case 4:
printf("Ingrese nombre de la cancion: ");
getchar();
fgets(nombre,41,stdin);
BuscarCancionxNombre(listaCanciones, nombre);
break;
return 0;
}
}
return 0;
}
|
C
|
#include<stdio.h>
void main()
{
int a,sum=0;
printf("ENTER THE NUMBER :\n");
scanf("%d",&a);
sum=(a*(a-1))/2;
printf("THE SUM OF NOS %d IS %d",a,sum);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: apuchill <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/04/06 17:31:30 by apuchill #+# #+# */
/* Updated: 2020/05/02 13:44:16 by apuchill ### ########.fr */
/* */
/* ************************************************************************** */
#include "../get_next_line.h"
#include <stdio.h>
#include <fcntl.h>
#define MAIN(string) "\033[1m\033[38;5;199m" string "\033[0m"
#define MAIN_1(string) "\033[35m" string "\033[0m"
#define HEADER_1(string) "\033[38;5;43m" string "\033[0m"
#define HEADER_2(string) "\033[38;5;75m" string "\033[0m"
#define HIGHLIGHT(string) "\033[38;5;191m" string "\033[0m"
void test(int fd)
{
char *line;
int ret;
int i;
line = NULL;
printf("> fd = %d\n", fd);
i = 1;
ret = 1;
while (ret == 1)
{
ret = get_next_line(fd, &line);
printf(HEADER_2("• Line n.%d ") HEADER_1("[RET=%d]: ") "\"%s\"\n", i, ret, line);
free(line);
line = NULL;
i++;
}
close(fd);
}
int main(void)
{
printf(MAIN("=== • Program started • ===\n"));
printf(MAIN_1("=== empty file ===\n"));
int fda;
fda = open("txt_files/t_empty.txt", O_RDONLY);
test(fda);
printf(MAIN_1("=== \\n file ===\n"));
int fdb;
fdb = open("txt_files/t_n.txt", O_RDONLY);
test(fdb);
printf(MAIN_1("=== Le Petit Prince ===\n"));
int fdc;
fdc = open("txt_files/t_ptiprinc.txt", O_RDONLY);
test(fdc);
printf(MAIN("=== • Program ended • ===\n\n"));
}
|
C
|
/*
shuf implementation
Copyright (c) 2014 Anthony DeDominic
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
// apparently getting the size of a pipe is stilly since it's like a queue
// once data is read, it gets destroyed meaning finding its size is pointless.
void readStdin(char **read_buffer)
{
int file_size = 1;
if (stdin == NULL)
{
printf("unknown failure\n");
exit(EXIT_FAILURE);
}
*read_buffer = (char*) malloc(file_size);
if (read_buffer == NULL)
{
printf("allocation fail\n");
exit(EXIT_FAILURE);
}
// reads from stdin till nothing left to read, (fread will return non 1)
int itr = 0;
while (fread(*read_buffer+itr, 1, 1, stdin) == 1)
{
// dynamically resizes memory geometrically to handle any size pipe
if (file_size == itr+1)
{
file_size *= 2; // geometric progression...
*read_buffer = (char*) realloc(*read_buffer, file_size);
if (*read_buffer == NULL)
{
printf("memory failure\n");
}
}
itr++; // next address box in read buffer
}
fclose(stdin);
}
// takes input and splits it by delimiters
int splitInput(char **buffer, char ***split_array, char delim[])
{
unsigned int number_of_strings = 0;
char *temp;
// gets number of strings that get delimited
temp = strpbrk(*buffer, delim);
while (temp != NULL)
{
number_of_strings++;
temp = strpbrk(temp+1, delim);
}
// allocates array of pointers
*split_array = (char**) malloc(number_of_strings*sizeof(char*));
if (*split_array == NULL)
{
printf("memory failure");
exit(EXIT_FAILURE);
}
// pointers are made from read buffer using strtok
// pointers are added to array of pointers
temp = strtok(*buffer, delim);
int itr;
for (itr=0; temp != NULL; itr++)
{
(*split_array)[itr] = temp;
temp = strtok(NULL, delim);
}
return number_of_strings;
}
// returns int [min, max)
int uniform(int min, int max)
{
int range = max - min;
return min + rand() % range;
}
void shuffle(char ***array, int size)
{
for (int itr = 0; itr < size; itr++)
{
int pos = uniform(itr, size);
char *temp = (*array)[itr];
(*array)[itr] = (*array)[pos];
(*array)[pos] = temp;
}
}
// testing shuffling
// should be 50, 50 chance of first position being a 1 or 2
void unit_test()
{
int ones = 0;
int twos = 0;
for (int x=0; x < 1000; x++)
{
char *test[] = {"1","2"};
char **ptrtest = test;
shuffle(&ptrtest, 2);
if (!strcmp(test[0], "1"))
{
ones++;
}
else
{
twos++;
}
}
printf("ones: %d, twos: %d", ones, twos);
}
// flags not implemented
int main(int argc, char *argv[])
{
srand(time(NULL));
//gets input from list of args
if (argc > 1)
{
if (!strcmp(argv[1], "--test"))
{
unit_test();
return 0;
}
argv++; // skips past program's name which is argv[0]
argc--; // reflects ignorance of program name
shuffle(&argv, argc);
for (int itr=0; itr < argc; itr++)
{
printf("%s\n", argv[itr]);
}
}
// reads from stdin (pipe, file)
else
{
char *buffer = NULL; //read buffer
readStdin(&buffer);
char **split_buffer = NULL; // splits read buffer by delimiters
int string_count = splitInput(&buffer, &split_buffer, "\n ");
shuffle(&split_buffer, string_count);
for (int itr = 0; itr < string_count; itr++)
{
printf("%s\n", split_buffer[itr]);
}
free(buffer);
free(split_buffer);
}
return 0;
}
|
C
|
/* Алгоритм работы программы:
*
* 1. Явная привязка всех процессов программы к строго определенному процессору системы с помощью функции sched_setaffinity() -
* необходимо для многопроцессорных и многоядерных систем для предотвращения распределения создаваемой процессами программы нагрузки
* 2. Запуск UL_NUM бесполезных процессов, создающих нагрузку на процессор
* 3. Изменение любезности главного процесса программы на произвольное целое
* 4. Создание начальной временной отметки
* 5. Выполнение главным процессом полезных действий - вычисление CRC-32 для произвольного текста
* 6. Создание конечной временной отметки
* 7. Подсчет времени, затраченного главным процессом на выполнение полезных действий
*
* Пункты 3 - 7 повторяются для различных значений любезности главного процесса
*
* Процессами программы используется политика планирования SCHED_OTHER (политика планирования по умолчанию),
* подразумевающая распределение процессорного времени с помощью значений любезности
*
* Теоретические результаты:
*
* Должна быть отслежена следующая зависимость: с увеличением любезности главного процесса увеличивается время выполнения им полезных действий
*
* Компиляция:
*
* gcc -lrt -lm main.c -o program.out
*
* Ключ -l связывает с программой часть библиотеки glibc (rt), реализующую функцию clock_gettime(),
* используемую главным процессом программы для создания временных отметок
*
* Запуск:
*
* su -c './program.out'
*
* (запускать программу необходимо от имени суперпользователя, так как процессы, имеющие действительным владельцем суперпользователя, имеют характеристику
* CAP_SYS_NICE, необходимую для использования отрицательных значений любезности)
*/
#define _GNU_SOURCE /* Для sched_setaffinity() */
#include <stdio.h>
#include <stdint.h>
#include <sys/mman.h> /* Для mmap() и munmap() */
#include <sched.h> /* Для sched_setaffinity() */
#include <time.h> /* Для clock_gettime() */
#include <signal.h> /* Для kill() */
#include <sys/wait.h> /* Для waitpid(), WIFEXITED и WIFSIGNALED */
#include <sys/types.h> /* Для fork() */
#include <errno.h> /* Для errno */
#include <unistd.h> /* Для nice() */
/* Функция set_cpu() содержит в себе программный код, устанавливающий в качестве процессора, на котором исполняются все процессы программы,
* первый процессор системы */
int set_cpu();
/* Функция good() содержит полезную нагрузку главного процесса - вычисление CRC-32 для произвольного текста */
void good();
/* UL_NUM - количество побочный процессов, создающих бесполезную нагрузку на процессор */
#define UL_NUM 15
/* Функция ul() содержит бесполезную нагрузку бесполезных процессов */
void ul();
int main()
{
printf("\n");
/* С помощью функции set_cpu() устанавливаем первый процессор системы как единственный,
* на котором должны выполнятся главный процесс программы и все его дочерние процессы */
if(set_cpu() == -1)
{
perror("Ошибка при установке первого процессора системы единственным, на котором должны выполняться данный процесс и все его дочерние процессы");
return -1;
}
int x, status, ul_pid[UL_NUM];
/* Для каждого бесполезного дочернего процесса повторять... */
for(x = 0; x < UL_NUM; x++)
if(
/* Запустить бесполезный дочерний процесс */
(ul_pid[x] = fork()) == -1
)
perror("Ошибка при запуске бесполезного дочернего процесса");
else if(! ul_pid[x])
{
/* Мы в очередном бесполезном дочернем процессе */
/* Запускаем бесполезную нагрузку */
ul();
/* Завершаем бесполезный дочерний процесс с кодом возврата 0
*
* (так как бесполезная нагрузка организована с помощью бесконечного цикла,
* данная строка никогда не будет достигнута) */
exit(0);
}
/* Мы в родительском (главном) процессе */
printf("Главный процесс:\n\n");
int nice_value;
struct timespec begin, end;
for(x = 0; x < 7; x++)
{
/* Обнуляем переменную errno
*
* Если значение errno не изменится после вызова функции nice(), то это будет означать,
* что данная функция завершилась успешно - надеяться на возврат nice() -1 только в случае ошибки некорректно,
* так как данная функция может вернуть -1 и в случае успеха - в том случае, если значение любезности процесса равно -1 */
errno = 0;
/* Отмечаем начальную временную точку и сохраняем информацию о ней в переменной begin
*
* (CLOCK_MONOTONIC - монотонные общесистемные часы, отсчитывающие время не известно от какого момента времени в прошлом,
* но делающие это строго монотонно и гарантирующие, что будут также отсчитывать время и в будущем) */
if(
clock_gettime(CLOCK_MONOTONIC, & begin) == -1
)
perror("Ошибка при создании начальной временной отметки");
/* С помощью функции nice() случайным образом изменяем значение любезности вызвавшего nice() процесса
* (главного процесса программы) на значение, переданное nice() в качестве параметра.
* Функция nice() возвращает значение любезности процесса */
else if(
(nice_value = nice((rand() % 2 ? -1 : 1) * x + rand() % 7 - 5)) == -1
&&
errno
)
perror("Ошибка при изменении значения любезности главного процесса");
else
{
/* Выводим в стандартный поток вывода текущее значение любезности главного процесса */
printf("\tЛюбезность: %d\n", nice_value);
/* Запускаем на выполнение полезную нагрузку главного процесса */
good();
/* Отмечаем конечную временную точку и сохраняем информацию о ней в переменной end */
if(
clock_gettime(CLOCK_MONOTONIC, & end) == -1
)
perror("Ошибка при создании конечной временной отметки");
else
/* Выводим в стандартный поток вывода время в секундах, затраченное главным процессом на выполнение полезных действий
*
* Поля структуры данных timespec:
*
* tv_sec - секунды
* tv_nsec - наносекунды */
printf("\tВремя выполнения: %.3f секунд\n\n", (end.tv_sec - begin.tv_sec) + (end.tv_nsec - begin.tv_nsec) / 1000000000.0);
}
}
/* Отправляем бесполезным дочерним процессам сигнал SIGKILL, предписывая, таким образом, ОС завершить все побочные дочерние процессы */
for(x = 0; x < UL_NUM; x++)
if(ul_pid[x] != -1)
kill(ul_pid[x], SIGKILL);
/* С помощью функции waitpid() последовательно дождемся завершения каждого из побочных дочерних процессов,
* проверяя при этом причину завершения - скорее всего, все побочные дочерние процессы будут завершены по сигналу
* SIGKILL - поэтому именно макрос WIFSIGNALED() первым вернет ненулевое значение */
for(x = 0; x < UL_NUM; x++)
if(ul_pid[x] != -1)
do
waitpid(ul_pid[x], & status, 0);
while (! WIFEXITED(status) && ! WIFSIGNALED(status));
return 0;
}
/* Функция set_cpu() содержит в себе программный код, устанавливающий в качестве процессора, на котором исполняются все процессы программы,
* первый процессор системы */
int set_cpu()
{
/* Переменная cpu_mask описывает маску процессоров, используемых процессами программы */
cpu_set_t cpu_mask;
/* Обнуляем маску */
CPU_ZERO(& cpu_mask);
/* Бит, отвечающий за первый процессор системы, устанавливаем в единицу */
CPU_SET(0, & cpu_mask);
/* Для данного процесса (первый параметр - 0) устанавливаем маску cpu_mask (третий параметр) размером в sizeof(cpu_mask) байт как
* маску используемых процессом процессоров системы. Все дочерние процессы данного процесса унаследуют данную маску */
return sched_setaffinity(0, sizeof(cpu_mask), & cpu_mask);
}
/* Функция good() содержит полезную нагрузку главного процесса - вычисление CRC-32 для произвольного текста */
void good()
{
/* Размер текста - 5 мегабайт */
#define BUF_LEN (1048576 * 5)
/* Выделение памяти для текстового буфера путем создания анонимного (MAP_ANONYMOUS) неразделяемого (MAP_PRIVATE) отображения */
unsigned char *real_buf = (unsigned char *) mmap(NULL, BUF_LEN, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if(real_buf != MAP_FAILED)
{
unsigned char *buf = real_buf;
uint16_t x, y;
uint32_t crc, crc_table[256], buf_len = BUF_LEN;
/* Генерация произвольного текста */
while (buf_len--)
buf[buf_len] = rand() % 256;
/* Подсчет CRC-32 */
buf_len = BUF_LEN;
for(x = 0; x < 256; x++)
{
crc = x;
for(y = 0; y < 8; y++)
if(crc & 1)
crc = (crc >> 1) ^ 0xEDB88320UL;
else
crc >>= 1;
crc_table[x] = crc;
};
crc = 0xFFFFFFFFUL;
while (buf_len--)
crc = crc_table[(crc ^ *buf++) & 0xFF] ^ (crc >> 8);
crc ^= 0xFFFFFFFFUL;
/* Удаление анонимного отображения */
munmap(real_buf, BUF_LEN);
}
}
/* Функция ul() содержит бесполезную нагрузку бесполезных процессов */
void ul()
{
int x;
/* В качестве бесполезной нагрузки - бесконечный цикл */
while(1)
x++;
}
|
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 */
typedef int u_int ;
struct iicrb_pin_access {int /*<<< orphan*/ ctx; int /*<<< orphan*/ (* setsda ) (int /*<<< orphan*/ ,int) ;int /*<<< orphan*/ (* setscl ) (int /*<<< orphan*/ ,int) ;scalar_t__ (* getsda ) (int /*<<< orphan*/ ) ;scalar_t__ (* getscl ) (int /*<<< orphan*/ ) ;} ;
/* Variables and functions */
int /*<<< orphan*/ DELAY (int const) ;
int IIC_EBUSERR ;
int /*<<< orphan*/ stub1 (int /*<<< orphan*/ ,int) ;
int /*<<< orphan*/ stub2 (int /*<<< orphan*/ ,int) ;
scalar_t__ stub3 (int /*<<< orphan*/ ) ;
scalar_t__ stub4 (int /*<<< orphan*/ ) ;
int /*<<< orphan*/ stub5 (int /*<<< orphan*/ ,int) ;
int /*<<< orphan*/ stub6 (int /*<<< orphan*/ ,int) ;
int /*<<< orphan*/ stub7 (int /*<<< orphan*/ ,int) ;
int /*<<< orphan*/ stub8 (int /*<<< orphan*/ ,int) ;
int
iic_recover_bus(struct iicrb_pin_access *pins)
{
const u_int timeout_us = 40000;
const u_int delay_us = 500;
int i;
/*
* Start with clock and data high.
*/
pins->setsda(pins->ctx, 1);
pins->setscl(pins->ctx, 1);
/*
* At this point, SCL should be high. If it's not, some slave on the
* bus is doing clock-stretching and we should wait a while. If that
* slave is completely locked up there may be no way to recover at all.
* We wait up to 40 milliseconds, a seriously pessimistic time (even a
* cheap eeprom has a max post-write delay of only 10ms), and also long
* enough to allow SMB slaves to timeout normally after 35ms.
*/
for (i = 0; i < timeout_us; i += delay_us) {
if (pins->getscl(pins->ctx))
break;
DELAY(delay_us);
}
if (i >= timeout_us)
return (IIC_EBUSERR);
/*
* At this point we should be able to control the clock line. Some
* slave may be part way through a byte transfer, and could be holding
* the data line low waiting for more clock pulses to finish the byte.
* Cycle the clock until we see the data line go high, but only up to 9
* times because if it's not free after 9 clocks we're never going to
* win this battle. We do 9 max because that's a byte plus an ack/nack
* bit, after which the slave must not be driving the data line anymore.
*/
for (i = 0; ; ++i) {
if (pins->getsda(pins->ctx))
break;
if (i == 9)
return (IIC_EBUSERR);
pins->setscl(pins->ctx, 0);
DELAY(5);
pins->setscl(pins->ctx, 1);
DELAY(5);
}
/*
* At this point we should be in control of both the clock and data
* lines, and both lines should be high. To complete the reset of a
* slave that was part way through a transaction, we need to do a
* START/STOP sequence, which leaves both lines high at the end.
* - START: SDA transitions high->low while SCL remains high.
* - STOP: SDA transitions low->high while SCL remains high.
* Note that even though the clock line remains high, we transition the
* data line no faster than it would change state with a 100khz clock.
*/
pins->setsda(pins->ctx, 0);
DELAY(5);
pins->setsda(pins->ctx, 1);
DELAY(5);
return (0);
}
|
C
|
/*******************************************************************************
* File name: output.c
*
* Description:
* This file contains the function(s) that will help write the new packed
* binary. The new file will be named woody and have the same access rights
* as the original ELF.
*
* Public function(s):
* -
*
* Notes:
* ...
*
* Author: Ludovic Montagnier (lmontagn)
*******************************************************************************/
#include "woody.h"
/* See file header for details. */
void write_new_file(char *packed_bin, t_fdet fdet)
{
int fd;
fd = open("woody", O_WRONLY|O_CREAT, fdet.bin_mode);
write(fd, packed_bin, fdet.bin_size);
close(fd);
}
|
C
|
/* 2mm.c: this file is part of PolyBench/C */
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
/* Include polybench common header. */
#include "polybench.h"
/* Include benchmark-specific header. */
#include "gemm.h"
/* Array initialization. */
static
void init_array(int ni, int nj, int nk, int nl,
DATA_TYPE *alpha,
DATA_TYPE *beta,
DATA_TYPE POLYBENCH_2D(A,NI,NK,ni,nk),
DATA_TYPE POLYBENCH_2D(B,NK,NJ,nk,nj),
DATA_TYPE POLYBENCH_2D(C,NJ,NL,nj,nl),
DATA_TYPE POLYBENCH_2D(D,NI,NL,ni,nl))
{
int i, j;
*alpha = 1.5;
*beta = 1.2;
for (i = 0; i < ni; i++)
for (j = 0; j < nk; j++)
A[i][j] = (DATA_TYPE) (i*j % ni) / ni;
for (i = 0; i < nk; i++)
for (j = 0; j < nj; j++)
B[i][j] = (DATA_TYPE) (i*(j+1) % nj) / nj;
for (i = 0; i < nj; i++)
for (j = 0; j < nl; j++)
C[i][j] = (DATA_TYPE) (i*(j+3) % nl) / nl;
for (i = 0; i < ni; i++)
for (j = 0; j < nl; j++)
D[i][j] = (DATA_TYPE) (i*(j+2) % nk) / nk;
}
/* DCE code. Must scan the entire live-out data.
Can be used also to check the correctness of the output. */
static
void print_array(int ni, int nl,
DATA_TYPE POLYBENCH_2D(D,NI,NL,ni,nl))
{
int i, j;
POLYBENCH_DUMP_START;
POLYBENCH_DUMP_BEGIN("D");
for (i = 0; i < ni; i++)
for (j = 0; j < nl; j++) {
if ((i * ni + j) % 20 == 0) fprintf (POLYBENCH_DUMP_TARGET, "\n");
fprintf (POLYBENCH_DUMP_TARGET, DATA_PRINTF_MODIFIER, D[i][j]);
}
POLYBENCH_DUMP_END("D");
POLYBENCH_DUMP_FINISH;
}
/* Main computational kernel. The whole function will be timed,
including the call and return. */
static
void kernel_2mm(int ni, int nj, int nk, int nl,
DATA_TYPE alpha,
DATA_TYPE beta,
DATA_TYPE POLYBENCH_2D(tmp,NI,NJ,ni,nj),
DATA_TYPE POLYBENCH_2D(A,NI,NK,ni,nk),
DATA_TYPE POLYBENCH_2D(B,NK,NJ,nk,nj),
DATA_TYPE POLYBENCH_2D(C,NJ,NL,nj,nl),
DATA_TYPE POLYBENCH_2D(D,NI,NL,ni,nl))
{
int i, j, k;
#pragma scop
/* D := alpha*A*B*C + beta*D */
for (i = 0; i < _PB_NI; i++)
for (j = 0; j < _PB_NJ; j++)
{
tmp[i][j] = SCALAR_VAL(0.0);
for (k = 0; k < _PB_NK; ++k)
tmp[i][j] += alpha * A[i][k] * B[k][j];
tmp[i][j] += beta * C[i][j];
}
#pragma endscop
}
int main(int argc, char** argv)
{
/* Retrieve problem size. */
int ni = NI;
int nj = NJ;
int nk = NK;
int nl = NL;
/* Variable declaration/allocation. */
DATA_TYPE alpha;
DATA_TYPE beta;
POLYBENCH_2D_ARRAY_DECL(tmp,DATA_TYPE,NI,NJ,ni,nj);
POLYBENCH_2D_ARRAY_DECL(A,DATA_TYPE,NI,NK,ni,nk);
POLYBENCH_2D_ARRAY_DECL(B,DATA_TYPE,NK,NJ,nk,nj);
POLYBENCH_2D_ARRAY_DECL(C,DATA_TYPE,NJ,NL,nj,nl);
POLYBENCH_2D_ARRAY_DECL(D,DATA_TYPE,NI,NL,ni,nl);
/* Initialize array(s). */
init_array (ni, nj, nk, nl, &alpha, &beta,
POLYBENCH_ARRAY(A),
POLYBENCH_ARRAY(B),
POLYBENCH_ARRAY(C),
POLYBENCH_ARRAY(D));
/* Start timer. */
polybench_start_instruments;
/* Run kernel. */
kernel_2mm (ni, nj, nk, nl,
alpha, beta,
POLYBENCH_ARRAY(tmp),
POLYBENCH_ARRAY(A),
POLYBENCH_ARRAY(B),
POLYBENCH_ARRAY(C),
POLYBENCH_ARRAY(D));
/* Stop and print timer. */
polybench_stop_instruments;
polybench_print_instruments;
/* Prevent dead-code elimination. All live-out data must be printed
by the function call in argument. */
polybench_prevent_dce(print_array(ni, nl, POLYBENCH_ARRAY(D)));
/* Be clean. */
POLYBENCH_FREE_ARRAY(tmp);
POLYBENCH_FREE_ARRAY(A);
POLYBENCH_FREE_ARRAY(B);
POLYBENCH_FREE_ARRAY(C);
POLYBENCH_FREE_ARRAY(D);
return 0;
}
|
C
|
#include<stdio.h>
#include<pthread.h>
int global[2];
void *sum_thread(void *arg)
{
int *args_array;
args_array = arg;
int n1,n2,sum;
n1=args_array[0];
n2=args_array[1];
sum = n1+n2;
printf("Hello!!! Welcome to LPU\n");
printf("Sum = %d\n",sum);
return NULL;
}
int main()
{
printf("First number: ");
scanf("%d",&global[0]);
printf("Second number: ");
scanf("%d",&global[1]);
pthread_t tid_sum, tid1;
pthread_create(&tid_sum,NULL,sum_thread,global);
pthread_join(tid_sum,NULL);
pthread_create(&tid1, NULL, sum_thread,NULL);
return 0;
}
|
C
|
/*
* Fairchild FAN5702 LED driver
*
* Authors: Antti Partanen <[email protected]>
*/
#ifdef USE_I2C
#include "fan5702.h"
int fan5702_open(struct i2c_device *dev, struct i2c_master *master)
{
/* try to detect fan5702 */
return i2c_open(dev, master, FAN5702_ADDR);
}
int fan5702_cfg(struct i2c_device *dev)
{
/* drive current to 20 mA and EN pin as enable */
IF_R(i2c_write_reg_byte(dev, 0x10, 0x18), -1);
IF_R(i2c_write_reg_byte(dev, 0x20, 0x00), -1);
return 0;
}
int fan5702_set(struct i2c_device *dev, uint8_t channel, uint8_t brightness)
{
switch (channel) {
case 3:
case 4:
case 5:
case 6:
channel = channel << 4;
break;
default:
error_set_last("invalid channel");
return -1;
}
return i2c_write_reg_byte(dev, channel, brightness);
}
/* tool related functions */
#ifdef COMPILE_TOOL_I2C
void tool_i2c_fan5702_help(void)
{
printf(
"Commands:\n"
" <CHANNEL>=<BRIGHTNESS> [...] Set given channels to given brightess each\n"
"Multiple channels can be defined.\n"
"\n"
"Accepted values:\n"
" CHANNEL 1-6\n"
" BRIGHTNESS 0-63\n"
);
}
int tool_i2c_fan5702_exec(struct i2c_master *master, uint8_t address, char *command, int argc, char *argv[])
{
int err = -1;
struct i2c_device dev;
/* check commands */
for (int i = 0; i < argc; i++) {
if (strlen(argv[i]) < 3) {
fprintf(stderr, "Invalid command: %s\n", argv[i]);
return -1;
} else if (argv[i][1] != '=') {
fprintf(stderr, "Invalid command: %s\n", argv[i]);
return -1;
} else if (argv[i][0] < '1' || argv[i][0] > '6') {
fprintf(stderr, "Invalid channel: %s\n", argv[i]);
return -1;
} else if (atoi(argv[i] + 2) < 0 || atoi(argv[i] + 2) > 63) {
fprintf(stderr, "Invalid value: %s\n", argv[i]);
return -1;
}
}
/* open chip */
if (fan5702_open(&dev, master)) {
fprintf(stderr, "Chip not found, reason: %s\n", error_last);
return -1;
} else if (fan5702_cfg(&dev)) {
fprintf(stderr, "Chip configuration failed, reason: %s\n", error_last);
return -1;
}
/* apply commands */
for (int i = 0; i < argc; i++) {
if (fan5702_set(&dev, argv[i][0] - '0', atoi(argv[i] + 2))) {
fprintf(stderr, "Failed to set channel, reason: %s\n", error_last);
break;
} else {
printf("Set channel %c brightness to %d%% (%d)\n", argv[i][0], 100 * atoi(argv[i] + 2) / 63, atoi(argv[i] + 2));
}
}
fan5702_close(&dev);
return err;
}
#endif
#endif
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ppm.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: qdurot <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/12/10 04:35:00 by qdurot #+# #+# */
/* Updated: 2017/12/10 04:35:00 by qdurot ### ########.fr */
/* */
/* ************************************************************************** */
#include "wolf.h"
int ppm_to_array3(char *path, t_env *e)
{
int i;
int fd;
char *line;
if (!(fd = open(path, O_RDONLY)))
error(e, OPEN_ERR);
if (get_next_line(fd, &line) < 1)
error(e, TEXTURE_ERR);
free(line);
get_next_line(fd, &line);
while (line[0] == '#')
{
free(line);
get_next_line(fd, &line);
}
i = 0;
e->file.width = ft_atoi(&line[i]);
while (ft_isdigit(line[i]))
i++;
e->file.height = ft_atoi(&line[i]);
free(line);
get_next_line(fd, &line);
free(line);
return (fd);
}
t_rgb *ppm_to_array2(char *path, t_env *e)
{
int fd;
char *line;
fd = ppm_to_array3(path, e);
if (!(line = malloc(e->file.width * e->file.height * 3)))
error(e, PPM_ERR);
read(fd, line, e->file.width * e->file.height * 3);
close(fd);
return ((t_rgb*)line);
}
int *ppm_to_array(char *path, t_env *e)
{
t_rgb *buf;
t_rgba *ret;
int i;
buf = ppm_to_array2(path, e);
i = -1;
if (!(ret = malloc(sizeof(t_rgba) * (e->file.width * e->file.height))))
return (NULL);
while (++i < (e->file.width * e->file.height))
{
ret[i].r = buf[i].b;
ret[i].g = buf[i].g;
ret[i].b = buf[i].r;
ret[i].a = 0;
}
free(buf);
return ((int*)ret);
}
|
C
|
/*
* stub driver for functions convert between int, quaternary, and
* vigesimal number
*
* project: hw3
* name: Nick Boyadjian
* date: 17/6/19
* file: itoxDriver.c
* notes:
*/
#include <stdio.h>
#include <string.h>
#include "itox.h"
#define LINE_LENGTH 1024 // Length of each input line
#define QUATERNARY (sizeof(int) * 4 + 1) // Length of quaternary string
#define VIGESIMAL (sizeof(int) * 2 + 1) // Length of vigesimal string
int main(void)
{
char quaternaryStr[QUATERNARY];
char vigesimalStr[VIGESIMAL];
char line[LINE_LENGTH];
int m, n;
/*write a loop here
* use fgets(line, LINELEN, stdin) to read from keyboard
* stop the loop if EOF
* use sscanf(line, "%d", &n) to convert input to int n
*/
while(fgets(line, LINE_LENGTH, stdin))
{
sscanf(line, "%d", &n);
printf("n = %d\n", n);
itoq(quaternaryStr, n);
m = qtoi(quaternaryStr);
printf("input decimal int: %d\n", n);
printf("quaternary representation: %s\n", quaternaryStr);
printf("reconverted decimal : %d\n", m);
itov(vigesimalStr, n);
m = vtoi(vigesimalStr);
printf("vigesimal representation: %s\n", vigesimalStr);
printf("reconverted decimal : %d\n\n", m);
}
return 0;
}
|
C
|
#include "frog_river_one.h"
#include <vector>
#include "gtest/gtest.h"
struct param_entry_t {
param_entry_t(int X, std::vector<int> &A, int result):
_X(X),
_A(A),
_result(result){
};
int _X;
std::vector<int> _A;
int _result;
};
class countAbsDifferenceParameters : public ::testing::TestWithParam<param_entry_t>{
};
TEST_P( countAbsDifferenceParameters, multipleNegativeValues){
// Test params
std::vector<int> A = GetParam()._A;
int X = GetParam()._X;
long int jump_amount = solution(X, A);
EXPECT_EQ(GetParam()._result, jump_amount);
}
std::vector<int> v1 = {1};
std::vector<int> v2 = {1, 2, 3, 4, 5};
std::vector<int> v3 = {1, 2, 4, 5};
std::vector<int> v5 = {4, 1, 3, 2};
std::vector<int> v6 = {4, 1, 3};
std::vector<int> v7 = {1, 2, 2, 5, 5};
std::vector<int> v8 = {1, 3, 1, 4, 2, 3, 5, 4};
param_entry_t p1(1, v1, 0);
param_entry_t p2(5, v2, 4);
param_entry_t p3(4, v3, -1);
param_entry_t p5(4, v5, 3);
param_entry_t p6(3, v6, -1);
param_entry_t p7(5, v7, -1);
param_entry_t p8(5, v8, 6);
INSTANTIATE_TEST_CASE_P( InstantionName,
countAbsDifferenceParameters,
::testing::Values(p1, p2, p3, p5, p6, p7, p8));
/* Tests factorial of negative numbers. */
/*
* TEST(checkForPermutation, largePermutation) {
* std::vector<int> v (100000, 1);
* unsigned long sum = 0;
* for (int i = 0; i < 100000; i++) {
* v[i] = i + 1;
* sum += i + 1;
* }
*
*
* long int is_permutation = solution(v);
*
* EXPECT_EQ(5000050000, sum);
* EXPECT_EQ(1, is_permutation );
* }
*/
//
////// Tests factorial of 0.
////TEST(FactorialTest, Zero) {
//// EXPECT_EQ(1, Factorial(0));
////}
////
//// Tests factorial of positive numbers.
//TEST(countAbsDifference, allValuesPositive) {
// // Numbers to be tested. /* ToDo: need to change this to test case (skramer, Fri 07 Mar 2014 09:05:32 PM CET) */
// int A[] = {1, 2, 3, 4};
//
// // Number of values to be tested
// int N = 4;
//
// // Splitting pointer
// int division_ptr = 0;
//
// long int min_diff = count_abs_difference(A, N, division_ptr);
//
// EXPECT_EQ(2, min_diff);
// EXPECT_EQ(2, division_ptr);
//}
//
//
//// Tests IsPrime()
//
//// Tests negative input.
//TEST(IsPrimeTest, Negative) {
// // This test belongs to the IsPrimeTest test case.
//
// EXPECT_FALSE(IsPrime(-1));
// EXPECT_FALSE(IsPrime(-2));
// EXPECT_FALSE(IsPrime(INT_MIN));
//}
//
//// Tests some trivial cases.
//TEST(IsPrimeTest, Trivial) {
// EXPECT_FALSE(IsPrime(0));
// EXPECT_FALSE(IsPrime(1));
// EXPECT_TRUE(IsPrime(2));
// EXPECT_TRUE(IsPrime(3));
//}
//
//// Tests positive input.
//TEST(IsPrimeTest, Positive) {
// EXPECT_FALSE(IsPrime(4));
// EXPECT_TRUE(IsPrime(5));
// EXPECT_FALSE(IsPrime(6));
// EXPECT_TRUE(IsPrime(23));
//}
//
//// Step 3. Call RUN_ALL_TESTS() in main().
////
//// We do this by linking in src/gtest_main.cc file, which consists of
//// a main() function which calls RUN_ALL_TESTS() for us.
////
//// This runs all the tests you've defined, prints the result, and
//// returns 0 if successful, or 1 otherwise.
////
//// Did you notice that we didn't register the tests? The
//// RUN_ALL_TESTS() macro magically knows about all the tests we
//// defined. Isn't this convenient?
|
C
|
#include<stdio.h>///incomplete version remoal form sorted will be easier.
int main(){
int a[512], n, l, i = 0, j, k;
while(scanf("%d", &n) != EOF){
a[i++] = n;
}
for(j = 1; j < i; j++){
l = j;
while(l != 0){
if(a[j] == a[l-1]){
for( k = j; k < i; k++){
a[k] = a[k+1];
i--;
}
j--;
}
l--;
}
}
for( k = 0; k < i; k++)
printf("%d ", a[k]);
return 0;
}
|
C
|
#include <stdio.h>
struct person{
int num;
char name[40];
char addr[40];
char hobby[40];
char favor[40];
};
int main(void) {
struct person per;
FILE *fp;
int i;
fp=fopen("my.bin","wb+");
while (1) {
printf("학번, 이름, 주소, 취미, 음식 : ");
i=scanf("%d", &per.num);
if(i==EOF)
break;
getchar();
scanf("%s%s%s%s",per.name,per.addr,per.hobby,per.favor);
fwrite(&per,sizeof(struct person),1,fp);
fflush(fp);
}
fclose(fp);
return 0;
}
|
C
|
#include <craftcore.h>
void cc_entity_refresh_matrix(cc_entity_t *ent)
{
cc_identity_matrix(ent->matrix);
cc_matrix_translate(ent->matrix, ent->px, ent->py, ent->pz);
cc_matrix_rotate(ent->matrix, ent->ry, ent->rx, ent->rz);
cc_matrix_scale(ent->matrix, ent->sx, ent->sy, ent->sz);
}
void cc_entity_init(cc_entity_t *ent)
{
memset(ent, 0, sizeof(cc_entity_t));
ent->sx = ent->sy = ent->sz = 1.0f;
cc_entity_refresh_matrix(ent);
}
void cc_entity_move(cc_entity_t *ent, float x, float y, float z)
{
float matrix[16];
cc_identity_matrix(matrix);
cc_matrix_rotate(matrix, ent->ry, ent->rx, ent->rz);
cc_matrix_translate(matrix, x, y, z);
cc_matrix_xyz(matrix, &x, &y, &z);
ent->px += x;
ent->py += y;
ent->pz += z;
cc_entity_refresh_matrix(ent);
}
void cc_entity_set_position(cc_entity_t *ent, float x, float y, float z)
{
ent->px = x;
ent->py = y;
ent->pz = z;
cc_entity_refresh_matrix(ent);
}
void cc_entity_get_rotation(cc_entity_t *ent, float *pitch, float *yaw, float *roll)
{
*pitch = ent->rx;
*yaw = ent->ry;
*roll = ent->rz;
}
void cc_entity_set_rotation(cc_entity_t *ent, float pitch, float yaw, float roll)
{
ent->rx = pitch;
ent->ry = yaw;
ent->rz = roll;
cc_entity_refresh_matrix(ent);
}
void cc_entity_turn(cc_entity_t *ent, float pitch, float yaw, float roll)
{
ent->rx += pitch;
ent->ry += yaw;
ent->rz += roll;
cc_entity_refresh_matrix(ent);
}
|
C
|
#include <stdio.h>
#include <math.h>
typedef long int INT64;
/*
* This is used evaulate the coefficient of (x, y) of
* gcd(a, b) = a * x + b * y;
*/
INT64 x_coeff, y_coeff;
INT64 eval_coeff(INT64 a, INT64 b)
{
INT64 d, temp, gcd;
if (b == 0) {
x_coeff = 1;
y_coeff = 0;
//printf("1. x = %ld, y = %ld\n", x_coeff, y_coeff);/* DEBUG PRINT */
return a;
} else {
gcd = eval_coeff(b, a % b);
temp = y_coeff;
y_coeff = (x_coeff - (floor((double)a / (double)b) * y_coeff));
x_coeff = temp;
//printf("2. x = %ld, y = %ld\n", x_coeff, y_coeff);/* DEBUG PRINT */
return gcd;
}
}
int main(int argc, char *argv[])
{
INT64 gcd;
INT64 a, b;
printf("Input a: \n");
scanf("%ld", &a);
printf("Input b: \n");
scanf("%ld", &b);
gcd = eval_coeff(a, b);
printf("GCD: %ld, X-coeff: %ld, Y-coeff: %ld\n", gcd, x_coeff, y_coeff);
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#define N 128
int main(int argc, const char *argv[])
{
char buf[N] = {};
int flags;
//使用fcntl函数实现非阻塞I/O
//对位或者寄存器的操作,一般使用读、改、写三步
//第一步:读取文件描述符状态标志位
if((flags = fcntl(0, F_GETFL)) < 0)
{
perror("fail to fcntl");
exit(1);
}
//第二步:修改文件状态标识位
flags = flags | O_NONBLOCK;
//flags |= O_NONBLOCK; //000004000
//第三步:将新的文件状态标志位写回去
if(fcntl(0, F_SETFL, flags) < 0)
{
perror("fail to fcntl");
exit(1);
}
while(1)
{
fgets(buf, N, stdin);
sleep(1);
printf("****************\n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void main()
{
int *numero = (int *)malloc(sizeof(int));
// aloque o espaço de um 'int', faça o casting para um valor int e guarde dentro de um ponteiro '*numero';
*numero = 1000;
printf("\nvalor do conteúdo do ponteiro: %d\n", *numero);
printf("Endereço que está sendo apontado: %p\n", numero);
printf("Endereço do próprio ponteiro: %p\n", &numero);
free(numero); //Avisa ao S.O. que este endereço está livre para a reciclagem;
}
|
C
|
/**
* @file led.h
* @author Francois Berder
* @date 2017
* @copyright 3-clause BSD
*/
#ifndef H_CORE_LED
#define H_CORE_LED
#include <stdint.h>
/** Index of LED's */
enum LED_INDEX {
LED_0 = 0x01,
LED_1 = 0x02,
ALL_LEDS = 0x03
};
/** Mode of LED's */
enum LED_MODE {
ON_OFF_MODE,
TIMER_MODE
};
/** Number of LEDS */
#define LED_CNT (2)
/**
* @brief Switch off all LEDs.
*
* @return 0 if successful, -1 otherwise
*/
int led_init(void);
/**
* @brief Switch on some LEDs.
*
* @param[in] mask
* @return 0 if successful, -1 otherwise
*/
int led_switch_on(uint8_t mask);
/**
* @brief Switch off some LEDs.
*
* @param[in] mask
* @return 0 if successful, -1 otherwise
*/
int led_switch_off(uint8_t mask);
/**
* @brief Switch on/off each LED depending on corresponding bit in @p led_value
*
* Each bit of the mask represents a LED. Only LED's whose corresponding bit in mask is set to 1
* will be switched on or off by this function depending on corresponding bit .
*
* For instance, to turn on LED_1 you have to set bit 1 of mask to 1 and bit 1 of value to 1. So,
* mask = LED_1 (= 0x02)
* value = 0x02
*
* @param[in] mask bit string to access LED'S
* @param[in] value bit string to set LED's value
* @return 0 if successful, -1 otherwise
*/
int led_set(uint8_t mask, uint8_t value);
/**
* @brief Configure all LEDS from mask in on/off mode.
*
* This function is only there for compatibility reasons with LetMeCreate, it does not
* do anything apart from returing 0.
*
* @param[in] mask bit string to access LED'S
* @return 0 if successful, -1 otherwise
*/
int led_configure_on_off_mode(uint8_t mask);
/**
* @brief Configure all LEDS from mask in timer mode. led_init must have been called before.
*
* This function is only there for compatibility reasons with LetMeCreate, it does not
* do anything apart from returing -1.
*
* @param[in] mask bit string to access LED'S
* @return 0 if successful, -1 otherwise
*/
int led_configure_timer_mode(uint8_t mask);
/**
* @brief Get the mode of a LED.
*
* Since LED's on clickers only support ON_OFF_MODE, this function always set
* led_mode to ON_OFF_MODE.
*
* @param[in] led_index
* @param[out] led_mode Current mode of the LED (see #LED_MODE)
* @return 0 if successful, -1 otherwise
*/
int led_get_mode(uint8_t led_index, uint8_t *led_mode);
/**
* @brief Configure delays for LEDS. LEDS must have been configured in timer mode before.
*
* This function is only there for compatibility reasons with LetMeCreate, it does not
* do anything apart from returing -1.
*
* @param[in] mask bit string to access LED'S
* @param[in] delay_on Defines how long the LED will stay on (in milliseconds)
* @param[in] delay_off Defines how long the LED will stay on (in milliseconds)
* @return -1
*/
int led_set_delay(uint8_t mask, uint32_t delay_on, uint32_t delay_off);
/**
* @brief Switch off all LED's.
*
* @return 0 if successful, -1 otherwise
*/
int led_release(void);
#endif
|
C
|
#include <stdio.h>
#include <ncurses.h>
#include <menu.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h> //<- technically speaking ncurses isn't really threadsafe but it works haha... see: https://stackoverflow.com/questions/29910562/why-has-no-one-written-a-threadsafe-branch-of-the-ncurses-library
/*
Begin rulebending: #define ROOM window
I'm classing each window and/or view as a room... :)
Here's the list:
1) Main menu
2) Readme
3) gameWindow
4) statsWindow
5) Fight view
FWIW here are the usable items:
1) Swords, used in fights
2) Health, again, used in fights
3) Stars, gained in fights and allows the user to end the game
4) Hunger, decrements health if you're too hungry
TODO: check sword quantity at each fight stage
clean up settings parser code
clean up key input handling in fight mode (or room should i say...)
yield thread on getch error?
investigate shared memory options for inter-terminal comms
clean up thread joins...
damage from animals
*/
/*GLOBAL VARIABLES*/
char *inventoryItems[4] = {"Health", "Hunger", "Swords", "Stars"}; //<- lets stats keep track of different character traits
int inventoryValues[4] = {10, 0, 0, 0};
int recentInput;
char charUnderCursor;
int movements;
int difficulty = 140;
int seed = 1000;
/*pthread definitions - this simplifies the locks and unlocks, see above stackoverflow link*/
pthread_t statsThread;
pthread_t gameThread;
pthread_t checkThread;
pthread_mutex_t MUTEX;
#define LOCK pthread_mutex_lock(&MUTEX)
#define UNLOCK pthread_mutex_unlock(&MUTEX)
//simplify window creation process
WINDOW *create_newwin(int height, int width, int starty, int startx) {
WINDOW *local_win;
local_win = newwin(height, width, starty, startx);
box(local_win, 0, 0);
wrefresh(local_win);
return local_win;
}
void *check_win_death(void *result)
{
int returnVal;
int i = 1;
while (i == 1)
{
if (inventoryValues[0] < 1)
{
returnVal = 0; //<-death
i++;
}
else if (inventoryValues[3] > 4)
{
returnVal = 1; //<-win
i++;
}
//keep cpu time down
sleep(1);
}
//not a pretty way of killing the threads, ideally we would do it from within each thread...
pthread_cancel(statsThread);
pthread_cancel(gameThread);
//return integer to main thread: https://stackoverflow.com/questions/2251452/how-to-return-a-value-from-pthread-threads-in-c
if (returnVal != 0)
{
*((int *)result) = returnVal;
pthread_exit(result);
}
else
{
pthread_exit(0);
}
}
void start_game_window(WINDOW *gameWindow, int cursorX, int cursorY)
{
char map[LINES][COLS];
//generate world and print to game window
const char *charToAdd;
start_color();
//initialise colour settings for printing - assume the terminal has colour support... it probably does...
init_pair(2, COLOR_BLUE, COLOR_CYAN); //<- water
init_pair(3, COLOR_BLACK, COLOR_GREEN); //<- trees
init_pair(1, COLOR_YELLOW, COLOR_GREEN); //<- grass (green background and yellow characters)
init_pair(5, COLOR_GREEN, COLOR_GREEN);//<- enemies - invisible (unused), would be enabled in the actual game, but for ease of marking it's not used...
init_pair(4, COLOR_WHITE, COLOR_RED); //<- boxes
srand(seed);
for (int j = 1; j < COLS-1; j++)
{
for (int i = 1; i < (LINES*0.8)-1; i++)
{
int nextCharType = rand() % 1000;
if (nextCharType <= 86)
{
charToAdd = "T";
wattron(gameWindow, COLOR_PAIR(3)); //<- this has to be done inside the if statement as the charTypes have different colours
mvwprintw(gameWindow, i, j, charToAdd);
wattroff(gameWindow, COLOR_PAIR(3));
}
else if (nextCharType > 86 && nextCharType <= 120)
{
charToAdd = "W";
wattron(gameWindow, COLOR_PAIR(2));
mvwprintw(gameWindow, i, j, charToAdd);
wattroff(gameWindow, COLOR_PAIR(2));
}
else if (nextCharType > 120 && nextCharType <= 125)
{
charToAdd = "B";
wattron(gameWindow, COLOR_PAIR(4));
mvwprintw(gameWindow, i, j, charToAdd);
wattroff(gameWindow, COLOR_PAIR(4));
}
else if (nextCharType > 125 && nextCharType <= difficulty)
{
charToAdd = "X";//X marks the spot
wattron(gameWindow, COLOR_PAIR(3));//<-enemies underneath the user are should be invisible but it would be harder to test the functionality.
mvwprintw(gameWindow, i, j, charToAdd);
wattroff(gameWindow, COLOR_PAIR(3));
}
else
{
charToAdd = " ";
wattron(gameWindow, COLOR_PAIR(1));
mvwprintw(gameWindow, i, j, charToAdd);
wattroff(gameWindow, COLOR_PAIR(1));
}
}
}
//position cursor and refresh window
wmove(gameWindow, cursorY, cursorX);
wrefresh(gameWindow);
//start keyboard capture
nodelay(gameWindow, TRUE);
keypad(gameWindow, true);
}
int fight_handler(WINDOW *gameWindow, int animal)
{
int health = 10;
char inputOption;
switch (animal)
{
case 0:
wprintw(gameWindow, " ___ ___\n");
wprintw(gameWindow, " ( _< >_ )\n");
wprintw(gameWindow, " // \\\\\n");
wprintw(gameWindow, " \\\\___..___//\n");
wprintw(gameWindow, " `-( )-'\n");
wprintw(gameWindow, " _|__|_\n");
wprintw(gameWindow, " /_|__|_\\\n");
wprintw(gameWindow, " /_|__|_\\\n");
wprintw(gameWindow, " /_\\__/_\\\n");
wprintw(gameWindow, " \\ || / _\n");
wprintw(gameWindow, " || ( )\n");
wprintw(gameWindow, " \\\\___//\n");
wprintw(gameWindow, " `---'\n");
wprintw(gameWindow, "\n\nYou just stood on a scorpion! - You've lost 2 health points!\n");
wrefresh(gameWindow);
inventoryValues[0] -= 2;
sleep(1);
break;
case 1:
wprintw(gameWindow, " __ __\n");
wprintw(gameWindow, "/ \\.-***-./ \\\n");
wprintw(gameWindow, "\\ - - /\n");
wprintw(gameWindow, " | o o |\n");
wprintw(gameWindow, " \\ .-'''-. /\n");
wprintw(gameWindow, " '-\\__Y__/-'\n");
wprintw(gameWindow, " `---`\n");
wprintw(gameWindow, "\n\nYou're being mauled by a bear! - Fight it off!\n");
wrefresh(gameWindow);
mvwprintw(gameWindow, LINES*0.6, COLS*0.25, "What would you like to use?");
for (int i = 0; i < 3; i++)
{
mvwprintw(gameWindow, (LINES*0.6)-2, COLS*0.25, "Enemy health: %d", health);
mvwprintw(gameWindow, (LINES*0.6)+1, COLS*0.25, "F1) Sword: %d (Deals 6 damage)", inventoryValues[2]);
mvwprintw(gameWindow, (LINES*0.6)+2, COLS*0.25, "F2) Hands (+2 hunger) (Deals 3 damage)");
wrefresh(gameWindow);
int j = 0;
while(j == 0)
{
int input;
if((input = wgetch(gameWindow)) == ERR)
{
//just loop again and see if we get an input in the buffer
}
else
{
switch(input)
{
case KEY_F(1):
inputOption = 'a';
j++;
break;
case KEY_F(2):
inputOption = 'b';
j++;
break;
default:
break;
}
}
}
//legacy from when using wscanw
if (inputOption == 'a')
{
LOCK;
health -= 5;
inventoryValues[2] -= 1;
UNLOCK;
}
else if (inputOption == 'b')
{
LOCK;
health -= 2;
UNLOCK;
}
if(health < 1)
{
werase(gameWindow);
wrefresh(gameWindow);
mvwprintw(gameWindow, (LINES*0.4), COLS*0.4, "You won, gained 2 stars!");
wrefresh(gameWindow);
LOCK;
inventoryValues[3] += 2;
UNLOCK;
i=3;
}
sleep(1);
}
break;
case 2:
wprintw(gameWindow, " /\\ \\ / /\\\n");
wprintw(gameWindow, "//\\\\ .. //\\\\\n");
wprintw(gameWindow, "//\\(( ))/\\\\\n");
wprintw(gameWindow, "/ < `' > \\\n");
wprintw(gameWindow, "\n\nA spider is about to bite you - kill it!\n");
wrefresh(gameWindow);
mvwprintw(gameWindow, LINES*0.6, COLS*0.25, "What would you like to use?");
for (int i = 0; i < 3; i++)
{
mvwprintw(gameWindow, (LINES*0.6)-2, COLS*0.25, "Enemy health: %d", health);
mvwprintw(gameWindow, (LINES*0.6)+1, COLS*0.25, "F1) Sword: %d (Deals 10 damage)", inventoryValues[2]);
mvwprintw(gameWindow, (LINES*0.6)+2, COLS*0.25, "F2) Hands (+2 hunger) (Deals 7 damage)");
wrefresh(gameWindow);
int j = 0;
while(j == 0)
{
int input;
if((input = wgetch(gameWindow)) == ERR)
{
//just loop again and see if we get an input in the buffer
}
else
{
switch(input)
{
case KEY_F(1):
inputOption = 'a';
j++;
break;
case KEY_F(2):
inputOption = 'b';
j++;
break;
default:
break;
}
}
}
//legacy from when using wscanw
if (inputOption == 'a')
{
LOCK;
health -= 10;
inventoryValues[2] -= 1;
UNLOCK;
}
else if (inputOption == 'b')
{
LOCK;
health -= 7;
UNLOCK;
}
if(health < 1)
{
werase(gameWindow);
wrefresh(gameWindow);
mvwprintw(gameWindow, (LINES*0.4), COLS*0.4, "You won, gained 1 star!");
wrefresh(gameWindow);
LOCK;
inventoryValues[3] += 1;
UNLOCK;
i=3;
}
sleep(1);
}
break;
case 3:
wprintw(gameWindow, " _\n");
wprintw(gameWindow, " / \\ _-'\n");
wprintw(gameWindow, " _/| \\-''- _ /\n");
wprintw(gameWindow, "__-' { | \\\\\n");
wprintw(gameWindow, " / \\\\\n");
wprintw(gameWindow, " / 'o. |o }\n");
wprintw(gameWindow, " | \\ ;\n");
wprintw(gameWindow, " ',\n");
wprintw(gameWindow, " \\_ __\\\n");
wprintw(gameWindow, " ''-_ \\.//\n");
wprintw(gameWindow, " / '-____'\n");
wprintw(gameWindow, " /\n");
wprintw(gameWindow, " _'\n");
wprintw(gameWindow, " _-'\n");
wprintw(gameWindow, "\n\nA pack of wolves is hunting you - escape quickly\n");
wrefresh(gameWindow);
mvwprintw(gameWindow, LINES*0.6, COLS*0.25, "What would you like to use?");
for (int i = 0; i < 3; i++)
{
mvwprintw(gameWindow, (LINES*0.6)-2, COLS*0.25, "Enemy health: %d", health);
mvwprintw(gameWindow, (LINES*0.6)+1, COLS*0.25, "F1) Sword: %d (Deals 5 damage)", inventoryValues[2]);
mvwprintw(gameWindow, (LINES*0.6)+2, COLS*0.25, "F2) Hands (+2 hunger) (Deals 2 damage)");
wrefresh(gameWindow);
int j = 0;
while(j == 0)
{
int input;
if((input = wgetch(gameWindow)) == ERR)
{
//just loop again and see if we get an input in the buffer
}
else
{
switch(input)
{
case KEY_F(1):
inputOption = 'a';
j++;
break;
case KEY_F(2):
inputOption = 'b';
j++;
break;
default:
break;
}
}
}
//legacy from when using wscanw
if (inputOption == 'a')
{
LOCK;
health -= 5;
inventoryValues[2] -= 1;
UNLOCK;
}
else if (inputOption == 'b')
{
LOCK;
health -= 2;
UNLOCK;
}
if(health < 1)
{
werase(gameWindow);
wrefresh(gameWindow);
mvwprintw(gameWindow, (LINES*0.4), COLS*0.4, "You won, gained 3 stars!");
wrefresh(gameWindow);
LOCK;
inventoryValues[3] += 3;
UNLOCK;
i=3;
}
sleep(1);
}
break;
}
sleep(5);
start_game_window(gameWindow, 10, 10);
return 0;
}
int can_move(int diffX, int diffY, char worldItems[5], WINDOW *gameWindow)
{
//check if we're on the enemy, if so launch the fight window
if (worldItems[4] == 'X')
{
werase(gameWindow);
wrefresh(gameWindow);
srand(time(NULL));
int r = rand() % 4;
fight_handler(gameWindow, r);
}
//hunger related damage
if (inventoryValues[1] >= 25)
{
//cap hunger at 10
inventoryValues[1] = 25;
inventoryValues[0]--;
}
//while we're at it, sanity check the health value :)
if (inventoryValues[0] >= 10)
{
inventoryValues[0] = 10;
}
else if (inventoryValues[0] < 0)
{
inventoryValues[0] = 0;
}
//diffX is the change in X, same idea with diffY
//worldItems array is the set of items 0:up 1:down 2:left 3:right 4:underneath the moving object
int i;
switch (diffX)
{
case 1:
i = 3;
break;
case -1:
i = 2;
break;
default:
break;
}
switch (diffY)
{
case 1:
i = 1;
break;
case -1:
i = 0;
break;
default:
break;
}
switch (worldItems[i])
{
case 'T':
return FALSE;
break;
case 'W':
//one liner for nanosleep - water should slow you down a bit
nanosleep((const struct timespec[]){{0, 500000000L}}, NULL);
return TRUE;
break;
//all other types can be moved onto without modification
default:
return TRUE;
break;
}
}
int open_settings()
{
//open the settings file and read each line
FILE *fp;
char line[100];
fp = fopen("settings.txt", "r");
if (fp == NULL)
{
//oops looks like the file hasn't been created yet... ask the user to open main.c
printf("There was an error opening the settings file, please ensure that settings.txt exists\n");
printf("Running the menu screen again should solve this issue.\n");
exit(1);
}
//read settings line by line
int j = 0;
while(fgets(line, 100, fp) != NULL)
{
//parse the line - first word is option, second is value
int i = 0;
char tmpVal[2];
while(line[i] != ' ')
{
//legacy from when I was parsing option names
i++;
}
i += 3;
int k = 0;
while(line[i] != '\n')
{
tmpVal[k] = line[i];
k++;
i++;
}
if (j == 1)
{
difficulty = atoi(tmpVal);
}
else if (j == 2)
{
seed = atoi(tmpVal);
}
//discard other values
j++;
}
fclose(fp);
}
void *stats_handler(void *p)
{
//allow us to stop the thread from another function
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL);
//start the ncurses window
WINDOW *statsWindow;
LOCK;
statsWindow = create_newwin(LINES*0.2, COLS, LINES*0.8, 0);
UNLOCK;
for(;;)
{
if(recentInput == 0)
{
//run the hunger stats: every 5 moves, the player hunger increases
if (movements >= 5)
{
LOCK;
inventoryValues[1]++;
movements =- 5;
UNLOCK;
}
//TODO: deal damage if the player is above 8 hunger
/*if (inventoryValues[1] >= 8)
{
inventoryValues[0]--;
}*/
}
else
{
//legacy from when stats was handling multiple input types
switch (recentInput)
{
case 10:
if(charUnderCursor == 'B')
{
int item = rand() % 2;
if (item == 0)
{
LOCK;
inventoryValues[2]++;
UNLOCK;
mvwprintw(statsWindow, 1, 1,"Picked up sword");
}
else
{
LOCK;
inventoryValues[1] -= 3;
UNLOCK;
mvwprintw(statsWindow, 1, 1,"Picked up food ");
}
}
else
{
mvwprintw(statsWindow, 1, 1,"No item here! ");
}
LOCK;
recentInput = 0;
charUnderCursor = '\0';
UNLOCK;
break;
}
//comfort sleep
nanosleep((const struct timespec[]){{0, 250000000L}}, NULL);
//get inventory and print
for (int i = 0; i < 4; i++)
{
mvwprintw(statsWindow, (i+1), (COLS*0.5), "%s: %d", inventoryItems[i], inventoryValues[i]);
}
LOCK;
wrefresh(statsWindow);
UNLOCK;
}
}
}
void *game_handler(void *p)
{
//allow us to stop the thread from another function
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL);
//start the ncurses window
WINDOW *gameWindow;
LOCK;
gameWindow = create_newwin(LINES*0.8, COLS, 0, 0);
UNLOCK;
//set cursor to the centre of the gameWindow
int cursorX = COLS/2;
int cursorY = LINES*0.4;
start_game_window(gameWindow, cursorX, cursorY);
for(;;)
{
int input;
if((input = wgetch(gameWindow)) == ERR)
{
//TODO: yield thread? - not really useful since we're only a few threads here so probably rescheduled immediately
}
else
{
//look around the character so we can tell whether to move or not.
char worldItems[5];
worldItems[0] = mvwinch(gameWindow, cursorY - 1, cursorX);
worldItems[1] = mvwinch(gameWindow, cursorY + 1, cursorX);
worldItems[2] = mvwinch(gameWindow, cursorY, cursorX - 1);
worldItems[3] = mvwinch(gameWindow, cursorY, cursorX + 1);
worldItems[4] = mvwinch(gameWindow, cursorY, cursorX);
wmove(gameWindow, cursorY, cursorX);
//this also handles input for the stats screen using global variable recentInput
switch(input)
{
case KEY_UP:
//character movements are a weird routine which should really be in a function but i couldn't work that out in time
if (can_move(0,-1, (char *)worldItems, gameWindow) == TRUE)
{
cursorY--;
wmove(gameWindow, cursorY, cursorX);
LOCK;
movements++;
UNLOCK;
}
break;
case KEY_DOWN:
if (can_move(0, 1, (char *)worldItems, gameWindow) == TRUE)
{
cursorY++;
wmove(gameWindow, cursorY, cursorX);
LOCK;
movements++;
UNLOCK;
}
break;
case KEY_LEFT:
if (can_move(-1, 0, (char *)worldItems, gameWindow) == TRUE)
{
cursorX--;
wmove(gameWindow, cursorY, cursorX);
LOCK;
movements++;
UNLOCK;
}
break;
case KEY_RIGHT:
if (can_move(1, 0, (char *)worldItems, gameWindow) == TRUE)
{
cursorX++;
wmove(gameWindow, cursorY, cursorX);
LOCK;
movements++;
UNLOCK;
}
break;
case 10:
//offload to stats handler
LOCK;
recentInput = 10;
charUnderCursor = winch(gameWindow);
UNLOCK;
break;
}
wrefresh(gameWindow);
}
}
}
int main()
{
open_settings();
//initialise screen
initscr();
cbreak();
noecho();
//create window threads
pthread_create(&statsThread, NULL, stats_handler, NULL);
pthread_create(&gameThread, NULL, game_handler, NULL);
//create win_death checker thread
int result;
pthread_create(&checkThread, NULL, check_win_death, &result);
//wait for thread completion
void *endType = 0;
pthread_join(statsThread, NULL);
pthread_join(gameThread, NULL);
pthread_join(checkThread, &endType);
endwin();
if (endType != 0)
{
printf("Congratulations, You won the game!\n");
}
else
{
printf("Oops, you died...\n");
}
return(0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/shm.h>
#include "getSamps.h"
long get_shared_memory_size(const char *designator){
int md;
struct stat file_stat;
int mode = S_IRWXU | S_IRWXG;
md = shm_open(designator, O_CREAT | O_RDWR, mode);
if (md == -1) {
printf("Got an error opening shm\n");
return -1;
}
if (fstat(md,&file_stat)){
perror("fstat error\n");
return -1;
}
close(md);
return file_stat.st_size;
}
shared_t *init_shared_memory(const char* designator, long size){
shared_t *ret = (shared_t*) calloc(1, sizeof(shared_t));
strncpy(ret->designator, designator, MAX_DES);
int mode = S_IRWXU | S_IRWXG;
int ferror;
ret->size = size;
ret->md = shm_open(designator, O_CREAT | O_RDWR | O_TRUNC, mode);
if(ret->md ==-1){
printf("Got an error opening shm\n");
return NULL;
}
ferror = ftruncate(ret->md, size);
if (ferror == -1) {
printf("Error in ftrunctate\n");
return NULL;
}
ret->memory = mmap(0,size,PROT_READ | PROT_WRITE, MAP_SHARED, ret->md, 0);
if (ret->memory == MAP_FAILED) {
printf("Error on mmap\n");
exit(1);
}
memset(ret->memory,0,size);
return ret;
}
shared_t *map_shared_memory(const char* designator){
shared_t *ret = (shared_t*) calloc(1,sizeof(shared_t));
int mode = S_IRWXU | S_IRWXG;
int ferror;
struct stat file_stat;
strncpy(ret->designator, designator, MAX_DES);
ret->md = shm_open(designator, O_CREAT | O_RDWR | O_TRUNC, mode);
if (ret->md == -1){
printf("Got an error opening shm\n");
return NULL;
}
if (fstat(ret->md, &file_stat)){
perror("fstat error\n");
return NULL;
}
ret->size = file_stat.st_size;
if (!ret->size){
printf("Size DNE\n");
return NULL;
}
ret->memory = mmap(0,ret->size,PROT_READ | PROT_WRITE, MAP_SHARED,ret->md,0);
if (ret->memory == MAP_FAILED) {
printf("error on mmap\n");
exit(1);
}
return ret;
}
shared_t* read_shared_memory(const char *designator, long size){
shared_t *ret = (shared_t*) calloc(1,sizeof(shared_t));
int mode = S_IRUSR | S_IRGRP;
struct stat file_stat;
strncpy(ret->designator, designator, MAX_DES);
ret->md = shm_open(ret->designator, O_RDONLY, mode);
if(ret->md == -1){
printf("Got an error opening shm\n");
return NULL;
}
if (fstat(ret->md, &file_stat)){
perror("fstat error\n");
return NULL;
}
ret->size = file_stat.st_size;
if(!ret->size){
printf("Size DNE\n");
return NULL;
}
ret->memory = mmap(0,ret->size, PROT_READ, MAP_SHARED,ret->md,0);
if (ret->memory == MAP_FAILED) {
printf("error on mmap\n");
exit(1);
}
return ret;
}
int destroy_shared_memory(shared_t* memory){
int err;
err = munmap(memory->memory, memory->size);
if (err) {
printf("Error unmapping the memory-dest\n");
return err;
}
err = shm_unlink(memory->designator);
if (err) {
printf("Error unlinking the memory\n");
return err;
}
free(memory);
return err;
}
int unmap_shared_memory(shared_t* memory){
int err;
err = munmap(memory->memory,memory->size);
if (err){
printf("Error unmapping the memory-umap\n");
return err;
}
close(memory->md);
free(memory);
return err;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "init.h"
#include "util.h"
#include "host.h"
#include "host-interpreter.h"
int main(int argc, char** argv){
// Init magic
if(!initBrainfuckDotCl())
fatalError("Failed to initialize Brainfuck.cl");
// Read in some BF code from some file
char* code = NULL;
if(!readFile("bf/cat.bf", &code))
fatalError("Failed to read in BF code");
// Create host
Host* host = initHost(code, 128);
free(code);
if(host==NULL)
fatalError("Failed to create host thread");
// Run host
if(!run(host, 0)){
freeHost(host);
terminateBrainfuckDotCl();
fatalError("BrainFuck program terminated unexpectedly.");
}
// KTHXBAI
freeHost(host);
terminateBrainfuckDotCl();
return 0;
}
|
C
|
/*
* ------------------------------
* ڿ ġȯ (replace) *
* ------------------------------
*/
#include <stdio.h>
#include <string.h>
void replace(char *,char *,char *);
char *search(char *,char *);
int main(void)
{
int k;
static char text[][256]={" --- ---",
" Ⱑ ܿ",
" ",
" 帮.",
" ",
"",
"Ƹ 濡 Ѹ.",
"ô ",
" ",
" ÿɼҼ.",
" Ⱑ ܿ",
" ",
" ƴ 긮.",
""};
k=0;
while (text[k][0]!='\0') {
replace(text[k],"","ȭ");
replace(text[k],"","");
printf("%s\n",text[k]);
k++;
}
return 0;
}
void replace(char *text,char *key,char *rep)
{
char *p,buf[256];
p=search(text,key);
while (p!=NULL) {
*p='\0';
strcpy(buf,p+strlen(key));
strcat(text,rep);
strcat(text,buf);
p=search(p+strlen(rep),key);
}
}
char *search(char *text,char *key)
{
int m,n;
char *p;
m=strlen(text);
n=strlen(key);
for (p=text;p<=text+m-n;p++) {
if (strncmp(p,key,n)==0)
return p;
}
return NULL;
}
|
C
|
#include "intmath.h"
//#define DEBUG
#ifdef DEBUG
#include "natfeats.h"
#define dbg(format, arg...) do { nf_printf("DEBUG: (%s):" format, __FUNCTION__, ##arg); } while (0)
#define out(format, arg...) do { nf_printf("" format, ##arg); } while (0)
#else
#define dbg(format, arg...) do { ; } while (0)
#endif /* DEBUG */
/*
* Sines of angles 1 - 90 degrees normalized between 0-32767.
*
* Courtesy of the EmuTOS development team
*/
static const short sin_tbl[92] =
{
0, 572, 1144, 1716, 2286, 2856, 3425, 3993,
4560, 5126, 5690, 6252, 6813, 7371, 7927, 8481,
9032, 9580, 10126, 10668, 11207, 11743, 12275, 12803,
13328, 13848, 14364, 14876, 15383, 15886, 16383, 16876,
17364, 17846, 18323, 18794, 19260, 19720, 20173, 20621,
21062, 21497, 21925, 22347, 22762, 23170, 23571, 23964,
24351, 24730, 25101, 25465, 25821, 26169, 26509, 26841,
27165, 27481, 27788, 28087, 28377, 28659, 28932, 29196,
29451, 29697, 29934, 30162, 30381, 30591, 30791, 30982,
31163, 31335, 31498, 31650, 31794, 31927, 32051, 32165,
32269, 32364, 32448, 32523, 32587, 32642, 32687, 32722,
32747, 32762, 32767, 32767
};
#define HALFPI 900
#define PI 1800
#define TWOPI 3600
/*
* ISin - Returns integer sin between -32767 - 32767.
*
* Uses integer lookup table sintable^[]. Expects angle in tenths of
* degree 0 - 3600. Assumes positive angles only.
*/
short isin(short angle)
{
short index;
short remainder;
short tmpsin; /* holder for sin. */
short quadrant; /* 0-3 = 1st, 2nd, 3rd, 4th. */
while (angle > 3600)
angle -= 3600;
quadrant = angle / HALFPI;
switch (quadrant)
{
case 0:
break;
case 1:
angle = PI - angle;
break;
case 2:
angle -= PI;
break;
case 3:
angle = TWOPI - angle;
break;
case 4:
angle -= TWOPI;
break;
};
index = angle / 10;
remainder = angle % 10;
tmpsin = sin_tbl[index];
if (remainder != 0) /* add interpolation. */
tmpsin += ((sin_tbl[index + 1] - tmpsin) * remainder) / 10;
if (quadrant > 1)
tmpsin = -tmpsin;
return (tmpsin);
}
/*
* Icos - Return integer cos between -32767 and 32767.
*/
short icos(short angle)
{
angle = angle + HALFPI;
return isin(angle);
}
/*
* Itan - Return integer tangens between -32767 and 32767
*/
short itan(short angle)
{
return (short) (32767L * isin(angle) / icos(angle));
}
|
C
|
/**************************
* ex4b2: Prime Factor Server
* ============================================================================
* The factor server makes a fifo and then runs at background,
* waits for input from client, calculate the prime factors by the algo
* and send the result back to client
*
* Written by: Shahar Aviv- 203489307, Tomer Fisher- 205364151
* LogIn: shaharav, tomerfi
*
* Compile: gcc -Wall ex4b2.c -o ex4b2
* Run: ./ex4b2
* ============================================================================
* Input: got it from the client
* ============================================================================
* Output: send the result back to client
* ============================================================================
*/
//---------------Include------------------------
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <math.h>
#include <signal.h>
//------------prototypes-------------------
int primeFactors(int n, FILE *fdw, int arr[]);
void signak_hadler(int i);
void open_namedpipe() ;
//----------main section------------------
int main()
{
signal(SIGINT, signak_hadler);
FILE *fdr, *fdw ;
open_namedpipe() ;
int n1, status, i ;
int arr[100] = {0};
while(1)
{
if(!(fdr = fopen("my_pipe3","r")))
{
perror("Cannot open fifo file for r");
exit(EXIT_FAILURE);
}
status = fscanf(fdr, "%d",&n1);
fclose(fdr) ;
if(status > 0)
{
if(!(fdw = fopen("my_pipe4","w")))
{
perror("Cannot open fifo file for w");
exit(EXIT_FAILURE);
}
arr[0] = primeFactors(n1,fdw, arr);
for(i = 1; i < arr[0] ; i++)
{
fprintf(fdw,"%d " ,arr[i]);
}
fprintf(fdw,"\n");
fflush(fdw);
fclose(fdw);
}
}
return EXIT_SUCCESS;
}
// -----A function to print all prime factors of a given number n--------
int primeFactors(int n, FILE *fdw, int arr[])
{
int i, j = 1;
// Print the number of 2s that divide n
while (n%2 == 0)
{
arr[j] = 2 ;
j++ ;
n = n/2;
}
// n must be odd at this point. So we can skip
// one element (Note i = i +2)
for (i = 3; i <= n/2; i = i+2)
{
// While i divides n, print i and divide n
while (n%i == 0 )
{
arr[j] = i ;
j++ ;
n /= i;
}
}
// This condition is to handle the case when n
// is a prime number greater than 2
if (n > 2)
{
arr[j] = n ;
j++ ;
}
return j ; //returns size
}
//-----------signak handler------------------------------
void signak_hadler(int i)
{
system("rm my_pipe3");
system("rm my_pipe4");
exit(EXIT_SUCCESS);
}
//-------------opening namepipe------------------------------
void open_namedpipe()
{
if(mkfifo("my_pipe3", S_IFIFO | 0644 ) == -1)
{
perror("cannot create fifo file");
exit(EXIT_FAILURE);
}
if(mkfifo("my_pipe4", S_IFIFO | 0644 ) == -1)
{
perror("cannot create fifo file");
exit(EXIT_FAILURE);
}
}
|
C
|
/**
* A base object for rooms located by Spherical coordinates.
*
* @author devo@eotl
* @alias SphericalRoomCode
*/
inherit RoomCode;
default private variables;
int *coordinates;
default public functions;
/**
* Return the rho, theta, and phi coordinates of this room within its
* containing zone.
*
* @return an int array of room coordinates, or 0 if coordinates are unknown
*/
int *query_coordinates() {
return coordinates;
}
/**
* Set the rho, theta and phi coordinates of this room within its containing
* zone.
*
* @param coords an int array of room coordinates, or 0 of coordinates are
* unknown
* @return 0 for failure, 1 for success
*/
int set_coordinates(int *coords) {
coordinates = coords;
return 1;
}
/**
* Get the rho coorindate of this room within its containing zone.
*
* @return the rho coordinate
*/
int query_rho_coordinate() {
return coordinates[RHO_COORD];
}
/**
* Set the rho coordinate of this room within its containing zone.
*
* @param coords the rho coordinate
* @return 0 for failure, 1 for success
*/
int set_rho_coordinate(int coord) {
coordinates[RHO_COORD] = coord;
return 1;
}
/**
* Get the rho coorindate of this room within its containing zone.
*
* @return the rho coordinate
*/
int query_theta_coordinate() {
return coordinates[THETA_COORD];
}
/**
* Set the theta coordinate of this room within its containing zone.
*
* @param coords the theta coordinate
* @return 0 for failure, 1 for success
*/
int set_theta_coordinate(int coord) {
coordinates[THETA_COORD] = coord;
return 1;
}
/**
* Get the phi coorindate of this room within its containing zone.
*
* @return the phi coordinate
*/
int query_phi_coordinate() {
return coordinates[PHI_COORD];
}
/**
* Set the phi coordinate of this room within its containing zone.
*
* @param coords the phi coordinate
* @return 0 for failure, 1 for success
*/
int set_phi_coordinate(int coord) {
coordinates[PHI_COORD] = coord;
return 1;
}
/**
* Return a zero-width mapping of the capabilities this program provides.
*
* @return a zero-width mapping of capabilities
*/
public mapping query_capabilities() {
return RoomCode::query_capabilities();
}
|
C
|
#include "funtzioak.h"
void pinInit()
{
wiringPiSetup();
pinMode(7,INPUT);//7
pinMode(0,INPUT);//11
pinMode(1,INPUT);//12
pinMode(2,INPUT);//13
pinMode(3,INPUT);//15
pinMode(4,INPUT);//16
pinMode(5,INPUT);//18
pinMode(6,INPUT);//22
pinMode(21,INPUT);//29
pinMode(22,INPUT);//31
pinMode(26,INPUT);//32
pinMode(23, OUTPUT);
pinMode(24, OUTPUT);
pinMode(27, OUTPUT);
pinMode(25, OUTPUT);
pinMode(28, OUTPUT);
}
char menua()
{
sleep(1);
digitalWrite(23,1);
char aukera=0;
int egoera=0;
/*printf("\n============================================");
printf("\n| MENUA | ");
printf("\n============================================\n");
printf("| a: Erreproduzitu.\n");
printf("| b: Grabatu.\n");
printf("| d: Grabatutakoa entzun.\n");
printf("| e: Jokoa\n");
printf("============================================\n");
printf("\n Sartu zure aukera: ");*/
while(egoera==0)
{
if(digitalRead(7)==1)
{
aukera=1;
egoera=1;
}
if(digitalRead(0)==1)
{
aukera=2;
egoera=1;
}
if(digitalRead(1)==1)
{
aukera=3;
egoera=1;
}
if(digitalRead(2)==1)
{
aukera=4;
egoera=1;
}
}
sleep(1);
system("clear");
digitalWrite(23,0);
return aukera;
}
int instrumento()
{
digitalWrite(24,1);
int instrumentua = 0;
/*printf("\n ============================================\n");
printf(" AUKERAK ");
printf("\n ============================================\n");
printf("| 1: PIANO\n");
printf("| 2: 8-BIT\n");
printf("| 3: BATERIA\n");
printf("| 4: UKELELE\n");
printf("===========================================\n");
printf("\n Sartu zure aukera: ");*/
while (instrumentua == 0)
{
if(digitalRead(7)==1)
{
instrumentua=4;
}
if(digitalRead(0)==1)
{
instrumentua=3;
}
if(digitalRead(1)==1)
{
instrumentua=2;
}
if(digitalRead(2)==1)
{
instrumentua=1;
}
}
sleep(1);
digitalWrite(24,0);
return instrumentua;
}
void aukeraExekutatu(char aukera, KATEA **burua, int instrumentua)
{
sleep(1);
switch (aukera)
{
case 4:
digitalWrite(27,1);
/*printf("\n TEKLAK\n");
printf("a-->DO s-->RE d-->MI f-->FA g-->SOL h-->LA j-->SI//gelditzeko 0 sakatu");
printf("\n");*/
moduLibrea(instrumentua);
digitalWrite(27,0);
break;
case 3:
digitalWrite(25,1);
/*printf("\n TEKLAK\n");
printf("a-->DO s-->RE d-->MI f-->FA g-->SOL h-->LA j-->SI//grabaketa bukatzeko 'p' sakatu");
printf("\n");*/
zerrendaBete(instrumentua, burua);
abestiaFitxategianIdatzi(*burua);
digitalWrite(25,0);
break;
case 2:
digitalWrite(28,1);
grabatutakoAbestiaIrakurri(burua);
grabatutakoaErreproduzitu(*burua, instrumentua);
digitalWrite(28,0);
break;
case 1:
game(instrumentua);
digitalWrite(27,0);
digitalWrite(25,0);
digitalWrite(28,0);
break;
default:
break;
sleep(1);
}
}
void moduLibrea(int instrumentua)
{
int nota=-1;
EGOERA egoera;
while (nota != 8)
{
egoera = zeinNota(¬a, egoera, instrumentua);
}
}
EGOERA zeinNota(int *nota, EGOERA egoera, int instrumentua)
{
egoera=nullJarri(egoera);
if((digitalRead(3)==1)&&(egoera.egoera1==0))
{
*nota=Si;
forkFuntzioa(instrumentua,*nota);
egoera.egoera1=1;
egoera.egoeraGen=1;
}
if((digitalRead(4)==1)&&(egoera.egoera2==0))
{
*nota=La;
forkFuntzioa(instrumentua,*nota);
egoera.egoera2=1;
egoera.egoeraGen=1;
}
if((digitalRead(5)==1)&&(egoera.egoera3==0))
{
*nota=Sol;
forkFuntzioa(instrumentua,*nota);
egoera.egoera3=1;
egoera.egoeraGen=1;
}
if((digitalRead(6)==1)&&(egoera.egoera4==0))
{
*nota=Fa;
forkFuntzioa(instrumentua,*nota);
egoera.egoera4=1;
egoera.egoeraGen=1;
}
if((digitalRead(21)==1)&&(egoera.egoera5==0))
{
*nota=Mi;
forkFuntzioa(instrumentua,*nota);
egoera.egoera5=1;
egoera.egoeraGen=1;
}
if((digitalRead(22)==1)&&(egoera.egoera6==0))
{
*nota=Re;
forkFuntzioa(instrumentua,*nota);
egoera.egoera6=1;
egoera.egoeraGen=1;
}
if((digitalRead(26)==1)&&(egoera.egoera7==0))
{
*nota=Do;
forkFuntzioa(instrumentua,*nota);
egoera.egoera7=1;
egoera.egoeraGen=1;
}
if(digitalRead(7)==1)
{
*nota=Bukatu;
egoera.egoeraGen=1;
}
return egoera;
}
EGOERA nullJarri(EGOERA egoera)
{
if(digitalRead(3)==0)egoera.egoera1=0;
if(digitalRead(4)==0)egoera.egoera2=0;
if(digitalRead(5)==0)egoera.egoera3=0;
if(digitalRead(6)==0)egoera.egoera4=0;
if(digitalRead(21)==0)egoera.egoera5=0;
if(digitalRead(22)==0)egoera.egoera6=0;
if(digitalRead(26)==0)egoera.egoera7=0;
return egoera;
}
int erreproduzitu(int instrumentua, int nota)
{
char soinua[100];
switch (nota)
{
case Do:
sprintf(soinua, "aplay %s%d.wav", DO, instrumentua);
system(soinua);
break;
case Re:
sprintf(soinua, "aplay %s%d.wav", RE, instrumentua);
system(soinua);
break;
case Mi:
sprintf(soinua, "aplay %s%d.wav", MI, instrumentua);
system(soinua);
break;
case Fa:
sprintf(soinua, "aplay %s%d.wav", FA, instrumentua);
system(soinua);
break;
case Sol:
sprintf(soinua, "aplay %s%d.wav", SOL, instrumentua);
system(soinua);
break;
case La:
sprintf(soinua, "aplay %s%d.wav", LA, instrumentua);
system(soinua);
break;
case Si:
sprintf(soinua, "aplay %s%d.wav", SI, instrumentua);
system(soinua);
break;
case Bukatu:
nota = 112;
break;
default:
break;
}
return nota;
}
//////////////////
void abestiaezabatu(KATEA **burua)
{
KATEA *ptrAux = *burua;
while (ptrAux != NULL)
{
ptrAux = ptrAux->ptrHurrengoa;
free(*burua);
*burua = ptrAux;
}
*burua=NULL;
}
KATEA* sortuNota(int tecla, long tartea)
{
KATEA *ptrBerria;
ptrBerria= (KATEA*)malloc(sizeof(KATEA));
ptrBerria->tecla = tecla;
ptrBerria->tartea = tartea;
ptrBerria->ptrHurrengoa = NULL;
return ptrBerria;
}
void zerrendanGorde(int tecla, KATEA**burua, long tartea)
{
KATEA *ptrBerria = *burua;
if (*burua == NULL)
{
*burua = sortuNota(tecla, tartea);
}
else
{
while (ptrBerria->ptrHurrengoa != NULL)
{
ptrBerria = ptrBerria->ptrHurrengoa;
}
ptrBerria->ptrHurrengoa = sortuNota(tecla, tartea);
}
}
void zerrendaBete(int instrumentua, KATEA**burua)
{
int tecla, egoera;
long tartea;
struct timeval hasiera,bukaera;
if(*burua!=NULL)
{
abestiaezabatu(burua);
}
while (tecla != 8)
{
egoera=0;
gettimeofday(&hasiera, NULL);
while(egoera==0)
{
egoera = notaJokua(&tecla, egoera);
}
gettimeofday(&bukaera, NULL);
tartea=(bukaera.tv_sec-hasiera.tv_sec)*1000000+(bukaera.tv_usec-hasiera.tv_usec);
erreproduzitu(instrumentua, tecla);
zerrendanGorde(tecla, burua, tartea);
}
}
void abestiaFitxategianIdatzi(KATEA *burua)
{
FILE *fitxategia;
fitxategia = fopen("abestia.txt", "w");
while (burua != NULL)
{
fprintf(fitxategia, "%d %li\n", burua->tecla,burua->tartea);
burua = burua->ptrHurrengoa;
}
fclose(fitxategia);
}
//////////////////
void grabatutakoAbestiaIrakurri(KATEA **burua)
{
int tecla;
FILE *fitxategia;
clock_t tartea;
KATEA *ptrAux,*ptrBerria;
if (*burua == NULL)
{
fitxategia = fopen("abestia.txt", "r");
while (fscanf(fitxategia, "%d %li\n", &tecla, &tartea) != EOF)
{
if (*burua == NULL)
{
ptrBerria = sortuNota(tecla, tartea);
*burua = ptrBerria;
ptrAux = *burua;
}
else
{
ptrBerria = sortuNota(tecla,tartea);
while (ptrAux->ptrHurrengoa != NULL)ptrAux = ptrAux->ptrHurrengoa;
ptrAux->ptrHurrengoa = ptrBerria;
}
}
fclose(fitxategia);
}
}
void grabatutakoaErreproduzitu(KATEA *burua,int instrumentua)
{
int tecla;
float tartea;
while (burua != NULL)
{
tecla = burua->tecla;
tartea=(float)burua->tartea /1000000;
sleep(tartea);
erreproduzitu(instrumentua, tecla);
burua = burua->ptrHurrengoa;
}
}
void forkFuntzioa(int instrumentua, int nota)
{
int pid=fork();
if(pid==-1)printf("errore bat fork");
else if(pid==0)
{
erreproduzitu(instrumentua, nota);
exit(0);
}
}
void game(int instrumentua)
{
int i=-1, e, nota, notakMak[50],notakJok[50], egoera=0, correct =1;
char soinua[100];
while(correct==1){
i++;
//makina
digitalWrite(27,1);
digitalWrite(25,1);
digitalWrite(28,1);
sprintf(soinua, "aplay .//Soinuak//empezar.wav");
system(soinua);
sleep(1);
for(e=0;e<=i;e++)
{
nota=rand() % 7 +1;
erreproduzitu(instrumentua, nota);
*(notakMak+e)=nota;
sleep(1);
}
//jokalaria
digitalWrite(27,0);
digitalWrite(25,0);
sprintf(soinua, "aplay .//Soinuak//empezar.wav");
system(soinua);
for(e=0;e<=i;e++)
{
egoera=0;
while(egoera==0)
{
egoera=notaJokua(¬a, egoera);
}
erreproduzitu(instrumentua, nota);
*(notakJok+e)=nota;
}
for(e=0;e<=i;e++)
{
if(*(notakMak+e)!=*(notakJok+e))correct=0;
}
if(correct==0)
{
digitalWrite(28,0);
digitalWrite(25,1);
digitalWrite(27,0);
sprintf(soinua, "aplay .//Soinuak//incorrect.wav");
system(soinua);
}
else
{
digitalWrite(27,1);
digitalWrite(25,0);
digitalWrite(28,0);
sprintf(soinua, "aplay .//Soinuak//correct.wav");
system(soinua);
}
sleep(2);
}
}
int notaJokua(int *nota, int egoera)
{
if(digitalRead(3)==1)
{
*nota=Si;
egoera=1;
}
if(digitalRead(4)==1)
{
*nota=La;
egoera=1;
}
if(digitalRead(5)==1)
{
*nota=Sol;
egoera=1;
}
if(digitalRead(6)==1)
{
*nota=Fa;
egoera=1;
}
if(digitalRead(21)==1)
{
*nota=Mi;
egoera=1;
}
if(digitalRead(22)==1)
{
*nota=Re;
egoera=1;
}
if(digitalRead(26)==1)
{
*nota=Do;
egoera=1;
}
if(digitalRead(7)==1)
{
*nota=Bukatu;
egoera=1;
}
return egoera;
}
|
C
|
#include <pebble.h>
static Window *s_main_window;
static TextLayer *s_time_layer, *s_date_layer;
static BitmapLayer *s_background_layer;
static GBitmap *s_background_bitmap;
static void update_time_and_date(){
time_t temp = time(NULL);
struct tm *tick_time = localtime(&temp);
static char time_buffer[] = "00:00";
if(clock_is_24h_style() == true){
strftime(time_buffer, sizeof(time_buffer), "%H:%M", tick_time);
}else{
strftime(time_buffer, sizeof(time_buffer), "%I:%M", tick_time);
}
if(time_buffer[0] == '0'){
memmove(time_buffer, &time_buffer[1], sizeof(time_buffer)-1);
}
text_layer_set_text(s_time_layer, time_buffer);
static char date_buffer[] = "September 16";
static char day_buffer[] = "16";
static char month_buffer[] = "September";
strftime(month_buffer, sizeof(month_buffer), "%B", tick_time);
strftime(day_buffer, sizeof(day_buffer), "%d", tick_time);
if(day_buffer[0] == '0'){
memmove(day_buffer, &day_buffer[1], sizeof(day_buffer)-1);
}
memcpy(date_buffer, month_buffer, strlen(month_buffer)+1);
memcpy(date_buffer+strlen(month_buffer), " ", 1);
memcpy(date_buffer+strlen(month_buffer)+1, day_buffer, strlen(day_buffer)+1);
text_layer_set_text(s_date_layer, date_buffer);
}
static void tick_handler(struct tm *tick_time, TimeUnits units_changed){
update_time_and_date();
}
static void main_window_load(Window *window){
s_background_bitmap = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_BACKGROUND);
s_background_layer = bitmap_layer_create(GRect(0, 0, 144, 154));
bitmap_layer_set_bitmap(s_background_layer, s_background_bitmap);
layer_add_child(window_get_root_layer(window), bitmap_layer_get_layer(s_background_layer));
s_time_layer = text_layer_create(GRect(2, 112, 142, 50));
text_layer_set_background_color(s_time_layer, GColorClear);
text_layer_set_text_color(s_time_layer, GColorWhite);
text_layer_set_text(s_time_layer, "");
text_layer_set_font(s_time_layer, fonts_get_system_font(FONT_KEY_ROBOTO_BOLD_SUBSET_49));
text_layer_set_text_alignment(s_time_layer, GTextAlignmentCenter);
layer_add_child(window_get_root_layer(window), text_layer_get_layer(s_time_layer));
s_date_layer = text_layer_create(GRect(2, 3, 142, 25));
text_layer_set_background_color(s_date_layer, GColorClear);
text_layer_set_text_color(s_date_layer, GColorWhite);
text_layer_set_text(s_date_layer, "");
text_layer_set_font(s_date_layer, fonts_get_system_font(FONT_KEY_ROBOTO_CONDENSED_21));
text_layer_set_text_alignment(s_date_layer, GTextAlignmentCenter);
layer_add_child(window_get_root_layer(window), text_layer_get_layer(s_date_layer));
}
static void main_window_unload(Window *window){
text_layer_destroy(s_time_layer);
text_layer_destroy(s_date_layer);
gbitmap_destroy(s_background_bitmap);
bitmap_layer_destroy(s_background_layer);
}
static void init() {
s_main_window = window_create();
window_set_window_handlers(s_main_window, (WindowHandlers) {
.load = main_window_load,
.unload = main_window_unload
});
window_set_background_color(s_main_window, GColorBlack);
window_stack_push(s_main_window, true);
update_time_and_date();
tick_timer_service_subscribe(MINUTE_UNIT, tick_handler);
}
static void deinit() {
window_destroy(s_main_window);
tick_timer_service_unsubscribe();
}
int main(void) {
init();
app_event_loop();
deinit();
}
|
C
|
//
// This file contains all of the implementations of the replacement_policy
// constructors from the replacement_policies.h file.
//
// It also contains stubs of all of the functions that are added to each
// replacement_policy struct at construction time.
//
// ============================================================================
// NOTE: It is recommended that you read the comments in the
// replacement_policies.h file for further context on what each function is
// for.
// ============================================================================
//
#include "replacement_policies.h"
// LRU Replacement Policy
// ============================================================================
// TODO feel free to create additional structs/enums as necessary
void lru_cache_access(struct replacement_policy *replacement_policy,
struct cache_system *cache_system, uint32_t set_idx, uint32_t tag, bool hadCacheHit, bool hadEviction, int inSetIndex)
{
// TODO update the LRU replacement policy state given a new memory access
// Update information in data pointer. eg. array to keep track of LRU, I'm using it like a clock
uint32_t setStartingIndex = set_idx * cache_system->associativity; // create starting index for the given set
uint32_t* dataArrayClock = ((uint32_t*)replacement_policy->data); // cast the void pointer
//if there was a hit then we simply update the rest of the non zero cash data clocks in the set, the hit index clock should be reset
if(hadCacheHit)
{
for(int i = setStartingIndex; i < (setStartingIndex + cache_system-> associativity); i++)
{
if(dataArrayClock[i] != 0){ // non zero as 0 is default and means empty line
// update the clocks
dataArrayClock[i] = dataArrayClock[i] + 1;
}
}
//reset the hit index to one
dataArrayClock[setStartingIndex + inSetIndex] = 1;
}
else
{
// else if there was a miss then we have to see if there was an eviction or an open spot
//if there was an eviction then we need to update the data clocks and reset the evicted index
if(hadEviction){
for(int i = setStartingIndex; i < (setStartingIndex + cache_system-> associativity); i++)
{
// update the clocks// should not be any 0's because an eviction means the set is full
dataArrayClock[i] = dataArrayClock[i] + 1;
}
//reset the hit index to one
dataArrayClock[setStartingIndex + inSetIndex] = 1;
}
else{
//otherwise we need to set this index in the data as most recently used(eg = 1) and everything that isn't 0 gets increased in the data clock
for(int i = setStartingIndex; i < (setStartingIndex + cache_system-> associativity); i++)
{
if(dataArrayClock[i] != 0){ // non zero as 0 is default and means empty line
// update the clocks
dataArrayClock[i] = dataArrayClock[i] + 1;
}
}
//reset the hit index to one
dataArrayClock[setStartingIndex + inSetIndex] = 1;
}
}
}
uint32_t lru_eviction_index(struct replacement_policy *replacement_policy,
struct cache_system *cache_system, uint32_t set_idx)
{
// TODO return the index within the set that should be evicted.
uint32_t setStartingIndex = set_idx * cache_system->associativity; // create starting index for the given set
uint32_t* dataArrayClock = ((uint32_t*)replacement_policy->data); // cast the void pointer
uint32_t setIndexCounter = 0; // this keeps track of the index in the set while i is the index in all of the cache lines
uint32_t indexStore = 0; // this stores the final largest index
uint32_t tempLongestTime = dataArrayClock[setStartingIndex]; // set the temp to the first element in the set
// iterate through the set and find the largest clock time. This has been untouched the longest and shoudl be evicted
for(int i = setStartingIndex; i < (setStartingIndex + cache_system-> associativity); i++)
{
if(dataArrayClock[i] > tempLongestTime)
{
tempLongestTime = dataArrayClock[i];
indexStore = setIndexCounter;
}
setIndexCounter++;
}
return indexStore;
}
void lru_replacement_policy_cleanup(struct replacement_policy *replacement_policy)
{
// TODO cleanup any additional memory that you allocated in the
// lru_replacement_policy_new function.
// dealocate the lru_rp-> data
free(replacement_policy->data);
//-----------------------------
}
struct replacement_policy *lru_replacement_policy_new(uint32_t sets, uint32_t associativity)
{
struct replacement_policy *lru_rp = calloc(1, sizeof(struct replacement_policy));
lru_rp->cache_access = &lru_cache_access;
lru_rp->eviction_index = &lru_eviction_index;
lru_rp->cleanup = &lru_replacement_policy_cleanup;
// TODO allocate any additional memory to store metadata here and assign to
// lru_rp->data.
// creating the table to use. malloc
lru_rp->data = (uint32_t*)calloc(sets * associativity,sizeof(uint32_t));
// --------------------------------------------------------
return lru_rp;
}
// RAND Replacement Policy
// ============================================================================
void rand_cache_access(struct replacement_policy *replacement_policy,
struct cache_system *cache_system, uint32_t set_idx, uint32_t tag, bool hadCacheHit, bool hadEviction, int inSetIndex)
{
// TODO update the RAND replacement policy state given a new memory access
//No reason to keep data-> no need to keep track of anything.
}
uint32_t rand_eviction_index(struct replacement_policy *replacement_policy,
struct cache_system *cache_system, uint32_t set_idx)
{
// TODO return the index within the set that should be evicted.
return rand() % cache_system->associativity; // pick random number between 0 and accociativity
}
void rand_replacement_policy_cleanup(struct replacement_policy *replacement_policy)
{
// TODO cleanup any additional memory that you allocated in the
// rand_replacement_policy_new function.
}
struct replacement_policy *rand_replacement_policy_new(uint32_t sets, uint32_t associativity)
{
// Seed randomness
srand(time(NULL));
struct replacement_policy *rand_rp = malloc(sizeof(struct replacement_policy));
rand_rp->cache_access = &rand_cache_access;
rand_rp->eviction_index = &rand_eviction_index;
rand_rp->cleanup = &rand_replacement_policy_cleanup;
// TODO allocate any additional memory to store metadata here and assign to
// rand_rp->data.
return rand_rp;
}
// LRU_PREFER_CLEAN Replacement Policy
// ============================================================================
void lru_prefer_clean_cache_access(struct replacement_policy *replacement_policy,
struct cache_system *cache_system, uint32_t set_idx, uint32_t tag, bool hadCacheHit, bool hadEviction, int inSetIndex)
{
// TODO update the LRU_PREFER_CLEAN replacement policy state given a new
// memory access
// Update information in data pointer. eg. array to keep track of LRU, I'm using it like a clock
uint32_t setStartingIndex = set_idx * cache_system->associativity; // create starting index for the given set
uint32_t* dataArrayClock = ((uint32_t*)replacement_policy->data); // cast the void pointer
//if there was a hit then we simply update the rest of the non zero cash data clocks in the set, the hit index clock should be reset
if(hadCacheHit)
{
for(int i = setStartingIndex; i < (setStartingIndex + cache_system-> associativity); i++)
{
if(dataArrayClock[i] != 0){ // non zero as 0 is default and means empty line
// update the clocks
dataArrayClock[i] = dataArrayClock[i] + 1;
}
}
//reset the hit index to one
dataArrayClock[setStartingIndex + inSetIndex] = 1;
}
else
{
// else if there was a miss then we have to see if there was an eviction or an open spot
//if there was an eviction then we need to update the data clocks and reset the evicted index
if(hadEviction){
for(int i = setStartingIndex; i < (setStartingIndex + cache_system-> associativity); i++)
{
// update the clocks// should not be any 0's because an eviction means the set is full
dataArrayClock[i] = dataArrayClock[i] + 1;
}
//reset the hit index to one
dataArrayClock[setStartingIndex + inSetIndex] = 1;
}
else{
//otherwise we need to set this index in the data as most recently used(eg = 1) and everything that isn't 0 gets increased in the data clock
for(int i = setStartingIndex; i < (setStartingIndex + cache_system-> associativity); i++)
{
if(dataArrayClock[i] != 0){ // non zero as 0 is default and means empty line
// update the clocks
dataArrayClock[i] = dataArrayClock[i] + 1;
}
}
//reset the hit index to one
dataArrayClock[setStartingIndex + inSetIndex] = 1;
}
}
}
uint32_t lru_prefer_clean_eviction_index(struct replacement_policy *replacement_policy,
struct cache_system *cache_system, uint32_t set_idx) {
// TODO return the index within the set that should be evicted.
uint32_t setStartingIndex = set_idx * cache_system->associativity; // create starting index for the given set
uint32_t *dataArrayClock = ((uint32_t *) replacement_policy->data); // cast the void pointer
uint32_t indexStore = 0; // this stores the final largest index
bool cleanLines = false;
//figure out if there are clean cashe lines and create new arrays of clean cache lines old index in the set, their curent clock,
int* cleanCasheLineIndexArray = (int*)calloc(cache_system->associativity,sizeof(int));
int* cleanCasheClockArray = (int*)calloc(cache_system->associativity,sizeof(int));
for(int i=0; i < cache_system->associativity; i++)// initiallize arrays to -1
{
cleanCasheLineIndexArray[i]= -1;
cleanCasheClockArray[i] = -1;
} // now they are initiallized to -1
int indexCounter1 = 0;
int arrayIndexCounter1=0;
for (int i = setStartingIndex; i < (setStartingIndex + cache_system->associativity); i++)
{
struct cache_line cl = cache_system->cache_lines[i];//get the cashe line
if (cl.status != MODIFIED)//check to see if the cashe line is dirty and if
{
// there is a non MODIFIED line
cleanLines = true;
// create the new arrays
cleanCasheLineIndexArray[arrayIndexCounter1] = indexCounter1;
cleanCasheClockArray[arrayIndexCounter1] = (int)dataArrayClock[i];
arrayIndexCounter1 ++;
}
indexCounter1 ++;
}
if(cleanLines == true) // if there are clean lines to evict
{
uint32_t tempLongestTime = cleanCasheClockArray[0]; // set the temp to the first element in the set
indexStore = cleanCasheLineIndexArray[0]; // this stores the final largest index
// iterate through the set and find the largest clock time that has not been modified.
for (int i = 0; i < cache_system->associativity; i++)
{
if(cleanCasheLineIndexArray[i] == -1)
{break;} // we have reached the end of our clean cashe
if (cleanCasheClockArray[i] > tempLongestTime )//if the line is clean and has been in longer
{
tempLongestTime = cleanCasheClockArray[i];
indexStore = cleanCasheLineIndexArray[i];// set it back to its correct index in the set
}
}
}
// if there are no clean, then we run just like LRU normal
else
{
uint32_t setIndexCounter = 0; // this keeps track of the index in the set while i is the index in all of the cache lines
uint32_t tempLongestTime = dataArrayClock[setStartingIndex]; // set the temp to the first element in the set
//reset variables
indexStore = 0; // this stores the final largest index
// iterate through the set and find the largest clock time. This has been untouched the longest and shoudl be evicted
for(int i = setStartingIndex; i < (setStartingIndex + cache_system-> associativity); i++)
{
if(dataArrayClock[i] > tempLongestTime)
{
tempLongestTime = dataArrayClock[i];
indexStore = setIndexCounter;
}
setIndexCounter++;
}
}
// return memory
free(cleanCasheLineIndexArray);
free(cleanCasheClockArray);
return indexStore;
}
void lru_prefer_clean_replacement_policy_cleanup(struct replacement_policy *replacement_policy)
{
// TODO cleanup any additional memory that you allocated in the
// lru_prefer_clean_replacement_policy_new function.
free(replacement_policy->data);
}
struct replacement_policy *lru_prefer_clean_replacement_policy_new(uint32_t sets,
uint32_t associativity)
{
struct replacement_policy *lru_prefer_clean_rp = malloc(sizeof(struct replacement_policy));
lru_prefer_clean_rp->cache_access = &lru_prefer_clean_cache_access;
lru_prefer_clean_rp->eviction_index = &lru_prefer_clean_eviction_index;
lru_prefer_clean_rp->cleanup = &lru_prefer_clean_replacement_policy_cleanup;
// TODO allocate any additional memory to store metadata here and assign to
// lru_prefer_clean_rp->data.
lru_prefer_clean_rp->data = (uint32_t*)calloc(sets * associativity,sizeof(uint32_t));
return lru_prefer_clean_rp;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
// Contains entries that need to be sorted
#define PATH_TO_SORT "../../toSort.txt"
// Contains already sorted entries
#define PATH_SORTED "../../sorted.txt"
static int* read_table(const char *path, int *amount) {
// Reads the contents of an unsorted table and returns pointer to it.
// User must provide amount argument, where the amount of numbers to sort
// will be stored (that amount is read from the file)
//
// Args:
// path: Path to file to open. First two lines are comments,
// third line is the amount of numbers to sort
// amount: Will store the size of the returned table of ints
//
// Returns:
// Pointer to allocated table filled with unsorted ints. If 0, than
// reading file has failed.
FILE *f = fopen(path, "r");
if (!f) {
printf("Failed to open file: %s\n", path);
return 0;
}
// Omit the first two lines, there are just comments
char *line;
size_t len = 0;
size_t read;
read = getline(&line, &len, f);
if (read == -1) {
printf("Failed while reading file: %s\n", path);
return 0;
}
read = getline(&line, &len, f);
if (read == -1) {
printf("Failed while reading file: %s\n", path);
return 0;
}
// Store the amount of numbers to sort
fscanf(f, "%d", amount);
int *tab = (int *)malloc(sizeof(int) * *amount);
int i;
for (i = 0; i < *amount; ++i) {
fscanf(f, "%d", &tab[i]);
}
fclose(f);
return tab;
}
static int compare_table(int *tab1, int *tab2, int amount) {
// Compares two tables, it is quietly assumed, that both have the same
// amount of entries. If there are is a single diffirence, it is pointed out
//
// Args:
// tab1: First table of ints to compare
// tab2: Second table of ints to compare
// amount: Amount of entries in the table
//
// Returns:
// 0 if tables are the same, -1 if not
int i;
for (i = 0; i < amount; ++i) {
if (tab1[i] != tab2[i]) {
printf("Diffirence at: %d\n", i);
printf(">>>%d %d\n", tab1[i], tab2[i]);
return -1;
}
}
return 0;
}
static void _quick_sort(int *tab, int start, int end) {
// Quicks sorts the provided table in place. Range is (start; end]
//
// Args:
// tab: point to the table filled with integers
// start: start of the table to sort
// end: end of the table to sort
if (end - start < 2) {
return;
}
// Store the mid value used for comparison
int mid = tab[start];
// The first free position where values lesser than mid might be put
int less = start + 1;
// Guess what this is for...
int temp;
// ptr points to the first position we can put data
for (int ptr = start + 1; ptr < end; ++ptr) {
if (tab[ptr] < mid) {
temp = tab[less];
tab[less] = tab[ptr];
tab[ptr] = temp;
++less;
}
// If the value is greater then we just move forward
else {
}
}
// This will cause 'less' to point at the last of the small numbers
less -= 1;
tab[start] = tab[less];
tab[less] = mid;
// After the swap 'less' point now to the middle
_quick_sort(tab, start, less);
// We add plus one, because less is now the middle in place
_quick_sort(tab, less + 1, end);
}
void quick_sort(int *tab, int amount) {
// Quick sorts the provided table in place
//
// Args:
// tab: point to the table filled with integers
// amount: size of the table
_quick_sort(tab, 0, amount);
}
int main(int argc, char *argv[]) {
int amount;
int *to_sort = read_table(PATH_TO_SORT, &amount);
if (to_sort == 0) {
printf("Failed to read table from file: %s\n", PATH_TO_SORT);
return errno;
}
int *sorted = read_table(PATH_SORTED, &amount);
if (sorted == 0) {
printf("Failed to read table from file: %s\n", PATH_SORTED);
free(to_sort);
return errno;
}
quick_sort(to_sort, amount);
if (compare_table(to_sort, sorted, amount) != 0) {
printf("Table wasn't sorted correctly!\n");
free(to_sort);
free(sorted);
return -1;
}
free(to_sort);
free(sorted);
printf("Table sorted correctly!\n");
return 0;
}
|
C
|
#include "holberton.h"
/**
* clear_bit - function to set value of a bit to 0 at given index
* @n: pointer to number
* @index: bit to change
* Return: 1 if worked or -1 if not
*/
int clear_bit(unsigned long int *n, unsigned int index)
{
if (index >= 64)
return (-1);
*n &= ~(1 << index);
return (1);
}
|
C
|
//Esme Rubinstein and Nuriel Leve
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
char * convertWordBack(){
char str[100];
bool uppercasep[100];
char * newString;
int len;
if(scanf("%[A-Za-z]", str) == 1){
len = strlen(str);
for (int i = 0; i<len; i++){
if (isupper(str[i])) {
uppercasep[i] = true;
str[i] = tolower(str[i]);
}
else{
uppercasep[i] = false;
}
}
//test the last three letters
if ((str[len-1] == 'y') && (str[len-2] == 'a') && (str[len-3] == 'y')) {
newString = (char*)malloc(sizeof(str));
strncpy(newString, str, len-3);
}
else if (str[len-1] == 'y' && str[len-2] == 'a'){
newString = (char*)malloc(sizeof(str));
str[len-2] = '\0';
//save the last letter before the 'ay' and move them to the front of the word, delete the 'ay'
strcpy(newString, &str[len-3]);
strncat(newString, str, len-3);
newString[len] = '\0';
}
else{
newString = (char*)malloc(sizeof(str));
strcpy(newString, str);
}
for (int i = 0; i < len; i++){
if (uppercasep[i]){
newString[i] = toupper(newString[i]);
}
}
}
else {
newString = "";
}
return newString;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
int mrand(int n);
void mreverse(int *arr,int n);
void printarr(int *arr,int n);
int main(int argc,char *argv[])
{
printf("随机1-100的整数,倒序打印\n");
printf("可加参数-s指定seed,-n指定范围\n");
int seed=(int)time(0);
int n=100;
int opt,i;
while((opt=getopt(argc,argv,"s:n:"))!=-1){
switch(opt){
case 's':seed=(int)atoi(optarg);
case 'n':n=(int)atoi(optarg);
}
}
int *arr=malloc(sizeof(int)*n);
srand(seed);
for(i=0;i<n;i++)
arr[i]=mrand(n);
mreverse(arr,n);
printarr(arr,n);
free(arr);
return 0;
}
int mrand(int n)
{
return (int)(rand()%(n+1));
}
void mreverse(int *arr,int n)
{
int i,j;
for(i=0;i<n;i++)
for(j=1;j<n-i;j++)
if(arr[j]>arr[j-1])
{
int temp=arr[j];
arr[j]=arr[j-1];
arr[j-1]=temp;
}
}
void printarr(int *arr,int n)
{
int i;
for(i=0;i<n;i++)
{
if(i%10==0)putchar('\n');
printf("%d,",arr[i]);
}
putchar('\b');putchar('\n');
}
|
C
|
/* Code By: Reza Jafar
Assignment: Write, in a file called mario.c in your ~/workspace/pset1 directory, a program that recreates this half-pyramid
using hashes (#) for blocks. However, to make things more interesting, first prompt the user for the half-pyramid’s
height, a non-negative integer no greater than 23. (The height of the half-pyramid pictured above happens to be 8.)
If the user fails to provide a non-negative integer no greater than 23, you should re-prompt for the same again.
Then, generate (with the help of printf and one or more loops) the desired half-pyramid. Take care to align the bottom-left
corner of your half-pyramid with the left-hand edge of your terminal window, as in the sample output below, wherein underlined
text represents some user’s input.
username:~/workspace/pset1 $ ./mario
height: 8
##
###
####
#####
######
#######
########
#########
Note that the rightmost two columns of blocks must be of the same height. No need to generate the pipe, clouds, numbers,
text, or Mario himself.
By contrast, if the user fails to provide a non-negative integer no greater than 23, your program’s output should instead
resemble the below, wherein underlined text again represents some user’s input. (Recall that GetInt will handle some,
but not all, re-prompting for you.)
*/
#include <stdio.h>
#include <cs50.h>
int main (void) {
//Prompt user for pyramid height
int height;
do {
printf("Please enter pyramid height: ");
height = GetInt();
}
while (height < 1 || height > 23);
//Print pyramid
for(int i=0; i < height; i++){
for (int spaces = 0; spaces < height - i - 1; spaces++){
printf(".");
}
for (int hashes = 0; hashes < i + 2; hashes++){
printf("#");
}
printf("\n");
}
}
|
C
|
#ifndef KLIBC_LINKED_LIST_T
#define KLIBC_LINKED_LIST_T
#define UNCHAIN_LINKED_LIST(elem) \
if (elem->prev) elem->prev->next = elem->next; \
if (elem->next) elem->next->prev = elem->prev;
#define CHAIN_LINKED_LIST(after, new_elem) \
new_elem->next = after->next; \
new_elem->prev = after; \
if(new_elem->next) new_elem->next->prev = new_elem; \
after->next = new_elem;
#define CHAIN_LINKED_LIST_BEFORE(before, new_elem) \
if (before->prev) before->prev->next = new_elem; \
new_elem->prev = before->prev; \
new_elem->next = before; \
before->prev = new_elem;
#endif
|
C
|
/*
** EPITECH PROJECT, 2019
** my_putstr_detect.c
** File description:
** réussis
*/
#include <unistd.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include "my.h"
int my_putstr_detect (char const *str)
{
int i;
i = 0;
if (str[i] < 32) {
my_putchar('/');
my_put_nbr(str[i]);
}
while (str [i] != '\0') {
my_putchar(str[i]);
i++;
}
return 0;
}
|
C
|
//
// Created by YANHAI on 2019/5/20.
//
#include <stdio.h>
double tax_calc(double income)
{
double tax = 0, tax_income;
if (income < 0)
return -1;
tax_income = income - 3500;
if (tax_income <= 0)
tax = 0;
else if (tax_income <= 1500)
tax = tax_income * 0.03;
else if (tax_income > 1500 && tax_income <= 4500)
tax = tax_income * 0.1 - 105;
else if (tax_income > 4500 && tax_income <= 9000)
tax = tax_income * 0.20 - 555;
else if (tax_income > 9000 && tax_income <= 35000)
tax = tax_income * 0.25 - 1005;
else if (tax_income > 35000 && tax_income <= 55000)
tax = tax_income * 0.30 - 2755;
else if (tax_income > 55000 && tax_income <= 8000)
tax = tax_income * 0.35 - 5505;
else if (tax_income > 80000)
tax = tax_income * 0.45 - 13505;
return tax;
}
int main()
{
double income, tax; /* 定义变量收入、应税所得、个人所得税 */
while (1) {
printf("请输入你的收入:\n");
scanf("%lf", &income);
tax = tax_calc(income);
if (tax < 0)
break;
printf("你所缴纳的税为 is:%.2f\n", tax);
printf("你的最终收入是 is:%.2f\n", income - tax);
}
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int iNo1=0,iCnt=0;
printf("Enter Range UpTo:");
scanf("%d",&iNo1);
for(int i=1;i<=iNo1;i++)
{
for(int j=1;j<=(i/2);j++)
{
if(i%j==0)
{
iCnt=iCnt+j;
}
}
if(iCnt==i)
{
printf("%d\t",i);
}
iCnt=0;
}
return(0);
}
|
C
|
/* Signed exponential Golomb encoder/decoder
Part of DataCompressor
Andreas Unterweger, 2013-2015 */
#include "err_codes.h"
#include "io_macros.h"
#include "seg.h"
static const io_uint_t zeros[1] = { 0 };
static io_int_t EncodeUEGCodeword(const io_uint_t value, bit_file_buffer_t * const out_bit_buf, FILE * const error_log_file)
{
const io_uint_t value_plus_one = value + 1;
io_uint_t temp_value = value_plus_one;
size_t prefix_length = 0;
while ((temp_value >>= 1) != 0) /* Determine prefix length */
prefix_length++;
WRITE_VALUE_BITS_CHECKED(zeros, prefix_length, out_bit_buf, error_log_file); /* Write prefix zeros */
WRITE_VALUE_BITS_CHECKED(&value_plus_one, 1 + prefix_length, out_bit_buf, error_log_file); /* Write delimiting one and postfix value residual */
return NO_ERROR;
}
static io_int_t EncodeSEGCodeword(const io_int_t value, bit_file_buffer_t * const out_bit_buf, FILE * const error_log_file)
{
if (value > 0)
return EncodeUEGCodeword(2 * (io_uint_t)IO_ABS(value) - 1, out_bit_buf, error_log_file);
else /* if (value <= 0) */
return EncodeUEGCodeword(2 * (io_uint_t)IO_ABS(value), out_bit_buf, error_log_file);
}
io_int_t EncodeSEG(bit_file_buffer_t * const in_bit_buf, bit_file_buffer_t * const out_bit_buf, const options_t * const options)
{
io_int_t ret;
while (!EndOfBitFileBuffer(in_bit_buf))
{
io_int_t current_value;
READ_VALUE_BITS_CHECKED((io_uint_t * const)¤t_value, options->value_size_bits, in_bit_buf, options->error_log_file);
current_value = EXTEND_IO_INT_SIGN(current_value, options->value_size_bits);
if ((ret = EncodeSEGCodeword(current_value, out_bit_buf, options->error_log_file)) != NO_ERROR)
return ret;
}
return NO_ERROR;
}
static io_int_t DecodeUEGCodeword(const size_t max_value_size_bits, io_uint_t * const value, int * const eos, bit_file_buffer_t * const in_bit_buf, FILE * const error_log_file)
{
size_t prefix_length = 0;
io_uint_t current_bit = 0;
*eos = 0;
while (current_bit == 0 && !EndOfBitFileBuffer(in_bit_buf)) /* Read prefix */
{
READ_VALUE_BITS_CHECKED(¤t_bit, (size_t)1, in_bit_buf, error_log_file);
if (current_bit == 0)
prefix_length++;
if (prefix_length >= max_value_size_bits) /* Max. prefix length for 64 bit values is 64 */
return ERROR_INVALID_FORMAT;
}
if (EndOfBitFileBuffer(in_bit_buf) && prefix_length != 0) /* EOF during prefix */
{
*eos = 1; /* Signal end of stream and abort */
return NO_ERROR;
}
*value = 0;
READ_VALUE_BITS_CHECKED(value, prefix_length, in_bit_buf, error_log_file); /* Read postfix value residual */
*value |= (io_uint_t)1 << prefix_length;
*value = *value - 1;
return NO_ERROR;
}
static io_int_t DecodeSEGCodeword(const size_t max_value_size_bits, io_int_t * const value, int * const eos, bit_file_buffer_t * const in_bit_buf, FILE * const error_log_file)
{
io_int_t ret;
io_uint_t abs_value;
if (((ret = DecodeUEGCodeword(max_value_size_bits + 1 > IO_SIZE_BITS ? IO_SIZE_BITS : max_value_size_bits + 1, &abs_value, eos, in_bit_buf, error_log_file)) != NO_ERROR) || *eos) /* SEG code words are one bit longer */
return ret;
*value = (abs_value + 1) / 2;
if ((abs_value & 1) == 0) /* Even code words encode negative values (odd code words encode positive values) */
*value = -*value;
return NO_ERROR;
}
io_int_t DecodeSEG(bit_file_buffer_t * const in_bit_buf, bit_file_buffer_t * const out_bit_buf, const options_t * const options)
{
while (!EndOfBitFileBuffer(in_bit_buf))
{
io_int_t current_value, ret;
int eos;
if ((ret = DecodeSEGCodeword(options->value_size_bits, ¤t_value, &eos, in_bit_buf, options->error_log_file)) != NO_ERROR)
return ret;
if (eos) /* Exit on EOS indicator */
break;
WRITE_VALUE_BITS_CHECKED((const io_uint_t * const)¤t_value, options->value_size_bits, out_bit_buf, options->error_log_file);
}
return NO_ERROR;
}
|
C
|
/*************************************************************************
> File Name: client.c
> Author: fx
> Mail: 1007160080qq.com
> Created Time: Thu 24 Aug 2017 07:57:48 PM PDT
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<pthread.h>
char name[30];
int Init(int port,const char* ip)
{
int sock = socket(AF_INET,SOCK_STREAM,0);
if(sock < 0)
{
perror("socket");
exit(-1);
}
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr.s_addr = inet_addr(ip);
int ret = connect(sock,(struct sockaddr*)&server,sizeof(server));
if(ret < 0)
{
printf("connect error\n");
perror("connect");
exit(-2);
}
printf("客户端启动成功\n");
return sock;
}
void* recv_thread(void* arg)
{
int sock = *((int*)arg);
while(1)
{
char buf[1024]={};
if(recv(sock,buf,sizeof(buf),0)<= 0)
{
return;
}
printf("%s\n",buf);
}
}
void Start(int port,const char* ip)
{
int sock = Init(port,ip);
pthread_t tid;
int ret = pthread_create(&tid,NULL,recv_thread,&sock);
if(ret < 0)
{
perror("pthread_create");
exit(-1);
}
pthread_detach(tid);
char buf2[1024]={};
sprintf(buf2,"%s进入了聊天室",name);
int ret_send_buf2 = send(sock,buf2,strlen(buf2),0);
if(ret_send_buf2 <=0)
{
perror("send");
exit(-2);
}
while(1)
{
char buf[1024]={};
scanf("%s",buf);
char msg[1024]={};
char* quit="\\q";
sprintf(msg,"%s:%s",name,buf);
int ret_send = send(sock,msg,strlen(msg),0);
if(ret_send <= 0 )
{
perror("send");
exit(-3);
}
if(strcasecmp(buf,quit) == 0)
{
memset(buf2,0,sizeof(buf2));
sprintf(buf2,"%s退出了聊天室",name);
send(sock,buf2,strlen(buf2),0);
break;
}
}
close(sock);
}
void Usage(const char* name)
{
printf("Usage is %s [IP] [PORT]\n",name);
}
int main(int argc,const char* argv[])
{
if(argc != 3)
{
Usage(argv[0]);
return 1;
}
printf("请输入昵称:");
scanf("%s",name);
Start(atoi(argv[2]),argv[1]);
return 0;
}
|
C
|
#include <stdio.h>
#include "helper.h"
#include <limits.h>
#include "lauxlib.h"
#include "lualib.h"
#define BITS_PER_WORD (CHAR_BIT * sizeof(unsigned int))
#define I_WORD(i) ((unsigned int )(i) / BITS_PER_WORD)
#define I_BIT(i) (1 << ((unsigned int)(i) % BITS_PER_WORD))
typedef struct NumArray{
int size;
unsigned int values[1];
} NumArray;
static int newarray(lua_State *L){
int size = luaL_checkinteger(L,1);
luaL_argcheck(L,size>1,1,"invalid size");
size_t bytes = sizeof( NumArray) + I_WORD(size - 1) * sizeof(unsigned int );
NumArray *array = (NumArray *)lua_newuserdata(L,bytes);
array->size = size;
for(int i = 0;i<=I_WORD(size-1);i++){
array->values[i] = 0;
}
return 1;
}
static int setarray(lua_State *L){
NumArray *array = (NumArray *)lua_touserdata(L,1);
int index = luaL_checkinteger(L,2) - 1;
luaL_checktype(L,3,LUA_TBOOLEAN);
luaL_argcheck(L,array!=NULL,1,"array expect");
luaL_argcheck(L,index >= 0 && index < array->size,2,"invalid index");
int value = lua_toboolean(L,3);
if(value){
array->values[I_WORD(index)] = array->values[I_WORD(index)] | I_BIT(index);
}else{
array->values[I_WORD(index)] = array->values[I_WORD(index)] & (~I_BIT(index));
}
return 0;
}
static int getarray(lua_State *L){
NumArray * array = (NumArray *)lua_touserdata(L,1);
int index = luaL_checkinteger(L,2) -1 ;
luaL_argcheck(L,array!=NULL,1,"array expect");
luaL_argcheck(L,index >= 0 && index < array->size,2,"invalid index");
lua_pushboolean(L,array->values[I_WORD(index)] & I_BIT(index));
return 1;
}
static int getsize(lua_State *L){
NumArray *array = (NumArray *)lua_touserdata(L,1);
luaL_argcheck(L,array!=NULL,1,"array expect");
lua_pushinteger(L,array->size);
return 1;
}
const static luaL_Reg funcs[] = {
{"new", newarray},
{"get", getarray},
{"set", setarray},
{"size",getsize},
{NULL,NULL}
};
static int lua_openarray(lua_State *L){
luaL_newlib(L,funcs);
return 1;
}
int main() {
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_getglobal(L,"package");
lua_getfield(L,-1,"preload");
lua_pushcfunction(L,lua_openarray);
lua_setfield(L,-2,"array");
if(luaL_loadfile(L,"./test.lua") || lua_pcall(L,0,0,0)){
error(L,"error load file %s",lua_tostring(L,-1));
}
lua_close(L);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
sem_t s1;
sem_t s2;
sem_t s3;
void* t1 (void* parametro)
{
sem_wait(&s1);
printf("Ma ");
sem_post(&s2);
pthread_exit(NULL);
}
void* t2 (void* parametro)
{
sem_wait(&s2);
printf("ra ");
sem_post(&s3);
pthread_exit(NULL);
}
void* t3 (void* parametro)
{
sem_wait(&s3);
printf("doo...\n");
sem_post(&s1);
pthread_exit(NULL);
}
int main ()
{
int iteraciones = 3;
// printf("Inicializando semaforo.\n");
sem_init(&s1,0,1);
sem_init(&s2,0,0);
sem_init(&s3,0,0);
// printf("Semaforo inicializado\n");
//pthread_mutex_init ( &mi_mutex, NULL);
// printf("Creando thread\n");
pthread_t p1; //una variable de tipo pthread_t sirve para identificar al hilo que se cree
pthread_t p2;
pthread_t p3;
int rc;
for(int i = 0; i < iteraciones; i++)
{
rc = pthread_create(&p1,NULL,t1,NULL);
rc = pthread_create(&p2,NULL,t2,NULL);
rc = pthread_create(&p3,NULL,t3,NULL);
}
if (rc){
printf("Error:unable to create thread, %d \n", rc);
exit(-1);
}
//pthread_mutex_destroy(&mi_mutex);
// printf("Saliendo\n");
pthread_exit(NULL);
// printf("Afuera\n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "bicicletas.h"
#include "LinkedList.h"
#include "controller.h"
int main()
{
int opcion=0;
int flagBicicleta=0;
int flagTiempo=0;
int flagOrden=0;
char nombreArchivo[40];
LinkedList* listaBicicletas=ll_newLinkedList();
LinkedList* listaBicicletasTipo = ll_newLinkedList();
if(listaBicicletas==NULL)
{
printf("No se pudo crear el linkedlist\n");
}
do
{
switch(menu())
{
case 1:
do
{
printf("Ingrese el nombre del archivo que quiere cargar: 'bicicletas.csv', 'bicicletastipo.csv' o 'bicicletasorden.csv'\n");
fflush(stdin);
gets(nombreArchivo);
flagBicicleta=1;
}
while(loadFromText(nombreArchivo, listaBicicletas)!=1);
if(flagBicicleta==1)
{
printf("Bicicletas cargadas con exito\n");
system("pause");
}
break;
case 2:
if(flagBicicleta!=0)
{
controller_listBicicletas(listaBicicletas);
system("pause");
}
else
{
printf("Debe cargar las bicicletas con la opcion 1 para acceder a esta opcion");
system("pause");
}
break;
case 3:
if(flagBicicleta!=0)
{
ll_map(listaBicicletas,asignarTiempos);
printf("Se aplico el tiempo correctamente\n");
flagTiempo=1;
system("pause");
}
else
{
printf("Debe cargar las bicicletas con la opcion 1 para acceder a esta opcion");
system("pause");
}
break;
case 4:
if(flagBicicleta!=0 && flagTiempo==0)
{
printf("Debe asignar el tiempo para acceder a esta opcion\n");
system("pause");
}
else if(flagBicicleta!=0 && flagTiempo!=0)
{
listaBicicletasTipo=ll_filter(listaBicicletas,filtrarTipo);
saveAsText("bicicletastipo.csv", listaBicicletasTipo);
printf("Bicicletas filtradas y guardadas con exito\n");
system("pause");
}
else
{
printf("Debe cargar las bicicletas con la opcion 1 para acceder a esta opcion\n");
system("pause");
}
break;
case 5:
if(flagBicicleta!=0)
{
controller_sortBicicletas(listaBicicletas);
controller_listBicicletas(listaBicicletas);
flagOrden=1;
system("pause");
}
else
{
printf("Debe cargar los paises con la opcion a para acceder a esta opcion\n");
system("pause");
}
break;
break;
case 6:
if(flagBicicleta!=0 && flagOrden==0)
{
printf("Debe ordenar las bicicletas con la opcion 5 para acceder a esta opcion\n");
system("pause");
}
else if(flagBicicleta!=0 && flagOrden!=0)
{
saveAsText("bicicletasorden.csv", listaBicicletas);
printf("Bicicletas guardadas en un archivo con exito\n");
system("pause");
}
else
{
printf("Debe cargar las bicicletas con la opcion 1 para acceder a esta opcion\n");
system("pause");
}
break;
case 7:
printf("Seguro que desea salir? Si no es asi presione 0: \n");
scanf("%d", &opcion);
break;
}
}
while(opcion==0);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>
#include "linkedListLib.h"
struct ListNode* deleteDuplicates(struct ListNode* head) {
struct ListNode* cur = head;
struct ListNode* delMe;
if(head == NULL || head->next == NULL)
return head;
while(cur->next != NULL) {
if(cur->next->val == cur->val) {
delMe = cur->next;
cur->next = cur->next->next;
}
else {
cur = cur->next;
}
}
return head;
}
int main(int argc, char const *argv[]) {
// struct ListNode* head = BuildByLength(9);
// struct ListNode* newNode = malloc(sizeof(struct ListNode));
// newNode->val = 5;
// newNode->next = NULL;
// SortedInsert(&head, newNode);
struct ListNode* nn1 = malloc(sizeof(struct ListNode));
nn1->val = 6;
nn1->next = NULL;
// SortedInsert(&head, nn1);
// PrintList(head);
// printf("---After Remove Duplicates\n");
// deleteDuplicates(head);
// PrintList(head);
deleteDuplicates(nn1);
PrintList(deleteDuplicates(nn1));
struct ListNode* nn2;
Push(&nn2, 2);
Push(&nn2, 1);
PrintList(deleteDuplicates(nn2));
// free(newNode);
// free(nn1);
return 0;
}
|
C
|
/*prerequisite is the program should be correct*/
#include<stdio.h>
#include<conio.h>
int multiline=0;
void remove_comment_and_print(char *s);
void main() //main start
{
FILE *fp = fopen("rcomment.c","r");
char c[500]; int flag; clrscr();
while(NULL!=fgets(c,80,fp))
{remove_comment_and_print(c) ; }
getch();
}
void remove_comment_and_print(char *s) /*test */
{
int len; int i=0;
for(len=0;s[len]!='\0';len++);
while(s[i]!='\0')
{
if(s[i]=='/')
{ if(s[i+1]=='/')
break;
else if(s[i+1]=='*')
multiline=1;
else
if(!multiline)
printf("%c",s[i]);
}
else if(s[i]=='*')
{ if(s[i+1]=='/')
{multiline=0;i++;}
else
if(!multiline)
printf("%c",s[i]);
} /*first */
else /* this is multine comment */
{ if(!multiline) /*this is test */
printf("%c",s[i]); /*again */
}
i++;
}
}
|
C
|
/*
============================================================================
Name : delta_stepping.c
Author : stam
Version :
Copyright : Your copyright notice
Description : Calculate Pi in MPI
============================================================================
*/
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include "mpi.h"
#include <time.h>
#include "limits.h"
#include <stddef.h>
#define NEWARRAY(x, n) do { (x) = calloc((n), sizeof *(x)); } while (0)
#define RESIZEARRAY(x, n) do { (x) = realloc((x), sizeof *(x) * (n) ); } while (0)
float precision = 0.00001;
//the graph will be represented as an array of nodes
typedef struct NODE{
int nodeId;//the id of the node
int *edgeList;//the array containing the adj node ids
double *weigthsList;//the weight to each edge
int maxEdges;//to dynamically allovate new size for the edge list
int numberOfEdges;
} NODE;
typedef struct BUCKETELEMENT{
double* tentDist;//-1.0 denotes infinite distance //-2.0 just initialized
int* nodeIds;
int* bucket2Index;//helper to find the element in constant time
int maxNodes;
int numberOfNodes;
int index;
} BUCKETELEMENT;
typedef struct REQUESTS{
int *targetId;
int numberOfelements;
double *weightSourceToTarget;
double tendDistanceOfSource;
}REQUESTS;
typedef struct REAMOVEDNODES{
int removedCount;//the count of the removedNodes
int *removedNodesIds;//the removed nodes
int sizeOfRemovedNodesIds;
} REAMOVEDNODES;
void pushToRemovedNodes(int nodeId,REAMOVEDNODES *removedNodes){
if(removedNodes==NULL){
NEWARRAY(removedNodes,10);
removedNodes->sizeOfRemovedNodesIds=10;
removedNodes->removedCount=0;
}
if(removedNodes->removedCount==removedNodes->sizeOfRemovedNodesIds){
NEWARRAY(removedNodes,removedNodes->sizeOfRemovedNodesIds*2);
removedNodes->sizeOfRemovedNodesIds=removedNodes->sizeOfRemovedNodesIds*2;
*(removedNodes->removedNodesIds+(removedNodes->removedCount))=nodeId;
removedNodes->removedCount++;
}else{
*(removedNodes->removedNodesIds+(removedNodes->removedCount))=nodeId;
removedNodes->removedCount++;
}
}
NODE* New_grapg(int numberOfNodes){
NODE *newGraph= calloc(numberOfNodes, sizeof(NODE));
assert(newGraph != NULL);
int i=0;
for(i=0;i<numberOfNodes;i++){
newGraph->numberOfEdges=0;
}
return newGraph;
}
BUCKETELEMENT* New_Bucket(int numberOfBuckets){
BUCKETELEMENT *newBucket = calloc(numberOfBuckets, sizeof(BUCKETELEMENT));
assert(newBucket!=NULL);
int i=0;
for(i=0;i<numberOfBuckets;i++){
(newBucket+i)->index=-2;//-2 just initialized
(newBucket+i)->numberOfNodes=0;
}
return newBucket;
}
BUCKETELEMENT* resizeBucket(BUCKETELEMENT* bucketArray,int newSize,int oldSize){
RESIZEARRAY(bucketArray,newSize);
assert(bucketArray!=NULL);
int i=0;
if(oldSize<newSize){
for(i=oldSize;i<newSize;i++){
(bucketArray+i)->index=-2;//-2 just initialized
(bucketArray+i)->numberOfNodes=0;
}
}
return bucketArray;
}
void buildFinalArray(REQUESTS *localRequests,int nodeId,double tentDist,int sizeOfGraph){
if(localRequests==NULL){
NEWARRAY(localRequests,1);
NEWARRAY(localRequests->targetId,sizeOfGraph);
NEWARRAY(localRequests->weightSourceToTarget,sizeOfGraph);
localRequests->numberOfelements=0;
}
*(localRequests->targetId+nodeId)=nodeId;
*(localRequests->weightSourceToTarget+nodeId)=tentDist;
}
void buildRequests(NODE aNode,REQUESTS *lightEdgesRequests,double delta,double tendDistSource){
int neigboursSize=aNode.numberOfEdges;
int kk=0;
int innerCounter=0;
if(lightEdgesRequests->targetId==NULL||lightEdgesRequests->weightSourceToTarget==NULL){
NEWARRAY(lightEdgesRequests->targetId,neigboursSize);//at max is neigboursSize
NEWARRAY(lightEdgesRequests->weightSourceToTarget,neigboursSize);
lightEdgesRequests->numberOfelements=0;
}else{
RESIZEARRAY(lightEdgesRequests->targetId,lightEdgesRequests->numberOfelements+neigboursSize);
RESIZEARRAY(lightEdgesRequests->weightSourceToTarget,lightEdgesRequests->numberOfelements+neigboursSize);
}
lightEdgesRequests->tendDistanceOfSource=tendDistSource;
for(kk=0 ; kk < neigboursSize ; kk++ ){
if( *((aNode.weigthsList)+kk) <= delta ){
*(lightEdgesRequests->targetId+innerCounter+(lightEdgesRequests->numberOfelements))=*(aNode.edgeList+kk);
*(lightEdgesRequests->weightSourceToTarget+(innerCounter+lightEdgesRequests->numberOfelements))=*((aNode.weigthsList)+kk);
lightEdgesRequests->numberOfelements++;
innerCounter++;
}
}
}
void buildHeavyRequests(NODE aNode,REQUESTS *heaveEdgesRequests,double delta,double tendDistSource){
int neigboursSize=aNode.numberOfEdges;
int kk=0;
int innerCounter=0;
if(heaveEdgesRequests->targetId==NULL||heaveEdgesRequests->weightSourceToTarget==NULL){
NEWARRAY(heaveEdgesRequests->targetId,neigboursSize);//at max is neigboursSize
NEWARRAY(heaveEdgesRequests->weightSourceToTarget,neigboursSize);
heaveEdgesRequests->numberOfelements=0;
}else{
RESIZEARRAY(heaveEdgesRequests->targetId,heaveEdgesRequests->numberOfelements+neigboursSize);
RESIZEARRAY(heaveEdgesRequests->weightSourceToTarget,heaveEdgesRequests->numberOfelements+neigboursSize);
}
heaveEdgesRequests->tendDistanceOfSource=tendDistSource;
for(kk=0 ; kk < neigboursSize ; kk++ ){
if( *((aNode.weigthsList)+kk) >= delta ){
*(heaveEdgesRequests->targetId+innerCounter+heaveEdgesRequests->numberOfelements)=*(aNode.edgeList+kk);
*(heaveEdgesRequests->weightSourceToTarget+innerCounter+heaveEdgesRequests->numberOfelements)=*((aNode.weigthsList)+kk);
heaveEdgesRequests->numberOfelements++;
innerCounter++;
}
}
}
int containtsElem(int searchNode,int *searchlist,int size){
int i;
for(i=0;i<size;i++){
if(searchlist[i]==searchNode){
return 1;
}else{
return 0;
}
}
return 0;///to fix
}
int isBucketEmpty(BUCKETELEMENT *aBucketElement,int *removedNodes,int size){
if(aBucketElement->numberOfNodes==0 || aBucketElement==NULL){
return 1;
}else{
int i=0;
int notFound=0;
for(i=0;i<aBucketElement->numberOfNodes;i++){
if(!containtsElem(*(aBucketElement->nodeIds+i),removedNodes,size)){
notFound=1;
break;
}
}
return !notFound;
}
}
int isBucketEmpty2(BUCKETELEMENT *aBucketElement){
if(aBucketElement->numberOfNodes==0 || aBucketElement==NULL){
return 1;
}else{
return 0;
}
}
void findnextNonEmptyBucket(BUCKETELEMENT *localBucketArray,int currentBucketIndex,int *localMinBuckInd,int localBucketSize){
int ii=0;
int found=0;
for(ii=currentBucketIndex ; ii < localBucketSize ;ii++){
if( !isBucketEmpty2((localBucketArray+ii)) ){
found=1;
break;
}
}
if(found){
*localMinBuckInd=ii;
}else{
*localMinBuckInd=0;///only the infiniteBucket is Non Empty
}
}
/* rangefrom inclusive end not inclusive */
int get_randomNumber(int rangefrom,int rangeTo)
{
return (rand() % rangeTo + rangefrom);
}
void pushEdge(NODE *anode,int edgeId,double edgeWeight){
if(anode->edgeList==NULL){
NEWARRAY(anode->edgeList,10);
NEWARRAY(anode->weigthsList,10);
anode->maxEdges=10;
}
/*we dynamically allocate space for the edges */
if(anode->maxEdges==anode->numberOfEdges){
anode->maxEdges=anode->maxEdges*2;
RESIZEARRAY((anode->edgeList),anode->maxEdges);
RESIZEARRAY((anode->weigthsList),anode->maxEdges);
}
*(anode->edgeList+anode->numberOfEdges)=edgeId;
*(anode->weigthsList+anode->numberOfEdges)=edgeWeight;
anode->numberOfEdges++;
}
void pushDistanceAndNode(BUCKETELEMENT *bucketarray, int nodeId, double distance,int index){
if(bucketarray->nodeIds==NULL){
NEWARRAY(bucketarray->nodeIds,5);
NEWARRAY(bucketarray->tentDist,5);
NEWARRAY(bucketarray->bucket2Index,5);
bucketarray->maxNodes=5;
}
/*we dynamically allocate space for the edges */
if(bucketarray->maxNodes==bucketarray->numberOfNodes){
bucketarray->maxNodes=bucketarray->maxNodes*2;
RESIZEARRAY((bucketarray->nodeIds),bucketarray->maxNodes);
RESIZEARRAY((bucketarray->tentDist),bucketarray->maxNodes);
RESIZEARRAY((bucketarray->bucket2Index),bucketarray->maxNodes);
}
*(bucketarray->nodeIds+bucketarray->numberOfNodes)=nodeId;
*(bucketarray->tentDist+bucketarray->numberOfNodes)=distance;
*(bucketarray->bucket2Index+bucketarray->numberOfNodes)=index;
bucketarray->numberOfNodes++;
}
void popDistanceAndNode(BUCKETELEMENT *bucketarray, int nodeId){
if(bucketarray->nodeIds==NULL){
return;
}
short foundFlag=0;
int* tempNodeIds = calloc((bucketarray->maxNodes - 1), sizeof(int)); // allocate an array with a size 1 less than the current one
double* tempDistances = calloc((bucketarray->maxNodes - 1), sizeof(double)); // allocate an array with a size 1 less than the current one
int* tempBucket2Index = calloc((bucketarray->maxNodes - 1), sizeof(double));
int i=0;
int j=0;
for(i=0; i<bucketarray->numberOfNodes; i++){
if(*(bucketarray->nodeIds+i)!=nodeId){
*(tempNodeIds+j)=*(bucketarray->nodeIds+i);
*(tempDistances+j)=*(bucketarray->tentDist+i);
*(tempBucket2Index+j)=*(bucketarray->bucket2Index+i);
j++;
}else{
foundFlag=1;
}
}
if(foundFlag){
memcpy(bucketarray->nodeIds, tempNodeIds, ((bucketarray->maxNodes - 1)) * sizeof(int));
memcpy(bucketarray->tentDist, tempDistances, ((bucketarray->maxNodes - 1)) * sizeof(int));
bucketarray->numberOfNodes--;
int N = bucketarray->numberOfNodes;
int totalSize = bucketarray->maxNodes;
if (N > 0 && N <= totalSize/4){
bucketarray->maxNodes = totalSize/2;
RESIZEARRAY((bucketarray->nodeIds),bucketarray->maxNodes);
RESIZEARRAY((bucketarray->tentDist),bucketarray->maxNodes);
}
}
}
double findTargetDistance(BUCKETELEMENT *locBucketArray,int nodeId,int sizeOfBucketArray,int *targetNodeBucketIndex,int *targetNodeIndexInBucket){
int ii=0;
int ee=0;
for(ii=0; ii<sizeOfBucketArray ;ii++ ){
for(ee=0 ; ee < (locBucketArray+ii)->numberOfNodes ; ee++){
int currentNode=*((locBucketArray+ii)->nodeIds+ee);
if(currentNode==nodeId){
*targetNodeBucketIndex=ii;
*targetNodeIndexInBucket=ee;
return *(locBucketArray+ii)->tentDist;
}
}
}
return 0.0;////tofix
}
int findNextBucketIndex(int *globalMinBuffer,int size){
int ii=0;
int tempMin=size;///pick a max size
int allmin=1;
for(ii=0;ii < size; ii++){
if(*globalMinBuffer!=0 && (*globalMinBuffer)<tempMin ){
tempMin=*globalMinBuffer;
allmin=0;
}
}
if(allmin){
return 0;
}else{
return tempMin;
}
}
void readEdges(NODE* graph,const char *line){
char *token;
short counter=0;
int startNode,endNode;
double weight;
const char s[2] = " ";
int startNodeId,endNodeId;
//printf("reading line %s \n",line);
/* get the first token */
token = strtok((const char *)line, s);
/* walk through other tokens */
while( token != NULL )
{
if(counter==0){
startNode=atoi(token);
}else if(counter==1){
endNode=atoi(token);
}else{
weight=atof(token);
}
token = strtok(NULL, s);
counter++;
}
pushEdge(graph+startNode,endNode,weight);//Check if the index of the graph is correct
}
int
main(int argc, char *argv[])
{
int my_rank; /* rank of process */
int num_procs=0; /* number of processes */
int source; /* rank of sender */
int dest = 0; /* rank of receiver */
int tag = 0; /* tag for messages */
char message[100]; /* storage for message */
MPI_Status status ; /* return status for receive */
/* start up MPI */
MPI_Init(&argc, &argv);
/* find out process rank */
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
/* find out number of processes */
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
/*declarations and initializations*/
int tempCountsPerProcess[num_procs-1];
char *nameOfGraphFile;
char line[80];
long elapsed_seconds;
int sizeOfScatteredList;
FILE *fr; /* declare the file pointer */
int *sizeOfGraph = NULL;
NODE *graph= NULL;
int *ind= NULL;
int maxSize;
NODE *localScatteredReceiveList;
NODE *globalScatteredList;
BUCKETELEMENT *localBucketArray;
NEWARRAY(sizeOfGraph,1);
memset( tempCountsPerProcess, 0, num_procs*sizeof(int) );//for c99 compiler
int sourceNodeId;
int currentBucketIndex;
int localMinBuckInd;
int *globalMinBuffer;
REQUESTS *requestsArray;
double delta;
int localBucketSize=0;
int terminateFlag=0;
int stillWorking;
int *stillWorkingArray=NULL;
NEWARRAY(stillWorkingArray,num_procs-1);
/*end of declarations and initializations*/
if(my_rank==0){
if(argc < 2){
printf("No Arguments \n Arguments:\n name of graph file \nintial delta value \n");
exit(1);
}
nameOfGraphFile=argv[1];
delta=atof(argv[2]);
sourceNodeId=atoi(argv[3]);
if(nameOfGraphFile!=NULL){
fr = fopen (nameOfGraphFile, "r"); /* open the file for reading */
/* elapsed.dta is the name of the file */
/* "rt" means open the file for reading text */
/* read the graph */
if(fr==NULL){
printf("error: the file does not exists \n");
exit(1);
}
fgets(line, 80, fr);
sscanf (line, "%ld", &elapsed_seconds);
*sizeOfGraph=atoi(line);
printf("first line %s \n",line);
printf("the size of the graph %d \n",*sizeOfGraph);
int nodeCounter=0;
while(fgets(line, 80, fr) != NULL)
{
/* get a line, up to 80 chars from fr. done if NULL */
sscanf (line, "%ld", &elapsed_seconds);
/* convert the string to a double int */
if(*sizeOfGraph<1){
printf("error: The size of the graph is < 1 \n");
exit(1);
}
graph=New_grapg(*sizeOfGraph);
if(atoi(line)!=-1){
readEdges(graph,line);
}
}
}
srand(clock());
int counter=0;
int countsPerProcess[num_procs-1];
memset( countsPerProcess, 0, (num_procs-1)*sizeof(int) );//for c99 compiler
NEWARRAY(ind,*(sizeOfGraph)-1);
for(counter=0;counter<*sizeOfGraph;counter++){
ind[counter]=get_randomNumber(0,num_procs);//generate the randomly assignments of nodes to processes u
countsPerProcess[ind[counter]]++;
}
maxSize=0;
for(counter=0;counter<num_procs;counter++){
if (maxSize<countsPerProcess[counter]){
maxSize=countsPerProcess[counter];
}
}
sizeOfScatteredList= maxSize*num_procs;
globalScatteredList=New_grapg(sizeOfScatteredList);
for(counter=0;counter<*sizeOfGraph;counter++){
*(globalScatteredList+maxSize*(ind[counter])+tempCountsPerProcess[(ind[counter])])=*(graph+counter);
tempCountsPerProcess[(ind[counter])]++;
}
printf("in here \n");
}
/* Declaration of new datatype */
const int nitems=5;
int blocklengths[5] = {1,1,1,1,1};
MPI_Datatype types[5] = {MPI_INT, MPI_INT,MPI_DOUBLE,MPI_INT,MPI_INT};
MPI_Datatype mpi_local_counts_type;
MPI_Aint offsets[5];
MPI_Aint addr[5];
MPI_Get_address(globalScatteredList, &addr[0]);
MPI_Get_address(&globalScatteredList->nodeId, &addr[1]);
MPI_Get_address(&globalScatteredList->edgeList, &addr[2]);
MPI_Get_address(&globalScatteredList->weigthsList, &addr[3]);
MPI_Get_address(&globalScatteredList->maxEdges, &addr[4]);
MPI_Get_address(&globalScatteredList->numberOfEdges, &addr[5]);
offsets[0] = addr[1] - addr[0];
offsets[1] = addr[2] - addr[0];
offsets[2] = addr[3] - addr[0];
offsets[3] = addr[4] - addr[0];
offsets[4] = addr[5] - addr[0];
MPI_Type_create_struct(nitems, blocklengths, offsets, types, &mpi_local_counts_type);
MPI_Type_commit(&mpi_local_counts_type);
/* end of new datatype */
const int nitems2=3;
int blocklengths2[4] = {1,1,1,1};
MPI_Datatype types2[4] = {MPI_INT, MPI_INT,MPI_DOUBLE};
MPI_Datatype mpi_request_type;
MPI_Aint offsets2[4];
MPI_Aint addr2[4];
MPI_Get_address(requestsArray, &addr2[0]);
MPI_Get_address(&requestsArray->targetId, &addr2[1]);
MPI_Get_address(&requestsArray->numberOfelements, &addr2[2]);
MPI_Get_address(&requestsArray->weightSourceToTarget, &addr2[3]);
MPI_Get_address(&requestsArray->tendDistanceOfSource, &addr2[4]);
offsets2[0] = addr2[1] - addr2[0];
offsets2[1] = addr2[2] - addr2[0];
offsets2[2] = addr2[3] - addr2[0];
offsets2[2] = addr2[4] - addr2[0];
MPI_Type_create_struct(nitems2, blocklengths2, offsets2, types2, &mpi_request_type);
MPI_Type_commit(&mpi_request_type);
/* end of new datatype */
MPI_Barrier(MPI_COMM_WORLD);
MPI_Bcast(sizeOfGraph,1,MPI_INT,0,MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
assert(sizeOfGraph != NULL);
if(my_rank!=0){
NEWARRAY(ind,*(sizeOfGraph)-1);
}
assert(ind != NULL);
MPI_Bcast(tempCountsPerProcess,num_procs-1,MPI_INT,0,MPI_COMM_WORLD);
MPI_Bcast(ind,(*sizeOfGraph)-1,MPI_INT,0,MPI_COMM_WORLD);
MPI_Bcast(&delta,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Bcast(&sizeOfScatteredList,1,MPI_INT,0,MPI_COMM_WORLD);
MPI_Bcast(&maxSize,1,MPI_INT,0,MPI_COMM_WORLD);
localScatteredReceiveList=New_grapg(maxSize);
MPI_Scatter(globalScatteredList,maxSize,mpi_local_counts_type,localScatteredReceiveList,maxSize,mpi_local_counts_type,0,MPI_COMM_WORLD);
localBucketArray=New_Bucket(2);//initial we start with only the 0 bucket and the infinite distance bucket
localBucketSize=2;
(localBucketArray)->index=-1;//go to the bucket that holds infinite
(localBucketArray)->numberOfNodes=0;
(localBucketArray+1)->index=0;//go to the bucket that holds source
(localBucketArray+1)->numberOfNodes=0;
/* fill the all the local nodes to the infinite bucket*/
int ll=0;
for(ll=0;ll<tempCountsPerProcess[my_rank];ll++){
if(((localScatteredReceiveList+ll)->nodeId)==sourceNodeId){
printf("found source node on process %d",my_rank);
//void pushDistanceAndNode(BUCKETELEMENT *bucketarray, int nodeId, double distance,int index,int *localBucketSize){
pushDistanceAndNode(localBucketArray+1,(localScatteredReceiveList+ll)->nodeId,0.0,0);
}else{
pushDistanceAndNode(localBucketArray,(localScatteredReceiveList+ll)->nodeId,-1.0,-1);
}
}
currentBucketIndex=1;//the infinite bucket is the bucket array element 0;
/*create requests */
while(!terminateFlag){
REAMOVEDNODES *R=NULL;
NEWARRAY(R,1);
R->removedNodesIds=NULL;
int isHeavyEgdesProcessed=-1;
int isBucketEmptyFlag=isBucketEmpty( (localBucketArray+currentBucketIndex),R->removedNodesIds,R->removedCount );
while( !isBucketEmptyFlag || !isHeavyEgdesProcessed ){
/*allocate variables */
REQUESTS *requestsToSendList;
REQUESTS *requestsToReceive;
NEWARRAY(requestsToSendList,1);
requestsToSendList->targetId=NULL;
requestsToSendList->weightSourceToTarget=NULL;
requestsToSendList->numberOfelements=0;
NEWARRAY(requestsToReceive,num_procs-1);///
requestsToReceive->targetId=NULL;
requestsToReceive->weightSourceToTarget=NULL;
/*end of allocate variables */
/* iterate all the nodes the bucket */
for(ll=0;ll<(localBucketArray+currentBucketIndex)->numberOfNodes;ll++){
//iterate all the edges
int nodeToProcess=*((localBucketArray+currentBucketIndex)->nodeIds+ll);
int indexInScatteredList=*((localBucketArray+currentBucketIndex)->bucket2Index+ll);
double sourceTentDist=*((localBucketArray+currentBucketIndex)->tentDist+ll);
if(!containtsElem(nodeToProcess,R->removedNodesIds,R->removedCount)){//if itis not inside the removed list
//void buildRequests(NODE aNode,REQUESTS *lightEdgesRequests,double delta,double tendDistSource){
buildRequests( (*(localScatteredReceiveList+indexInScatteredList)) ,requestsToSendList,delta,sourceTentDist);
pushToRemovedNodes(nodeToProcess,R);
}else if(isHeavyEgdesProcessed==0){
buildHeavyRequests((*(localScatteredReceiveList+indexInScatteredList)),requestsToSendList,delta,sourceTentDist);
}
}
/*end of iterate all the nodes the bucket */
MPI_Barrier(MPI_COMM_WORLD);
MPI_Allgather(requestsToSendList,1,mpi_request_type,requestsToReceive,1,mpi_request_type,MPI_COMM_WORLD);
int tempOuterCounter=0;
int tempInnerCounter=0;
/* all processes perform Relaxations */
for( tempOuterCounter=0 ; tempOuterCounter < num_procs-1; tempOuterCounter++){
for(tempInnerCounter=0 ; tempInnerCounter < (requestsToReceive+tempOuterCounter)->numberOfelements ; tempInnerCounter++){
if((requestsToReceive+tempOuterCounter)->numberOfelements!=0){
int currentTargeNodeId=*( (requestsToReceive+tempOuterCounter)->targetId+tempInnerCounter );
if( ind[currentTargeNodeId]==my_rank ){//if true the the node must be someware in the bucket O(n) time for searching ///or improvement we could use a hashSet ..
int targetNodeBucketIndex=0;
int targeNodeIndexInsideBucket=0;
double tentDistSource=(requestsToReceive+tempOuterCounter)->tendDistanceOfSource;
double tentDistTarget=findTargetDistance(localBucketArray,currentTargeNodeId,localBucketSize,&targetNodeBucketIndex,&targeNodeIndexInsideBucket);
double sourceToTargetWeight=*((requestsToReceive+tempOuterCounter)->weightSourceToTarget+tempInnerCounter);
if( (tentDistSource+sourceToTargetWeight < tentDistTarget) || ( tentDistTarget == ( -0.1 ) ) ){
popDistanceAndNode(localBucketArray+targetNodeBucketIndex,currentTargeNodeId);
int arrayIndexToInsertNeWdDist=( (tentDistSource+sourceToTargetWeight)/(int)delta)+1;
if( (arrayIndexToInsertNeWdDist+1) >= localBucketSize){
RESIZEARRAY(localBucketArray,(arrayIndexToInsertNeWdDist+2));
localBucketSize=(arrayIndexToInsertNeWdDist+2);
pushDistanceAndNode(localBucketArray+arrayIndexToInsertNeWdDist+1,currentTargeNodeId,tentDistSource+sourceToTargetWeight,arrayIndexToInsertNeWdDist);//change the bucket the node is
}
}
}
}
}
}
/* deallocate space for dynamically allocated variables */
free(requestsToSendList->targetId);
free(requestsToSendList->weightSourceToTarget);
free(requestsToReceive->weightSourceToTarget);
free(requestsToReceive->targetId);
free(requestsToSendList);
free(requestsToReceive);
isBucketEmptyFlag=isBucketEmpty( (localBucketArray+currentBucketIndex),R->removedNodesIds,R->removedCount );
if(isBucketEmptyFlag){
isHeavyEgdesProcessed++;
}
MPI_Barrier(MPI_COMM_WORLD);
stillWorking=(!isBucketEmptyFlag || !isHeavyEgdesProcessed);
MPI_Allgather(&stillWorking,1,MPI_INT,stillWorkingArray,1,MPI_INT,MPI_COMM_WORLD);
}
free(R->removedNodesIds);
free(R);
int ii=0;
terminateFlag=1;
for(ii=0;ii<num_procs-1;ii++){
if(*(stillWorkingArray+ii)!=0){
terminateFlag=0;
break;
}
}
if(isBucketEmptyFlag && !terminateFlag && !stillWorking){//other processes still work but current has no more work
/*allocate variables */
REQUESTS *requestsToSendList;
REQUESTS *requestsToReceive;
NEWARRAY(requestsToSendList,1);
requestsToSendList->targetId=NULL;
requestsToSendList->weightSourceToTarget=NULL;
requestsToSendList->numberOfelements=0;
NEWARRAY(requestsToReceive,num_procs-1);///
requestsToReceive->targetId=NULL;
requestsToReceive->weightSourceToTarget=NULL;
/*end of allocate variables */
MPI_Barrier(MPI_COMM_WORLD);
MPI_Allgather(requestsToSendList,1,mpi_request_type,requestsToReceive,1,mpi_request_type,MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
stillWorking=(!isBucketEmptyFlag || !isHeavyEgdesProcessed);
free(requestsToSendList->targetId);
free(requestsToSendList->weightSourceToTarget);
free(requestsToReceive->weightSourceToTarget);
free(requestsToReceive->targetId);
free(requestsToSendList);
free(requestsToReceive);
/* deallocate space for dynamically allocated variables */
}else if(isBucketEmptyFlag && terminateFlag && !stillWorking){//all processes finished processing their bucket check if there is a bucket to process
//findnextNonEmptyBucket(BUCKETELEMENT *localBucketArray,int currentBucketIndex,int *localMinBuckInd,int localBucketSize){
findnextNonEmptyBucket(localBucketArray,currentBucketIndex,&localMinBuckInd,localBucketSize);
MPI_Allgather(&localMinBuckInd,1,MPI_INT,globalMinBuffer,1,MPI_INT,MPI_COMM_WORLD);
currentBucketIndex=findNextBucketIndex(globalMinBuffer,num_procs-1);
if(currentBucketIndex==0){
terminateFlag=1;
}else{
terminateFlag=0;
}
}
}
/*allocate variables */
REQUESTS *requestsToFinalArray;
REQUESTS *requestsToReceiveFinal;
NEWARRAY(requestsToFinalArray,1);
requestsToFinalArray->targetId=NULL;
requestsToFinalArray->weightSourceToTarget=NULL;
requestsToFinalArray->numberOfelements=0;
NEWARRAY(requestsToReceiveFinal,num_procs-1);///
requestsToReceiveFinal->targetId=NULL;
requestsToReceiveFinal->weightSourceToTarget=NULL;
/*end of allocate variables */
int tempCounter=0;
while(tempCounter<localBucketSize){
int tempInnerCounter=0;
while(tempInnerCounter<localBucketArray->numberOfNodes){
buildFinalArray(requestsToFinalArray+tempCounter,*(localBucketArray->nodeIds+tempInnerCounter),*(localBucketArray->tentDist+tempInnerCounter),*sizeOfGraph);
tempInnerCounter++;
}
tempCounter++;
}
MPI_Barrier(MPI_COMM_WORLD);
MPI_Gather( requestsToFinalArray, 1, mpi_request_type, requestsToReceiveFinal, 1, mpi_request_type, 0, MPI_COMM_WORLD);
if(my_rank==0){
tempCounter=0;
while( tempCounter < num_procs){
int tempInnerCounter=0;
while(tempInnerCounter<(requestsToFinalArray+tempCounter)->numberOfelements){
printf("NodeID:=%d---> distance:=%f",*(requestsToFinalArray+tempCounter)->targetId+tempInnerCounter,*(requestsToFinalArray+tempCounter)->weightSourceToTarget+tempInnerCounter);
tempInnerCounter++;
}
tempCounter++;
}
}
/* shut down MPI */
MPI_Barrier(MPI_COMM_WORLD);
MPI_Finalize();
return 0;
}
|
C
|
/*
* C Program to Implement Queue Data Structure using Linked List
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <queue.h>
#include <time.h>
/****************************************************
*
*
* FUNCTION DECLARATION
*
*
*****************************************************/
int frontelement();
void enq(int data);
void deq();
bool isEmpty();
void display();
void create();
void queuesize();
/****************************************************
*
*
* FUNCTION DEFINITION
*
*
*****************************************************/
/* Create an empty queue. Initialize the front and rear QueueNode Ptr to NULL*/
void queue_create(QueuePtr *anyQueueFront, QueuePtr *anyQueueRear)
{
*anyQueueFront = NULL;
*anyQueueRear = NULL;
//printf("create Queue\n");
}
/* Enqueing QueueNode to the rear pointer */
QueuePtr queue_enq(QueuePtr *anyQueueFront, QueuePtr *anyQueueRear, int taskID, QueueTask operation, int operand)
{
QueuePtr rear;
QueuePtr temp;
/*Initialize the local variables*/
rear = *anyQueueRear;
//queue is empty
if (rear == NULL)
{
rear = (QueuePtr)malloc(1*sizeof(QueueNode));
rear->next = NULL;
(rear->data).taskID = taskID;
(rear->data).operation = operation;
(rear->data).operand = operand;
*anyQueueRear = rear;
*anyQueueFront = *anyQueueRear;
return rear;
}
else
{
temp = (QueuePtr)malloc(1*sizeof(QueueNode));
(temp->data).taskID = taskID;
(temp->data).operation = operation;
(temp->data).operand = operand;
temp->next = NULL;
(*anyQueueRear)->next = temp;
*anyQueueRear = temp;
return temp;
}
}
/* Displaying the queue elements */
void queue_display(QueuePtr anyQueueFront, QueuePtr anyQueueRear)
{
QueuePtr front1 = NULL;
front1 = anyQueueFront;
QueuePtr rear1 = NULL;
rear1 = anyQueueRear;
/* queue is empty if both front and rear nodes are null */
if ((front1 == NULL) && (rear1 == NULL))
{
printf("Queue is empty\n");
return;
}
printf("Display Task ID Queue: \n");
/* while havent reached the rear node, print and traverse down the queue */
while (front1 != rear1)
{
//printf("TaskID: %ld", (front1->info).taskID);
queue_printTask(front1);
front1 = front1->next;
}
if (front1 == rear1){
//printf("%ld", (front1->info).taskID);
queue_printTask(front1);
}
printf("\nDone display\n");
}
/* Figure out which Operation to print for each QueueNode */
void queue_printTask(QueuePtr anyQueue){
QueueTask qt = (anyQueue->data).operation;
//int opNum = (int) qt;
printf("Main: Enqueue TaskID: %ld: ", (anyQueue->data).taskID);
switch (qt){
case TaskInsert:
printf("Insert %d\n", (anyQueue->data).operand);
break;
case TaskDelete:
printf("Delete %d\n", (anyQueue->data).operand);
break;
case TaskSearch:
printf("Search %d\n", (anyQueue->data).operand);
break;
case TaskPrint:
printf("Print\n");
break;
case TaskNull:
break;
default:
printf("fail\n");
}
}
/*
* Dequeing the queue, while doing that, pass in the value for the
* taskID, operation and operand by reference in the calling method
* also free up the QueueNode just dequeued from the queue.
* return true if succesfully dequeue a node from the queue
*/
bool queue_deq(QueuePtr *anyQueueFront, QueuePtr *anyQueueRear, int *taskID, QueueTask *operation, int *operand)
{
QueuePtr front1 = *anyQueueFront;
QueuePtr rear1 = *anyQueueRear;
/**/
/* check if front is null */
if (front1 == NULL)
{
printf("\n Error: Trying to display elements from empty queue\n");
return false;
}
else
if (front1->next != NULL) /* the queue still has next Node */
{
*taskID = front1->data.taskID;
*operation = front1->data.operation;
*operand = front1->data.operand;
front1 = *anyQueueFront;
*anyQueueFront = (*anyQueueFront)->next;
free(front1);
}
else /* reach end of the queue*/
{
*taskID = front1->data.taskID;
*operation = front1->data.operation;
*operand = front1->data.operand;
*anyQueueFront = NULL;
*anyQueueRear = NULL;
}
return true;
///////--------------------------------------------------------
/*
QueuePtr temp;
Bool retval;
if(!queue_isEmpty(*anyQueue)){
*taskID = anyQueue->front->TaskInfo.taskID;
*operation = anyQueue->front->TaskInfo.taskID;
*operand anyQueue->front->TaskInfo.operand;
temp = anyQueue->front;
anyQueue->front = anyQueue->front->next;
free(temp);
if(anyQueue->front == NULL)
anyQueue->rear = NULL;
retval = true;
}
return retval;
*/
///////--------------------------------------------------------
}
/* Display if queue is empty or not */
/* Function returns true if queue is Empty, false otherwise */
bool queue_isEmpty(QueuePtr anyQueueFront, QueuePtr anyQueueRear)
{
// only need to check to make sure front and rear QueueNode is NULL or not
if ((anyQueueFront == NULL) && (anyQueueRear == NULL)){
return true;
}
else{
return false;
}
}
/* Free up all the QueueNode in the Queue */
void queue_destroy(QueuePtr *anyQueueFront, QueuePtr *anyQueueRear){
int taskID; // long or int?
QueueTask operation;
int operand;
/* while the queue is not empty*/
while(!queue_isEmpty(*anyQueueFront, *anyQueueRear)){
/* dequeue one node at a time*/
queue_deq(anyQueueFront, anyQueueRear, &taskID, &operation, &operand);
}
}
|
C
|
/****************************************Copyright (c)****************************************************
**
** http://www.onecm.com
**
**------------------------------------File Info----------------------------------------------------------*/
/*
* @Description: 双向链表
* @version:
* @Author: Saber
* @Date: 2020-08-25 15:01:17
* @FilePath: \STM32F103C8_Demo\Core\OcmDataStream\ocm_list.h
* @LastEditors: Saber
* @LastEditTime: 2020-08-31 09:57:41
* @**
* **********************************************************************************************************
*/
#include "ocm_core.h"
/**
* initialize a list object
*/
#define OCM_LIST_OBJECT_INIT(object) \
{ \
&(object), &(object) \
}
/**
* list function defined
*/
ocm_inline void ocm_list_init(ocm_list_t *l)
{
l->next = l->prev = l;
}
ocm_inline void ocm_list_insert_after(ocm_list_t *l, ocm_list_t *n)
{
l->next->prev = n;
n->next = l->next;
l->next = n;
n->prev = l;
}
ocm_inline void ocm_list_insert_before(ocm_list_t *l, ocm_list_t *n)
{
l->prev->next = n;
n->prev = l->prev;
l->prev = n;
n->next = l;
}
// 从链表中移除,并没有释放占用的内存
ocm_inline void ocm_list_remove(ocm_list_t *n)
{
n->prev->next = n->next;
n->next->prev = n->prev;
n->next = n->prev = n;
}
ocm_inline void ocm_list_isempty(const ocm_list_t *l)
{
return l->next == l;
}
ocm_inline ocm_size_t ocm_list_len(const ocm_list_t *l)
{
ocm_size_t len = 0;
const ocm_list_t *p = l;
while (p->next != l)
{
p = p->next;
len++;
}
return len;
}
/**
* list function defined
*/
/**
* @brief get the struct for this entry
* @param node the entry point
* @param type the type of structure
* @param member the name of list in structure
*/
#define ocm_list_entry(node, type, member) \
ocm_container_of(node, type, member)
/**
* @brief: iterate over a list
* @param pos the rt_list_t * to use as a loop cursor
* @param head the head for your list
* @return {type}
*/
#define ocm_list_for_each(pos, head) \
for (pos = (head)->next; pos != (head); pos = pos->next)
/**
* @brief: get the first element from a list
* @param ptr the list head to take the element from.
* @param type the type of the struct this is embedded in.
* @param member the name of the list_struct within the struct.
* @return {type}
*/
#define ocm_list_first_entry(ptr, type, member) \
ocm_list_entry((ptr)->next, type, member)
|
C
|
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
string lowercase(string key);
bool test_alphabetic(string key);
bool test_unique(string key);
void make_cipher(string key);
int main(int argc, string argv[])
{
int error = 0;
string key = argv[1];
//if no key entered set error to 1
if (argc == 2 && strlen(key) == 26 && test_alphabetic(key) == true && test_unique(key) == true)
{
//make cypher text using lowercase version of key
make_cipher(lowercase(key));
}
else
{
//set error to 1
printf("Inputted key is invalid. Please choose a key");
printf(" with 26 unique alphabetic characters\n");
error = 1;
}
return error;
}
//function to find whether every character in a string is alphabetic
bool test_alphabetic(string key)
{
bool alpha = true;
for (int i = 0; i < strlen(key); i++)
{
int c = (int) key[i];
if (c < 65 || (c > 90 && c < 97) || c > 122)
{
//set alpha to false and break loop
//implies non-alphabetic character found
alpha = false;
break;
}
else
{
//do nothing
;
}
}
return alpha;
}
//function to find whether every character in a string is unique
bool test_unique(string key)
{
bool u = true;
for (int i = 0; i < strlen(key); i++)
{
int c = (int) key[i];
if (u == true)
{
for (int j = 0; j < strlen(key); j++)
{
if (j == i)
{
//skip if testing against self
;
}
else if (c == (int) key[j])
{
//set alpha to false and break loop
//implies non-unique character found
u = false;
break;
}
else
{
//do nothing
;
}
}
}
else
{
//if non-unique character found exit loop and return false
break;
}
}
return u;
}
//function to convert all uppercase to lower case for key as my convention
string lowercase(string key)
{
for (int i = 0; i < strlen(key); i++)
{
//find integer value of char (ASCII)
int c = (int) key[i];
//check if uppercase
if (c > 64 && c < 91)
{
//if uppercase make lowercase
c += 32;
key[i] = (char) c;
}
else
{
//if not do nothing
;
}
}
return key;
}
//function to turn text into cypher text
string cipher(string key, string text)
{
//iterate through text
for (int i = 0; i < strlen(text); i++)
{
//find text character
int c = (int) text[i];
//check if tect character is originally uppercase
if (c > 64 && c < 91)
{
//find poistion of text character in alphabet
int n = c - 64;
//find key character at that position
int k = (int) key[n - 1];
//if uppercase keep uppercase with key
text[i] = (char)(k - 32);
}
else if (c > 96 && c < 123)
{
//find poistion of text character in alphabet
int n = c - 96;
//find key character at that position
int k = (int) key[n - 1];
//if uppercase keep uppercase with key
text[i] = (char) k;
}
else
{
//do nothing
;
}
}
return text;
}
//function to get text from user and return cyphertext
void make_cipher(string key)
{
string plaintext = get_string("plaintext: ");
printf("ciphertext: %s\n", cipher(key, plaintext));
}
|
C
|
/*************************************************************************
> File Name: 4.2.c
> Author:
> Mail:
> Created Time: Tue 04 Apr 2017 05:04:24 AM PDT
************************************************************************/
#include<stdio.h>
#include<math.h>
int main()
{
int n = 0;
printf("请输入一个三位数:\n");
scanf("%d",&n);
int m = n/100;
int l = (n%100)/10;
int k = n % 10;
int a = m*m*m;
int b = l*l*l;
int c = k*k*k;
if(n == (a+b+c))
printf("该数是水仙花数!");
else
printf("不是水仙花数!");
return 0;
}
|
C
|
#include "winsock2.h"
#include "ws2tcpip.h"
#include <stdio.h>
#include <time.h>
#include <string.h>
#include "libs/strlib.h"
#include <sys/types.h>
#include <errno.h>
//#include <dir.h>
#include <direct.h>
#include <sys/stat.h>
#define PORT 6789
string getHeader(string filename, int length, int Ecode, string Estring, string protocol);
string getTime();
string getModTime(string filename);
string getMime(string filename);
int getFileSize(FILE * file);
string checkConGET(char *get_http);
string getHost();
void GetCurrentPath(char* buffer);
int main( int argc, const char* argv[]){
WSADATA wsaData;
WORD wVersionRequested = MAKEWORD( 2, 2 );
int err = WSAStartup( wVersionRequested, &wsaData );
struct sockaddr_in sin;
struct sockaddr_in clientAddr;
struct in_addr client_ip_addr;
struct stat sb;
string directoryName = "wwwroot";
FILE *in_file;
FILE *log_file;
int clientAddrLen, ch;
int ok, i, strLength, iResult;
string header, filename = "";
char cmdHTTP[80], filenameHTTP[80], protocolHTTP[80];
SOCKET s;
SOCKET s1;
char CurrentPath[_MAX_PATH];
string test = "";
string test2 = "";
int e;
//Directory stuff
e = stat(directoryName, &sb);
if (e != 0)
{
printf("The directory does not exist. Creating new directory...\n");
e = mkdir((char*)directoryName);
if (e != 0)
{
printf("Could not create a directory. Exiting...");
return 1;
}
}
//Initialize socket
s = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT);
sin.sin_addr.s_addr = INADDR_ANY;
bind(s, (struct sockaddr *)&sin, sizeof(sin));
if( listen(s,SOMAXCONN)==SOCKET_ERROR){
printf("\n\nERROR\n\nFailure to listen. Please restart the server.\n\n");
getchar();
return 1;
}
// Hämtar våran nuvarande working directory. För att använda en mapp så måste vi
// ha den absoluta sökvägen eller liknande.
GetCurrentPath(CurrentPath);
test = Concat (CurrentPath,"\\wwwroot\\" );
printf("PATH: %s\n", test);
printf("Server started. Waiting for connections on %s at port %d\n\n", getHost(),PORT);
clientAddrLen = sizeof(clientAddr);
while(TRUE){
//Skapar loggfil samt felhantering
char in_buf[2048];
test2 = Concat(test,"webserver_log.txt");
log_file = fopen(test2, "a+");
if (log_file==NULL){
printf("You must create a wwwroot folder. Restart the server.\n");
getchar();
return 0;
}
//Börjar vänta på klienter.
s1 = accept(s, (struct sockaddr *)&clientAddr, &clientAddrLen);
recv(s1, in_buf, sizeof(in_buf), 0);
printf("\nRecieved from browser: \n%s",in_buf);
// Fixar till clientents ipadress från byte>ip-struktur
memcpy(&client_ip_addr, &clientAddr.sin_addr.s_addr, 4);
printf("\nAccept completed (IP address of client = %s port = %d) \n",
inet_ntoa(client_ip_addr), ntohs(clientAddr.sin_port));
ok = sscanf(in_buf,"%s %s %s",cmdHTTP,filenameHTTP,protocolHTTP);
//printf("Recived: %s %s %s\n",cmdHTTP,filenameHTTP,protocolHTTP);
// Tar bort '\' från filnamnet
strLength = strlen(filenameHTTP);
for(i = 1; i <= strLength+1; i++)
filenameHTTP[i-1] = filenameHTTP[i];
test2 = Concat(test,filenameHTTP);
// Öppnar en stream till filen genom readbyte-metoden.
in_file = fopen(test2, "rb");
// Om filen finns eller en ogiltig mime typ så skickar den en 404 ERROR, annars så går den vidare
// med att skicka filen.
if (in_file!=NULL && getMime(test2) != NULL){
//Conditional GET variabler initeras
char modTimeMonth[10], modTimeTime[10], modTimeWDay[10];
char conTimeMonth[10], conTimeTime[10], conTimeWDay[10];
int modTimeYear, modTimeDay, conTimeYear, conTimeDay;
//Läser in Last-Modified
sscanf(getModTime(test2),"%s %d %s %d %s",modTimeWDay,&modTimeDay,modTimeMonth,&modTimeYear,modTimeTime);
printf("Last-Modified: %s %d %d %s\n\n",modTimeMonth,modTimeDay,modTimeYear,modTimeTime);
//Läser in If-Modified-Since
if(checkConGET(in_buf) != ""){
sscanf(checkConGET(in_buf),"%s %d %s %d %s",conTimeWDay,&conTimeDay,conTimeMonth,&conTimeYear,conTimeTime);
printf("If-Modified-Since: %s %d %d %s\n\n",conTimeMonth,conTimeDay,conTimeYear,conTimeTime);
//Kollar om If-Modified-Since är nyare än Last-Modified
if (conTimeYear >= modTimeYear && strcmp(conTimeMonth, modTimeMonth)>=0 && conTimeDay >= modTimeDay && strcmp(conTimeTime, modTimeTime)>=0){
printf("Reply: 304 NOT MODIFIED, Sending only the header.");
header = getHeader(test2, 0, 304, "Not Modified", protocolHTTP);
send(s1,header,strlen(header),0);
}
}
if(checkConGET(in_buf) == ""){
printf("No conditional GET found..\n");
//Skickar normal header.
header = getHeader(test2, getFileSize(in_file), 200, "OK", protocolHTTP);
printf("Sending header: \n%s",header);
send(s1,header,strlen(header),0);
printf("Reply: 200 OK, sending %s which is %d bytes long.\n",filenameHTTP, getFileSize(in_file));
//Skickar filen
while(!feof(in_file)) {
char buffer[256];
int len = fread(buffer,1,256,in_file);
send(s1,buffer,len,0);
}
}
fclose(in_file);
}
else {
send(s1,"HTTP/1.1 404 Not Found\nConnection: close\n\n<html><body><h1>ERROR 404</h1></br>FILE NOT FOUND.</body></html>",strlen("HTTP/1.1 404 Not Found\nConnection: close\n\n<html><body><h1>ERROR 404</h1></br>FILE NOT FOUND.</body></html>"),0);
printf("Reply: 404 NOT FOUND, Requested file %s not found.\n",filenameHTTP);
}
fprintf(log_file,"Client %s on port %d sent %s /%s %s \n",inet_ntoa(client_ip_addr), ntohs(clientAddr.sin_port),cmdHTTP,filenameHTTP,protocolHTTP);
fprintf(log_file,"Server %s on port %d answered with \n%s %s \n",getHost(),PORT,header,filenameHTTP);
fprintf(log_file,"\n-----------------------------------------------------------\n");
fclose(log_file);
closesocket(s1);
}
closesocket(s);
WSACleanup();
getchar();
}
string getHeader(string filename, int length, int Ecode, string Estring, string protocol){
string header = "";
header = Concat(header, protocol);
header = Concat(header, Concat(" ",IntegerToString(Ecode)));
header = Concat(header, Concat(" ",Estring));
header = Concat(header, Concat("\nDate: ",getTime()));
header = Concat(header, "\nServer: OscKenWEB/1.0");
header = Concat(header, Concat("\nLast-Modified: ", getModTime(filename)));
header = Concat(header, Concat("\nContent-Length: ", IntegerToString(length+4)));
header = Concat(header, "\nConnection: close\n");
header = Concat(header, Concat("Content-Type: ", getMime(filename)));
header = Concat(header, "\n\n");
//printf("HEADER\n%s\n", header);
return header;
}
string getTime(){
time_t now;
char timebuf[100];
string time1 = "";
int i;
now = time(NULL);
strftime(timebuf ,30,"%a, %d %b %Y %X GMT",gmtime(&now));
for (i = 0; i<30;i++)
time1 = Concat(time1, CharToString(timebuf[i]));
return time1 ;
}
string getModTime(string filename){
char timeStr[100];
string time1 = "";
int i;
struct stat test;
if (!stat(filename, &test))
{
strftime(timeStr, 30, "%a, %d %b %Y %X GMT", localtime( &test.st_mtime));
//printf("\nLast modified date and time = %s\n", timeStr);
}
else
{
printf("error getting mtime\n");
return NULL;
}
for (i = 0; i<30;i++)
time1 = Concat(time1, CharToString(timeStr[i]));
return time1;
}
string getMime(string name){
string dot = strrchr(name, '.');
if (dot==NULL) return NULL;
if (strcmp(dot, ".html") == 0 || strcmp(dot, ".htm") == 0) return "text/html";
if (strcmp(dot, ".jpg") == 0 || strcmp(dot, ".jpeg") == 0) return "image/jpeg";
if (strcmp(dot, ".gif") == 0) return "image/gif";
if (strcmp(dot, ".png") == 0) return "image/png";
if (strcmp(dot, ".css") == 0) return "text/css";
if (strcmp(dot, ".au") == 0) return "audio/basic";
if (strcmp(dot, ".wav") == 0) return "audio/wav";
if (strcmp(dot, ".avi") == 0) return "video/x-msvideo";
if (strcmp(dot, ".mpeg") == 0 || strcmp(dot, ".mpg") == 0) return "video/mpeg";
if (strcmp(dot, ".mp3") == 0) return "audio/mpeg";
return NULL;
}
int getFileSize(FILE * file)
{
int fileSize = 0;
fseek (file , 0 , SEEK_END);
fileSize = ftell (file);
rewind (file);
return fileSize;
}
string checkConGET(char *in_buf){
string HTTPinput = in_buf;
int i = FindString("If-Modified-Since:",HTTPinput,0);
//printf("\nINPUT:\n\n%s \n\n\n",HTTPinput);
if(i != -1) {
string value = SubString(HTTPinput, i+18,i+18+30);
//printf("I got a conditional GET with the date: %s..\n",value);
return value;
}
else {
//printf("No conditional GET found..\n");
}
return "";
}
// Hämtar datorns WAN ipadress.
string getHost(){
WSADATA wsaData;
WORD wVersionRequested = MAKEWORD( 2, 2 );
int err = WSAStartup( wVersionRequested, &wsaData );
char ac[80];
struct in_addr addr;
struct hostent *phe;
if (gethostname(ac, sizeof(ac)) == SOCKET_ERROR) {
return "ERROR";
}
phe = gethostbyname(ac);
memcpy(&addr, phe->h_addr_list[0], sizeof(struct in_addr));
return inet_ntoa(addr);
}
void GetCurrentPath(char* buffer)
{
getcwd(buffer, _MAX_PATH);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "csapp.h"
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <pthread.h>
#include <unistd.h>
/* Recommended max cache and object sizes */
#define MAX_CACHE_SIZE 1049000
#define MAX_OBJECT_SIZE 102400
#define MAX_LEN 2000
/* You won't lose style points for including this long line in your code */
static const char *user_agent_hdr = "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:10.0.3) Gecko/20120305 Firefox/10.0.3\r\n";
static char *http_version_hdr = "HTTP/1.0";
int sd;
struct sockaddr_in addr;
struct http_header;
struct http_header{
char* name;
char* value;
struct http_header* next;
};
typedef struct http_header http_header;
typedef struct{
char* type;
char* url;
char* version;
http_header* next;
} http_request;
http_request* parseReq(char* buffer){
printf("%s\n", "PARSING REQ");
http_request* request = malloc(sizeof(http_request));
char* buffer_rest = buffer;
char* line = strtok_r(strdup(buffer), "\r\n", &buffer_rest);
char* line_rest = line;
char* type = strtok_r(strdup(line), " ", &line_rest);
request->type = type;//TODO need to malloc?
char* url = strtok_r(NULL, " ", &line_rest);
request->url = url;
char* version = strtok_r(NULL, " ", &line_rest);
request->version = version;
http_header* current = NULL;
while (line = strtok_r(NULL, "\r\n", &buffer_rest)){
line_rest = line;
char* name = strtok_r(strdup(line), ": ", &line_rest);
//printf("%s:%s\n", name, line_rest);
http_header* header = malloc(sizeof(http_header));
header->name = name;
header->value = line_rest;//TODO malloc string?
header->next = NULL;
if (current == NULL){
request->next = header;
current = header;
}
else{
current->next = header;
current = header;
}
//printf("%s\n", line);
}
printf("%s\n", "PARSED");
return request;
}
void add_header(http_request* request, char* name, char* value){
//TODO does it matter the order of headers?
http_header* new_header = malloc(sizeof(http_header));
new_header->name = name;
new_header->value = value;
http_header* next = request->next;
new_header->next = next;
request->next = new_header;
}
void remove_header(http_request* request, char* name){
http_header* past = NULL;
http_header* current = request->next;
while (current){
if (strcmp(current->name, name) == 0){
http_header* tmp = current;
current = current->next;
if (past){
past->next = current;
}
else{
request->next = current;
}
free(tmp);
}
else{
past = current;
current = current->next;
}
}
}
char* get_header(http_request* request, char* name){
http_header* current = request->next;
while (current){
if (strcmp(current->name, name) == 0){
return current->value;
}
current = current->next;
}
return NULL;
}
void replace_user_agent(http_request* request){
remove_header(request, "User-Agent");
add_header(request, "User-Agent", user_agent_hdr);
}
char* get_host_from_url(char* url){
char* url_rest = url;
char* host = strtok_r(url, "/", &url_rest);
printf("%s\n", "HOSTS");
printf("%s\n", url);
printf("%s\n", host);
printf("%s\n", url_rest);
return host;
}
char* get_content_from_url(char* url){
char* url_rest = url;
char* host = strtok_r(url, "//", &url_rest);
host = strtok_r(NULL, "/", &url_rest);
char* content = malloc(sizeof(url));
strcpy(content, "/");
strcat(content, url_rest);
return content;
}
void switchRequest(http_request* request){
request->version = http_version_hdr;
replace_user_agent(request);
remove_header(request, "Connection");
add_header(request, "Connection", "close");
remove_header(request, "Proxy-Connection");
add_header(request, "Proxy-Connection", "close");
if (!get_header(request, "Host")){
char* host = get_host_from_url(request->url);
add_header(request, "Host", host);
}
if (request->url[0] != '/'){
char* content = get_content_from_url(request->url);
request->url = content;
}
}
char* req_to_str(http_request* request){
//TODO need to malloc?
char* buffer = malloc(MAX_OBJECT_SIZE);
strcpy(buffer, request->type);
strcat(buffer, " ");
strcat(buffer, request->url);
strcat(buffer, " ");
strcat(buffer, request->version);
strcat(buffer, "\r\n");
http_header* current = request->next;
while(current){
strcat(buffer, current->name);
strcat(buffer, ":");//TODO add space?
strcat(buffer, current->value);
strcat(buffer, "\r\n");
current = current->next;
}
strcat(buffer, "\r\n");
return buffer;//TODO free
}
char *trimwhitespace(char *str){
char *end;
// Trim leading space
while(isspace((unsigned char)*str)) str++;
if(*str == 0) // if it's all spaces
return str;
// Trim trailing space
end = str + strlen(str) - 1;
while(end > str && isspace((unsigned char)*end)) end--;
// Add new ending char
end[1] = '\0';
return str;
}
char* makeRequest(char* host, char* request){
char* host_rest = host;
char* server = strtok_r(host, ":", &host_rest);
char* port = NULL;
if (host_rest != NULL){
port = host_rest;
}
server = trimwhitespace(server);
port = trimwhitespace(port);
rio_t rio;
int request_sock = Open_clientfd(server, port);
char* response = malloc(MAX_OBJECT_SIZE);
memset(response, 0, sizeof(response));
Rio_readinitb(&rio, request_sock);
Rio_writen(request_sock, request, strlen(request));
//send(request_sock, request, strlen(request), 0);
char* response_line[MAXLINE];
int header_size = 0;
//Read headers
while (Rio_readlineb(&rio, response_line, MAXLINE) > 0){
if (strcmp(response_line, "\r\n") == 0){
break;
}
header_size += strlen(response_line);
//printf("{%s}", response_line);
strcat(response, response_line);
}
strcat(response, "\r\n");//TODO need this?
header_size += 2;
//printf("\nBEGIN<%s>END\n", response);
//Read body
char body[MAX_OBJECT_SIZE];
Rio_readnb(&rio, body, (MAX_OBJECT_SIZE - header_size));
memcpy(response+header_size, body, (MAX_OBJECT_SIZE - header_size));
//recv(request_sock, response, MAX_OBJECT_SIZE, 0);
close(request_sock);
return response;
}
void *handle_connection( void *fdp){ //STUB. TODO finish
printf("%s\n", "MADE THREAD");
int fd = *((int *)fdp);
Pthread_detach(Pthread_self());
Free(fdp);
///////////copied code to read and write
char* buffer = Malloc(MAX_OBJECT_SIZE);
recv(fd, buffer, MAX_OBJECT_SIZE, 0);
printf("Buffer %s\n", buffer);
http_request* request = parseReq(buffer);
if (request == NULL){
printf("%s\n", "Invalid HTTP request");
close(fd);
exit(-1);
}
switchRequest(request);
char* reqBuffer = req_to_str(request);
char* host = get_header(request, "Host");
char* response = makeRequest(host, reqBuffer); //TODO
free(reqBuffer);
//send response
Rio_writen(fd, response, MAX_OBJECT_SIZE);
//free buffer
free(buffer);
close(fd);
free(request);
return 0;
}
int main(int argc, char** argv){
printf("%s\n", "Begin main");
int listenfd, *connfdp;
socklen_t clientlen;
struct sockaddr_storage clientaddr;
pthread_t tid;
//Check args
if (argc < 2){
printf("Wrong args: %s \n", argv[0]);
exit(0);
}
//run proxy
printf("%s\n", "RUN PROXYHh");
listenfd = open_listenfd(argv[1]);
while (1) {
clientlen=sizeof(struct sockaddr_storage);
connfdp = malloc(sizeof(int)); //line:conc:echoservert:beginmalloc
*connfdp = accept(listenfd, (SA *) &clientaddr, &clientlen); //line:conc:echoservert:endmalloc
pthread_create(&tid, NULL, handle_connection, connfdp);
}
return 0;
}
int at_end( char *pointer ) {
printf("%s\n", "END FUNCT");
return( pointer[0] == '\r' &&
pointer[3] == '\n' );
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* print_arg.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: oboualla <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/11/20 07:24:50 by oboualla #+# #+# */
/* Updated: 2020/02/02 22:27:30 by zamazzal ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static uint get_type(uint type)
{
uint typ2;
if (!type)
return (0);
typ2 = 1;
while (--type)
typ2 *= 2;
return (typ2);
}
void print_type_lower(uint type_lower, uint flag, va_list ap)
{
if (print_type_lower1(type_lower, flag, ap))
return ;
if (print_type_lower2(type_lower, flag, ap))
return ;
if (print_type_lower3(type_lower, flag, ap))
return ;
if (print_point_adress(type_lower, flag, ap))
return ;
}
void print_type_upper(uint type_upper, uint flag, va_list ap)
{
if (print_type_upper1(type_upper, flag, ap))
return ;
}
size_t get_conver(uint flag)
{
size_t i;
i = 1;
if ((flag & LLINT) || (flag & SCHR))
i += 2;
if ((flag & SINT) || (flag & LINT))
i += 1;
return (i);
}
int search_format(char *format, va_list ap)
{
uint type_lower;
uint type_upper;
uint flag;
char search;
flag = 0;
type_lower = 0;
type_upper = 0;
flag = get_flag(format);
search = format[get_conver(flag)];
if (ft_islower(search))
type_lower = search - 96;
else if (ft_isupper(search))
type_upper = search - 64;
type_lower = get_type(type_lower);
type_upper = get_type(type_upper);
if (type_lower)
print_type_lower(type_lower, flag, ap);
else if (type_upper)
print_type_upper(type_upper, flag, ap);
return (get_conver(flag) + 1);
}
|
C
|
#include <stdio.h>
#define IN 1
#define OUT 0
int main(int argc, char const *argv[]){
int c, nw, state;
nw = 0;
state = OUT;
while((c = getchar()) != EOF){
if(c == '\n' || c == ' ' || c == '\t'){
printf("\n");
} else{
printf("%c", c);
}
}
}
|
C
|
/*
** init_server_exchange.c for in /home/renard_e/2/systeme_unix_reseaux/PSU_2016_myftp/src
**
** Made by Gregoire Renard
** Login <[email protected]>
**
** Started on Mon May 15 16:08:44 2017 Gregoire Renard
** Last update Wed May 17 09:10:17 2017 Gregoire Renard
*/
#include "myftp.h"
static void init_exchange(t_client * const client, int port)
{
if (port == -1)
client->exchange.s_in_server.sin_port = 0;
else
client->exchange.s_in_server.sin_port = htons(port);
client->exchange.s_in_server.sin_family = AF_INET;
client->exchange.s_in_server.sin_addr.s_addr = INADDR_ANY;
}
int init_server_exchange(t_client * const client,
int port)
{
client->exchange.len = sizeof(client->exchange.s_in_server);
if ((client->exchange.pe = getprotobyname("TCP")) == NULL)
return (ERROR);
if ((client->exchange.fd_server =
socket(AF_INET, SOCK_STREAM, client->exchange.pe->p_proto)) == -1)
return (ERROR);
init_exchange(client, port);
if (((bind(client->exchange.fd_server,
(const struct sockaddr *)&client->exchange.s_in_server,
sizeof(client->exchange.s_in_server))) == -1)
|| ((listen(client->exchange.fd_server, MAX_QUEUE)) == -1)
|| ((getsockname(client->exchange.fd_server,
(struct sockaddr *)&client->exchange.s_in_server,
&client->exchange.len)) == -1))
{
close(client->exchange.fd_server);
return (ERROR);
}
if (port == -1)
client->exchange.port = ntohs(client->exchange.s_in_server.sin_port);
return (SUCCESS);
}
|
C
|
/*
FUNCTION
<<strncasecmp>>---case-insensitive character string compare
INDEX
strncasecmp
SYNOPSIS
#include <strings.h>
int strncasecmp(const char *<[a]>, const char * <[b]>, size_t <[length]>);
DESCRIPTION
<<strncasecmp>> compares up to <[length]> characters
from the string at <[a]> to the string at <[b]> in a
case-insensitive manner.
RETURNS
If <<*<[a]>>> sorts lexicographically after <<*<[b]>>> (after
both are converted to lowercase), <<strncasecmp>> returns a
number greater than zero. If the two strings are equivalent,
<<strncasecmp>> returns zero. If <<*<[a]>>> sorts
lexicographically before <<*<[b]>>>, <<strncasecmp>> returns a
number less than zero.
PORTABILITY
<<strncasecmp>> is in the Berkeley Software Distribution.
<<strncasecmp>> requires no supporting OS subroutines. It uses
tolower() from elsewhere in this library.
QUICKREF
strncasecmp
*/
#include <strings.h>
#include <ctype.h>
int
strncasecmp (const char *s1,
const char *s2,
size_t n)
{
int d = 0;
for ( ; n != 0; n--)
{
const int c1 = tolower(*s1++);
const int c2 = tolower(*s2++);
if (((d = c1 - c2) != 0) || (c2 == '\0'))
break;
}
return d;
}
|
C
|
/*
* Author: Chengyue Gong, Zixuan Li, Wentao Wang
* Orgnization: Washington University in St. Louis
*/
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int main()
{
printf ("getuid returned: %d\n", getuid());
int return_val = setuid(0);
printf ("setuid returned: %d\n", setuid(0));
if( return_val != 0 ) printf("Error: setuid failed! Reason: %s\n", strerror(errno));
return 0;
}
|
C
|
#include "text.h"
#include "mylib.h"
void drawChar(int x, int y, char ch, unsigned short color)
{
for(int down = 0; down < 8; down++)
{
for(int across = 0; across < 6; across++)
{
if(fontdata_6x8[OFFSET(across, down, 6)+ch*48])
{
setPixel(x + across, y + down, color);
}
}
}
}
/*
*
* I didn't code this in class but I will go over it next lecture
*
* You can call it like this:
*
* drawString(10, 10, "Hello!", YELLOW);
*
* or like this:
*
* char *message = "This is a message.";
* drawString(20, 5, message, RED);
*
* or like this:
*
* char buffer[41] = "This is a char array!";
* drawString(30, 5, buffer, GREEN);
*
*/
void drawString(int x, int y, char *str, unsigned short color)
{
while(*str)
{
drawChar(x, y, *str++, color);
x +=6;
}
}
|
C
|
//ݸʽ
#include<stdio.h>
int main()
{
int a;
char c;
double m,n;
scanf("%lf %d %c %lf",&m,&a,&c,&n);
printf("%c %d %.2lf %.2lf",c,a,m,n);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int numero, i;
int cadenaNumero[6];
for( i = 0 ; i < 6 ; i++ ) {
if(!isdigit(cadenaNumero[i])) {
printf("Ingrese un numero: ");
}
}
numero = atoi(cadenaNumero);
printf("%d" , &numero);
return 0;
}
|
C
|
#include "holberton.h"
/**
* create_file - creates a file of variable name
* (permissions should be rw-------)
* @filename: name of created file
* @text_content: text to be written into file
*
* Return: 1 on SUCCESS
* -1 on FAILURE
*/
int create_file(const char *filename, char *text_content)
{
int fd, wr, i, textlen = 0;
if (text_content == NULL)
textlen = 0;
else
{
for (i = 0; text_content[i]; ++i, ++textlen)
;
}
fd = open(filename, O_CREAT | O_TRUNC | O_WRONLY, 0600);
if (fd == -1)
return (-1);
wr = write(fd, text_content, textlen);
if (wr == -1)
return (-1);
close(fd);
return (1);
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(void) {
int a;
printf("何か整数を入力してください\n");
scanf("%d", &a);
a = a % 3;
switch (a) {
case 0: printf("余りは0です。 %d\n", a); break;
case 1: printf("余りは1です。 %d\n", a); break;
case 2: printf("余りは2です。 %d\n", a); break;
default: printf("その値は無効です。 %d\n", a);
}
return 0;
}
|
C
|
// Print prime radicals of numbers.
// (c) Wendy Rhodes
#include <stdio.h>
#include <stdlib.h>
int rad(int wow)
{
int prod = 1;
int baz = 2;
int before;
while (wow > 1) {
before = wow;
while (wow % baz == 0) {
wow = wow/baz; // factor!
}
if (wow < before) prod = prod * baz; // product!
baz += 1;
}
return prod;
}
int main()
{
int n;
int rd;
int count;
count = fscanf(stdin,"%d",&n);
while (count == 1) {
rd = rad(n); // do it!
printf("%d\n",rd);
count = fscanf(stdin,"%d",&n);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef int Data;
typedef enum dir { no, lft, rgt } dir;
enum trv { pre = 1, in = 2, post = 3 };
typedef struct _node
{
Data data;
int id;
struct _node* left;
struct _node* right;
} Node;
typedef struct _binarytree
{
Node* root;
Node* tempLeft;
Node* tempRight;
Node* tempParent;
int n;
} Tree;
bool initTree(Tree* tr)
{
tr->root = tr->tempLeft = tr->tempParent = tr->tempRight = NULL;
tr->n = 0;
return true;
}
bool isInternal(const Node* node)
{
return node->left || node->right ? true : false;
}
bool isExternal(const Node* node)
{
return !node->left && !node->right ? true : false;
}
Node* createNode(const Data d, const int id)
{
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) return NULL;
newNode->left = newNode->right = NULL;
newNode->data = d;
newNode->id = id;
return newNode;
}
bool insertNode(Tree* tr, const Data d, const int id, const dir dr)
{
Node* node = createNode(d, id);
if (!node) return false;
tr->n++;
if (dr == lft && tr->tempLeft || dr == rgt && tr->tempRight || dr == no || tr->tempRight && tr->tempLeft) // Make parent node
{
node->left = tr->tempLeft;
node->right = tr->tempRight;
tr->tempLeft = tr->tempRight = 0;
if (dr == lft) tr->tempLeft = node;
else if (dr == rgt) tr->tempRight = node;
else tr->root = tr->tempParent = node;
}
else if (dr == lft && !tr->tempLeft) // for external node
tr->tempLeft = node;
else if (dr == rgt && !tr->tempRight)
tr->tempRight = node;
if ((!tr->root || isInternal(node)) && !tr->tempParent)
tr->root = node;
return true;
}
void postorderTrv(Node* pos, const int id, bool prt, int* tot) // Post Order Traversal is used to calculate total usage
{
if (isInternal(pos) && pos->left)
postorderTrv(pos->left, id, false, tot);
if (isInternal(pos) && pos->right)
postorderTrv(pos->right, id, false, tot);
if (pos->id == id || prt)
{
if (isInternal(pos) && pos->left)
postorderTrv(pos->left, id, true, tot);
if (isInternal(pos) && pos->right)
postorderTrv(pos->right, id, true, tot);
*tot += pos->data;
}
return;
}
void freeAll(Node* pos)
{
if (isInternal(pos) && pos->left)
freeAll(pos->left);
if (isInternal(pos) && pos->right)
freeAll(pos->right);
free(pos);
}
void finder(Tree* tr, const int id)
{
if (id > 8 || id < 1)
{
printf("-1\n");
return;
}
int tot = 0;
postorderTrv(tr->root, id, false, &tot);
printf("%d\n", tot);
}
int main(void)
{
Tree t;
int id;
initTree(&t);
insertNode(&t, 80, 8, rgt);
insertNode(&t, 130, 7, lft);
insertNode(&t, 120, 6, rgt);
insertNode(&t, 50, 3, rgt);
insertNode(&t, 20, 1, no);
insertNode(&t, 90, 5, rgt);
insertNode(&t, 70, 4, lft);
insertNode(&t, 30, 2, lft);
t.root->left = t.tempLeft;
scanf("%d", &id);
finder(&t, id);
freeAll(t.root);
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2019
** my.h
** File description:
**
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <unistd.h>
#ifndef MY_H
#define MY_H
typedef struct flag
{
char c;
int (*f)(va_list*);
} flag;
int my_putchar(int c);
int my_put_nbr(int nb);
int my_putstr(char const *str);
int my_strlen(char const *str);
int my_getnbr(char const *str);
int my_printf(char *str, ...);
int my_put_nbr_abs(int nb);
int my_putnbr_base(int nbr, char const *base);
int my_putstr_wrap(va_list *arg);
int my_putchar_wrap(va_list *arg);
int my_putnbr_b_wrap(va_list *arg);
int my_putnbr_o_wrap(va_list *arg);
int my_putnbr_x_wrap(va_list *arg);
int my_putnbr_big_x_wrap(va_list *arg);
int my_put_nbr_wrap(va_list *arg);
int my_put_nbr_abs_wrap(va_list *arg);
int my_put_percent(va_list *arg);
#endif
|
C
|
#include <stdio.h>
#include<stdio.h>
struct priority_preemptive
{
char pn;
int at, bt, ct, wt, tat, priority;
int s;
}pq[10];
int limit;
void at_Sorting()
{
struct priority_preemptive temp;
int i, j;
for(i = 0; i < limit - 1; i++)
{
for(j = i + 1; j < limit; j++)
{
if(pq[i].at > pq[j].at)
{
temp = pq[i];
pq[i] = pq[j];
pq[j] = temp;
}
}
}
}
int main()
{
char c; int x;
do{
printf("1.FCFS\n2.PRIORITY\n3.SJF\n4.ROUND ROBIN\n5.PRE-EMPTIVE PRIORITY\n6.SRTF\n");
scanf("%d",&x);
switch(x)
{
case 1:
{
int at[10],bt[10],gnc[10],wt[10],tat[10];
float awt=0;
float atat=0;
int n,i,j;
for(i=0;i<10;i++)
{
at[i]=0;
bt[i]=0;
gnc[i]=0;
tat[i]=0;
wt[i]=0;
}
printf("enter the number of process that you want to proceed \n");
scanf("%d",&n);
printf("enter all the process \n");
int p[10];
for(i=0;i<n;i++)
scanf("%d",&p[i]);
printf("enter all the arrival time \n");
for(i=0;i<n;i++)
{
scanf("%d",&at[i]);
}
printf("enter all the brust time \n");
for(i=0;i<n;i++)
{
scanf("%d",&bt[i]);
}
gnc[0]=0;
for(i=0;i<10;i++)
gnc[i+1]=gnc[i]+bt[i];
for(i=0;i<n;i++)
{
wt[i]=gnc[i]-at[i];
tat[i]=gnc[i+1]-at[i];
awt=awt+wt[i];
atat=atat+tat[i];
}
awt =awt/n;
atat=atat/n;
printf("\n\tprocess\tarrival time\tbrust time\twaiting time\tturn arround time\n");
for(i=0;i<n;i++)
{
printf("\tp%d\t\t%d\t\t%d\t\t%d\t\t%d\n",i,at[i],bt[i],wt[i],tat[i]);
}
printf("the average waiting time is %f\n",awt);
printf("the average turn around time is %f\n",atat);
break;
}
case 2:
{
int bt[20],prty[20],wt[20],tat[20];
int n,i,j,pos,temp;
float awt,atat,total=0;
printf("Enter Total Number of Process:");
scanf("%d",&n);
printf("enter all the process \n");
int p[10];
for(i=0;i<n;i++)
scanf("%d",&p[i]);
printf("enter all the brust time \n");
for(i=0;i<n;i++)
{
scanf("%d",&bt[i]);
}
printf("enter all the priority time \n");
for(i=0;i<n;i++)
{
scanf("%d",&prty[i]);
}
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(prty[j]<prty[pos])
pos=j;
}
temp=prty[i];
prty[i]=prty[pos];
prty[pos]=temp;
temp=bt[i];
bt[i]=bt[pos];
bt[pos]=temp;
temp=p[i];
p[i]=p[pos];
p[pos]=temp;
}
wt[0]=0;
for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];
total+=wt[i];
}
awt=total/n;
total=0;
printf("\nProcess\t Burst Time \tWaiting Time\tTurnaround Time");
for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i];
total+=tat[i];
printf("\nP[%d]\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}
atat=total/n;
printf("\n\nthe average waiting time=%f",awt);
printf("\naverage turnaround time=%f\n",atat);
break;
}
case 3:{
int bt[20],wt[20],tat[20],i,j,n,pos,temp;
float awt,atat,total=0;
printf("Enter number of process:");
scanf("%d",&n);
printf("enter all the process \n");
int p[10];
for(i=0;i<n;i++)
scanf("%d",&p[i]);
printf("\nEnter Burst Time:\n");
for(i=0;i<n;i++)
{
scanf("%d",&bt[i]);
}
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(bt[j]<bt[pos])
pos=j;
}
temp=bt[i];
bt[i]=bt[pos];
bt[pos]=temp;
temp=p[i];
p[i]=p[pos];
p[pos]=temp;
}
wt[0]=0;
for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];
total+=wt[i];
}
awt=total/n;
total=0;
printf("\nProcess\t Burst Time \tWaiting Time\tTurnaround Time");
for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i];
total+=tat[i];
printf("\np[%d]\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}
atat=total/n;
printf("\n\nAverage Waiting Time=%f",awt);
printf("\nAverage Turnaround Time=%f\n",atat);
break;
}
case 4:
{
int i,j,n,time,remain,d=0,qt;
int wt=0,tat=0,at[10],bt[10],t[10];
printf("Enter Total Process:\t ");
scanf("%d",&n);
remain=n;
for(i=0;i<n;i++)
{
printf("Enter Arrival Time and Burst Time for Process Process Number %d :",i+1);
scanf("%d",&at[i]);
scanf("%d",&bt[i]);
t[i]=bt[i];
}
printf("Enter Time Quantum:\t");
scanf("%d",&qt);
printf("\n\nProcess\t|Turnaround Time|Waiting Time\n\n");
for(time=0,i=0;remain!=0;)
{
if(t[i]<=qt && t[i]>0)
{
time+=t[i];
t[i]=0;
d=1;
}
else if(t[i]>0)
{
t[i]-=qt;
time+=qt;
}
if(t[i]==0 && d==1)
{
remain--;
printf("P[%d]\t|\t%d\t|\t%d\n",i+1,time-at[i],time-at[i]-bt[i]);
wt+=time-at[i]-bt[i];
tat+=time-at[i];
d=0;
}
if(i==n-1)
i=0;
else if(at[i+1]<=time)
i++;
else
i=0;
}
printf("\nAverage Waiting Time= %f\n",wt*1.0/n);
printf("Avg Turnaround Time = %f",tat*1.0/n);
break;
}
case 5:
{
int i, time = 0, bt = 0, largest;
char c;
float wait_time = 0, tat = 0, average_wt, average_tat;
printf("\nEnter Total Number of Processes:\t");
scanf("%d", &limit);
for(i = 0, c = 'A'; i < limit; i++, c++)
{
pq[i].pn = c;
printf("\nEnter Details For Process[%C]:\n", pq[i].pn);
printf("Enter Arrival Time:\t");
scanf("%d", &pq[i].at );
printf("Enter Burst Time:\t");
scanf("%d", &pq[i].bt);
printf("Enter Priority:\t");
scanf("%d", &pq[i].priority);
pq[i].s = 0;
bt = bt + pq[i].bt;
}
at_Sorting();
pq[9].priority = -9999;
printf("\nProcess Name\tArrival Time\tBurst Time\tPriority\tWaiting Time");
for(time = pq[0].at; time < bt;)
{
largest = 9;
for(i = 0; i < limit; i++)
{
if(pq[i].at <= time && pq[i].s != 1 && pq[i].priority > pq[largest].priority)
{
largest = i;
}
}
time = time + pq[largest].bt;
pq[largest].ct = time;
pq[largest].wt = pq[largest].ct - pq[largest].at - pq[largest].bt;
pq[largest].tat = pq[largest].ct - pq[largest].at;
pq[largest].s = 1;
wait_time = wait_time + pq[largest].wt;
tat = tat + pq[largest].tat;
printf("\n%c\t\t%d\t\t%d\t\t%d\t\t%d", pq[largest].pn, pq[largest].at, pq[largest].bt, pq[largest].priority, pq[largest].wt);
}
average_wt = wait_time / limit;
average_tat = tat / limit;
printf("\n\nAverage waiting time:\t%f\n", average_wt);
printf("Average Turnaround Time:\t%f\n", average_tat);
break;}
case 6:
{
int at[10], bt[10], temp[10];
int i, smallest, c = 0, time, n;
double wt = 0, tat = 0, end;
float awt, atat;
printf("\nEnter the Total Number of Processes:\t");
scanf("%d", &n);
printf("\nEnter Details of %d Processes\n", n);
for(i = 0; i < n; i++)
{
printf("\nEnter Arrival Time:\t");
scanf("%d", &at[i]);
printf("Enter Burst Time:\t");
scanf("%d", &bt[i]);
temp[i] = bt[i];
}
bt[9] = 9999;
for(time = 0; c != n; time++)
{
smallest = 9;
for(i = 0; i < n; i++)
{
if(at[i] <= time && bt[i] < bt[smallest] && bt[i] > 0)
{
smallest = i;
}
}
bt[smallest]--;
if(bt[smallest] == 0)
{
c++;
end = time + 1;
wt = wt + end - at[smallest] - temp[smallest];
tat = tat + end - at[smallest];
}
}
awt = wt / n;
atat = tat / n;
printf("\n\nAverage Waiting Time:\t%lf\n", awt);
printf("Average Turnaround Time:\t%lf\n", atat);
break;
}
{
default:
printf("invalid choice");
break;
}
}
//printf("to continue press 'Y' or 'y' else any letter to exit\n");
//1
//scanf("%c",&c);
}
while(1);
}
|
C
|
#include "core/tint.h"
tint rgb(unsigned int red,unsigned int green,unsigned int blue,unsigned int alpha)
{
return (tint)
{
.r = red,
.g = green,
.b = blue,
.a = alpha
};
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct linkedList
{
int data;
struct linkedList *next;
};
typedef struct linkedList *node;
node q=NULL,head=NULL;
node createNode(int a)
{
node p=(node)malloc(sizeof(struct linkedList));
p->data=a;
p->next=NULL;
return p;
}
node create(FILE *fp,int n)
{
int i,a;
node p;
for(i=0;i<n;i++)
{
fscanf(fp,"%d",&a);
p=createNode(a);
if(i==0)
head=p;
else
q->next=p;
q=p;
}
}
void add_node(int a)
{
node p=createNode(a);
if(head==NULL)
head=p;
else
q->next=p;
q=p;
}
void h_occur(FILE *f)
{
int max_elem, max_freq;
max_freq = 0;
node i,j;
int count,check;
for(i=head;i!=NULL;i=i->next)
{
count = 0;
check=i->data;
for(j=head;j!=NULL;j=j->next)
{
if (j->data == check)
count++;
}
if (count>max_freq)
{
max_freq = count;
max_elem = check;
}
}
fprintf(f,"%d\n",max_elem);
}
void print(FILE *f)
{
node p;
for(p=head;p!=NULL;p=p->next)
fprintf(f,"%d ",p->data);
fprintf(f,"\n");
}
int main()
{
FILE *fp,*f;
int i,n;
char c;
fp=fopen("input.txt","r");
f=fopen("output.txt","w");
while ( fscanf(fp,"%c",&c)!=EOF )
{
//printf("%c",c);
if (c=='c')
{
int n,p;
fscanf(fp,"%d",&n);
create(fp,n);
}
else if (c=='p')
{
print(f);
}
else if (c=='h')
{
h_occur(f);
}
else if (c=='a')
{
fscanf(fp,"%d",&n);
add_node(n);
}
else if (c=='s')
return 0;
}
fclose(fp);
fclose(f);
}
|
C
|
#include <xc.h>
#include "ST7735.h"
#include "hw7.h"
char message[19];
void LCD_drawchar(unsigned short x, unsigned short y, unsigned short color, char c){
int ii;
int jj;
if (x<124 | y<152){
for (ii=0;ii<5;ii++){
for (jj=0;jj<8;jj++){
if (ASCII[c - 0x20][ii]>>jj & 0x1){
LCD_drawPixel(x+ii,y+jj, color);
}
else {
LCD_drawPixel(x+ii,y+jj, WHITE);
}
}
}
}
}
void draw_string(unsigned short x, unsigned short y, unsigned short color, char *z){
int i = 0;
while (z[i]){
LCD_drawchar((x+6*i),y,color,z[i]);
i++;
}
}
void progress_bar(unsigned short x, unsigned short y, int length, int pos){
int a;
int b;
for (a = 0; a < pos; a++){
for (b = 0; b<8;b++){
LCD_drawPixel(x+a,y+b,BLUE);
}
}
for (a = 0; a < (length - pos); a++){
for (b = 0; b<8;b++){
LCD_drawPixel(x+a + pos,y+b,RED );
}
}
}
|
C
|
#include "box.h"
/* draws an object's bounding box */
void drawBoundingBox(BoundingBox box){
/* permet d'avoir une forme sans remplissage */
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glBegin(GL_QUADS);
glVertex2f(box.minX, box.maxY);
glVertex2f(box.maxX, box.maxY);
glVertex2f(box.maxX, box.minY);
glVertex2f(box.minX, box.minY);
glEnd();
/* rétablit le remplissage */
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
/* depending on the object, its position, defines the bounding box correctly */
void initBoundingBox(BoundingBox* bb, float posX, float posY, char type)
{
/* default width of a bounding box is 1 */
bb->minX = posX;
bb->maxX = posX+1;
switch(type){
/* for the vertical bullets */
case 'v':
case 'V':
bb->minX += 0.5 - BULLET_HEIGHT / 2;
bb->maxX -= 0.5 - BULLET_HEIGHT / 2;
/* for bonus */
case 'b':
bb->minY = posY;
bb->maxY = posY + BONUS_SIZE;
break;
/* for the obstacles */
case 'w':
bb->minY = posY;
bb->maxY = posY + WALL_SIZE;
break;
/* for the shooter */
case 's':
bb->maxX += SHOOTER_SIZE - 1;
bb->minY = posY;
bb->maxY = posY + SHOOTER_SIZE;
break;
/* for the ennemies */
case 'm':
case 't':
case 'T':
bb->maxX += ENNEMY_SIZE - 1;
bb->minY = posY;
bb->maxY = posY + ENNEMY_SIZE;
break;
/* for the boss */
case 'B':
bb->maxX += 10;
bb->minY = (HEIGHT - BOSS_SIZE - 1) / 2;
bb->maxY = HEIGHT - bb->minY;
break;
/* for the horizontal bullets */
case 'H':
case 'h':
bb->maxY = posY + 1 - BULLET_HEIGHT / 2;
bb->minY = bb->maxY - BULLET_HEIGHT;
break;
/* for the boss bullets */
case 'M':
bb->minY = posY;
bb->maxY = bb->minY + BOSS_BULLETS_HEIGHT;
break;
default:
break;
}
}
|
C
|
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
char buf1[] = "abcdefgh";
char buf2[] = "ABCDEFGH";
char zero[] = "\0";
int main(int argc, char *argv[])
{
int fd;
if((fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC)) < 0) {
printf("open error\n");
exit(1);
}
if(write(fd, buf1, strlen(buf1)) != strlen(buf1)) {
printf("write buf1 error\n");
exit(1);
}
int i;
for(i = 0; i < 16376; i++)
{
write(fd, zero, 1);
}
if(write(fd, buf2, strlen(buf2)) != strlen(buf2)) {
printf("write buf2 error\n");
exit(1);
}
close(fd);
}
|
C
|
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include "mcpack.h"
#define htonll(x) ((1==htonl(1)) ? (x) : ((uint64_t)htonl((x) & 0xFFFFFFFF) << 32) | htonl((x) >> 32))
#define ntohll(x) ((1==ntohl(1)) ? (x) : ((uint64_t)ntohl((x) & 0xFFFFFFFF) << 32) | ntohl((x) >> 32))
#define VARINT_LIMIT 5
#define VARLONG_LIMIT 10
mc_buffer_t mc_buffer_new() {
mc_buffer_t buffer;
buffer.allocate = true;
buffer.used = false;
buffer.data = NULL;
buffer.size = 0;
buffer.allocated_size = 0;
buffer.read_ptr = 0;
return buffer;
}
mc_buffer_t mc_buffer_new_static(unsigned char *data, size_t size) {
mc_buffer_t buffer;
buffer.allocate = false;
buffer.used = false;
buffer.data = data;
buffer.size = 0;
buffer.allocated_size = size;
buffer.read_ptr = 0;
return buffer;
}
mc_buffer_t mc_buffer_make(unsigned char *data, size_t size) {
mc_buffer_t buffer = mc_buffer_new_static(data, size);
buffer.size = size;
return buffer;
}
static void mc_buffer_init_alloc(mc_buffer_t *buffer) {
if (buffer->allocate)
buffer->data = malloc(1);
buffer->used = 1;
}
int mc_buffer_require_size(mc_buffer_t *buffer, size_t size) {
if(size > buffer->allocated_size) {
if(buffer->allocate) {
buffer->data = realloc(buffer->data, size);
buffer->allocated_size = size;
} else {
return -1;
}
}
return 0;
}
void mc_buffer_free(mc_buffer_t *buffer) {
if (buffer->used && buffer->allocate) {
free(buffer->data);
buffer->allocated_size = 0;
}
buffer->used = 0;
buffer->size = 0;
}
static int mc_buffer_append(mc_buffer_t *buf, unsigned char byte) {
if (buf->size >= buf->allocated_size) {
if (buf->allocate) {
//buf->allocated_size = buf->allocated_size != 0 ? buf->allocated_size * 2 : 1;
buf->allocated_size++;
buf->data = realloc(buf->data, buf->allocated_size);
} else {
return -1;
}
}
buf->data[buf->size] = byte;
buf->size++;
return 1;
}
static int mc_buffer_appendx(mc_buffer_t *buf, unsigned long long x, size_t n) {
size_t orig_pos = buf->size;
for (size_t i = 0; i < n; i++) {
if (mc_buffer_append(buf, x) == -1) {
buf->size = orig_pos;
return -1;
}
x = x >> 8;
}
return n;
}
static int var_append(mc_buffer_t *buf, long long value, int limit) {
unsigned char temp;
int buf_err;
for(int i=0; i < limit; i++) {
temp = (unsigned char)(value & 0b01111111);
value >>= 7;
if (value != 0) {
temp |= 0b10000000;
}
buf_err = mc_buffer_append(buf, temp);
if (buf_err == -1)
return -1;
if(value == 0)
break;
}
if(value != 0)
return -1;
return 0;
}
int mc_var_read(mc_buffer_t *buf, long long *result, int limit) {
int num_read = 0;
*result = 0;
if ((buf->size - buf->read_ptr) == 0)
return -1;
unsigned char read;
do {
if (buf->read_ptr + num_read >= buf->size)
return -1;
read = buf->data[buf->read_ptr + num_read];
int value = (read & 0b01111111);
*result |= (value << (7 * num_read));
num_read++;
if (num_read > limit)
return -1;
} while ((read & 0b10000000) != 0);
buf->read_ptr += num_read;
return num_read;
}
int mc_packv(mc_buffer_t *buffer, const char *fmt, va_list ap) {
mc_buffer_init_alloc(buffer);
for(size_t i = 0; i < strlen(fmt); i++) {
//curflags = fmtflags;
//memset(&fmtflags, 0, sizeof(fmtflags));
int buf_err = 0;
uint8_t arg1;
uint16_t arg2;
uint32_t arg4;
uint64_t arg8;
const char *args;
size_t args_len;
const unsigned char *argB;
long long argB_len;
switch(fmt[i]) {
// Bool
case 'b':
arg1 = va_arg(ap, unsigned int) ? 0x01 : 0x00;
buf_err = mc_buffer_append(buffer, arg1);
break;
// Byte
case '1':
arg1 = va_arg(ap, unsigned int);
buf_err = mc_buffer_append(buffer, arg1);
break;
// Short
case '2':
arg2 = htons((uint16_t)va_arg(ap, unsigned int));
buf_err = mc_buffer_appendx(buffer, arg2, 2);
break;
// Int
case '4':
arg4 = htonl(va_arg(ap, uint32_t));
buf_err = mc_buffer_appendx(buffer, arg4, 4);
break;
// Long
case '8':
//arg8 = htonll(va_arg(ap, uint64_t));
arg8 = va_arg(ap, uint64_t);
arg8 = htonll(arg8);
buf_err = mc_buffer_appendx(buffer, arg8, 8);
break;
// VarInt
case 'i':
buf_err = var_append(buffer, va_arg(ap, int), VARINT_LIMIT);
break;
// VarLong
case 'I':
buf_err = var_append(buffer, va_arg(ap, long long), VARLONG_LIMIT);
break;
// String
case 's':
args = va_arg(ap, const char *);
args_len = strlen(args);
if(var_append(buffer, args_len, VARINT_LIMIT) == -1)
return -1;
mc_buffer_require_size(buffer, args_len);
memcpy(buffer->data + buffer->size, args, args_len);
buffer->size += args_len;
break;
// Byte Array
case 'B':
argB_len = va_arg(ap, long long);
argB = va_arg(ap, const unsigned char *);
if(var_append(buffer, argB_len, VARINT_LIMIT) == -1)
return -1;
mc_buffer_require_size(buffer, argB_len);
memcpy(buffer->data + buffer->size, argB, argB_len);
buffer->size += argB_len;
break;
};
if(buf_err == -1)
return -1;
}
return buffer->size;
}
int mc_pack(mc_buffer_t *buffer, const char *fmt, ...) {
va_list ap;
int ret;
va_start(ap, fmt);
ret = mc_packv(buffer, fmt, ap);
va_end(ap);
return ret;
}
static uint64_t mcbuffer_read_int(mc_buffer_t buffer, int bytes) {
uint64_t value = 0;
for (int i = 0; i < bytes; i++) {
//value += buffer.data[buffer.pos + i] << (i * 8);
value = value << 8;
value += buffer.data[buffer.read_ptr + i];
}
return value;
}
static size_t get_left_data_read(mc_buffer_t buffer) {
return buffer.size - buffer.read_ptr;
}
int mc_unpackv(mc_buffer_t buffer, const char *fmt, va_list ap) {
for(size_t i = 0; i < strlen(fmt); i++) {
//curflags = fmtflags;
//memset(&fmtflags, 0, sizeof(fmtflags));
uint8_t *arg1;
uint16_t *arg2;
uint32_t *arg4;
uint64_t *arg8;
int *argi;
long long *argI;
char **args;
unsigned char **argB;
long long *argB_len;
long long argi_val, string_len;
// TODO: Test whether endianness conversion in 1,2,4,8 is OK
switch(fmt[i]) {
// Bool
// Byte
case 'b':
case '1':
if (get_left_data_read(buffer) < 1)
return -1;
if ((arg1 = va_arg(ap, uint8_t *)) != NULL) {
*arg1 = mcbuffer_read_int(buffer, 1);
}
buffer.read_ptr++;
break;
// Short
case '2':
if (get_left_data_read(buffer) < 2)
return -1;
if ((arg2 = va_arg(ap, uint16_t *)) != NULL) {
*arg2 = mcbuffer_read_int(buffer, 2);
}
buffer.read_ptr += 2;
break;
// Int
case '4':
if (get_left_data_read(buffer) < 4)
return -1;
if ((arg4 = va_arg(ap, uint32_t *)) != NULL) {
*arg4 = mcbuffer_read_int(buffer, 4);
}
buffer.read_ptr += 4;
break;
// Long
case '8':
if (get_left_data_read(buffer) < 8)
return -1;
if ((arg8 = va_arg(ap, uint64_t *)) != NULL) {
*arg8 = mcbuffer_read_int(buffer, 8);
}
buffer.read_ptr += 8;
break;
// VarInt
case 'i':
if (mc_var_read(&buffer, &argi_val, VARINT_LIMIT) == -1)
return -1;
if ((argi = va_arg(ap, int *)) != NULL) {
*argi = argi_val;
}
break;
// VarLong
case 'I':
if(mc_var_read(&buffer, &argi_val, VARLONG_LIMIT) == -1)
return -1;
if ((argI = va_arg(ap, long long *)) != NULL) {
*argI = argi_val;
}
break;
// String
case 's':
args = va_arg(ap, char **);
if (mc_var_read(&buffer, &string_len, VARINT_LIMIT) == -1)
return -1;
if (get_left_data_read(buffer) < (size_t)string_len)
return -1;
if(args != NULL) {
*args = malloc(string_len + 1);
(*args)[string_len] = '\0';
strncpy(*args, (const char*)buffer.data + buffer.read_ptr, string_len);
}
buffer.read_ptr += string_len;
break;
// Byte array
case 'B':
argB_len = va_arg(ap, long long*);
argB = va_arg(ap, unsigned char**);
if (mc_var_read(&buffer, &string_len, VARINT_LIMIT) == -1)
return -1;
if(argB_len != NULL)
*argB_len = string_len;
if (get_left_data_read(buffer) < (size_t)string_len)
return -1;
if(argB != NULL) {
*argB = malloc(string_len);
memcpy(*argB, (const unsigned char*)buffer.data + buffer.read_ptr, string_len);
}
buffer.read_ptr += string_len;
break;
};
if(buffer.read_ptr > buffer.size) {
return -1;
}
}
return buffer.read_ptr;
}
int mc_unpack(mc_buffer_t buffer, const char *fmt, ...) {
va_list ap;
int ret;
va_start(ap, fmt);
ret = mc_unpackv(buffer, fmt, ap);
va_end(ap);
return ret;
}
int mc_unpack_raw(unsigned char *buf, size_t sz, const char *fmt, ...) {
va_list ap;
int ret;
mc_buffer_t buffer;
buffer.data = buf;
buffer.allocated_size = sz;
buffer.size = sz;
buffer.used = 0;
buffer.read_ptr = 0;
va_start(ap, fmt);
ret = mc_unpackv(buffer, fmt, ap);
va_end(ap);
return ret;
}
|
C
|
#include <avr/io.h>
#include <util/twi.h>
#include <avr/interrupt.h>
#include "I2C_slave.h"
void I2C_init(uint8_t address){
TWAR = (address << 1); // load address into TWI address register
TWCR = (1<<TWIE) | (1<<TWEA) | (1<<TWINT) | (1<<TWEN); // set the TWCR to enable address matching and enable TWI, clear TWINT, enable TWI interrupt
}
void I2C_stop(void){
// clear acknowledge and enable bits
TWCR &= ~( (1<<TWEA) | (1<<TWEN) );
}
ISR(TWI_vect){
uint8_t data; // temporary stores the received data
if( (TWSR & 0xF8) == TW_SR_SLA_ACK ){ // own address has been acknowledged
buffer_address = 0xFF;
TWCR |= (1<<TWIE) | (1<<TWINT) | (1<<TWEA) | (1<<TWEN); // clear TWI interrupt flag, prepare to receive next byte and acknowledge
}
else if( (TWSR & 0xF8) == TW_SR_DATA_ACK ){ // data has been received in slave receiver mode
rxbuffer[0] = 'b';
data = TWDR; // save the received byte inside data
if(buffer_address == 0xFF){ // check wether an address has already been transmitted or not
buffer_address = data;
TWCR |= (1<<TWIE) | (1<<TWINT) | (1<<TWEA) | (1<<TWEN); // clear TWI interrupt flag, prepare to receive next byte and acknowledge
}
else{ // if a databyte has already been received
rxbuffer[buffer_address] = data; // store the data at the current address
buffer_address++; // increment the buffer address
if(buffer_address < 0xFF){ // if there is still enough space inside the buffer
TWCR |= (1<<TWIE) | (1<<TWINT) | (1<<TWEA) | (1<<TWEN); // clear TWI interrupt flag, prepare to receive next byte and acknowledge
}
else{
TWCR |= (1<<TWIE) | (1<<TWINT) | (0<<TWEA) | (1<<TWEN); // clear TWI interrupt flag, prepare to receive last byte and don't acknowledge
}
}
}
else if( (TWSR & 0xF8) == TW_ST_DATA_ACK ){ // device has been addressed to be a transmitter
data = TWDR;// copy data from TWDR to the temporary memory
if( buffer_address == 0xFF ){ // if no buffer read address has been sent yet
buffer_address = data;
}
// copy the specified buffer address into the TWDR register for transmission
TWDR = 0x48;//txbuffer[buffer_address];
buffer_address++; // increment buffer read address
if(buffer_address < 0xFF){ // if there is another buffer address that can be sent
TWCR |= (1<<TWIE) | (1<<TWINT) | (1<<TWEA) | (1<<TWEN); // clear TWI interrupt flag, prepare to send next byte and receive acknowledge
}
else{
TWCR |= (1<<TWIE) | (1<<TWINT) | (0<<TWEA) | (1<<TWEN); // clear TWI interrupt flag, prepare to send last byte and receive not acknowledge
}
}
else{
// if none of the above apply prepare TWI to be addressed again
TWCR |= (1<<TWIE) | (1<<TWEA) | (1<<TWEN);
}
}
|
C
|
/*! \file
*
* \brief Simulation Functions Header File
*
* DESCRIPTION
* Specifies functions that are used to get simulation information and start
* simulations.
*
*/
#ifndef _SIMULATION_H_
#define _SIMULATION_H_
#include "common-typedefs.h"
#include <spin1_api.h>
// the position and human readable terms for each element from the region
// containing the timing details.
typedef enum region_elements{
APPLICATION_MAGIC_NUMBER, SIMULATION_TIMER_PERIOD, INFINITE_RUN,
N_SIMULATION_TICS, SDP_EXIT_RUNTIME_COMMAND_PORT,
SIMULATION_N_TIMING_DETAIL_WORDS
} region_elements;
typedef enum simulation_commands{
CMD_STOP = 6, CMD_RUNTIME = 7, SDP_SWITCH_STATE = 8
}simulation_commands;
//! \brief Reads the timing details for the simulation out of a region,
//! which is formatted as:
//! uint32_t magic_number;
//! uint32_t timer_period;
//! uint32_t n_simulation_ticks;
//! \param[in] address The address of the region
//! \param[in] expected_application_magic_number The expected value of the magic
//! number that checks if the data was
//! meant for this code
//! \param timer_period[out] a pointer to an int to receive the timer period,
//! in microseconds
//! \param n_simulation_ticks[out] a pointer to an int to receive the number
//! of simulation time steps to be performed
//! \param infinite_run[out] a pointer to an int which represents if the model
//! should run for infinite time
//! \return True if the data was found, false otherwise
bool simulation_read_timing_details(
address_t address, uint32_t expected_application_magic_number,
uint32_t* timer_period, uint32_t* n_simulation_ticks,
uint32_t* infinite_run);
//! \brief Starts the simulation running, returning when it is complete
void simulation_run();
//! \brief cleans up the house keeping, falls into a sync state and handles
//! the resetting up of states as required to resume.
//! \param[in] timer_function: The callback function used for the
//! timer_callback interrupt registration
//! \param[in] timer_function_priority: the priority level wanted for the
//! timer callback used by the application model.
void simulation_handle_pause_resume(
callback_t timer_function, int timer_function_priority);
//! \brief handles the new commands needed to resume the binary with a new
//! runtime counter, as well as switching off the binary when it truly needs
//! to be stopped.
//! \param[in] mailbox ????????????
//! \param[in] port ??????????????
//! \return does not return anything
void simulation_sdp_packet_callback(uint mailbox, uint port);
//! \brief handles the registration of the SDP callback
//! \param[in] simulation_ticks_pointer Pointer to the number of simulation
//! ticks, to allow this to be updated when requested via SDP
//! \param[in] infinite_run_pointer Pointer to the infinite run flag, to allow
//! this to be updated when requested via SDP
//! \param[in] sdp_packet_callback_priority The priority to use for the
//! SDP packet reception
void simulation_register_simulation_sdp_callback(
uint32_t *simulation_ticks_pointer, uint32_t *infinite_run_pointer,
int sdp_packet_callback_priority);
#endif // _SIMULATION_H_
|
C
|
#include <stdio.h>
int main()
{
int a;
scanf("%d",&a);
int b,i,j;
for(i=0;;i++){
int c=0;
b=a+1+i;
for(j=2;j<b;j++){
if(b%j==0)
{c=1;
break;
}
}
if(c!=1)
break;
}
printf("%d",b);
return 0;
}
|
C
|
/*
* mpu9250.c
*
* Created on: 24.06.2017
* Author: MyDev
*/
//===================================================================================================================
//====== Set of useful function to access acceleration. gyroscope, magnetometer, and temperature data
//===================================================================================================================
#include <XI_Sensors/sensors.h>
#include "XI_Bios/bios.h"
#include "mpu9250.h"
// Specify sensor full scale
uint8_t Gscale = GFS_250DPS;
uint8_t Ascale = AFS_2G;
uint8_t Mscale = MFS_16BITS; // Choose either 14-bit or 16-bit magnetometer resolution
uint8_t Mmode = 0x02; // 2 for 8 Hz, 6 for 100 Hz continuous magnetometer data read
float aRes, gRes, mRes; // scale resolutions per LSB for the sensors
uint8_t MPU9250_read8(uint8_t MPU9250_address, uint8_t MPU9250_reg, uint8_t MPU9250_buffer_size){
i2c_MPU9250_Transaction.slaveAddress = MPU9250_address;
i2c_MPU9250_Transaction.writeBuf = txMPU9250_Buffer;
i2c_MPU9250_Transaction.writeCount = 1;
i2c_MPU9250_Transaction.readBuf = rxMPU9250_Buffer;
i2c_MPU9250_Transaction.readCount = MPU9250_buffer_size;
txMPU9250_Buffer[0] = MPU9250_reg;
I2C_transfer(i2c, &i2c_MPU9250_Transaction);
// return value is in txMPU9250_Buffer
return 0;
}
uint8_t MPU9250_write8(uint8_t MPU9250_address, uint8_t MPU9250_reg, uint8_t MPU9250_value){
uint8_t value = 0;
i2c_MPU9250_Transaction.slaveAddress = MPU9250_ADDRESS;
i2c_MPU9250_Transaction.writeBuf = txMPU9250_Buffer;
i2c_MPU9250_Transaction.writeCount = 2;
i2c_MPU9250_Transaction.readBuf = rxMPU9250_Buffer;
i2c_MPU9250_Transaction.readCount = 2;
txMPU9250_Buffer[0] = MPU9250_reg;
txMPU9250_Buffer[1] = MPU9250_value;
I2C_transfer(i2c, &i2c_MPU9250_Transaction);
return value;
}
void getMres(void) {
switch (Mscale)
{
// Possible magnetometer scales (and their register bit settings) are:
// 14 bit resolution (0) and 16 bit resolution (1)
case MFS_14BITS:
mRes = 10.*4912./8190.; // Proper scale to return milliGauss
break;
case MFS_16BITS:
mRes = 10.*4912./32760.0; // Proper scale to return milliGauss
break;
}
}
void getGres(void) {
switch (Gscale)
{
// Possible gyro scales (and their register bit settings) are:
// 250 DPS (00), 500 DPS (01), 1000 DPS (10), and 2000 DPS (11).
// Here's a bit of an algorith to calculate DPS/(ADC tick) based on that 2-bit value:
case GFS_250DPS:
gRes = 250.0/32768.0;
break;
case GFS_500DPS:
gRes = 500.0/32768.0;
break;
case GFS_1000DPS:
gRes = 1000.0/32768.0;
break;
case GFS_2000DPS:
gRes = 2000.0/32768.0;
break;
}
}
void getAres(void) {
switch (Ascale)
{
// Possible accelerometer scales (and their register bit settings) are:
// 2 Gs (00), 4 Gs (01), 8 Gs (10), and 16 Gs (11).
// Here's a bit of an algorith to calculate DPS/(ADC tick) based on that 2-bit value:
case AFS_2G:
aRes = 2.0/32768.0;
break;
case AFS_4G:
aRes = 4.0/32768.0;
break;
case AFS_8G:
aRes = 8.0/32768.0;
break;
case AFS_16G:
aRes = 16.0/32768.0;
break;
}
}
void readAccelData(int16_t *destination)
{
//uint8_t rawData[6]; // x/y/z accel register data stored here
MPU9250_read8(MPU9250_ADDRESS, ACCEL_XOUT_H, 6); // Read the six raw data registers into data array
destination[0] = ((int16_t)rxMPU9250_Buffer[0] << 8) | rxMPU9250_Buffer[1] ; // Turn the MSB and LSB into a signed 16-bit value
destination[1] = ((int16_t)rxMPU9250_Buffer[2] << 8) | rxMPU9250_Buffer[3] ;
destination[2] = ((int16_t)rxMPU9250_Buffer[4] << 8) | rxMPU9250_Buffer[5] ;
}
void readGyroData(int16_t *destination)
{
//uint8_t rawData[6]; // x/y/z gyro register data stored here
MPU9250_read8(MPU9250_ADDRESS, GYRO_XOUT_H, 6); // Read the six raw data registers sequentially into data array
destination[0] = ((uint16_t) rxMPU9250_Buffer[0] << 8) | rxMPU9250_Buffer[1]; // Turn the MSB and LSB into a signed 16-bit value
destination[1] = ((uint16_t) rxMPU9250_Buffer[2] << 8) | rxMPU9250_Buffer[3];
destination[2] = ((uint16_t) rxMPU9250_Buffer[4] << 8) | rxMPU9250_Buffer[5];
}
void readMagData(int16_t *destination)
{
//uint8_t c = 0;
//uint8_t rawData[7]; // x/y/z gyro register data, ST2 register stored here, must read ST2 at end of data acquisition
MPU9250_read8(AK8963_ADDRESS, AK8963_ST1, 1); // Read the six raw data registers sequentially into data array
if(rxMPU9250_Buffer[0] & 0x01){
MPU9250_read8(AK8963_ADDRESS, AK8963_XOUT_L, 7); // Read the six raw data and ST2 registers sequentially into data array
if(!(rxMPU9250_Buffer[6] & 0x08)){ // Check if magnetic sensor overflow set, if not then report data
destination[0] = ((int16_t)rxMPU9250_Buffer[1] << 8) | rxMPU9250_Buffer[0] ; // Turn the MSB and LSB into a signed 16-bit value
destination[1] = ((int16_t)rxMPU9250_Buffer[3] << 8) | rxMPU9250_Buffer[2] ; // Data stored as little Endian
destination[2] = ((int16_t)rxMPU9250_Buffer[5] << 8) | rxMPU9250_Buffer[4] ;
}
}
}
int16_t readTempData(void)
{
//uint8_t rawData[2]; // x/y/z gyro register data stored here
MPU9250_read8(MPU9250_ADDRESS, TEMP_OUT_H, 2); // Read the two raw data registers sequentially into data array
return ((int16_t)rxMPU9250_Buffer[0] << 8) | rxMPU9250_Buffer[1] ; // Turn the MSB and LSB into a 16-bit value
}
// Accelerometer and gyroscope self test; check calibration wrt factory settings
void MPU9250_self_test(float *destination){ // Should return percent deviation from factory trim values, +/- 14 or less deviation is a pas
uint8_t rawData[6] = {0, 0, 0, 0, 0, 0};
uint8_t selfTest[6];
int32_t gAvg[3] = {0}, aAvg[3] = {0}, aSTAvg[3] = {0}, gSTAvg[3] = {0};
float factoryTrim[6];
uint8_t FS = 0;
int i = 0;
MPU9250_write8(MPU9250_ADDRESS, SMPLRT_DIV, 0x00); // Set gyro sample rate to 1 kHz
MPU9250_write8(MPU9250_ADDRESS, CONFIG, 0x02); // Set gyro sample rate to 1 kHz and DLPF to 92 Hz
MPU9250_write8(MPU9250_ADDRESS, GYRO_CONFIG, FS<<3); // Set full scale range for the gyro to 250 dps
MPU9250_write8(MPU9250_ADDRESS, ACCEL_CONFIG2, 0x02); // Set accelerometer rate to 1 kHz and bandwidth to 92 Hz
MPU9250_write8(MPU9250_ADDRESS, ACCEL_CONFIG, FS<<3); // Set full scale range for the accelerometer to 2 g
for(i = 0; i < 200; i++){ // get average current values of gyro and acclerometer
MPU9250_read8(MPU9250_ADDRESS, ACCEL_XOUT_H, 6); // Read the six raw data registers into data array
aAvg[0] += (int16_t)((int16_t)rxMPU9250_Buffer[0] << 8 | rxMPU9250_Buffer[1]); // Turn the MSB and LSB into a signed 16-bit value
aAvg[1] += (int16_t)((int16_t)rxMPU9250_Buffer[2] << 8 | rxMPU9250_Buffer[3]);
aAvg[2] += (int16_t)((int16_t)rxMPU9250_Buffer[4] << 8 | rxMPU9250_Buffer[5]);
MPU9250_read8(MPU9250_ADDRESS, GYRO_XOUT_H, 6); // Read the six raw data registers sequentially into data array
aAvg[0] += (int16_t)((int16_t)rxMPU9250_Buffer[0] << 8 | rxMPU9250_Buffer[1]); // Turn the MSB and LSB into a signed 16-bit value
aAvg[1] += (int16_t)((int16_t)rxMPU9250_Buffer[2] << 8 | rxMPU9250_Buffer[3]);
aAvg[2] += (int16_t)((int16_t)rxMPU9250_Buffer[4] << 8 | rxMPU9250_Buffer[5]);
}
for(i = 0; i < 3; i++){
aAvg[i] /= 200;
gAvg[i] /= 200;
}
// Configure the accelerometer for self-test
MPU9250_write8(MPU9250_ADDRESS, ACCEL_CONFIG, 0xE0); // Enable self test on all three axes and set accelerometer range to +/- 2 g
MPU9250_write8(MPU9250_ADDRESS, GYRO_CONFIG, 0xE0); // Enable self test on all three axes and set gyro range to +/- 250 degrees/s
__delay_ms(25);
for(i = 0; i < 200; i++){
MPU9250_read8(MPU9250_ADDRESS, ACCEL_XOUT_H, 6); // Read the six raw data registers into data array
aSTAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ; // Turn the MSB and LSB into a signed 16-bit value
aSTAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ;
aSTAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ;
MPU9250_read8(MPU9250_ADDRESS, GYRO_XOUT_H, 6); // Read the six raw data registers sequentially into data array
gSTAvg[0] += (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ; // Turn the MSB and LSB into a signed 16-bit value
gSTAvg[1] += (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ;
gSTAvg[2] += (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ;
}
for (i =0; i < 3; i++) { // Get average of 200 values and store as average self-test readings
aSTAvg[i] /= 200;
gSTAvg[i] /= 200;
}
// Configure the gyro and accelerometer for normal operation
MPU9250_write8(MPU9250_ADDRESS, ACCEL_CONFIG, 0x00);
MPU9250_write8(MPU9250_ADDRESS, GYRO_CONFIG, 0x00);
__delay_ms(25); // Delay a while to let the device stabilize
MPU9250_read8(MPU9250_ADDRESS, SELF_TEST_X_ACCEL, 1); // X-axis accel self-test results
selfTest[0] = rxMPU9250_Buffer[0];
MPU9250_read8(MPU9250_ADDRESS, SELF_TEST_Y_ACCEL, 1); // Y-axis accel self-test results
selfTest[1] = rxMPU9250_Buffer[0];
MPU9250_read8(MPU9250_ADDRESS, SELF_TEST_Z_ACCEL, 1); // Z-axis accel self-test results
selfTest[2] = rxMPU9250_Buffer[0];
MPU9250_read8(MPU9250_ADDRESS, SELF_TEST_X_GYRO, 1); // X-axis gyro self-test results
selfTest[3] = rxMPU9250_Buffer[0];
MPU9250_read8(MPU9250_ADDRESS, SELF_TEST_Y_GYRO, 1); // Y-axis gyro self-test results
selfTest[4] = rxMPU9250_Buffer[0];
MPU9250_read8(MPU9250_ADDRESS, SELF_TEST_Z_GYRO, 1); // Z-axis gyro self-test results
selfTest[5] = rxMPU9250_Buffer[0];
// Retrieve factory self-test value from self-test code reads
factoryTrim[0] = (float)(2620/1<<FS)*(pow( 1.01 , ((float)selfTest[0] - 1.0) )); // FT[Xa] factory trim calculation
factoryTrim[1] = (float)(2620/1<<FS)*(pow( 1.01 , ((float)selfTest[1] - 1.0) )); // FT[Ya] factory trim calculation
factoryTrim[2] = (float)(2620/1<<FS)*(pow( 1.01 , ((float)selfTest[2] - 1.0) )); // FT[Za] factory trim calculation
factoryTrim[3] = (float)(2620/1<<FS)*(pow( 1.01 , ((float)selfTest[3] - 1.0) )); // FT[Xg] factory trim calculation
factoryTrim[4] = (float)(2620/1<<FS)*(pow( 1.01 , ((float)selfTest[4] - 1.0) )); // FT[Yg] factory trim calculation
factoryTrim[5] = (float)(2620/1<<FS)*(pow( 1.01 , ((float)selfTest[5] - 1.0) )); // FT[Zg] factory trim calculation
// Report results as a ratio of (STR - FT)/FT; the change from Factory Trim of the Self-Test Response
// To get percent, must multiply by 100
for (i = 0; i < 3; i++) {
destination[i] = 100.0*((float)(aSTAvg[i] - aAvg[i]))/factoryTrim[i] - 100.; // Report percent differences
destination[i+3] = 100.0*((float)(gSTAvg[i] - gAvg[i]))/factoryTrim[i+3] - 100.; // Report percent differences
}
}
// Function which accumulates gyro and accelerometer data after device initialization. It calculates the average
// of the at-rest readings and then loads the resulting offsets into accelerometer and gyro bias registers.
uint8_t MPU9250_calibrate(float *dest1, float *dest2){
uint8_t data[12]; // data array to hold accelerometer and gyro x, y, z, data
uint16_t i, packet_count, fifo_count;
int32_t gyro_bias[3] = {0, 0, 0}, accel_bias[3] = {0, 0, 0};
// reset device
MPU9250_write8(MPU9250_ADDRESS, PWR_MGMT_1, 0x80); // Write a one to bit 7 reset bit; toggle reset device
__delay_ms(100);
// get stable time source; Auto select clock source to be PLL gyroscope reference if ready
// else use the internal oscillator, bits 2:0 = 001
MPU9250_write8(MPU9250_ADDRESS, PWR_MGMT_1, 0x01);
MPU9250_write8(MPU9250_ADDRESS, PWR_MGMT_2, 0x00);
__delay_ms(200);
// Configure device for bias calculation
MPU9250_write8(MPU9250_ADDRESS, INT_ENABLE, 0x00); // Disable all interrupts
MPU9250_write8(MPU9250_ADDRESS, FIFO_EN, 0x00); // Disable FIFO
MPU9250_write8(MPU9250_ADDRESS, PWR_MGMT_1, 0x00); // Turn on internal clock source
MPU9250_write8(MPU9250_ADDRESS, I2C_MST_CTRL, 0x00); // Disable I2C master
MPU9250_write8(MPU9250_ADDRESS, USER_CTRL, 0x00); // Disable FIFO and I2C master modes
MPU9250_write8(MPU9250_ADDRESS, USER_CTRL, 0x0C); // Reset FIFO and DMP
__delay_ms(15);
// Configure MPU6050 gyro and accelerometer for bias calculation
MPU9250_write8(MPU9250_ADDRESS, CONFIG, 0x01); // Set low-pass filter to 188 Hz
MPU9250_write8(MPU9250_ADDRESS, SMPLRT_DIV, 0x00); // Set sample rate to 1 kHz
MPU9250_write8(MPU9250_ADDRESS, GYRO_CONFIG, 0x00); // Set gyro full-scale to 250 degrees per second, maximum sensitivity
MPU9250_write8(MPU9250_ADDRESS, ACCEL_CONFIG, 0x00); // Set accelerometer full-scale to 2 g, maximum sensitivity
uint16_t gyrosensitivity = 131; // = 131 LSB/degrees/sec
uint16_t accelsensitivity = 16384; // = 16384 LSB/g
// Configure FIFO to capture accelerometer and gyro data for bias calculation
MPU9250_write8(MPU9250_ADDRESS, USER_CTRL, 0x40); // Enable FIFO
MPU9250_write8(MPU9250_ADDRESS, FIFO_EN, 0x78); // Enable gyro and accelerometer sensors for FIFO (max size 512 bytes in MPU-9150)
__delay_ms(40); // accumulate 40 samples in 40 milliseconds = 480 bytes
// At end of sample accumulation, turn off FIFO sensor read
MPU9250_write8(MPU9250_ADDRESS, FIFO_EN, 0x00);
MPU9250_read8(MPU9250_ADDRESS, FIFO_COUNTH, 2);
fifo_count = ((uint16_t)rxMPU9250_Buffer[0] << 8) | rxMPU9250_Buffer[1];
packet_count = fifo_count/12;// How many sets of full gyro and accelerometer data for averaging
for(i = 0; i < packet_count; i++){
int16_t accel_temp[3] = {0, 0, 0}, gyro_temp[3] = {0, 0, 0};
MPU9250_read8(MPU9250_ADDRESS, FIFO_R_W, 12); // read data for averaging
accel_temp[0] = (int16_t) ( ((int16_t)rxMPU9250_Buffer[0] << 8) | rxMPU9250_Buffer[1] ); // Form signed 16-bit integer for each sample in FIFO
accel_temp[1] = (int16_t) ( ((int16_t)rxMPU9250_Buffer[2] << 8) | rxMPU9250_Buffer[3] );
accel_temp[2] = (int16_t) ( ((int16_t)rxMPU9250_Buffer[4] << 8) | rxMPU9250_Buffer[5] );
gyro_temp[0] = (int16_t) ( ((int16_t)rxMPU9250_Buffer[6] << 8) | rxMPU9250_Buffer[7] );
gyro_temp[1] = (int16_t) ( ((int16_t)rxMPU9250_Buffer[8] << 8) | rxMPU9250_Buffer[9] );
gyro_temp[2] = (int16_t) ( ((int16_t)rxMPU9250_Buffer[10] << 8) | rxMPU9250_Buffer[11] );
accel_bias[0] += (int32_t) accel_temp[0]; // Sum individual signed 16-bit biases to get accumulated signed 32-bit biases
accel_bias[1] += (int32_t) accel_temp[1];
accel_bias[2] += (int32_t) accel_temp[2];
gyro_bias[0] += (int32_t) gyro_temp[0];
gyro_bias[1] += (int32_t) gyro_temp[1];
gyro_bias[2] += (int32_t) gyro_temp[2];
}
accel_bias[0] /= (int32_t) packet_count; // Normalize sums to get average count biases
accel_bias[1] /= (int32_t) packet_count;
accel_bias[2] /= (int32_t) packet_count;
gyro_bias[0] /= (int32_t) packet_count;
gyro_bias[1] /= (int32_t) packet_count;
gyro_bias[2] /= (int32_t) packet_count;
if(accel_bias[2] > 0L) {accel_bias[2] -= (int32_t) accelsensitivity;} // Remove gravity from the z-axis accelerometer bias calculation
else {accel_bias[2] += (int32_t) accelsensitivity;}
// Construct the gyro biases for push to the hardware gyro bias registers, which are reset to zero upon device startup
data[0] = (-gyro_bias[0]/4 >> 8) & 0xFF; // Divide by 4 to get 32.9 LSB per deg/s to conform to expected bias input format
data[1] = (-gyro_bias[0]/4) & 0xFF; // Biases are additive, so change sign on calculated average gyro biases
data[2] = (-gyro_bias[1]/4 >> 8) & 0xFF;
data[3] = (-gyro_bias[1]/4) & 0xFF;
data[4] = (-gyro_bias[2]/4 >> 8) & 0xFF;
data[5] = (-gyro_bias[2]/4) & 0xFF;
MPU9250_write8(MPU9250_ADDRESS, XG_OFFSET_H, data[0]);
MPU9250_write8(MPU9250_ADDRESS, XG_OFFSET_L, data[1]);
MPU9250_write8(MPU9250_ADDRESS, YG_OFFSET_H, data[2]);
MPU9250_write8(MPU9250_ADDRESS, YG_OFFSET_L, data[3]);
MPU9250_write8(MPU9250_ADDRESS, ZG_OFFSET_H, data[4]);
MPU9250_write8(MPU9250_ADDRESS, ZG_OFFSET_L, data[5]);
// Output scaled gyro biases for display in the main program
dest1[0] = (float) gyro_bias[0]/(float) gyrosensitivity;
dest1[1] = (float) gyro_bias[1]/(float) gyrosensitivity;
dest1[2] = (float) gyro_bias[2]/(float) gyrosensitivity;
// Construct the accelerometer biases for push to the hardware accelerometer bias registers. These registers contain
// factory trim values which must be added to the calculated accelerometer biases; on boot up these registers will hold
// non-zero values. In addition, bit 0 of the lower byte must be preserved since it is used for temperature
// compensation calculations. Accelerometer bias registers expect bias input as 2048 LSB per g, so that
// the accelerometer biases calculated above must be divided by 8.
int32_t accel_bias_reg[3] = {0, 0, 0}; // A place to hold the factory accelerometer trim biases
MPU9250_read8(MPU9250_ADDRESS, XA_OFFSET_H, 2);
accel_bias_reg[0] = (int32_t) (((uint16_t)txMPU9250_Buffer[0] << 8) | txMPU9250_Buffer[1]);
MPU9250_read8(MPU9250_ADDRESS, YA_OFFSET_H, 2);
accel_bias_reg[1] = (int32_t) (((uint16_t)txMPU9250_Buffer[0] << 8) | txMPU9250_Buffer[1]);
MPU9250_read8(MPU9250_ADDRESS, ZA_OFFSET_H, 2);
accel_bias_reg[2] = (int32_t) (((uint16_t)txMPU9250_Buffer[0] << 8) | txMPU9250_Buffer[1]);
uint32_t mask = 1uL; // Define mask for temperature compensation bit 0 of lower byte of accelerometer bias registers
uint8_t mask_bit[3] = {0, 0, 0}; // Define array to hold mask bit for each accelerometer bias axis
for(i = 0; i < 3; i++) {
if((accel_bias_reg[i] & mask)) mask_bit[i] = 0x01; // If temperature compensation bit is set, record that fact in mask_bit
}
// Construct total accelerometer bias, including calculated average accelerometer bias from above
accel_bias_reg[0] -= (accel_bias[0]/8); // Subtract calculated averaged accelerometer bias scaled to 2048 LSB/g (16 g full scale)
accel_bias_reg[1] -= (accel_bias[1]/8);
accel_bias_reg[2] -= (accel_bias[2]/8);
data[0] = (accel_bias_reg[0] >> 8) & 0xFF;
data[1] = (accel_bias_reg[0]) & 0xFF;
data[1] = data[1] | mask_bit[0]; // preserve temperature compensation bit when writing back to accelerometer bias registers
data[2] = (accel_bias_reg[1] >> 8) & 0xFF;
data[3] = (accel_bias_reg[1]) & 0xFF;
data[3] = data[3] | mask_bit[1]; // preserve temperature compensation bit when writing back to accelerometer bias registers
data[4] = (accel_bias_reg[2] >> 8) & 0xFF;
data[5] = (accel_bias_reg[2]) & 0xFF;
data[5] = data[5] | mask_bit[2]; // preserve temperature compensation bit when writing back to accelerometer bias registers
// Apparently this is not working for the acceleration biases in the MPU-9250
// Are we handling the temperature correction bit properly?
// Push accelerometer biases to hardware registers
MPU9250_write8(MPU9250_ADDRESS, XA_OFFSET_H, data[0]);
MPU9250_write8(MPU9250_ADDRESS, XA_OFFSET_L, data[1]);
MPU9250_write8(MPU9250_ADDRESS, YA_OFFSET_H, data[2]);
MPU9250_write8(MPU9250_ADDRESS, YA_OFFSET_L, data[3]);
MPU9250_write8(MPU9250_ADDRESS, ZA_OFFSET_H, data[4]);
MPU9250_write8(MPU9250_ADDRESS, ZA_OFFSET_L, data[5]);
// Output scaled accelerometer biases for display in the main program
dest2[0] = (float)accel_bias[0]/(float)accelsensitivity;
dest2[1] = (float)accel_bias[1]/(float)accelsensitivity;
dest2[2] = (float)accel_bias[2]/(float)accelsensitivity;
return 1;
}
uint8_t AK8963_init(float *destinations){
// First extract the factory calibration for each magnetometer axis
//int8_t rawData[3]; // x/y/z gyro calibration data stored here
MPU9250_write8(AK8963_ADDRESS, AK8963_CNTL, 0x00); // Power down magnetometer
__delay_ms(10);
MPU9250_write8(AK8963_ADDRESS, AK8963_CNTL, 0x0F); // Enter Fuse ROM access mode
__delay_ms(10);
MPU9250_read8(AK8963_ADDRESS, AK8963_ASAX, 3); // Read the x-, y-, and z-axis calibration values
destinations[0] = (float)(rxMPU9250_Buffer[0] - 128)/256. + 1.; // Return x-axis sensitivity adjustment values, etc.
destinations[1] = (float)(rxMPU9250_Buffer[1] - 128)/256. + 1.;
destinations[1] = (float)(rxMPU9250_Buffer[2] - 128)/256. + 1.;
MPU9250_write8(AK8963_ADDRESS, AK8963_CNTL, 0x0F); // Power down magnetometer
__delay_ms(10);
// Configure the magnetometer for continuous read and highest resolution
// set Mscale bit 4 to 1 (0) to enable 16 (14) bit resolution in CNTL register,
// and enable continuous mode data acquisition Mmode (bits [3:0]), 0010 for 8 Hz and 0110 for 100 Hz sample rates
MPU9250_write8(AK8963_ADDRESS, AK8963_CNTL, Mscale << 4 | Mmode);
__delay_ms(10);
return 0;
}
uint8_t MPU9250_init(void){
uint8_t c = 0;
// wake up device
MPU9250_write8(MPU9250_ADDRESS, PWR_MGMT_1, 0x00);
__delay_ms(100);
// get stable time source
MPU9250_write8(MPU9250_ADDRESS, PWR_MGMT_1, 0x01);
__delay_ms(200);
// Configure Gyro and Thermometer
// Disable FSYNC and set thermometer and gyro bandwidth to 41 and 42 Hz, respectively;
// minimum delay time for this setting is 5.9 ms, which means sensor fusion update rates cannot
// be higher than 1 / 0.0059 = 170 Hz
// DLPF_CFG = bits 2:0 = 011; this limits the sample rate to 1000 Hz for both
// With the MPU9250, it is possible to get gyro sample rates of 32 kHz (!), 8 kHz, or 1 kHz
MPU9250_write8(MPU9250_ADDRESS, CONFIG, 0x03);
// Set sample rate = gyroscope output rate/(1 + SMPLRT_DIV)
MPU9250_write8(MPU9250_ADDRESS, SMPLRT_DIV, 0x04); // Use a 200 Hz rate; a rate consistent with the filter update rate
// determined inset in CONFIG above
// Set gyroscope full scale range
// Range selects FS_SEL and GFS_SEL are 0 - 3, so 2-bit values are left-shifted into positions 4:3
MPU9250_read8(MPU9250_ADDRESS, GYRO_CONFIG, 1); // get current GYRO_CONFIG register value
c = rxMPU9250_Buffer[0];
// c = c & ~0xE0; // Clear self-test bits [7:5]
c = c & ~0x03; // Clear Fchoice bits [1:0]
c = c & ~0x18; // Clear GFS bits [4:3]
c = c | Gscale << 3; // Set full scale range for the gyro
// c =| 0x00; // Set Fchoice for the gyro to 11 by writing its inverse to bits 1:0 of GYRO_CONFIG
MPU9250_write8(MPU9250_ADDRESS, GYRO_CONFIG, c); // Write new GYRO_CONFIG value to register
// Set accelerometer full-scale range configuration
MPU9250_read8(MPU9250_ADDRESS, ACCEL_CONFIG, 1); // get current ACCEL_CONFIG register value
c = rxMPU9250_Buffer[0];
// c = c & ~0xE0; // Clear self-test bits [7:5]
c = c & ~0x18; // Clear AFS bits [4:3]
c = c | Ascale << 3; // Set full scale range for the accelerometer
MPU9250_write8(MPU9250_ADDRESS, ACCEL_CONFIG, c); // Write new ACCEL_CONFIG register value
// Set accelerometer sample rate configuration
// It is possible to get a 4 kHz sample rate from the accelerometer by choosing 1 for
// accel_fchoice_b bit [3]; in this case the bandwidth is 1.13 kHz
MPU9250_read8(MPU9250_ADDRESS, ACCEL_CONFIG2, 1);
c = rxMPU9250_Buffer[0];
c = c & ~0x0F; // Clear accel_fchoice_b (bit 3) and A_DLPFG (bits [2:0])
c = c | 0x03; // Set accelerometer rate to 1 kHz and bandwidth to 41 Hz
MPU9250_write8(MPU9250_ADDRESS, ACCEL_CONFIG2, c); // Write new ACCEL_CONFIG2 register value
// The accelerometer, gyro, and thermometer are set to 1 kHz sample rates,
// but all these rates are further reduced by a factor of 5 to 200 Hz because of the SMPLRT_DIV setting
// Configure Interrupts and Bypass Enable
// Set interrupt pin active high, push-pull, hold interrupt pin level HIGH until interrupt cleared,
// clear on read of INT_STATUS, and enable I2C_BYPASS_EN so additional chips
// can join the I2C bus and all can be controlled by the Arduino as master
MPU9250_write8(MPU9250_ADDRESS, INT_PIN_CFG, 0x22);
MPU9250_write8(MPU9250_ADDRESS, INT_ENABLE, 0x01); // Enable data ready (bit 0) interrupt
__delay_ms(100);
return 1;
}
|
C
|
#ifndef INSTRUCAO_H_
#define INSTRUCAO_H_
/* Tipos de dados e funcoes para tratar instrucoes
* codificadas.
*/
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define ROTULO_MAX_SIZE 32 //Maior tamanho admitido para um rotulo em codigo assembly
//INSTRUCTION SET DA ARQUITETURA:
#define LD_OPCODE 0x00
#define ST_OPCODE 0x01
#define MOVE_OPCODE 0x02
#define NEG_OPCODE 0x03
#define NOT_OPCODE 0x04
#define ADD_OPCODE 0x05
#define SUB_OPCODE 0x06
#define MULT_OPCODE 0x07
#define DIV_OPCODE 0x08
#define AND_OPCODE 0x09
#define OR_OPCODE 0x0A
#define SLL_OPCODE 0x0B
#define SLR_OPCODE 0x0C
#define LI_OPCODE 0x10
#define BEQZ_OPCODE 0x11
#define BNEZ_OPCODE 0x12
#define BGTZ_OPCODE 0x13
#define BLEZ_OPCODE 0x14
#define ADDI_OPCODE 0x20
#define SUBI_OPCODE 0x21
#define MULTI_OPCODE 0x22
#define DIVI_OPCODE 0x23
#define ANDI_OPCODE 0x24
#define ORI_OPCODE 0x25
#define BEQ_OPCODE 0x26
#define BNE_OPCODE 0x27
#define BGT_OPCODE 0x28
#define BGE_OPCODE 0x29
#define BLT_OPCODE 0x2A
#define BLE_OPCODE 0x2B
#define B_OPCODE 0x30
//Tempos de execucao para cada tipo de instrucao (podem ser modificados pelo usuario)
uint8_t XTIME_LD;
uint8_t XTIME_ST;
uint8_t XTIME_MOVE;
uint8_t XTIME_NEG;
uint8_t XTIME_NOT;
uint8_t XTIME_ADD;
uint8_t XTIME_SUB;
uint8_t XTIME_MULT;
uint8_t XTIME_DIV;
uint8_t XTIME_AND;
uint8_t XTIME_OR;
uint8_t XTIME_SLL;
uint8_t XTIME_SLR;
uint8_t XTIME_LI;
uint8_t XTIME_BEQZ;
uint8_t XTIME_BNEZ;
uint8_t XTIME_BGTZ;
uint8_t XTIME_BLEZ;
uint8_t XTIME_ADDI;
uint8_t XTIME_SUBI;
uint8_t XTIME_MULTI;
uint8_t XTIME_DIVI;
uint8_t XTIME_ANDI;
uint8_t XTIME_ORI;
uint8_t XTIME_BEQ;
uint8_t XTIME_BNE;
uint8_t XTIME_BGT;
uint8_t XTIME_BGE;
uint8_t XTIME_BLT;
uint8_t XTIME_BLE;
uint8_t XTIME_B;
//Registro de instrucao: utilizado pelo codificador/decodificador
typedef struct instrucao_t
{
uint32_t codificada;
uint32_t tipo_instrucao;
uint32_t operando1;
uint32_t operando2;
uint32_t operando3;
int32_t imediato;
}instrucao_t;
//Lista de rotulos para um programa em assembly
typedef struct lista_rotulo_t
{
char rotulo[ROTULO_MAX_SIZE];
uint32_t endereco;
struct lista_rotulo_t *prox;
}lista_rotulo_t;
int Decodificar_Instrucao(uint32_t codigo, instrucao_t *destino); //cria uma nova struct instrucao a partir de uma instrucao codificada e grava em *destino. Retorna diferente de zero em caso de erro
uint32_t Codificar_Instrucao(char *instrucao, lista_rotulo_t *lista); //codifica uma instrucao em uma linha de codigo em linguagem de montagem
uint32_t Montar_Codigo(char *codigo, uint32_t *heap, uint32_t tamanho_memoria, uint32_t *text_end); //monta codigo em linguagem de montagem a partir de um programa assembly passado em char *codigo, aplicando analise sintatica e preenchendo tabela de labels (rotulos). O codigo de maquina resultante eh colocado em uint32_t *heap, e o endereco da ultima instrucao eh gravado em uint32_t *text_end
int Adicionar_Rotulo(lista_rotulo_t **lista, char *nome, uint32_t posicao); //Adiciona um rotulo em uma lista, com a posicao para a qual ele aponta
uint32_t Buscar_Rotulo(lista_rotulo_t *lista, char *rotulo); //Busca um rotulo na lista e retorna a posicao para a qual ele aponta
uint32_t Calcular_Tamanho_Instrucao(char *instrucao); //Calcula o tamanho em bytes de uma instrucao
#endif
|
C
|
#include <unistd.h>
void ft_swap_bit(unsigned char octet)
{
int i = 128;
unsigned char temp1 = octet >> 4;
unsigned char temp2 = octet << 4;
unsigned char temp = temp1 | temp2;
while (i > 0)
{
if (temp < i)
{
write (1, "0", 1);
i = i / 2;
}
else
{
write (1, "1", 1);
temp = temp - i;
i = i / 2;
}
}
}
int main(void)
{
unsigned char x = 25;
ft_swap_bit(x);
return (0);
}
|
C
|
#include <stdio.h>
//
void InsertSort(int *arr, int len)
{
for (int i = 1; i < len; ++i)
{
int temp = arr[i];
int j = i - 1;
while (j >= 0 && temp < arr[j])
{
arr[j + 1] = arr[j];
--j;
}
arr[j + 1] = temp;
}
}
//ϣ
void ShellSort(int *arr, int len)
{
int increment = len;
while (increment > 1)
{
increment = increment / 3 + 1;
//飬Ȼÿһ
for (int i = 0; i < increment; ++i)
{
//ÿִв
for (int j = i + increment; j < len; j += increment)
{
int temp = arr[j];
int k = j - increment;
while (k >= 0 && temp < arr[k])
{
arr[k + increment] = arr[k];
k -= increment;
}
arr[k + increment] = temp;
}
}
}
}
//
void QuickSort(int *arr, int start, int end)
{
int i = start;
int j = end;
if (i >= j)
return;
int temp = arr[i];
while (i < j)
{
//ұҵһȻֵСķŵ
while (i < j && arr[j] >= temp)
{
--j;
}
if (i < j && arr[j] < temp)
{
arr[i] = arr[j];
++i;
}
//ҵһȻֵķŵұ
while (i < j && arr[i] < temp)
{
++i;
}
if (i < j && arr[i] >= temp)
{
arr[j] = arr[i];
--j;
}
}
arr[i] = temp;
QuickSort(arr, start, i - 1);
QuickSort(arr, i + 1, end);
}
//ϲ
//void Merge(int *arr1, int start1, int end1, int *arr2, int start2, int end2, int *arr3)
//{
// int i = start1;
// int j = start2;
//
// int length = 0;
//
// while (i <= end1 && j <= end2)
// {
// if (arr1[i] < arr2[j])
// {
// arr3[length] = arr1[i];
// ++i;
// }
// else
// {
// arr3[length] = arr2[j];
// ++j;
// }
// length++;
// }
//
// while (i <= end1)
// {
// arr3[length++] = arr1[i++];
// }
//
// while (j <= end2)
// {
// arr3[length++] = arr2[j++];
// }
//}
void Merge(int *arr, int start, int mid, int end, int *temp)
{
int i = start;
int j = mid + 1;
int length = 0;
while (i <= mid &&j <= end)
{
if (arr[i] < arr[j])
{
temp[length++] = arr[i++];
}
else
{
temp[length++] = arr[j++];
}
}
while (i <= mid)
{
temp[length++] = arr[i++];
}
while (j <= end)
{
temp[length++] = arr[j++];
}
for (int i = 0; i < length; ++i)
{
arr[start + i] = temp[i];
}
}
void MergeSort(int *arr, int start, int end, int *temp)
{
if (start == end)
return;
int mid = (start + end) / 2;
MergeSort(arr, start, mid,temp);
MergeSort(arr, mid + 1, end,temp);
//ϲ
Merge(arr, start, mid, end, temp);
}
int main()
{
int arr[10] = { 2, 7, 4, 8, 6, 5, 1, 9, 0, 3 };
for (int i = 0; i < 10; ++i)
{
printf("%d ", arr[i]);
}
printf("\n");
//InsertSort(arr, 10);
//ShellSort(arr, 10);
//QuickSort(arr, 0, 9);
int temp[10];
MergeSort(arr, 0, 9, temp);
for (int i = 0; i < 10; ++i)
{
printf("%d ", arr[i]);
}
/*int arr1[3] = { 1, 3, 5 };
int arr2[5] = { 0, 2, 4, 6, 7 };
int arr3[8];
Merge(arr1, 0, 2, arr2, 0, 4, arr3);
for (int i = 0; i < 8; ++i)
{
printf("%d ", arr3[i]);
}
printf("\n");*/
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[]) {
int a, *pa;
a = 10;
pa = &a;
*pa = 20;
printf("valor pa -> %i\n", *pa);
printf("valor a -> %i\n", a);
return 0;
}
|
C
|
/*
* (C) Copyright 2019-2022 Intel Corporation.
*
* SPDX-License-Identifier: BSD-2-Clause-Patent
*/
#include <stddef.h>
#include <setjmp.h>
#include <stdarg.h>
#include <cmocka.h>
#include <daos/test_utils.h>
#include <daos/checksum.h>
#include <daos_srv/evtree.h>
#include <daos_srv/srv_csum.h>
#include <daos/tests_lib.h>
#include <daos/test_perf.h>
static void
print_chars(const uint8_t *buf, const size_t len, const uint32_t max)
{
int i;
if (buf == NULL)
return;
for (i = 0; i < len && (i < max || max == 0); i++)
print_error("%c", buf[i]);
}
#define FAKE_UPDATE_BUF_LEN (1024*1024)
static char fake_update_buf_copy[FAKE_UPDATE_BUF_LEN];
static char *fake_update_buf = fake_update_buf_copy;
static int fake_update_bytes;
static int fake_update_called;
static int
fake_reset(void *daos_mhash_ctx)
{
fake_update_buf[0] = '>';
fake_update_buf++;
fake_update_bytes++;
return 0;
}
static int
fake_update(void *daos_mhash_ctx, uint8_t *buf, size_t buf_len)
{
fake_update_called++;
if (fake_update_bytes + buf_len < FAKE_UPDATE_BUF_LEN) {
strncpy(fake_update_buf, (char *)buf, buf_len);
fake_update_buf += buf_len;
fake_update_bytes += buf_len;
fake_update_buf[0] = '|';
fake_update_buf++;
fake_update_bytes++;
}
return 0;
}
static int
fake_finish(void *daos_mhash_ctx, uint8_t *buf, size_t buf_len)
{
int i;
/** Fill checksum with 'N' to indicate creating new checksum */
for (i = 0; i < buf_len; i++)
buf[i] = 'N';
return 0;
}
static int fake_compare_called;
static bool
fake_compare(void *daos_mhash_ctx,
uint8_t *buf1, uint8_t *buf2,
size_t buf_len)
{
fake_compare_called++;
return true;
}
static struct hash_ft fake_algo = {
.cf_reset = fake_reset,
.cf_update = fake_update,
.cf_finish = fake_finish,
.cf_compare = fake_compare,
.cf_hash_len = sizeof(uint32_t),
.cf_type = 999,
.cf_name = "fake"
};
static void
reset_fake_algo()
{
memset(fake_update_buf_copy, 0, FAKE_UPDATE_BUF_LEN);
fake_update_buf = fake_update_buf_copy;
fake_update_called = 0;
fake_update_bytes = 0;
fake_compare_called = 0;
}
#define FAKE_UPDATE_SAW(buf) fake_update_saw(__FILE__, __LINE__, \
buf, sizeof(buf)-1)
void fake_update_saw(char *file, int line, char *buf, size_t len)
{
if (len != fake_update_bytes ||
memcmp(fake_update_buf_copy, buf, len) != 0) {
print_error("%s:%dExpected to see '", file, line);
print_chars((uint8_t *) buf, len, 0);
print_error("' in '");
print_chars((uint8_t *) fake_update_buf_copy, fake_update_bytes,
FAKE_UPDATE_BUF_LEN);
print_error("'\n");
fail();
}
}
/**
* -------------------------------------------------------------------------
* Testing fetch of aligned and unaligned extents
*
* These tests verify that the server logic for creating new checksums
* or copying stored checksums works properly. Each test should have a layout
* diagram of sorts in the comment header (if it fits easily). Gennerally a '_'
* represents a hole that will exist in the request.
*
* There is a setup section that defines the request, chunk size,
* record size and the layout of what extents are "stored". The setup
* will create a bsgl with biov for each layout as though it were
* coming from VOS. It should take into
* account the prefix/suffix needed to represent raw vs req extents (.sel = req,
* .ful = raw).
* To verify correctness, a fake csum algo structure is used that
* remembers what data it sees while "updating" and then can verify that the
* correct data was used for "calculating" the new checksums.
* - In the checksum (ASSERT_CSUM) "SSSS" means that the stored checksum was
* copied. "CCCC" means that a new checksum was created.
* - In the observed data for a checksum update (FAKE_UPDATE_SAW), a '>' means
* that a new checksum was started, and '|' separates calls to checksum
* update.
* -------------------------------------------------------------------------
*/
struct vos_fetch_test_context {
size_t nr; /** Num of bsgl.bio_iov/biov_csums pairs */
struct bio_sglist bsgl;
struct dcs_ci_list biov_csums;
daos_iod_t iod;
struct daos_csummer *csummer;
struct dcs_iod_csums *iod_csum;
};
struct extent_info {
char *data;
struct evt_extent sel;
struct evt_extent ful;
bool is_hole;
};
struct array_test_case_args {
int request_idx;
int request_len;
uint64_t chunksize;
uint64_t rec_size;
struct extent_info layout[24];
};
#define ARRAY_TEST_CASE_CREATE(ctx, ...) array_test_case_create(ctx, \
&(struct array_test_case_args)__VA_ARGS__)
static void
array_test_case_create(struct vos_fetch_test_context *ctx,
struct array_test_case_args *setup)
{
uint32_t csum_len;
uint64_t rec_size;
uint32_t cs;
size_t i = 0;
size_t j;
size_t nr;
uint8_t *dummy_csums;
daos_csummer_init(&ctx->csummer, &fake_algo, setup->chunksize, 0);
csum_len = daos_csummer_get_csum_len(ctx->csummer);
cs = daos_csummer_get_chunksize(ctx->csummer);
assert_true(cs != 0);
dummy_csums = (uint8_t *)"SSSSSSSSSSSSSSSSSSSSSSSSSS";
rec_size = setup->rec_size;
/** count number of layouts */
while (setup->layout[i].data != NULL)
i++;
nr = i;
ctx->nr = nr;
bio_sgl_init(&ctx->bsgl, nr);
ctx->bsgl.bs_nr_out = nr;
assert_success(dcs_csum_info_list_init(&ctx->biov_csums, 10));
for (i = 0; i < nr; i++) {
struct extent_info *l;
char *data;
struct bio_iov *biov;
struct dcs_csum_info info;
uint8_t csum_buf[128];
size_t data_len;
size_t num_of_csum;
bio_addr_t addr = {0};
l = &setup->layout[i];
data = l->data;
data_len = (l->ful.ex_hi - l->ful.ex_lo + 1) * rec_size;
biov = &ctx->bsgl.bs_iovs[i];
bio_iov_set(biov, addr,
evt_extent_width(&l->sel) * rec_size);
bio_iov_set_extra(biov,
(l->sel.ex_lo - l->ful.ex_lo) *
rec_size,
(l->ful.ex_hi - l->sel.ex_hi) *
rec_size);
if (l->is_hole) {
BIO_ADDR_SET_HOLE(&biov->bi_addr);
biov->bi_buf = NULL;
} else {
D_ALLOC(biov->bi_buf, data_len);
memcpy(bio_iov2raw_buf(biov), data, data_len);
/** Just a rough count */
num_of_csum = data_len / cs + 1;
assert_true(csum_len * num_of_csum <= ARRAY_SIZE(csum_buf));
info.cs_csum = csum_buf;
info.cs_buf_len = csum_len * num_of_csum;
info.cs_nr = num_of_csum;
info.cs_len = csum_len;
info.cs_chunksize = cs;
for (j = 0; j < num_of_csum; j++)
ci_insert(&info, j, dummy_csums, csum_len);
dcs_csum_info_save(&ctx->biov_csums, &info);
}
}
ctx->iod.iod_nr = 1;
ctx->iod.iod_size = rec_size;
ctx->iod.iod_type = DAOS_IOD_ARRAY;
D_ALLOC_PTR(ctx->iod.iod_recxs);
ctx->iod.iod_recxs->rx_idx = setup->request_idx;
ctx->iod.iod_recxs->rx_nr = setup->request_len;
daos_csummer_alloc_iods_csums(ctx->csummer, &ctx->iod, 1, false,
NULL, &ctx->iod_csum);
}
static void
test_case_destroy(struct vos_fetch_test_context *ctx)
{
int i;
daos_csummer_free_ic(ctx->csummer, &ctx->iod_csum);
for (i = 0; i < ctx->nr; i++) {
void *bio_buf = bio_iov2raw_buf(&ctx->bsgl.bs_iovs[i]);
if (bio_buf)
D_FREE(bio_buf);
}
dcs_csum_info_list_fini(&ctx->biov_csums);
if (ctx->iod.iod_recxs)
D_FREE(ctx->iod.iod_recxs);
bio_sgl_fini(&ctx->bsgl);
daos_csummer_destroy(&ctx->csummer);
}
static int
fetch_csum_verify_bsgl_with_args(struct vos_fetch_test_context *ctx)
{
return ds_csum_add2iod(
&ctx->iod, ctx->csummer, &ctx->bsgl, &ctx->biov_csums, NULL,
ctx->iod_csum);
}
#define ASSERT_CSUM(ctx, csum) \
assert_memory_equal(csum, ctx.iod_csum->ic_data->cs_csum, \
sizeof(csum) - 1)
#define ASSERT_CSUM_EMPTY(ctx, idx) \
assert_int_equal( \
0, *(ctx.iod_csum->ic_data->cs_csum + (idx * ctx.iod_csum->ic_data->cs_len)))
#define ASSERT_CSUM_IDX(ctx, csum, idx) \
assert_memory_equal(csum, ctx.iod_csum->ic_data->cs_csum + \
(idx * ctx.iod_csum->ic_data->cs_len), \
sizeof(csum) - 1)
/**
* Single extent that is a single chunk. Request matches extent
*
* Should look like this:
* Fetch extent: 1 2 3 \0 |
* epoch 1 extent: 1 2 3 \0 |
* index: 0 1 2 3 |
*/
static void
request_that_matches_single_extent(void **state)
{
struct vos_fetch_test_context ctx;
/** Setup */
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 0,
.request_len = 4,
.chunksize = 4,
.rec_size = 1,
.layout = {
{.data = "123", .sel = {0, 3}, .ful = {0, 3},},
{.data = NULL}
}
});
memset(ctx.iod_csum->ic_data->cs_csum, 0,
ctx.iod_csum->ic_data->cs_buf_len);
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
ASSERT_CSUM(ctx, "SSSS");
FAKE_UPDATE_SAW("");
test_case_destroy(&ctx);
}
/**
* Single extent that is smaller than a single chunk. Request matches extent
*
* Should look like this:
* Fetch extent: A B C
* epoch 1 extent: A B C
* index: 0 1 2
*/
static void
extent_smaller_than_chunk(void **state)
{
struct vos_fetch_test_context ctx;
/** Setup */
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 0,
.request_len = 3,
.chunksize = 8,
.rec_size = 1,
.layout = {
{.data = "ABC", .sel = {0, 2}, .ful = {0, 2},},
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
ASSERT_CSUM(ctx, "SSSS");
FAKE_UPDATE_SAW("");
/** Never have to create a new csum because there's only 1 extent */
assert_int_equal(0, fake_update_called);
assert_int_equal(0, fake_compare_called);
/** clean up */
test_case_destroy(&ctx);
}
/**
* Single extent that is multiple chunks. Request matches extent
*
* Should look like this:
* Fetch extent: 1 2 | 3 4 | 5 6 | 7 \0 |
* epoch 1 extent: 1 2 | 3 4 | 5 6 | 7 \0 |
* index: 0 1 | 2 3 | 4 5 | 6 7 |
*/
static void
request_that_matches_single_extent_multiple_chunks(void **state)
{
struct vos_fetch_test_context ctx;
/** Setup */
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 0,
.request_len = 8,
.chunksize = 2,
.rec_size = 1,
.layout = {
{.data = "1234567", .sel = {0, 7}, .ful = {0, 7},},
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
ASSERT_CSUM(ctx, "SSSS");
FAKE_UPDATE_SAW("");
test_case_destroy(&ctx);
}
/**
* Single extent that isn't chunk aligned at beginning or end, but request
* matches extent so still don't need new checksum
*
* Should look like this:
* Fetch extent: 2 | 3 4 | 5 6 | \0 |
* epoch 1 extent: 2 | 3 4 | 5 6 | \0 |
* index: 0 1 | 2 3 | 4 5 | 6 7 |
*/
static void
request_that_matches_single_extent_multiple_chunks_not_aligned(void **state)
{
struct vos_fetch_test_context ctx;
/** Setup */
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 1,
.request_len = 6,
.chunksize = 2,
.rec_size = 1,
.layout = {
{.data = "23456", .sel = {1, 6}, .ful = {1, 6},},
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
ASSERT_CSUM(ctx, "SSSSSSSSSSSSSSSS");
FAKE_UPDATE_SAW("");
test_case_destroy(&ctx);
}
/**
* Two extents that are chunk aligned and request is chunk aligned. Stored
* checksums are copied.
*
* Should look like this:
* Fetch extent: Z Y X W | V U T S
* epoch 2 extent: | V U T S
* epoch 1 extent: Z Y X W |
* index: 0 1 2 3 | 4 5 6 7
*/
static void
request_that_matches_multiple_aligned_extents(void **state)
{
struct vos_fetch_test_context ctx;
/** Setup */
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 0,
.request_len = 8,
.chunksize = 4,
.rec_size = 1,
.layout = {
{.data = "ZYXW", .sel = {0, 3}, .ful = {0, 3},},
{.data = "VUTS", .sel = {4, 7}, .ful = {4, 7},},
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
ASSERT_CSUM(ctx, "SSSSSSSS");
FAKE_UPDATE_SAW("");
test_case_destroy(&ctx);
}
/**
* Two extents that are chunk aligned and request is chunk aligned. Stored
* checksums are copied. Same as previous but extents are in reverse order
*
* Should look like this:
* Fetch extent: Z Y X W | V U T S
* epoch 2 extent: Z Y X W |
* epoch 1 extent: | V U T S
* index: 0 1 2 3 | 4 5 6 7
*/
static void
request_that_matches_multiple_aligned_extents2(void **state)
{
struct vos_fetch_test_context ctx;
/** Setup */
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 0,
.request_len = 8,
.chunksize = 4,
.rec_size = 1,
.layout = {
{.data = "VUTS", .sel = {4, 7}, .ful = {4, 7},},
{.data = "ZYXW", .sel = {0, 3}, .ful = {0, 3},},
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
ASSERT_CSUM(ctx, "SSSSSSSS");
FAKE_UPDATE_SAW("");
test_case_destroy(&ctx);
}
/**
* One extent. Requesting larger (at end) extent than what exists. Will still
* copy stored checksum because only stored extent is returned.
*
* Should look like this:
* Fetch extent: Z Y X W | V U _ _
* epoch 1 extent: Z Y X W | V U
* index: 0 1 2 3 | 4 5 6 7
*/
static void
request_that_is_more_than_extents(void **state)
{
struct vos_fetch_test_context ctx;
/** Setup */
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 0,
.request_len = 8,
.chunksize = 4,
.rec_size = 1,
.layout = {
{.data = "ZYXWVU", .sel = {0, 5}, .ful = {0, 5},},
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
ASSERT_CSUM(ctx, "SSSS");
FAKE_UPDATE_SAW("");
assert_int_equal(0, fake_update_called);
assert_int_equal(0, fake_compare_called);
test_case_destroy(&ctx);
}
/**
* One single chunk length extent, but only first half is requested. Will need
* to create a new checksum and verify whole original extent.
*
* Should look like this:
* Fetch extent: Z Y X W
* epoch 1 extent: Z Y X W V U T S |
* index: 0 1 2 3 4 5 6 7 |
*/
static void
partial_chunk_request0(void **state)
{
struct vos_fetch_test_context ctx;
/** Setup */
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 0,
.request_len = 4,
.chunksize = 8,
.rec_size = 1,
.layout = {
{.data = "ZYXWVUTS", .sel = {0, 3}, .ful = {0, 7},},
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
FAKE_UPDATE_SAW(">ZYXW|>ZYXWVUTS|");
ASSERT_CSUM(ctx, "NNNN");
assert_int_equal(2, fake_update_called);
assert_int_equal(1, fake_compare_called);
test_case_destroy(&ctx);
}
/**
* One single chunk length extent, but only last half is requested. Will need
* to create a new checksum and verify whole original extent.
*
* Should look like this:
* Fetch extent: V U T S |
* epoch 1 extent: Z Y X W V U T S |
* index: 0 1 2 3 4 5 6 7 |
*/
static void
partial_chunk_request1(void **state)
{
struct vos_fetch_test_context ctx;
/** Setup */
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 4,
.request_len = 4,
.chunksize = 8,
.rec_size = 1,
.layout = {
{.data = "ZYXWVUTS", .sel = {4, 7}, .ful = {0, 7},},
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
FAKE_UPDATE_SAW(">VUTS|>ZYXWVUTS|");
ASSERT_CSUM(ctx, "NNNN");
assert_int_equal(2, fake_update_called);
assert_int_equal(1, fake_compare_called);
test_case_destroy(&ctx);
}
/**
* One single chunk length extent, but only middle part is requested. Will need
* to create a new checksum and verify whole original extent.
*
* Should look like this:
* Fetch extent: X W V U |
* epoch 1 extent: Z Y X W V U T S |
* index: 0 1 2 3 4 5 6 7 |
*/
static void
partial_chunk_request2(void **state)
{
struct vos_fetch_test_context ctx;
/** Setup */
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 2,
.request_len = 4,
.chunksize = 8,
.rec_size = 1,
.layout = {
{.data = "ZYXWVUTS", .sel = {2, 5}, .ful = {0, 7},},
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
FAKE_UPDATE_SAW(">XWVU|>ZYXWVUTS|");
ASSERT_CSUM(ctx, "NNNN");
assert_int_equal(2, fake_update_called);
assert_int_equal(1, fake_compare_called);
test_case_destroy(&ctx);
}
/**
* Single extent that spans multiple chunks. Request is only part of first
* and last chunk so those should have new checksums, while only the
* beginning/ending chunks are verified. The two middle chunks' checksums
* should be copied.
*
* Should look like this:
* Fetch extent: X W | V U T S | Z Y X W | V U |
* epoch 1 extent: Z Y X W | V U T S | Z Y X W | V U T S |
* index: 0 1 2 3 | 4 5 6 7 | 8 9 10 11 |12 13 14 15 |
* Should create a new csum for the first chunk, copy the middle 2 chunks, then
* create a new csum for the last chunk
*/
static void
request_needs_new_and_copy(void **state)
{
struct vos_fetch_test_context ctx;
/** Setup */
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 2,
.request_len = 12,
.chunksize = 4,
.rec_size = 1,
.layout = {
{.data = "ZYXWVUTSZYXWVUTS", .sel = {2, 13},
.ful = {0, 15},},
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
FAKE_UPDATE_SAW(">XW|>ZYXW|>VU|>VUTS|");
assert_int_equal(4, fake_update_called);
assert_int_equal(2, fake_compare_called);
ASSERT_CSUM(ctx, "NNNNSSSSSSSSNNNN");
test_case_destroy(&ctx);
}
/**
* Two extents, second overlaps the first partially in first chunk and
* completely in second chunk. First chunk will need new checksum, second will
* be copied from second extent. The first chunk of both first and second
* extents will need to be verified.
*
*
* Should look like this:
* Fetch extent: 1 A | B \0
* epoch 2 extent: A | B \0
* epoch 1 extent: 1 2 | 3 \0
* index: 0 1 | 2 3
*/
static void
unaligned_chunks_csums_new_csum_is_created(void **state)
{
struct vos_fetch_test_context ctx;
/** Setup */
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 0,
.request_len = 4,
.chunksize = 2,
.rec_size = 1,
.layout = {
{.data = "123", .sel = {0, 0}, .ful = {0, 3},},
{.data = "AB", .sel = {1, 3}, .ful = {1, 3},},
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
FAKE_UPDATE_SAW(">1|A|>12|>A|");
ASSERT_CSUM(ctx, "NNNNSSSS");
assert_int_equal(4, fake_update_called);
assert_int_equal(2, fake_compare_called);
test_case_destroy(&ctx);
}
/**
* Make sure not verifying chunks that are not part of fetch, even
* though parts of the extent are. Request is first part of two extents, but
* not part of the second chunk of extent two. When verifying, should not need
* second chunk.
*
* Should look like this:
* Fetch extent: 5 A B C
* epoch 2 extent: A B C D E F G | H I J
* epoch 1 extent: 5 6 7
* index: 0 1 2 3 4 5 6 7 | 8 9 10
*/
static void
extent_larger_than_request(void **state)
{
struct vos_fetch_test_context ctx;
/**
* Fetching a whole single chunk that's made up of two extents.
* Only the first 2 bytes of first are visible, but will need to verify
* the whole chunk from the first.
*
*/
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 0,
.request_len = 4,
.chunksize = 8,
.rec_size = 1,
.layout = {
{.data = "567",
.sel = {0, 0}, .ful = {0, 2} },
{.data = "ABCDEFGHI",
.sel = {1, 3}, .ful = {1, 10} },
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
FAKE_UPDATE_SAW(">5|ABC|>567|>ABCDEFG|");
assert_int_equal(4, fake_update_called);
assert_int_equal(2, fake_compare_called);
ASSERT_CSUM(ctx, "NNNN");
/** clean up */
test_case_destroy(&ctx);
}
/**
* First extent isn't aligned but everything else is. Because first chunk is
* made up of a single extent (even though it is unaligned), a new checksum is
* not needed and can be copied.
*
* Should look like this:
* Fetch extent: A | C \0
* epoch 2 extent: | C \0
* epoch 1 extent: A | B \0
* index: 0 1 | 2 3
*/
static void
unaligned_first_chunk(void **state)
{
struct vos_fetch_test_context ctx;
/** Setup */
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 1,
.request_len = 3,
.chunksize = 2,
.rec_size = 1,
.layout = {
{.data = "AB", .sel = {1, 1}, .ful = {1, 3} },
{.data = "C", .sel = {2, 3}, .ful = {2, 3} },
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
FAKE_UPDATE_SAW("");
ASSERT_CSUM(ctx, "SSSSSSSS");
assert_int_equal(0, fake_update_called);
assert_int_equal(0, fake_compare_called);
test_case_destroy(&ctx);
}
/**
* Two extents that don't overlap, but don't align (meet i nthe middle of a
* chunk). Will copy stored checksums for first and last chunk, but create a
* new one for the middle chunk.
*
* Should look like this:
* Fetch extent: A B C | D E F | G H I |
* epoch 2 extent: | E F | G H I |
* epoch 1 extent: A B C | D | |
* index: 0 1 2 | 3 4 5 | 6 7 8 |
*/
static void
fetch_multiple_unaligned_extents(void **state)
{
struct vos_fetch_test_context ctx;
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 0,
.request_len = 9,
.chunksize = 3,
.rec_size = 1,
.layout = {
{.data = "ABCD", .sel = {0, 3}, .ful = {0, 3} },
{.data = "EFGHI", .sel = {4, 8}, .ful = {4, 8} },
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
FAKE_UPDATE_SAW(">D|EF|>D|>EF|");
assert_int_equal(4, fake_update_called);
assert_int_equal(2, fake_compare_called);
ASSERT_CSUM(ctx, "SSSSNNNNSSSS");
/** clean up */
test_case_destroy(&ctx);
}
/**
*
* Many extents without overlapping
*
* Should look like this:
* Fetch extent: A B C D | E F
* epoch 6 extent: | F
* epoch 5 extent: | E
* epoch 4 extent: D |
* epoch 3 extent: C |
* epoch 2 extent: B |
* epoch 1 extent: A |
* index: 0 1 2 3 | 4 5
*/
static void
many_extents(void **state)
{
struct vos_fetch_test_context ctx;
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 0,
.request_len = 6,
.chunksize = 4,
.rec_size = 1,
.layout = {
{.data = "A", .sel = {0, 0}, .ful = {0, 0} },
{.data = "B", .sel = {1, 1}, .ful = {1, 1} },
{.data = "C", .sel = {2, 2}, .ful = {2, 2} },
{.data = "D", .sel = {3, 3}, .ful = {3, 3} },
{.data = "E", .sel = {4, 4}, .ful = {4, 4} },
{.data = "F", .sel = {5, 5}, .ful = {5, 5} },
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
FAKE_UPDATE_SAW(">A|B|C|D|>A|>B|>C|>D|>E|F|>E|>F|");
ASSERT_CSUM(ctx, "NNNN");
/** clean up */
test_case_destroy(&ctx);
}
/**
* Request begins before extent. This will be represented by VOS as an extent
* that is a hole first.
*
* Should look like this:
* Fetch extent: _ _ X W | V U T S
* epoch 1 extent: X W | V U T S
* index: 0 1 2 3 | 4 5 6 7
*/
static void
request_that_begins_before_extent(void **state)
{
struct vos_fetch_test_context ctx;
/** Setup */
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 0,
.request_len = 8,
.chunksize = 4,
.rec_size = 1,
.layout = {
{.data = "", .sel = {0, 1}, .ful = {0, 1},
.is_hole = true},
{.data = "XWVUTS", .sel = {2, 7}, .ful = {2, 7},},
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
ASSERT_CSUM(ctx, "SSSS");
FAKE_UPDATE_SAW("");
assert_int_equal(0, fake_update_called);
assert_int_equal(0, fake_compare_called);
test_case_destroy(&ctx);
}
/**
* Two extents with a gap in the middle. Requesting all. The hole will be
* represented by VOS as a third extent that is a hole. Even though the first
* extent's hi isn't aligned, the stored checksum will still work.
*
* Should look like this:
* Fetch extent: A B C | D _ _ | G H I |
* epoch 2 extent: | | G H I |
* epoch 1 extent: A B C | D | |
* index: 0 1 2 | 3 4 5 | 6 7 8 |
*/
static void
fetch_with_hole(void **state)
{
struct vos_fetch_test_context ctx;
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 0,
.request_len = 9,
.chunksize = 3,
.rec_size = 1,
.layout = {
{.data = "ABCD", .sel = {0, 3}, .ful = {0, 3} },
{.data = "", .sel = {4, 5}, .ful = {4, 5},
.is_hole = true},
{.data = "GHI", .sel = {6, 8}, .ful = {6, 8} },
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
FAKE_UPDATE_SAW("");
ASSERT_CSUM(ctx, "SSSSSSSSSSSS");
/** clean up */
test_case_destroy(&ctx);
}
/**
* Hole within a single chunk
*
* Should look like this:
* Fetch extent: A B C _ _ _ G H |
* epoch 2 extent: G H |
* epoch 1 extent: A B C |
* index: 0 1 2 3 4 5 6 7 |
*/
static void
fetch_with_hole2(void **state)
{
struct vos_fetch_test_context ctx;
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 0,
.request_len = 8,
.chunksize = 8,
.rec_size = 1,
.layout = {
{.data = "ABC", .sel = {0, 2}, .ful = {0, 2} },
{.data = "", .sel = {3, 5}, .ful = {3, 5},
.is_hole = true},
{.data = "GHI", .sel = {6, 7}, .ful = {6, 7} },
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
FAKE_UPDATE_SAW(">ABC|GH|>ABC|>GH|");
ASSERT_CSUM(ctx, "NNNN");
/** clean up */
test_case_destroy(&ctx);
}
/**
*
* Many holes in a single chunk
*
* Should look like this:
* Fetch extent: A _ B _ C _ D _ E _ F
* epoch 6 extent: F
* epoch 5 extent: E
* epoch 4 extent: D
* epoch 3 extent: C
* epoch 2 extent: B
* epoch 1 extent: A
* index: 0 1 2 3 4 5 6 7 8 9 10
*/
static void
fetch_with_hole3(void **state)
{
struct vos_fetch_test_context ctx;
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 0,
.request_len = 20,
.chunksize = 16,
.rec_size = 1,
.layout = {
{.data = "A", .sel = {0, 0}, .ful = {0, 0} },
{.data = "", .sel = {1, 1}, .ful = {1, 1},
.is_hole = true},
{.data = "B", .sel = {2, 2}, .ful = {2, 2} },
{.data = "", .sel = {3, 3}, .ful = {3, 3},
.is_hole = true},
{.data = "C", .sel = {4, 4}, .ful = {4, 4} },
{.data = "", .sel = {5, 5}, .ful = {5, 5},
.is_hole = true},
{.data = "D", .sel = {6, 6}, .ful = {6, 6} },
{.data = "", .sel = {7, 7}, .ful = {7, 7},
.is_hole = true},
{.data = "E", .sel = {8, 8}, .ful = {8, 8} },
{.data = "", .sel = {9, 9}, .ful = {9, 9},
.is_hole = true},
{.data = "F", .sel = {10, 10}, .ful = {10, 10} },
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
FAKE_UPDATE_SAW(">A|B|C|D|E|F|>A|>B|>C|>D|>E|>F|");
ASSERT_CSUM(ctx, "NNNN");
/** clean up */
test_case_destroy(&ctx);
}
/**
*
* 2 holes, first spans a whole chunk, second starts in middle of a chunk and
* ends in middle of next chunk
*
* Should look like this:
* Fetch extent: _ _ _ _ _ _ _ _ | A B C D E F _ _ | _ _ G H I J K L
* epoch 2 extent: | | G H I J K L
* epoch 1 extent: | A B C D E F |
* index: 0 1 2 3 4 5 6 7 | 8 9 10 11 12 13 14 15 |16 17 18 19 20 21 22 23
*/
static void
fetch_with_hole4(void **state)
{
struct vos_fetch_test_context ctx;
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 0,
.request_len = 23,
.chunksize = 8,
.rec_size = 1,
.layout = {
{.data = "", .sel = {0, 7}, .ful = {0, 7},
.is_hole = true},
{.data = "ABCDEF", .sel = {8, 13}, .ful = {8, 13} },
{.data = "", .sel = {14, 17}, .ful = {14, 17},
.is_hole = true},
{.data = "GHIJKL", .sel = {18, 23}, .ful = {18, 23} },
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
FAKE_UPDATE_SAW("");
ASSERT_CSUM_EMPTY(ctx, 0);
ASSERT_CSUM_IDX(ctx, "SSSS", 1);
/** clean up */
test_case_destroy(&ctx);
}
/**
* Will create a new checksum for the first chunk, but there's a hole that
* continues into the next chunk.
*
* Should look like this:
* Fetch extent: A B C _ | _ _ _ _ | _ G H |
* epoch 3 extent: | | G H |
* epoch 2 extent: B C | | |
* epoch 1 extent: A | | |
* index: 0 1 2 3 | 4 5 6 7 | 8 9 10 11 |
*/
static void
fetch_with_hole5(void **state)
{
struct vos_fetch_test_context ctx;
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 0,
.request_len = 12,
.chunksize = 4,
.rec_size = 1,
.layout = {
{.data = "ABC", .sel = {0, 0}, .ful = {0, 0} },
{.data = "BC", .sel = {1, 2}, .ful = {1, 2} },
{.data = "", .sel = {3, 8}, .ful = {3, 8},
.is_hole = true},
{.data = "GH", .sel = {9, 10}, .ful = {9, 10} },
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
FAKE_UPDATE_SAW(">A|BC|>A|>BC|");
ASSERT_CSUM(ctx, "NNNN");
ASSERT_CSUM_EMPTY(ctx, 1);
ASSERT_CSUM_IDX(ctx, "SSSS", 2);
/** clean up */
test_case_destroy(&ctx);
}
/**
* Will skip the first chunk of the request, then create a checksum for the A
* in the second chunk. Request has two chunks even though it is only 1 chunk
* in length.
*
* Should look like this:
* Fetch extent: _ _ _ | A | |
* epoch 1 extent: | A B C D | |
* index: 0 1 2 3 | 4 5 6 7 | 8 9 10 11 |
*/
static void
fetch_with_hole6(void **state)
{
struct vos_fetch_test_context ctx;
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 1,
.request_len = 4,
.chunksize = 4,
.rec_size = 1,
.layout = {
{.data = "", .sel = {1, 3}, .ful = {1, 3},
.is_hole = true},
{.data = "ABCD", .sel = {4, 4}, .ful = {4, 7} },
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
FAKE_UPDATE_SAW(">A|>ABCD|");
ASSERT_CSUM_EMPTY(ctx, 0);
ASSERT_CSUM_IDX(ctx, "NNNN", 1);
/** clean up */
test_case_destroy(&ctx);
}
/**
* Hole within a single chunk
*
* Should look like this:
* Fetch extent: A | B _ | _ _ | | H I | J K | L M
* epoch 3 punch: | _ | _ _ | _ _ |
* epoch 1 extent: A | B C | D E | F G | H I | J K | L M
* index: 0 1 | 2 3 | 4 5 | 6 7 | 8 9 | 10 11 | 12 13
*/
static void
fetch_with_hole7(void **state)
{
struct vos_fetch_test_context ctx;
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 1,
.request_len = 13,
.chunksize = 2,
.rec_size = 1,
.layout = {
{.data = "ABCDEFGHIJKLM", .sel = {1, 2}, .ful = {1, 13} },
{.data = "", .sel = {3, 7}, .ful = {3, 7}, .is_hole = true},
{.data = "HIJKLM", .sel = {8, 13}, .ful = {1, 13} },
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
FAKE_UPDATE_SAW(">B|>BC|");
ASSERT_CSUM(ctx, "SSSS");
/** clean up */
test_case_destroy(&ctx);
}
/**
* If multiple recx are part of an iod, there will be more biov's than needed
* for a single recx.
*
* Fetch extent: A B C D | E
* epoch 2 extent: | F G H | I J K
* epoch 1 extent: A B C D | E |
* index: 0 1 2 3 | 4 5 6 7 | 8 9 10
*/
static void
request_is_only_part_of_biovs(void **state)
{
struct vos_fetch_test_context ctx;
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 0,
.request_len = 5,
.chunksize = 4,
.rec_size = 1,
.layout = {
{.data = "ABCDE",
.sel = {0, 4}, .ful = {0, 4} },
{.data = "FGHIJK",
.sel = {5, 10}, .ful = {5, 10} },
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
FAKE_UPDATE_SAW("");
ASSERT_CSUM(ctx, "SSSSSSSS");
/** clean up */
test_case_destroy(&ctx);
}
static void
larger_records(void **state)
{
struct vos_fetch_test_context ctx;
const int buf_len = 1024;
char large_data01[buf_len];
char large_data02[buf_len];
int i;
for (i = 0; i < buf_len; i++) {
large_data01[i] = 'A' + i % ('Z' + 1 - 'A');
large_data02[i] = 'a' + i % ('z' + 1 - 'a');
}
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 0,
.request_len = 8,
.chunksize = 12,
.rec_size = 4,
.layout = {
{.data = large_data02,
.sel = {0, 3}, .ful = {0, 3} },
{.data = large_data01,
.sel = {4, 7}, .ful = {4, 7} },
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
/** 1 record from 1st extent (mnop) and 2 records from 2nd extent
* (ABCDEFGH)
*/
FAKE_UPDATE_SAW(">mnop|ABCDEFGH|>mnop|>ABCDEFGH|");
ASSERT_CSUM(ctx, "SSSSNNNN");
/** clean up */
test_case_destroy(&ctx);
}
static void
larger_records2(void **state)
{
struct vos_fetch_test_context ctx;
char *large_data01;
char *large_data02;
D_ALLOC(large_data01, 1024 * 16);
D_ALLOC(large_data02, 1024 * 16);
memset(large_data01, 'A', 1024 * 16);
memset(large_data02, 'B', 1024 * 16);
ARRAY_TEST_CASE_CREATE(&ctx, {
.request_idx = 0,
.request_len = 12,
.chunksize = 1024 * 32,
.rec_size = 1024,
.layout = {
{.data = large_data02,
.sel = {0, 2}, .ful = {0, 2} },
{.data = large_data01,
.sel = {2, 11}, .ful = {0, 11} },
{.data = NULL}
}
});
/** Act */
assert_success(fetch_csum_verify_bsgl_with_args(&ctx));
/** Verify */
assert_int_equal(4, fake_update_called);
assert_int_equal(2, fake_compare_called);
/** clean up */
test_case_destroy(&ctx);
D_FREE(large_data01);
D_FREE(large_data02);
}
/**
* ----------------------------------------------------------------------------
* Single Value Test
* ----------------------------------------------------------------------------
*/
static void
update_fetch_sv(void **state)
{
struct daos_csummer *csummer;
struct bio_iov biov = {0};
struct bio_sglist bsgl = {0};
/** vos_update_begin will populate a list of csum_infos (one for each
* biov 'extent'
*/
struct dcs_csum_info from_vos_begin = {0};
struct dcs_ci_list from_vos_begin_list = {0};
struct dcs_csum_info csum_info = {0};
struct dcs_iod_csums iod_csums = {0};
uint32_t iod_csum_value = 0;
daos_iod_t iod = {0};
char *data = "abcd";
uint32_t csum = 0x12345678;
daos_csummer_init(&csummer, &fake_algo, 4, 0);
iod.iod_type = DAOS_IOD_SINGLE;
iod.iod_size = strlen(data);
iod.iod_nr = 1;
ci_set(&csum_info, &iod_csum_value, sizeof(uint32_t), sizeof(uint32_t),
1, CSUM_NO_CHUNK, 1);
iod_csums.ic_data = &csum_info;
biov.bi_buf = data;
biov.bi_data_len = strlen(data);
bsgl.bs_iovs = &biov;
bsgl.bs_nr_out = 1;
bsgl.bs_nr = 1;
ci_set(&from_vos_begin, &csum, sizeof(uint32_t), sizeof(uint32_t), 1,
CSUM_NO_CHUNK, 1);
assert_success(dcs_csum_info_list_init(&from_vos_begin_list, 1));
dcs_csum_info_save(&from_vos_begin_list, &from_vos_begin);
ds_csum_add2iod(&iod, csummer, &bsgl, &from_vos_begin_list, NULL,
&iod_csums);
assert_memory_equal(csum_info.cs_csum, from_vos_begin.cs_csum,
from_vos_begin.cs_len);
daos_csummer_destroy(&csummer);
dcs_csum_info_list_fini(&from_vos_begin_list);
}
#define assert_csum_err(fn) assert_rc_equal(-DER_CSUM, (fn))
static void
key_verify(void **state)
{
struct daos_csummer *csummer;
daos_key_t dkey = {0};
char dkey_buf[32] = {0};
struct dcs_csum_info *dkey_csum = NULL;
daos_iod_t iods = {0};
struct dcs_iod_csums *iod_csums = NULL;
char akey_buf[32] = {0};
daos_csummer_init_with_type(&csummer, HASH_TYPE_CRC32, 4, 0);
d_iov_set(&dkey, dkey_buf, ARRAY_SIZE(dkey_buf));
sprintf(dkey_buf, "dkey");
d_iov_set(&iods.iod_name, akey_buf, ARRAY_SIZE(akey_buf));
sprintf(akey_buf, "akey");
assert_success(daos_csummer_calc_key(csummer, &dkey, &dkey_csum));
assert_success(daos_csummer_calc_iods(csummer, NULL, &iods, NULL, 1, true, NULL, 0,
&iod_csums));
assert_success(ds_csum_verify_keys(csummer, &dkey, dkey_csum, &iods, iod_csums, 1, NULL));
MEASURE_TIME(ds_csum_verify_keys(csummer, &dkey, dkey_csum, &iods, iod_csums, 1, NULL),
noop(), noop());
sprintf(dkey_buf, "corrupted");
assert_csum_err(ds_csum_verify_keys(csummer, &dkey, dkey_csum, &iods, iod_csums, 1, NULL));
daos_csummer_free_ci(csummer, &dkey_csum);
daos_csummer_free_ic(csummer, &iod_csums);
daos_csummer_destroy(&csummer);
}
static int
sct_setup(void **state)
{
return 0;
}
static int
sct_teardown(void **state)
{
reset_fake_algo();
return 0;
}
/* Convenience macro for unit tests */
#define TA(desc, test_fn) \
{ desc, test_fn, sct_setup, sct_teardown }
static const struct CMUnitTest srv_csum_tests[] = {
TA("SRV_CSUM_ARRAY01: Whole extent requested",
request_that_matches_single_extent),
TA("SRV_CSUM_ARRAY02: Whole extent requested, broken into multiple "
"chunks", request_that_matches_single_extent_multiple_chunks),
TA("SRV_CSUM_ARRAY03: Whole extent requested, broken into multiple "
"chunks, not aligned to chunk",
request_that_matches_single_extent_multiple_chunks_not_aligned),
TA("SRV_CSUM_ARRAY04: Multiple aligned extents requested",
request_that_matches_multiple_aligned_extents),
TA("SRV_CSUM_ARRAY05: Multiple aligned extents requested",
request_that_matches_multiple_aligned_extents2),
TA("SRV_CSUM_ARRAY06: Request more than exists",
request_that_is_more_than_extents),
TA("SRV_CSUM_ARRAY07: Partial Extents, first part of chunk",
partial_chunk_request0),
TA("SRV_CSUM_ARRAY08: Partial Extents, last part of chunk",
partial_chunk_request1),
TA("SRV_CSUM_ARRAY09: Partial Extents, middle part of chunk",
partial_chunk_request2),
TA("SRV_CSUM_ARRAY10: Partial chunks and full chunks",
request_needs_new_and_copy),
TA("SRV_CSUM_ARRAY11: Partial Extents, chunks don't align",
unaligned_chunks_csums_new_csum_is_created),
TA("SRV_CSUM_ARRAY12: Partial Extents, first extent isn't aligned",
unaligned_first_chunk),
TA("SRV_CSUM_ARRAY13: Partial Extents, extent smaller than chunk",
extent_smaller_than_chunk),
TA("SRV_CSUM_ARRAY14: Extent is larger than chunk",
extent_larger_than_request),
TA("SRV_CSUM_ARRAY15: Full and partial chunks",
fetch_multiple_unaligned_extents),
TA("SRV_CSUM_ARRAY16: Many sequential extents", many_extents),
TA("SRV_CSUM_ARRAY17: Begins with hole", request_that_begins_before_extent),
TA("SRV_CSUM_ARRAY18: Hole in middle", fetch_with_hole),
TA("SRV_CSUM_ARRAY19: Hole in middle", fetch_with_hole2),
TA("SRV_CSUM_ARRAY20: Many holes in middle", fetch_with_hole3),
TA("SRV_CSUM_ARRAY21: First chunk is hole", fetch_with_hole4),
TA("SRV_CSUM_ARRAY22: Handle holes while creating csums", fetch_with_hole5),
TA("SRV_CSUM_ARRAY22: Hole spans past first chunk", fetch_with_hole6),
TA("SRV_CSUM_ARRAY13: Hole in middle spans multiple chunks", fetch_with_hole7),
TA("SRV_CSUM_ARRAY24: First recx request of multiple", request_is_only_part_of_biovs),
TA("SRV_CSUM_ARRAY25: Fetch with larger records1", larger_records),
TA("SRV_CSUM_ARRAY26: Fetch with larger records2", larger_records2),
TA("SRV_CSUM_SV01: Various scenarios for update/fetch with fault injection",
update_fetch_sv),
TA("SRV_CSUM_01: Server side key verification", key_verify),
};
int
main(int argc, char **argv)
{
int rc = 0;
#if CMOCKA_FILTER_SUPPORTED == 1 /** for cmocka filter(requires cmocka 1.1.5) */
char filter[1024];
if (argc > 1) {
snprintf(filter, 1024, "*%s*", argv[1]);
cmocka_set_test_filter(filter);
}
#endif
rc += cmocka_run_group_tests_name(
"Storage and retrieval of checksums for Array Type",
srv_csum_tests, NULL, NULL);
return rc;
}
|
C
|
/***************************************************************************
> Filename : 019.c
> Author : oneface - [email protected]
> Company : 一尊还酹江月
> Time : 2018-04-24 15:31:26
> Description:
- This program is free software; you can redistribute it and/or modify it
- under the terms of the GNU General Public License as published by the
- Free Software Foundation; either version 2 of the License, or (at your
- option) any later version.
**************************************************************************/
#include <stdio.h>
int main()
{
char *ptr = "h1234 world";
unsigned int uc;
sscanf(ptr + 1, "%4x", &uc);
printf("%d\n", uc);
return 0;
}
|
C
|
/* Authors : Antoine Laurens, Adrien Thabuis, Hugo Viard
* this file is the code for the demonstration of the PWM module
*/
#include <stdio.h>
#include <inttypes.h>
#include <unistd.h>
#include "system.h"
#include "io.h"
// adresses to write to
#define ENABLE_PWM_ADDR 0//0b000
#define PERIOD_ADDR 1//0b001
#define DUTY_CYCLE_ADDR 2//0b010
#define POLARITY_ADDR 3//0b011
#define CLK_DIVIDER_MSB_ADDR 4//0b100
#define CLK_DIVIDER_LSB_ADDR 5//0b101
#define SYS_FREQ 50000000 // system freq of 50 MHz
#define CLK_DIVIDER 1000
#define ACTIVE_LOW 0
#define ACTIVE_HIGH 1
#define ONE_SECOND 1000000
void enablePWM(void){
IOWR_8DIRECT(PWMPORT_0_BASE, ENABLE_PWM_ADDR, 0x01);
}
void disablePWM(void){
IOWR_8DIRECT(PWMPORT_0_BASE, ENABLE_PWM_ADDR, 0x00);
}
void setClockDivider(int division_factor){
int MSB = division_factor & 0xFF00; // get the first 8 most significant bits
MSB = MSB >> 8; // put the bits in the LSB to write to the register
int LSB = division_factor & 0x00FF; // get the 8 least significant bits
IOWR_8DIRECT(PWMPORT_0_BASE, CLK_DIVIDER_MSB_ADDR, MSB);
IOWR_8DIRECT(PWMPORT_0_BASE, CLK_DIVIDER_LSB_ADDR, LSB);
}
int setPeriod(int periodInMS,int clkDivider){
int periodInTicks = SYS_FREQ / clkDivider / 1000 * periodInMS;
IOWR_8DIRECT(PWMPORT_0_BASE, PERIOD_ADDR, periodInTicks);
return periodInTicks;
}
void setDutyCycle(int percentage,int periodInTicks){
int duty_cycle = (double)periodInTicks / (100.0/(double)percentage);
IOWR_8DIRECT(PWMPORT_0_BASE, DUTY_CYCLE_ADDR, duty_cycle);
}
void setPolarity(int polarity){
IOWR_8DIRECT(PWMPORT_0_BASE, POLARITY_ADDR, polarity);
}
int main(void)
{
enablePWM();
int read_debugg1 = 0;
int read_debugg2 = 0;
int read_debugg3 = 0;
int read_debugg4 = 0;
while(1)
{
read_debugg1 = IORD_8DIRECT(PWMPORT_0_BASE, ENABLE_PWM_ADDR);
read_debugg2 = IORD_8DIRECT(PWMPORT_0_BASE, PERIOD_ADDR);
read_debugg3 = IORD_8DIRECT(PWMPORT_0_BASE, DUTY_CYCLE_ADDR);
read_debugg4 = IORD_8DIRECT(PWMPORT_0_BASE, POLARITY_ADDR);
printf("Enable = %d, Period = %d, DutyCycle = %d, Polarity = %d\n",
read_debugg1, read_debugg2, read_debugg3, read_debugg4);
setClockDivider(CLK_DIVIDER);
periodInTicks = setPeriod(2,CLK_DIVIDER);
setDutyCycle(25,periodInTicks);
setPolarity(ACTIVE_LOW);
usleep(ONE_SECOND);
periodInTicks = setPeriod(2,CLK_DIVIDER);
setDutyCycle(50,periodInTicks);
setPolarity(ACTIVE_HIGH);
usleep(ONE_SECOND);
periodInTicks = setPeriod(2,CLK_DIVIDER);
setDutyCycle(75,periodInTicks);
setPolarity(ACTIVE_HIGH);
usleep(ONE_SECOND);
periodInTicks = setPeriod(2,CLK_DIVIDER);
setDutyCycle(75,periodInTicks);
setPolarity(ACTIVE_LOW);
usleep(ONE_SECOND);
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: leoperei <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/07/30 21:51:33 by leoperei #+# #+# */
/* Updated: 2021/08/08 19:52:48 by leoperei ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static t_size ft_count_until(char const *str, char end, unsigned int equal)
{
t_size qty;
qty = -1;
while (str[++qty])
if ((equal && str[qty] != end)
|| (!equal && str[qty] == end))
return (qty);
return (qty);
}
static t_size ft_count_words(char const *str, char delimiter)
{
t_size i;
t_size words;
words = 0;
i = ft_count_until(str, delimiter, 1);
while (str[i])
{
words++;
i += ft_count_until((str + i), delimiter, 0);
i += ft_count_until((str + i), delimiter, 1);
}
return (words);
}
static void *ft_clean_matrix(void **matrix)
{
t_size i;
i = -1;
while (matrix[++i])
free(matrix[i]);
free(matrix);
return (NULL);
}
char **ft_split(char const *string, char delimiter)
{
int i;
int word;
int words;
int word_size;
char **strings;
if (!string)
return (NULL);
words = ft_count_words(string, delimiter);
strings = (char **) ft_calloc((words + 1), sizeof(char *));
if (!strings)
return (NULL);
i = ft_count_until(string, delimiter, 1);
word = -1;
while (++word < words)
{
word_size = ft_count_until((string + i), delimiter, 0);
strings[word] = (char *) malloc(sizeof(char) * (word_size + 1));
if (!strings[word])
return (ft_clean_matrix((void **)strings));
ft_strlcpy(strings[word], (string + i), (word_size + 1));
i += ft_count_until((string + i + word_size), delimiter, 1);
i += word_size;
}
return (strings);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* mtrx_new.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aanzieu <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/12/10 15:37:23 by aanzieu #+# #+# */
/* Updated: 2018/12/10 15:44:01 by aanzieu ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/scop.h"
GLfloat *mat3(void)
{
GLfloat *matrix;
matrix = (GLfloat *)calloc(9, sizeof(GLfloat));
memset(matrix, 0, sizeof(GLfloat) * 9);
matrix[0] = 1.0f;
matrix[4] = 1.0f;
matrix[8] = 1.0f;
return (matrix);
}
GLfloat *mat4(void)
{
GLfloat *matrix;
matrix = (GLfloat *)calloc(16, sizeof(GLfloat));
memset(matrix, 0, sizeof(GLfloat) * 16);
matrix[0] = 1.0f;
matrix[5] = 1.0f;
matrix[10] = 1.0f;
matrix[15] = 1.0f;
return (matrix);
}
GLfloat *mat4_clone(GLfloat *matrix)
{
GLfloat *new_matrix;
new_matrix = mat4();
memcpy(new_matrix, matrix, sizeof(GLfloat) * 16);
free(matrix);
return (new_matrix);
}
|
C
|
//
// Created by aaron on 16-11-3.
//
#include <stdio.h>
#include <stdlib.h>
#include "avltree.h"
void main(void) {
const int N = 16;
AvlTree T = makeEmpty(NULL);
int a[] = {1, 2, 3, 4, 5, 6, 7, 16, 15, 14, 13, 12, 11, 10, 8, 9};
for (int i = 0; i < N; ++i) {
T = insert(a[i], T);
}
postorderTraversal(T);
printf("\n");
printf("min: %d, max: %d\n", retrive(findMin(T)), retrive(findMax(T)));
printf("find(3) == %d\n", retrive(find(19, T)));
}
|
C
|
#include<stdio.h>
int main(int argc, char const *argv[])
{
printf("Storage size for int: %ld\n",sizeof(int));
printf("Storage size for int: %ld\n",sizeof(long));
printf("Storage size for int: %ld\n",sizeof(char));
printf("Storage size for int: %ld\n",sizeof(double));
printf("Storage size for int: %ld\n",sizeof(float));
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
typedef struct listad{
struct listad *ant;
char panc;
struct listad *prox;
}TLISTA;
TLISTA* limpalist(char *panc){
TLISTA *aux,*bef,*inicio;
int tam = strlen(panc),a;
for(a=0;a<tam;a++){
if(a){
if(panc[a] != panc[a-1]){
aux = (TLISTA*)malloc(sizeof(TLISTA));
aux->ant = bef;
aux->panc = panc[a];
aux->prox = NULL;
bef->prox = aux;
bef = aux;
}
}else{
aux = (TLISTA*)malloc(sizeof(TLISTA));
aux->ant = NULL;
aux->panc = panc[a];
aux->prox = NULL;
bef = aux;
inicio = aux;
}
}
return inicio;
}
void printds(TLISTA *inicio){
TLISTA *aux = inicio;
while(aux != NULL){
printf("%c",aux->panc);
aux = aux->prox;
}
printf("\n");
}
void swap(TLISTA *inicio){
TLISTA *aux;
aux = inicio->ant;
while(aux != NULL){
if(aux->panc == '-'){
aux->panc = '+';
}else{
aux->panc = '-';
}
aux = aux->ant;
}
}
int main(){
TLISTA *aux,*inicio;
int casos,a,cont;
char panc[105];
scanf("%d", &casos);
for (a=1;a<=casos;a++){
scanf("%s",panc);
inicio = limpalist(panc);
aux = inicio;
if(inicio->prox == NULL){
if(inicio->panc == '-'){
printf("Case #%d: 1\n",a);
}else{
printf("Case #%d: 0\n",a);
}
continue;
}
swap(inicio->prox);
aux = aux->prox;
cont = 1;
while(aux!=NULL){
if(aux->ant->panc != aux->panc){
cont++;
swap(aux);
aux = inicio;
}
aux = aux->prox;
}
if(inicio->panc == '-'){
printf("Case #%d: %d\n",a,cont + 1);
}else{
printf("Case #%d: %d\n",a,cont);
}
// printds(inicio);
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.