language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>
#define PID_FILE "runtime/ramtits.pid"
int main(void)
{
FILE *fp;
char filename[256];
unsigned pid;
sprintf(filename,"%s",PID_FILE);
if ((fp=fopen(filename,"r")))
{
fscanf(fp,"%u\n",&pid);
printf("[RaMTITS] - Shutting down the talker...\n");
kill(pid,SIGKILL);
fclose(fp);
unlink(filename);
unlink("runtime/dns_server.pid");
}
else printf("[RaMTITS] - Failed to locate: [%s]\n",PID_FILE);
exit(0);
}
|
C
|
#include <stdio.h>
void bubble_sort(int* a, int n) {
int i, j, k;
for (i = 0; i < n - 1; i++)
for (j = 0; j < n; j++)
for (k = 0; k < n; k++)
if (a[k] > a[j]) {
int temp = a[j];
a[j] = a[k];
a[k] = temp;
}
}
int main() {
int n, i;
printf("Введите размер массива");
scanf("%d", &n);
int* a = (int*)malloc(sizeof(int) * n);
printf("Введите элементы массива");
for (i = 0; i < n; i++)
scanf("%d", a + i);
bubble_sort(a, n);
for (i = 0; i < n; i++)
printf("%d ", a[i]);
return 0;
}
|
C
|
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include"files.h"
void rm_defact_func(FILE *fsource, int magicNumber, char *fname)
{
char buf[256];
FILE *fp;
fp = fopen("temp.mgd", "w");
fprintf(fp, "%d\n", magicNumber);
while(fgets(buf, 256, fsource)) {
if(strstr(buf, "-1") == NULL)
fputs(buf, fp);
}
fclose(fsource);
fclose(fp);
remove(fname);
rename("temp.mgd", fname);
}
void process_source_file(FILE *fsource, char *fname)
{
char buf[128], filename[128];
FILE *fp;
int magicNumber;
fscanf(fsource, "%d\n", &magicNumber);
if(magicNumber == FILE_LIST) {
memset(buf, '\0', 128);
while (fgets(buf, 127, fsource)) {
sscanf(buf, "%s", filename);
if( (fp=fopen(filename, "r"))!=NULL) {
process_source_file(fp, filename);
}
memset(buf, '\0', 128);
}
} else if (magicNumber == FILE_MODIFIED_GPS_TAXI
|| magicNumber == FILE_MODIFIED_GPS_BUS) {
rm_defact_func(fsource, magicNumber, fname);
}
}
int main(int argc, char**argv)
{
FILE *fsource;
if(argc < 2) {
printf("%s is used to remove defact reports in mgd files\n", argv[0]);
printf("Usage: %s .mgd|.lst ...\n", argv[0]);
exit(1);
}
while(argc > 1) {
if((fsource=fopen(argv[1], "r"))!=NULL) {
printf("Loading %s file ...\n", argv[1]);
process_source_file(fsource, argv[1]);
}
argc--;
argv++;
}
return 0;
}
|
C
|
#include "set.h"
#define CAPACITY_INCR 2
struct _Set {
void **store;
unsigned int capacity;
unsigned int size;
};
bool set_full(Set *set);
Set *set_new()
{
Set *set = (Set *) malloc(sizeof(Set));
set->store = malloc(CAPACITY_INCR * sizeof(void *));
if (!set->store)
return NULL;
set->capacity = CAPACITY_INCR;
set->size = 0;
return set;
}
void set_destroy(Set *set, void (*item_destroy)(void *))
{
if (!set)
return;
for (int i = 0; i < set->size; i++)
item_destroy(set->store[i]);
free(set);
}
status set_empty(Set *set)
{
if (!set)
return ERROR;
set->size = 0;
return OK;
}
int set_size(Set *set)
{
if (!set)
return -1;
return set->size;
}
status set_insert(Set *set, void *item)
{
if (!set || !item)
return ERROR;
if (set_full(set))
{
void **new_store = realloc(set->store, (set->capacity + CAPACITY_INCR) * sizeof(void *));
if (!new_store)
return ERROR;
else
{
set->store = new_store;
set->capacity += CAPACITY_INCR;
}
}
if (!set_search(set, item))
{
set->store[set->size] = item;
set->size++;
return OK;
}
else
return ERROR;
}
bool set_search(Set *haystack, void *needle)
{
for (int i = 0; i < haystack->size; i++)
{
if (haystack->store[i] == needle)
return true;
}
return false;
}
status set_union(Set *a, Set *b, Set *r)
{
if (!a || !b || !r)
return ERROR;
set_empty(r);
for (int i = 0; i < a->size; i++)
{
if (!set_insert(r, a->store[i]))
return ERROR;
}
for (int i = 0; i < b->size; i++)
{
// skip duplicate elements
if (set_search(r, b->store[i]))
continue;
if (!set_insert(r, b->store[i]))
return ERROR;
}
return OK;
}
status set_intersection(Set *a, Set *b, Set *r)
{
if (!a || !b || !r)
return ERROR;
Set *min_set, *other_set;
if (a->size < b->size)
{
min_set = a;
other_set = b;
}
else
{
min_set = b;
other_set = a;
}
set_empty(r);
for (int i = 0; i < min_set->size; i++)
{
if (set_search(other_set, min_set->store[i]))
{
if (!set_search(r, min_set->store[i]))
{
if (!set_insert(r, min_set->store[i]))
{
set_empty(r);
return ERROR;
}
}
}
}
return OK;
}
bool set_full(Set *set)
{
if (set->size == set->capacity)
return true;
return false;
}
|
C
|
/* reset.c -- set box 'b' to be invalid */
#include <limits.h>
#include "geom/box.h"
void box_reset(box_t *b)
{
const box_t invalid = { INT_MAX, INT_MAX, INT_MIN, INT_MIN };
*b = invalid;
}
|
C
|
#include "libmx.h"
int mx_memcmp(const void *s1, const void *s2, size_t n) {
unsigned char *c_dst = (unsigned char *)s1;
unsigned char *c_src = (unsigned char *)s2;
while (n-- > 0)
if (*c_dst++ != *c_src++)
return (*--c_dst - *--c_src);
return (0);
}
|
C
|
#include<stdio.h>
#include<stddef.h>
#include<unistd.h>
struct mb{
size_t size;
int fr;
struct mb *next;
};
char memory[10000];
struct mb *list = (void*)memory;
void init()
{
list->size = 10000-sizeof(struct mb);
list->fr=1;
list->next= NULL;
}
void split(struct mb *c,size_t si)
{
struct mb *new=(void *)((void*)c + si + sizeof(struct mb));
new->size= c->size - si - sizeof(struct mb);
new->fr=1;
new->next = c->next;
c->size=si;
c->fr=0;
c->next = new->next;
}
void *mallocn(size_t bytes)
{
struct mb *curr,*prev; void *result;
if(!(list->size))
{
init();
}
curr=list;
while((curr->size < bytes) || (curr->fr == 0) || (curr->next!=NULL))
{
prev=curr;
curr=curr->next;
}
if(curr->size==bytes)
{
result = (void*)(++curr);
return result;
}
else if(curr->size>(bytes + sizeof(struct mb)))
{
split(curr,bytes);
result = (void*)(++curr);
return result;
}
else
{
printf("\n NO memory");
return NULL;
}
}
void merge()
{
struct mb *curr,*prev;
curr=list;
while(curr->next!=NULL)
{
if(curr->next->fr && curr->fr)
{
curr->size+=curr->next->size + sizeof(struct mb);
curr->next=curr->next->next;
}
prev=curr;
curr=curr->next;
}
}
void freen(struct mb **ptr)
{
if(*ptr>=(void*)memory && *ptr<(void*)(memory+10000))
{
struct mb *curr=*ptr;
--curr;
curr->fr =1;
merge();
*ptr=NULL;
}
else
printf("\n Invalid Pointer! \n");
}
int main()
{
int *p = (int *)mallocn(100*sizeof(int));
printf("\n %p",p);
freen(&p);
if(p==NULL)
printf("\n FREED!!");
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
double find_perimeter(double area);
int main() {
//printf("hello world this is cake");
int input_cases, i;
double input;
double result;
scanf("%d", &input_cases);
for(i = 0; i < input_cases; i++) {
scanf("%lf", &input);
result = find_perimeter(input);
printf("%f\n", result);
}
return 0;
}
double find_perimeter(double area){
double perim = 0;
double side = 0;
/*logic: given AREA, find minimum perimeter
* minimum perimeter = square
* square = AREA = x^2
* side = root(AREA)
* 2(side + 2(side) = Perimeter*/
side = sqrt(area);
//printf("side: %0.0f", side);
perim = (2*side + 2*side);
return perim;
}
|
C
|
#include <time.h>
#include <stdlib.h>
int *getRandom(){
static int random [10];
srand((unsigned)time(NULL));
for(int i = 0; i < 10; i++){
random[i] = rand();
printf("%d\n", random[i]);
}
return random;
}
int main ()
{
int *random_pointer = getRandom();
for(int i=0; i < 10; i++){
printf("*(random_pointer + [%d]) is %d\n", i, *(random_pointer + i));
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define BUFSIZE 1024
// char buf[BUFSIZE];
//int n;
int copy_stdin2out()
{
int n;
char buf[BUFSIZE];
while((n=read(1,buf,BUFSIZE))>0)
{
write(0,buf,n);
}
}
int main()
{
int pd[2], pid;
pipe(pd);
pid = fork();
if (pid == 0)
{ // in child
dup2(pd[1], 0);
close(pd[0]);
close(pd[1]);
copy_stdin2out();
exit(0);
}
else // in parent
{
dup2(pd[0], 1);
close(pd[1]);
close(pd[0]);
//sleep(5);
// wait();
copy_stdin2out();
wait(NULL);
exit(0);
}
}
|
C
|
#include "my_conv.h"
int my_int2dec(char *dst, int v, unsigned n)
{
int i;
if (n == 0)
return 0;
if (v < 0)
{
i = my_uint2dec(dst + 1, (unsigned)(-v), n - 1);
if (i != 0)
{
*dst = '-';
return i + 1;
}
return i;
}
else
return my_uint2dec(dst, (unsigned) v, n);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "math2.h"
#include <time.h>
int main ()
{
int opc;
double a, b, c, d;
while (1)
{
puts ("Digite '1' para calcular a area de um quadrado");
puts ("Digite '2' para calcular a area de um trapezio");
puts ("Digite '3' para calcular a area de um losango");
puts ("Digite '4' para calcular a area de um poligono (5 lados ou mais)");
puts ("Digite '5' para calcular um juros simples");
puts ("Digite '6' para calcular um montante de juros simples");
puts ("Digite '7' para calcular um montande de juros compostos");
puts ("Digite '0' para sair");
scanf ("%d", &opc);
switch (opc)
{
case 1: //calcula quadrado
printf ("Digite o lado do quadrado: ");
scanf ("%lf", &a);
printf ("\n");
printf ("O valor do quadrado eh: %.2lf\n", calc_quadrado (a));
sleep (2);
puts ("\n");
break;
case 2: //calcula trapezio
printf ("Digite as duas bases do trapezio: ");
scanf ("%lf %lf", &a, &b);
printf ("Digite a altura do trapezio: ");
scanf ("%lf", &c);
printf ("\n");
printf ("O valor do trapezio eh: %.2lf\n", calc_trapezio (a, b, c));
sleep (2);
puts ("\n");
break;
case 3: //calcula losango
printf ("Digite as duas diagonais do losango: ");
scanf ("%lf %lf", &a, &b);
printf ("\n");
printf ("O valor do losango eh: %.2lf\n", calc_losango (a, b));
sleep (2);
puts ("\n");
break;
case 4: //calcula poligono
printf ("Digite a medida de um lado do poligono: ");
scanf ("%lf", &a);
printf ("\n");
printf ("Digite a quantidade de lados do poligono: ");
scanf ("%lf", &b);
printf ("\n");
printf ("Digite o tamanho da apotema: ");
scanf ("%lf", &c);
printf ("\n");
printf ("O valor do poligono eh: %.2lf\n", calc_polig_regular (a, b, c));
sleep (2);
puts ("\n");
break;
case 5: //calcula juros simples
printf ("Digite o capital aplicado, a taxa e o tempo de aplicacao: ");
scanf ("%lf %lf %lf", &a, &b, &c);
printf ("\n");
printf ("Juros simples: %.3lf\n", calc_juros_simp (a, b, c));
sleep (2);
break;
case 6: //calcula montante simples
printf ("Digite o capital aplicado e o juros simples da aplicacao: ");
scanf ("%lf %lf", &a, &b);
printf ("\n");
printf ("Montante simples: %.3lf\n", calc_mont_simp (a, b));
sleep (2);
break;
case 7:
printf ("Digite o capital aplicado, a taxa e o tempo de aplicacao: ");
scanf ("%lf %lf %lf", &a, &b, &c);
printf ("\n");
printf ("Montante composto: %.3lf\n", calc_mont_comp (a, b, c));
sleep (2);
break;
case 0:
return 0;
default:
printf ("Entrada invalida");
puts ("\n");
sleep (2);
break;
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void birthday(int number)
{
//ռ Ǭ ȭ ϴ
int year = number / 10000;
int month = number % 10000 / 100;
int day = number % 100;
if (year > 17)
printf("19%d %d %d\n", year, month, day);
else if (year > 0 && year < 10)
printf("200%d %d %d\n", year, month, day);
else if (year >= 10 && year <= 17)
printf("20%d %d %d\n", year, month, day);
}
int main(void)
{
int number;
while (1) // ֱ
{
printf(" ԷϽÿ:");
scanf("%d", &number);
birthday(number);
}
return 0;
}
|
C
|
/*
* vmm.c
*
* Created on: 09.07.2012
* Author: pascal
*/
/*
* vmm_SysPMMAlloc(): Rueckgabewerte: 1=Kein freier Speicherplatz mehr vorhanden
*/
#include "vmm.h"
#include "pmm.h"
#include "memory.h"
#include "display.h"
#include "paging.h"
#include "stdlib.h"
#include "string.h"
#include "lock.h"
#include "cpu.h"
#include <assert.h>
#define NULL (void*)0
#define VMM_SIZE_PER_PAGE MM_BLOCK_SIZE
#define VMM_SIZE_PER_TABLE 4096
#define VMM_MAX_ADDRESS MAX_ADDRESS
//Flags für AVL Bits
#define VMM_PAGE_FULL (1 << 0)
#define VMM_GUARD_PAGE (1 << 1)
#define VMM_PAGES_PER_PML4 VMM_PAGES_PER_PDP * PAGE_ENTRIES
#define VMM_PAGES_PER_PDP VMM_PAGES_PER_PD * PAGE_ENTRIES
#define VMM_PAGES_PER_PD VMM_PAGES_PER_PT * PAGE_ENTRIES
#define VMM_PAGES_PER_PT PAGE_ENTRIES
#define VMM_EXTEND(address) ((int64_t)((address) << 16) >> 16)
#define VMM_GET_ADDRESS(PML4i, PDPi, PDi, PTi) (void*)VMM_EXTEND(((uint64_t)PML4i << 39) | ((uint64_t)PDPi << 30) | (PDi << 21) | (PTi << 12))
#define VMM_ALLOCATED(entry) ((entry & PG_P) || (PG_AVL(entry) & (VMM_UNUSED_PAGE | VMM_GUARD_PAGE))) //Prüft, ob diese Page schon belegt ist
#define PAGE_TABLE_INDEX(address, level) (((uintptr_t)(address) >> (12 + (3 - (level)) * 9)) & 0x1FF)
#define PML4_INDEX(address) PAGE_TABLE_INDEX(address, 0)
#define PDP_INDEX(address) PAGE_TABLE_INDEX(address, 1)
#define PD_INDEX(address) PAGE_TABLE_INDEX(address, 2)
#define PT_INDEX(address) PAGE_TABLE_INDEX(address, 3)
#define MAPPED_PHYS_MEM_BASE 0xFFFFFF8000000000
#define MAPPED_PHYS_MEM_GET(addr) ((void*)(MAPPED_PHYS_MEM_BASE + (paddr_t)(addr)))
struct vmm_context {
paddr_t physAddress;
};
struct unmap_result {
paddr_t paddr;
uint16_t avl;
};
const uint16_t PML4e = PML4_INDEX(KERNELSPACE_END) + 1;
const uint16_t PDPe = PDP_INDEX(KERNELSPACE_END) + 1;
const uint16_t PDe = PD_INDEX(KERNELSPACE_END) + 1;
const uint16_t PTe = PT_INDEX(KERNELSPACE_END) + 1;
static lock_t vmm_lock = LOCK_INIT;
context_t kernel_context;
//Funktionen, die nur in dieser Datei aufgerufen werden sollen
uint8_t vmm_ChangeMap(context_t *context, void *vAddress, paddr_t pAddress, uint8_t flags, uint16_t avl);
/*
* Löscht eine (virtuelle) Page.
* Parameter: address = virtuelle Addresse der Page
*/
static void clearPage(void *address)
{
asm volatile("rep stosq" : :"c"(VMM_SIZE_PER_PAGE / sizeof(uint64_t)), "D"((uintptr_t)address & ~0xFFF), "a"(0) :"memory");
}
/*
* Gibt zurück, ob die entsprechende Page belegt ist oder nicht
* Parameter: Address = virtuelle Addresse
* Rückgabewert: true = Page ist frei
* false = Page ist belegt
*/
static bool isPageFree(const uint64_t *const PML4E, const uint64_t *const PDPE, const uint64_t *const PDE, const uint64_t *const PTE)
{
//PML4 Eintrag überprüfen
if((*PML4E & PG_P) == 0) //Wenn PML4-Eintrag vorhanden ist
return true;
//Ansonsten überprüfe PDP-Eintrag
else if((*PDPE & PG_P) == 0) //Wenn PDP-Eintrag vorhanden ist
return true;
//Ansonsten überprüfe PD-Eintrag
else if((*PDE & PG_P) == 0) //Wenn PD-Eintrag vorhanden ist
return true;
//Ansonsten überprüfe PT-Eintrag
return !VMM_ALLOCATED(*PTE);
}
static uint8_t map_entry(void *vAddress, paddr_t pAddress, uint8_t flags, uint16_t avl, PageTable_t table, uint32_t level)
{
uint32_t index = PAGE_TABLE_INDEX(vAddress, level);
PageTable_t next_table = MAPPED_PHYS_MEM_GET(table[index].Address << 12);
if(!table[index].P) {
table[index].entry = 0;
if(level == 3) {
table[index].P = !(avl & (VMM_UNUSED_PAGE | VMM_GUARD_PAGE));
table[index].RW = flags & VMM_FLAGS_WRITE;
table[index].US = flags & VMM_FLAGS_USER;
table[index].PWT = flags & VMM_FLAGS_PWT;
table[index].PCD = flags & VMM_FLAGS_NO_CACHE;
table[index].G = flags & VMM_FLAGS_GLOBAL;
table[index].AVL1 = avl;
table[index].AVL2 = avl >> 3;
table[index].Address = pAddress >> 12;
table[index].NX = flags & VMM_FLAGS_NX;
return 0;
} else {
paddr_t address = pmm_Alloc();
if(address == 1) return 1;
table[index].P = 1;
table[index].PWT = 1;
table[index].RW = 1; // Always mark as writable so that this recursive mapping method works
table[index].Address = address >> 12;
next_table = MAPPED_PHYS_MEM_GET(address);
clearPage(next_table);
}
} else if (level == 3) {
return 2;
}
// Potentially relax restriction
table[index].US |= flags & VMM_FLAGS_USER;
// There is no need for TLB invalidation here as the CPU will rewalk the page tables if it encounters a restriction validation
uint8_t res = map_entry(vAddress, pAddress, flags, avl, next_table, level + 1);
//Full flags setzen
uint16_t i;
for(i = 0; i < PAGE_ENTRIES; i++) {
if(!VMM_ALLOCATED(table[i].entry))
break;
}
if(i == PAGE_ENTRIES) {
table[index].AVL1 |= VMM_PAGE_FULL;
table[index].AVL2 |= VMM_PAGE_FULL >> 3;
}
return res;
}
static uint8_t map(context_t *context, void *vAddress, paddr_t pAddress, uint8_t flags, uint16_t avl) {
return map_entry(vAddress, pAddress, flags, avl, MAPPED_PHYS_MEM_GET(context->physAddress), 0);
}
static void *getFreePages(context_t *context, void *start, void *end, size_t pages)
{
PML4_t *const PML4 = MAPPED_PHYS_MEM_GET(context->physAddress);
size_t found_pages = 0;
//Einträge in die Page Tabellen
uint16_t start_PML4i = PML4_INDEX(start);
uint16_t start_PDPi = PDP_INDEX(start);
uint16_t start_PDi = PD_INDEX(start);
uint16_t start_PTi = PT_INDEX(start);
uint16_t end_PML4i = PML4_INDEX(end);
uint16_t end_PDPi = PDP_INDEX(end);
uint16_t end_PDi = PD_INDEX(end);
uint16_t end_PTi = PT_INDEX(end);
//Anfang des zusammenhängenden Bereichs
uint16_t begin_PML4i = start_PML4i;
uint16_t begin_PDPi = start_PDPi;
uint16_t begin_PDi = start_PDi;
uint16_t begin_PTi = start_PTi;
for (uint16_t PML4i = start_PML4i; PML4i <= end_PML4i; PML4i++)
{
if((PML4->PML4E[PML4i] & PG_P))
{
//Es sind noch Pages frei
if(!(PG_AVL(PML4->PML4E[PML4i]) & VMM_PAGE_FULL))
{
PDP_t *const PDP = MAPPED_PHYS_MEM_GET(PML4->PML4E[PML4i] & PG_ADDRESS);
uint16_t last_PDPi = (PML4i == end_PML4i) ? end_PDPi : PAGE_ENTRIES - 1;
for(uint16_t PDPi = (PML4i == start_PML4i) ? start_PDPi : 0; PDPi <= last_PDPi; PDPi++)
{
if((PDP->PDPE[PDPi] & PG_P))
{
//Es sind noch Pages frei
if(!(PG_AVL(PDP->PDPE[PDPi]) & VMM_PAGE_FULL))
{
PD_t *const PD = MAPPED_PHYS_MEM_GET(PDP->PDPE[PDPi] & PG_ADDRESS);
uint16_t last_PDi = (PML4i == end_PML4i && PDPi == end_PDPi) ? end_PDi : PAGE_ENTRIES - 1;
for(uint16_t PDi = (PML4i == start_PML4i && PDPi == start_PDPi) ? start_PDi : 0; PDi <= last_PDi; PDi++)
{
if((PD->PDE[PDi] & PG_P))
{
//Es sind noch Pages frei
if(!(PG_AVL(PD->PDE[PDi]) & VMM_PAGE_FULL))
{
PT_t *const PT = MAPPED_PHYS_MEM_GET(PD->PDE[PDi] & PG_ADDRESS);
uint16_t last_PTi = (PML4i == end_PML4i && PDPi == end_PDPi && PDi == end_PDi) ? end_PTi : PAGE_ENTRIES - 1;
for(uint16_t PTi = (PML4i == start_PML4i && PDPi == start_PDPi && PDi == start_PDi) ? start_PTi : 0;
PTi <= last_PTi; PTi++)
{
if(VMM_ALLOCATED(PT->PTE[PTi]))
{
found_pages = 0;
continue;
}
else
{
if(found_pages == 0)
{
begin_PTi = PTi;
begin_PDi = PDi;
begin_PDPi = PDPi;
begin_PML4i = PML4i;
}
found_pages++;
}
if(found_pages >= pages)
return VMM_GET_ADDRESS(begin_PML4i, begin_PDPi, begin_PDi, begin_PTi);
}
}
else
{
found_pages = 0;
continue;
}
}
else
{
if(found_pages == 0)
{
begin_PTi = 0;
begin_PDi = PDi;
begin_PDPi = PDPi;
begin_PML4i = PML4i;
}
found_pages += VMM_PAGES_PER_PT;
}
if(found_pages >= pages)
return VMM_GET_ADDRESS(begin_PML4i, begin_PDPi, begin_PDi, begin_PTi);
}
}
else
{
found_pages = 0;
continue;
}
}
else
{
if(found_pages == 0)
{
begin_PTi = 0;
begin_PDi = 0;
begin_PDPi = PDPi;
begin_PML4i = PML4i;
}
found_pages += VMM_PAGES_PER_PD;
}
if(found_pages >= pages)
return VMM_GET_ADDRESS(begin_PML4i, begin_PDPi, begin_PDi, begin_PTi);
}
}
else
{
found_pages = 0;
continue;
}
}
else
{
if(found_pages == 0)
{
begin_PTi = 0;
begin_PDi = 0;
begin_PDPi = 0;
begin_PML4i = PML4i;
}
found_pages += VMM_PAGES_PER_PDP;
}
if(found_pages >= pages)
return VMM_GET_ADDRESS(begin_PML4i, begin_PDPi, begin_PDi, begin_PTi);
}
return NULL;
}
static uint8_t unmap_entry(void *vAddress, PageTable_t table, uint32_t level, struct unmap_result *unmap_res) {
const uint8_t FLAG_CLEAR_FULL_FLAG = 1 << 0;
const uint8_t FLAG_DELETE_TABLE = 1 << 1;
uint32_t index = PAGE_TABLE_INDEX(vAddress, level);
if (level < 3) {
if (!table[index].P) return FLAG_CLEAR_FULL_FLAG;
PageTable_t next_table = MAPPED_PHYS_MEM_GET(table[index].Address << 12);
uint8_t res = unmap_entry(vAddress, next_table, level + 1, unmap_res);
if (res & FLAG_DELETE_TABLE) {
pmm_Free(table[index].Address << 12);
} else {
if (res & FLAG_CLEAR_FULL_FLAG) {
// Clear full flag
table[index].AVL1 &= ~VMM_PAGE_FULL;
table[index].AVL2 &= ~(VMM_PAGE_FULL >> 3);
}
return res;
}
} else {
unmap_res->paddr = table[index].Address << 12;
unmap_res->avl = PG_AVL(table[index].entry);
}
table[index].entry = 0;
if (level == 3) {
InvalidateTLBEntry(vAddress);
}
// Check if we still need this page table
if (level > 0) {
for (uint16_t i = 0; i < PAGE_ENTRIES; i++) {
if (VMM_ALLOCATED(table[i].entry)) {
return FLAG_CLEAR_FULL_FLAG;
}
}
}
return FLAG_DELETE_TABLE | FLAG_CLEAR_FULL_FLAG;
}
static struct unmap_result unmap(context_t *context, void *vAddress)
{
struct unmap_result res = {};
unmap_entry(vAddress, MAPPED_PHYS_MEM_GET(context->physAddress), 0, &res);
return res;
}
/*
* Initialisiert die virtuelle Speicherverwaltung.
* Parameter: Speicher = Grösse des phys. Speichers
* Stack = Zeiger auf den Stack
*/
bool vmm_Init()
{
extern uint8_t kernel_start, kernel_end, kernel_code_start, kernel_code_end;
PML4_t *PML4 = (PML4_t*)(cpu_readControlRegister(CPU_CR3) & 0xFFFFFFFFFF000); //nur die Adresse wollen wir haben
//Ersten Eintrag überarbeiten
setPML4Entry(0, PML4, 1, 1, 0, 0, 0, 0, 0, 0, PML4->PML4E[0] & PG_ADDRESS);
// Map first 512GiB to the end of the virtual memory. For this we are using 2MiB pages initially
// Currently the first 16MiB are identity mapped
// For this we temporarily map the pml4 as pdp in the second entry of the pml4
setPML4Entry(1, PML4, 1, 1, 0, 0, 0, 0, 0, 1, (uintptr_t)PML4);
setPML4Entry(PML4_INDEX(MAPPED_PHYS_MEM_BASE), PML4, 1, 1, 0, 0, 0, 0, 0, 1, pmm_Alloc());
PageTable_t pdp = (PageTable_t)(((1ul << 27) | (1 << 18) | (1 << 9) | PML4_INDEX(MAPPED_PHYS_MEM_BASE)) << 12);
if (cpuInfo.page_size_1gb) {
// We use 1GiB pages
paddr_t paddr = 0;
for (uint32_t i = 0; i < 512; i++) {
PageTableEntry_t pdp_entry = {
.P = true,
.RW = true,
.PS_PAT = true,
.G = true,
.NX = true,
.Address = paddr >> 12
};
*(pdp++) = pdp_entry;
paddr += MM_BLOCK_SIZE * 512 * 512;
}
} else {
// We use 2MiB pages
paddr_t highest_address = pmm_getHighestAddress();
paddr_t paddr = 0;
for (uint32_t i = 0; i < 512 && paddr < highest_address; i++) {
PageTableEntry_t pdp_entry = {
.P = true,
.RW = true,
.NX = true,
.Address = pmm_Alloc() >> 12
};
*(pdp++) = pdp_entry;
PageTable_t pd = (PageTable_t)(((1ul << 27) | (1 << 18) | (PML4_INDEX(MAPPED_PHYS_MEM_BASE) << 9) | i) << 12);
for (uint32_t j = 0; j < 512 && paddr < highest_address; j++) {
PageTableEntry_t pd_entry = {
.P = true,
.RW = true,
.PS_PAT = true,
.G = true,
.NX = true,
.Address = paddr >> 12
};
*(pd++) = pd_entry;
paddr += MM_BLOCK_SIZE * 512;
}
}
}
// Unmap PML4 again
clearPML4Entry(1, PML4);
// Clear TLB
cpu_writeControlRegister(CPU_CR3, PML4);
//PML4 in Kernelkontext eintragen
kernel_context.physAddress = (uintptr_t)PML4;
PML4 = MAPPED_PHYS_MEM_GET(PML4);
// Mark all pages tables as reserved
vmm_getPageTables(pmm_markPageReserved);
//Speicher bis 1MB bearbeiten
//Addresse 0 ist nicht gemappt
unmap(&kernel_context, NULL);
for(uint8_t *i = (uint8_t*)0x1000; i < (uint8_t*)0x100000; i += 0x1000)
{
vmm_ChangeMap(&kernel_context, i, (paddr_t)i, VMM_FLAGS_GLOBAL | VMM_FLAGS_NX | VMM_FLAGS_WRITE, 0);
}
uint8_t *i;
for(i = &kernel_start; i <= &kernel_end; i += 0x1000)
{
if(i >= &kernel_code_start && i <= &kernel_code_end)
{
vmm_ChangeMap(&kernel_context, i, vmm_getPhysAddress(&kernel_context, i), VMM_FLAGS_GLOBAL, 0);
}
else
{
vmm_ChangeMap(&kernel_context, i, vmm_getPhysAddress(&kernel_context, i), VMM_FLAGS_GLOBAL | VMM_FLAGS_NX | VMM_FLAGS_WRITE, 0);
}
}
//Den restlichen virtuellen Speicher freigeben
while(!vmm_getPageStatus(&kernel_context, i))
{
unmap(&kernel_context, i);
i += 0x1000;
}
SysLog("VMM", "Initialisierung abgeschlossen");
return true;
}
//Userspace Funktionen
/*
* Reserviert ein Speicherblock mit der Blockgrösse Length (in Pages)
* Parameter: Length = Die Anzahl Pages, die reserviert werden sollen
* Rückgabewerte: Adresse zum Speicherblock
* NULL = Ein Fehler ist aufgetreten
*/
void *vmm_Alloc(context_t *context, size_t Length)
{
return vmm_Map(context, NULL, 0, Length, VMM_FLAGS_WRITE | VMM_FLAGS_USER | VMM_FLAGS_NX);
}
/*
* Gibt Speicherplatz im Userspace frei
* Parameter: vAddress = Virtuelle Adresse, an die der Block anfängt
* Pages = Anzahl Pages, die dieser Block umfasst
*/
void vmm_Free(context_t *context, void *vAddress, size_t Pages)
{
vmm_UnMap(context, vAddress, Pages, true);
}
//------------------------Systemfunktionen---------------------------
/*
* Reserviert Speicherplatz für den Kernel an
* der Addresse vAddress und der Länge Length.
* Params:
* vAddress = Virtuelle Addresse, an die der Speicherplatz gemappt werden soll (fakultativ)
* Length = Anzahl Pages die reserviert werden sollen (mind. 1)
* Ignore = Gibt an ob der Parameter vAddress ignoriert (1) werden soll oder nicht (0)
*
* Rückgabewert: virt. Addresse des angeforderten Speicherbereichs
* NULL bei Fehler
*/
void *vmm_SysAlloc(size_t Length)
{
return vmm_Map(&kernel_context, NULL, 0, Length, VMM_FLAGS_WRITE | VMM_FLAGS_GLOBAL | VMM_FLAGS_NX);
}
/*
* Gibt den für den Stack der Physikalischen Speicherverwaltung reservierten Speicherplatz
* an der Addresse vAddress und der Länge Length frei.
* Params:
* vAddress = Virtuelle Addresse des Speicherplatzes, der freigegeben werden soll
* Length = Anzahl Pages die freigegeben werden sollen
*/
void vmm_SysFree(void *vAddress, size_t Length)
{
vmm_UnMap(&kernel_context, vAddress, Length, true);
}
/*
* Reserviert Speicher für DMA und mappt diesen
* Params: maxAddress = maximale physische Adresse für den Speicherbereich
* size = Anzahl Pages des Speicherbereichs
* phys = Zeiger auf Variable, in der die phys. Adresse geschrieben wird
*/
void *vmm_AllocDMA(paddr_t maxAddress, size_t Size, paddr_t *Phys)
{
//Freie virt. Adresse finden
uint64_t Pages = Size;
//Physischen Speicher allozieren
*Phys = pmm_AllocDMA(maxAddress, Size);
if(*Phys == 1) return NULL;
return vmm_Map(&kernel_context, NULL, *Phys, Pages, VMM_FLAGS_NO_CACHE | VMM_FLAGS_NX | VMM_FLAGS_WRITE);
}
static void walkPageTable(PageTable_t table, uint32_t level, void(*callback)(paddr_t)) {
const uint32_t end = PAGE_ENTRIES - (level == 0);
for (uint32_t i = 0; i < end; i++) {
if (table[i].P) {
paddr_t page = table[i].Address << 12;
callback(page);
if (level < 2) { // We don't walk though the PTs as we only want the page tables
PageTable_t next_table = (PageTable_t)MAPPED_PHYS_MEM_GET(page);
walkPageTable(next_table, level + 1, callback);
}
}
}
}
void vmm_getPageTables(void(*callback)(paddr_t)) {
paddr_t pml4 = cpu_readControlRegister(CPU_CR3) & PG_ADDRESS;
callback(pml4);
walkPageTable((PageTable_t)MAPPED_PHYS_MEM_GET(pml4), 0, callback);
}
//----------------------Allgemeine Funktionen------------------------
static void *mapPages(context_t *context, void *vAddress, paddr_t pAddress, size_t pages, uint8_t flags, bool guard) {
bool unused = pAddress == 0;
bool allocate = flags & VMM_FLAGS_ALLOCATE;
uint16_t avl = (unused && !allocate) ? VMM_UNUSED_PAGE : 0;
if (pages == 0) return NULL;
if (guard) pages += MM_GUARD_PAGES * 2;
return LOCKED_RESULT(vmm_lock, {
if (vAddress == NULL) {
void *start = (void*)((flags & VMM_FLAGS_USER) ? USERSPACE_START : KERNELSPACE_START);
void *end = (void*)((flags & VMM_FLAGS_USER) ? USERSPACE_END : KERNELSPACE_END);
vAddress = getFreePages(context, start, end, pages);
}
bool error = false;
size_t i;
for (i = 0; i < pages; i++) {
paddr_t paddr = 0;
uintptr_t currentOffset = i * VMM_SIZE_PER_PAGE;
uint16_t actual_avl = avl;
uint8_t actual_flags = flags;
bool is_guard_page = guard && (i < MM_GUARD_PAGES || i >= pages - MM_GUARD_PAGES);
if (is_guard_page) {
actual_avl = VMM_GUARD_PAGE;
actual_flags = 0;
} else if (allocate) {
paddr = pmm_Alloc();
if (paddr == 1) {
error = true;
break;
}
} else {
paddr = pAddress + currentOffset * !unused;
}
if (map(context, vAddress + currentOffset, paddr, actual_flags, actual_avl) != 0) {
error = true;
break;
}
if (allocate && !is_guard_page) clearPage(vAddress + currentOffset);
}
if (error) {
for (size_t j = 0; j < i; j++) {
paddr_t paddr = unmap(context, vAddress + j * VMM_SIZE_PER_PAGE).paddr;
if (allocate) pmm_Free(paddr);
}
}
error ? NULL : (vAddress + guard * MM_GUARD_PAGES * VMM_SIZE_PER_PAGE);
});
}
void *vmm_Map(context_t *context, void *vAddress, paddr_t pAddress, size_t pages, uint8_t flags) {
return mapPages(context, vAddress, pAddress, pages, flags, false);
}
void *vmm_MapGuarded(context_t *context, void *vAddress, paddr_t pAddress, size_t pages, uint8_t flags) {
return mapPages(context, vAddress, pAddress, pages, flags, true);
}
static void unmapPages(context_t *context, void *vAddress, size_t pages, bool freePages, bool guard) {
pages += guard * MM_GUARD_PAGES * 2;
vAddress -= guard * MM_GUARD_PAGES * VMM_SIZE_PER_PAGE;
LOCKED_TASK(vmm_lock, {
for(size_t i = 0; i < pages; i++)
{
paddr_t pAddress = unmap(context, vAddress + i * VMM_SIZE_PER_PAGE).paddr;
if(freePages && pAddress != 0)
pmm_Free(pAddress);
}
});
}
void vmm_UnMap(context_t *context, void *vAddress, size_t pages, bool freePages) {
return unmapPages(context, vAddress, pages, freePages, false);
}
void vmm_UnMapGuarded(context_t *context, void *vAddress, size_t pages, bool freePages) {
return unmapPages(context, vAddress, pages, freePages, true);
}
/*
* Ändert das Mapping einer Page. Falls die Page nicht vorhanden ist, wird sie gemappt
* Params: vAddress = Neue virt. Addresse der Page
* pAddress = Neue phys. Addresse der Page
* flags = neue Flags der Page
* Rückgabewert: 0 = Alles in Ordnung
* 1 = zu wenig phys. Speicher vorhanden
*/
uint8_t vmm_ChangeMap(context_t *context, void *vAddress, paddr_t pAddress, uint8_t flags, uint16_t avl)
{
//Einträge in die Page Tabellen
const uint16_t PML4i = PML4_INDEX(vAddress);
const uint16_t PDPi = PDP_INDEX(vAddress);
const uint16_t PDi = PD_INDEX(vAddress);
const uint16_t PTi = PT_INDEX(vAddress);
PML4_t *const PML4 = MAPPED_PHYS_MEM_GET(context->physAddress);
PDP_t *const PDP = MAPPED_PHYS_MEM_GET(PML4->PML4E[PML4i] & PG_ADDRESS);
PD_t *const PD = MAPPED_PHYS_MEM_GET(PDP->PDPE[PDPi] & PG_ADDRESS);
PT_t *const PT = MAPPED_PHYS_MEM_GET(PD->PDE[PDi] & PG_ADDRESS);
//Flags auslesen
bool US = (flags & VMM_FLAGS_USER);
bool G = (flags & VMM_FLAGS_GLOBAL);
bool RW = (flags & VMM_FLAGS_WRITE);
bool NX = (flags & VMM_FLAGS_NX);
bool P = !(avl & VMM_UNUSED_PAGE);
bool PCD = (flags & VMM_FLAGS_NO_CACHE);
bool PWT = (flags & VMM_FLAGS_PWT);
return LOCKED_RESULT(vmm_lock, {
uint8_t res = 0;
if(isPageFree(&PML4->PML4E[PML4i], &PDP->PDPE[PDPi], &PD->PDE[PDi], &PT->PTE[PTi]))
{
if(map(context, vAddress, pAddress, flags, avl) == 1)
{
res = 1;
}
}
else
{
setPTEntry(PTi, PT, P, RW, US, PWT, PCD, 0, 0, G, avl, 0, NX, pAddress);
//Reserved bits zurücksetzen
PD->PDE[PDi] &= ~0x1C0;
PDP->PDPE[PDPi] &= ~0x1C0;
PML4->PML4E[PML4i] &= ~0x1C0;
InvalidateTLBEntry((void*)vAddress);
}
res;
});
}
/*
* Mappt eine virtuelle Adresse an eine andere Adresse
* Die src Addresse wird nicht auf Gültigkeit überprüft
* Params: src = virt. Addresse der Speicherstelle
* dst = virt. Addresse an die remappt werden soll
* length = Anzahl Pages, die die Speicherstelle lang ist
* us = ist das Ziel ein Userspace?
*
* Rückgabewert: 0 = Speicherstelle wurde erfolgreich virt. verschoben
* 1 = zu wenig phys. Speicherplatz vorhanden
* 2 = Destinationaddresse ist schon belegt
*///TODO: Bei Fehler alles Rückgängig machen
uint8_t vmm_ReMap(context_t *src_context, void *src, context_t *dst_context, void *dst, size_t length, uint8_t flags)
{
for (size_t i = 0; i < length; i++) {
struct unmap_result res = unmap(src_context, src + i * VMM_SIZE_PER_PAGE);
uint8_t r;
if ((r = map(dst_context, dst + i * VMM_SIZE_PER_PAGE, res.paddr, flags, res.avl)) != 0)
return r;
}
return 0;
}
/*
* Sucht die zugehörigen virtuelle Adresse der übergebenen phys. Adresse
* Parameter: pAddress = die phys. Addresse der zu suchenden virt. Adresse
* Rückgabewert: virtuelle Adresse der phys. Adresse
* 0 = phys. Adresse wurde nicht gemappt
*/
/*uintptr_t vmm_getVirtAddress(uintptr_t pAddress)
{
register uintptr_t i;
for(i = 0; i < VMM_MAX_ADDRESS; i += VMM_SIZE_PER_PAGE)
{
if(vmm_getPhysAddress(i) == pAddress)
return i;
}
return 0;
}*/
//Hilfsfunktionen
/*
* Gibt zurück, ob die entsprechende Page belegt ist oder nicht
* Parameter: Address = virtuelle Addresse
* Rückgabewert: true = Page ist frei
* false = Page ist belegt
*/
bool vmm_getPageStatus(context_t *context, void *Address)
{
//Einträge in die Page Tabellen
const uint16_t PML4i = PML4_INDEX(Address);
const uint16_t PDPi = PDP_INDEX(Address);
const uint16_t PDi = PD_INDEX(Address);
const uint16_t PTi = PT_INDEX(Address);
const PML4_t *const PML4 = MAPPED_PHYS_MEM_GET(context->physAddress);
const PDP_t *const PDP = MAPPED_PHYS_MEM_GET(PML4->PML4E[PML4i] & PG_ADDRESS);
const PD_t *const PD = MAPPED_PHYS_MEM_GET(PDP->PDPE[PDPi] & PG_ADDRESS);
const PT_t *const PT = MAPPED_PHYS_MEM_GET(PD->PDE[PDi] & PG_ADDRESS);
return isPageFree(&PML4->PML4E[PML4i], &PDP->PDPE[PDPi], &PD->PDE[PDi], &PT->PTE[PTi]);
}
paddr_t vmm_getPhysAddress(context_t *context, void *virtualAddress)
{
//Einträge in die Page Tabellen
const uint16_t PML4i = PML4_INDEX(virtualAddress);
const uint16_t PDPi = PDP_INDEX(virtualAddress);
const uint16_t PDi = PD_INDEX(virtualAddress);
const uint16_t PTi = PT_INDEX(virtualAddress);
const PML4_t *const PML4 = MAPPED_PHYS_MEM_GET(context->physAddress);
const PDP_t *const PDP = MAPPED_PHYS_MEM_GET(PML4->PML4E[PML4i] & PG_ADDRESS);
const PD_t *const PD = MAPPED_PHYS_MEM_GET(PDP->PDPE[PDPi] & PG_ADDRESS);
const PT_t *const PT = MAPPED_PHYS_MEM_GET(PD->PDE[PDi] & PG_ADDRESS);
return isPageFree(&PML4->PML4E[PML4i], &PDP->PDPE[PDPi], &PD->PDE[PDi], &PT->PTE[PTi]) ? 0 : (paddr_t)(PT->PTE[PTi] & PG_ADDRESS);
}
void vmm_unusePages(context_t *context, void *virt, size_t pages)
{
for(void *address = virt; address < virt + pages * VMM_SIZE_PER_PAGE; address += VMM_SIZE_PER_PAGE)
{
//Einträge in die Page Tabellen
const uint16_t PML4i = PML4_INDEX(address);
const uint16_t PDPi = PDP_INDEX(address);
const uint16_t PDi = PD_INDEX(address);
const uint16_t PTi = PT_INDEX(address);
const PML4_t *const PML4 = MAPPED_PHYS_MEM_GET(context->physAddress);
const PDP_t *const PDP = MAPPED_PHYS_MEM_GET(PML4->PML4E[PML4i] & PG_ADDRESS);
const PD_t *const PD = MAPPED_PHYS_MEM_GET(PDP->PDPE[PDPi] & PG_ADDRESS);
PT_t *const PT = MAPPED_PHYS_MEM_GET(PD->PDE[PDi] & PG_ADDRESS);
if(!isPageFree(&PML4->PML4E[PML4i], &PDP->PDPE[PDPi], &PD->PDE[PDi], &PT->PTE[PTi]) && (PG_AVL(PT->PTE[PTi]) & VMM_UNUSED_PAGE) == 0)
{
paddr_t entry = PT->PTE[PTi];
pmm_Free(entry & PG_ADDRESS);
setPTEntry(PTi, PT, 0, !!(entry & PG_RW), !!(entry & PG_US), !!(entry & PG_PWT), !!(entry & PG_PCD), !!(entry & PG_A),
!!(entry & PG_D), !!(entry & PG_G), PG_AVL(entry) | VMM_UNUSED_PAGE, !!(entry & PG_PAT), !!(entry & PG_NX), 0);
InvalidateTLBEntry(address);
}
}
}
void vmm_usePages(context_t *context, void *virt, size_t pages)
{
void *address = (void*)((uintptr_t)virt & ~0xFFF);
for(; address < (void*)((uintptr_t)virt & ~0xFFF) + pages * VMM_SIZE_PER_PAGE; address += VMM_SIZE_PER_PAGE)
{
//Einträge in die Page Tabellen
const uint16_t PML4i = PML4_INDEX(address);
const uint16_t PDPi = PDP_INDEX(address);
const uint16_t PDi = PD_INDEX(address);
const uint16_t PTi = PT_INDEX(address);
const PML4_t *const PML4 = MAPPED_PHYS_MEM_GET(context->physAddress);
const PDP_t *const PDP = MAPPED_PHYS_MEM_GET(PML4->PML4E[PML4i] & PG_ADDRESS);
const PD_t *const PD = MAPPED_PHYS_MEM_GET(PDP->PDPE[PDPi] & PG_ADDRESS);
PT_t *const PT = MAPPED_PHYS_MEM_GET(PD->PDE[PDi] & PG_ADDRESS);
uint64_t entry = PT->PTE[PTi];
paddr_t pAddr = pmm_Alloc();
if(pAddr == 1)
Panic("VMM", "Out of memory!");
setPTEntry(PTi, PT, 1, !!(entry & PG_RW), !!(entry & PG_US), !!(entry & PG_PWT), !!(entry & PG_PCD), !!(entry & PG_A),
!!(entry & PG_D), !!(entry & PG_G), PG_AVL(entry) & ~VMM_UNUSED_PAGE, !!(entry & PG_PAT), !!(entry & PG_NX), pAddr);
InvalidateTLBEntry(address);
clearPage(address);
}
}
//Prozesse
/*
* Überprüft, ob ein Pointer in den Userspace bereich zeigt,
* Parameter: Den zu überprüfenden Pointer
* Rückgabe: True, wenn der Pointer in den Userspace zeigt, ansonsten false
*/
bool vmm_userspacePointerValid(const void *ptr, const size_t size)
{
return (USERSPACE_START <= (uintptr_t)ptr && (uintptr_t)ptr + size <= USERSPACE_END);
}
/*
* Erstellt einen neuen virtuellen Adressraum und intialisiert diesen
*/
context_t *createContext()
{
context_t *context = malloc(sizeof(context_t));
context->physAddress = pmm_Alloc();
PML4_t *newPML4 = memset(MAPPED_PHYS_MEM_GET(context->physAddress), 0, MM_BLOCK_SIZE);
//Kernel in den Adressraum einbinden
PML4_t *const PML4 = MAPPED_PHYS_MEM_GET(kernel_context.physAddress);
for(uint16_t PML4i = 0; PML4i < PML4e; PML4i++)
newPML4->PML4E[PML4i] = PML4->PML4E[PML4i];
//Den letzten Eintrag verwenden wir als Zeiger auf den Anfang der Tabelle. Das ermöglicht das Editieren derselben.
newPML4->PML4E[511] = PML4->PML4E[511];
return context;
}
/*
* Löscht einen virtuellen Adressraum
*/
void deleteContext(context_t *context)
{
//Erst alle Pages des Kontextes freigeben
PML4_t *PML4 = MAPPED_PHYS_MEM_GET(context->physAddress);
for(uint16_t PML4i = PML4e; PML4i < PAGE_ENTRIES - 1; PML4i++)
{
//Ist der Eintrag gültig
if(PML4->PML4E[PML4i] & PG_P)
{
//PDP mappen
paddr_t PDP_phys = PML4->PML4E[PML4i] & PG_ADDRESS;
PDP_t *PDP = MAPPED_PHYS_MEM_GET(PDP_phys);
for(uint16_t PDPi = 0; PDPi < PAGE_ENTRIES; PDPi++)
{
//Ist der Eintrag gültig
if(PDP->PDPE[PDPi] & PG_P)
{
//PD mappen
paddr_t PD_phys = PDP->PDPE[PDPi] & PG_ADDRESS;
PD_t *PD = MAPPED_PHYS_MEM_GET(PD_phys);
for(uint16_t PDi = 0; PDi < PAGE_ENTRIES; PDi++)
{
//Ist der Eintrag gültig
if(PD->PDE[PDi] & PG_P)
{
//PT mappen
paddr_t PT_phys = PD->PDE[PDi] & PG_ADDRESS;
PT_t *PT = MAPPED_PHYS_MEM_GET(PT_phys);
for(uint16_t PTi = 0; PTi < PAGE_ENTRIES; PTi++)
{
//Ist die Page alloziiert
if(PT->PTE[PTi] & PG_P)
pmm_Free(PT->PTE[PTi] & PG_ADDRESS);
}
//PT löschen
PD->PDE[PDi] = 0;
pmm_Free(PT_phys);
}
}
//PD löschen
PDP->PDPE[PDPi] = 0;
pmm_Free(PD_phys);
}
}
//PDP löschen
PML4->PML4E[PML4i] = 0;
pmm_Free(PDP_phys);
}
}
//Restliche Datenstrukturen freigeben
pmm_Free(context->physAddress);
free(context);
}
/*
* Aktiviert einen virtuellen Adressraum
*/
void activateContext(const context_t *context) {
cpu_writeControlRegister(CPU_CR3, context->physAddress);
}
int vmm_handlePageFault(context_t *context, void *page, uint64_t errorcode)
{
uint16_t PML4i = PML4_INDEX(page);
uint16_t PDPi = PDP_INDEX(page);
uint16_t PDi = PD_INDEX(page);
uint16_t PTi = PT_INDEX(page);
const PML4_t *const PML4 = MAPPED_PHYS_MEM_GET(context->physAddress);
const PDP_t *const PDP = MAPPED_PHYS_MEM_GET(PML4->PML4E[PML4i] & PG_ADDRESS);
const PD_t *const PD = MAPPED_PHYS_MEM_GET(PDP->PDPE[PDPi] & PG_ADDRESS);
const PT_t *const PT = MAPPED_PHYS_MEM_GET(PD->PDE[PDi] & PG_ADDRESS);
//Activate unused pages
if(!isPageFree(&PML4->PML4E[PML4i], &PDP->PDPE[PDPi], &PD->PDE[PDi], &PT->PTE[PTi]) && (PG_AVL(PT->PTE[PTi]) & VMM_UNUSED_PAGE))
{
vmm_usePages(context, page, 1);
return 0;
}
if (PG_AVL(PT->PTE[PTi]) & VMM_GUARD_PAGE) {
return 2;
}
return 1;
}
|
C
|
/*program to print the strings of the two-dimensional character array*/
#include<stdio.h>
main ( )
{
char arr[5][10] = {
"riti",
"niti",
"kriti",
"kittu",
"nitin"
};
int i;
for ( i=0;i<5;i++)
{
printf ( " base address = %u",&arr[ i] );
printf ( " string = %s\n",arr[ i] );
}
}
|
C
|
/*
*Author: Vinit
*Platform: Linux
*Hardware: R-Pi 3b+
*Task: Socket client
*
*/
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<sys/un.h>
#include<unistd.h>
struct {
int msg_no;
char str[20];
}soc_payload;
void main(int argc, char *argv[])
{
if(1==argc|| ( strlen(argv[1]) >20 ) )
{
printf("No input or max count exceed\n");
exit(EXIT_FAILURE);
}
int soc_fd=0;
int cl_soc_fd=0;
struct sockaddr_un soc_address;
struct sockaddr_un client_soc_address;
int cl_len=0;
int ret_val=0;
soc_fd = socket(AF_UNIX,SOCK_STREAM,0); //Two way communication byte stream
if(-1 == soc_fd)
{
printf("socket Error %s",strerror(soc_fd));
exit(EXIT_FAILURE);
}
soc_address.sun_family = AF_UNIX;
strcpy(soc_address.sun_path,"my_socket");
ret_val=connect(soc_fd,(struct sockaddr *)&soc_address,sizeof(soc_address));
if(-1 == ret_val)
{
printf("connect Error %s\n",strerror(ret_val));
exit(EXIT_FAILURE);
}
printf("Here\n");
char buff[20];
soc_payload.msg_no=1;
strcpy(soc_payload.str,argv[1]);
ret_val=write(soc_fd,&soc_payload,sizeof(soc_payload));
if(-1==ret_val)
{
printf("Write Error %s\n",strerror(ret_val));
}
close(soc_fd);
exit(EXIT_SUCCESS);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/wait.h>
#include<fcntl.h>
#include<pthread.h>
#include<sys/time.h>
int tcp, udp;
void * startKelsa(void *threadNum)
{
int *counter;
printf("\nIN thread func\n");
counter = (void *) threadNum;
printf("\nCOUNTER %d\n", *counter);
switch(*counter)
{
case 0:
printf("\nStarting UDP thread\n");
startUDP();
break;
case 1:
printf("\nStarting TCP thread\n");
startTCP();
break;
default:
break;
}
}
int startUDP()
{
char buffer[4096];
int len;
struct sockaddr_in clientAddress;
len = sizeof(clientAddress);
printf("\n Waiting in UDP\n");
//for(;;)
//{
printf("\n Waiting in UDP\n");
recvfrom(udp, buffer, 4096, 0, (struct sockaddr *) &clientAddress, &len);
printf("\nI AM HERE IN UDP AND RECEIVED %s FROM CLIENT\n", buffer);
//}
return 0;
}
int startTCP()
{
int sd, len;
struct sockaddr_in clientAddress;
char buffer[4096];
len = sizeof(clientAddress);
printf("\n Waiting in TCP\n");
//for(;;)
//{
printf("\n Waiting in TCP\n");
//listen(tcp, 10);
sd = accept(tcp, (struct sockaddr *) &clientAddress, &len);
if ( sd < 0 )
{
printf("\nPrintf TCP accept failure\n");
}
recv(sd, buffer, 4096, 0);
printf("\nI AM IN HERE IN TCP AND RECEIVED %s FROM CLIENT\n", buffer);
//}
return 0;
}
int main(int argc, char *argv[])
{
int i_rc, counter, *ptr[2];
struct sockaddr_in serverAddress, serverAddress1;
pthread_t tid[2];
tcp = socket (AF_INET, SOCK_STREAM, 0);
if ( tcp < 0 )
{
printf("\nTCP socket error\n");
return -1;
}
printf("\nTCP socket success");
udp = socket(AF_INET, SOCK_DGRAM, 0);
if ( udp < 0 )
{
printf("\nUDP socket error\n");
return -1;
}
printf("\nUDP socket success\n");
memset(&serverAddress, 0, sizeof(struct sockaddr_in));
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(3491);
serverAddress.sin_addr.s_addr = inet_addr("192.168.139.134");
memset(&(serverAddress.sin_zero), '\0', 8);
/*memset(&serverAddress1, 0, sizeof(struct sockaddr_in));
serverAddress1.sin_family = AF_INET;
serverAddress1.sin_port = htons(3491);
serverAddress1.sin_addr.s_addr = inet_addr("192.168.139.134");
memset(&(serverAddress1.sin_zero), '\0', 8);*/
// Bind
i_rc = bind(udp, (struct sockaddr *) &serverAddress, sizeof(serverAddress));
if ( -1 == i_rc )
{
printf("\nUnable to bind UDP\n");
return -1;
}
printf("\n UDP bind success");
i_rc = bind(tcp, (struct sockaddr *) &serverAddress, sizeof(serverAddress));
if ( -1 == i_rc )
{
printf("\nUnable to bind TCP\n");
return -1;
}
printf("\n TCP bind success");
listen(tcp, 10);
for (counter = 0; counter < 2; counter++)
{
ptr[counter] = (int *)malloc(sizeof(int));
*(ptr[counter]) = counter;
printf("\nCOUNTER IN MAIN : %d\n", counter);
i_rc = pthread_create(&tid[counter], NULL, startKelsa, (void *) ptr[counter]);
if ( 0 != i_rc )
{
printf("\npthread creation failure\n");
}
else
{
printf("\npthread creation successful in main\n");
}
}
for (counter = 0; counter < 2; counter++)
{
pthread_join(tid[counter], NULL);
}
} // End of main()
|
C
|
#include <stdio.h>
#include <string.h>
#include <locale.h>
int nxt_blnk(char* str, int pos);
int main()
{
setlocale(LC_CTYPE, "rus");
char text[100] = {0}; //Тестовый текст
int n;
setlocale(LC_CTYPE, "rus");
printf("Введите текст: \n");
gets(text);
printf("Введите номер символа: \n");
scanf("%d", &n);
printf("Первый пробел после %d символа - %d", n, nxt_blnk(text, n - 1));
return 0;
}
int nxt_blnk(char* str, int pos)
{
int result;
if(pos < 0 || pos > strlen(str))
return -1;
for(int i = pos + 1; i < strlen(str); i++)
{
if(str[i] == ' ')
{
result = i;
return result + 1;
}
}
return 0;
}
|
C
|
/** @defgroup MleCore Magic Lantern Core Utility Library API */
/**
* @file mlExpandFilename.h
* @ingroup MleCore
*
* This file contains function definitions for expanding a
* UNIX-like filename pathcontaining tilde notation and
* environment variables, plus strftime(3) notation
*
* Notations that are supported include
* <ol>
* <li>Leading tildes</li>
* <ol>
* <li>If not followed by a user name, refers to current
* user's HOME directory.</li>
* <li>If followed by a valid user name, refers to the
* home directory of that user.</li>
* <li>If followed by an invalid user name, no replacement
* is done.</li>
* </ol>
* <li>Embedded environment variables.</li>
* <ol>
* <li>$WORD notation. WORD may be alphanumeric with
* any characters in the constant SPECIALS below (only
* an underscore for now).</li>
* <li>${WORD} notation. WORD may contain anything.</li>
* <li>If WORD is not an environment variable, it is replaced
* by an empty string, unless...</li>
* <li>Undefined environment variables that are in the Known
* table below have the corresponding values used.</li>
* </ol>
* <li>Percent notation.</li>
* <ol>
* <li>if %n is used, a counting integer is substituted.</li>
* <li>Other % keys are passed to strftime.</li>
* </ol>
* </ol>
*/
// COPYRIGHT_BEGIN
//
// The MIT License (MIT)
//
// Copyright (c) 2015-2020 Wizzer Works
//
// 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.
//
// For information concerning this header file, contact Mark S. Millard,
// of Wizzer Works at msm@wizzerworks.com.
//
// More information concerning Wizzer Works may be found at
//
// http://www.wizzerworks.com
//
// COPYRIGHT_END
#ifndef __MLE_EXPANDFILENAME_H_
#define __MLE_EXPANDFILENAME_H_
#include "mle/MleUtil.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* Set the filename index.
*
* @param The index to set.
*/
MLE_UTIL_API void mlFilenameIndexSet(int);
/**
* Increment the filename index.
*/
MLE_UTIL_API void mlFilenameIndexIncrement(void);
/**
* Expand the specified filename.
*
* @param name The file name to expand.
*
* @return The result is newly malloc'ed storage; it's up to the caller to
* mleFree() this.
*/
MLE_UTIL_API char * mlFilenameExpand(const char *name);
#ifdef __cplusplus
} /* end of 'extern "C"' */
#endif
#endif /* __MLE_EXPANDFILENAME_H_ */
|
C
|
#include <stdio.h>
void print_array(int* array, size_t size);
void insert_array(int* array, size_t size, int position, int value);
void remove_array(int* array, size_t size, int value);
void search_array(int* array, size_t size, int value);
void update_array(int* array, size_t size, int position, int value);
int main()
{
size_t array_size = 4;
int array[] = {1, 2, 2, 7};
print_array(&array[0], array_size);
insert_array(&array[0], array_size, 1, 5);
remove_array(&array[0], array_size, 2);
search_array(&array[0], array_size, 2);
search_array(&array[0], array_size, 45);
update_array(&array[0], array_size, 1, 0);
print_array(&array[0], array_size);
return 0;
}
void print_array(int* p, size_t size)
{
for(int index = 0; index < size; index++)
{
printf("%d", *(p + index));
}
printf("\n");
}
void insert_array(int* p, size_t size, int position, int value)
{
// The size of an array is fixed, so, for insertion operation we only can print the new array
for(int index = 0; index < size; index++)
{
if(index != position)
printf("%d", *(p + index));
else
{
printf("%d", value);
printf("%d", *(p + index));
}
}
printf("\n");
}
void remove_array(int* p, size_t size, int value)
{
for(int index = 0; index < size; index++)
{
if(*(p + index) != value)
printf("%d", *(p + index));
}
printf("\n");
}
void search_array(int* p, size_t size, int value)
{
int match = 0;
for(int index = 0; index < size; index++)
{
if(*(p + index) == value)
match = 1;
}
if(match != 0)
printf("True\n");
else
printf("False\n");
}
void update_array(int* p, size_t size, int position, int value)
{
for(int index = 0; index < size; index++)
{
if(index == position)
*(p + index) = value;
}
printf("\n");
}
|
C
|
#include<stdio.h>
unsigned long long people[65]={0},clubs[101]={0};
int stack[65],stop=0,club,target;
void find(int now,unsigned long long num){
if(stop)return;
if(now==target){
for(int i=0;i<target;i++)printf("%d\n",stack[i]);
stop=1;
return;
}for(int i=stack[now-1];i<club;i++){
if((num&clubs[i])==0){
stack[now]=i;
find(now+1,(num|clubs[i]));
}
}
}
int main(){
scanf("%d%d",&club,&target);
unsigned long long t=1;
for(int i=0;i<64;i++){
people[i]=t;
t=t<<1;
}for(int i=0;i<club;i++){
int member;
scanf("%d",&member);
for(int j=0;j<member;j++){
int id;
scanf("%d",&id);
clubs[i]|=people[id];
}
}find(0,0);
}
|
C
|
#include "holberton.h"
/**
* print_alphabet_x10 - entry
* @a - number
* @counter - the counter
* function void print_alphabet voi
*/
void print_alphabet_x10(void)
{
char a;
char counter;
for (counter = 0; counter <= 9; counter++)
{
for (a = 'a'; a <= 'z'; a++)
{
_putchar(a);
}
_putchar('\n');
}
}
|
C
|
#include <stdio.h>
02
#include <stdlib.h>
03
04
struct freq
05
{
06
char *x[64];
07
int y;
08
};
09
10
struct freq array1[100];
11
12
int main()
13
{
14
15
FILE * input;
16
int i,j;
17
char tempWord[] ="hello";
18
input = fopen("random.txt","r");
19
20
for (i=0;i<=10;i++) //go through the 10 elements in text file
21
{
22
//scan each word into a temporary variable
23
// **** NOT COMPLETE, JUST USING TEMPWORD ASSIGNED ABOVE TO CHECK WORKING.
24
25
//loop through the existing array to check if the temp value equals a word
26
// if it does increment the corresponding counter
27
for(j=0;j<=10;j++){
28
if(strcmp(array1[j].x, tempWord) == 0){ //if it does equal the scanned word
29
array1[j].y++; //increment its count
30
}
31
}
32
33
//if it doesn't add it to the array
34
35
fscanf(input, "%s",array1[i].x);
36
37
printf("WORD %i: %s ",i,array1[i].x);
38
printf(" COUNT IS: %i", array1[i].y);
39
printf("\n");
40
}
41
42
fclose(input);
43
return 0;
44
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "utils.h"
int main(void)
{
int n;
long long s;
scanf("%lld", &s);
sp_srand(s);
while (scanf("%d", &n) == 1)
{
Node *list = mk_list(n);
Node *u = list;
for (int i = 0; i < n;)
{
long long sum = 0;
int cnt = 1;
while (u && cnt < 100000)
{
sum += u->v * cnt;
u = u->next;
cnt++;
i++;
}
printf("%lld\n", sum);
}
rm_list(list);
}
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2020
** server
** File description:
** teams gestion
*/
#include "server.h"
void init_next_thread(server_t *server, int i, int k, int j)
{
strcpy(server->teams[i].channel[k].thread[j].thread_content, "NULL");
strcpy(server->teams[i].channel[k].thread[j].thread_title, "NULL");
strcpy(server->teams[i].channel[k].thread[j].thread_id, "NULL");
}
void init_first_comment(server_t *server, int i, int k, int j)
{
server->teams[i].channel[k].thread[j].comment[0] = malloc(sizeof(char) * 5);
strcpy(server->teams[i].channel[k].thread[j].comment[0], "NULL");
}
void set_thread(thread_t *thread, char *name, char *desc)
{
char *id = generate_id();
strcpy(thread->thread_id, id);
strcpy(thread->thread_title, name);
strcpy(thread->thread_content, desc);
free(id);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <string.h>
#include <ctype.h>
#define ARG_INPUT_MAXSIZE 1024000
typedef struct seq
{
int64_t *s;
size_t m;
} seq;
typedef struct sseq
{
seq *seq;
size_t n;
} sseq;
typedef struct uintstruct
{
int64_t *fib;
size_t n;
} uintstruct;
size_t string_to_int( char *str, size_t l, seq *st, int m )
{
if ( m<0 )
exit(1);
uint64_t i, j, k;
char *cur = str;
char *curswp = cur;
int64_t *seq;
for ( i=0; cur < str+l && i<m; i++ )
{
curswp = cur;
cur += strcspn(cur, "0123456789");
if ( cur == str+l )
break;
cur += strcspn(cur, " \t\n\0") + 1;
}
cur = str;
seq = malloc (sizeof(int64_t)*i);
for ( j=0; j<i; j++ )
{
cur += strcspn(cur, "0123456789");
seq[j]=atoll(cur);
cur += strcspn(cur, " \t\n\0") + 1;
}
st->s = seq;
st->m=i;
return i;
}
void input (seq **st)
{
char *arg = malloc( ARG_INPUT_MAXSIZE );
st[0] = malloc(sizeof(seq));
printf("enter M:\n");
int m;
scanf("%d\n", &m);
fgets(arg, ARG_INPUT_MAXSIZE, stdin);
string_to_int( arg, strlen(arg), st[0], m );
}
void erase_seq (seq *st)
{
free( st->s );
free( st );
}
void erase_sseq ( sseq *sst )
{
uint64_t i;
for (i=0; i<sst->n; i++)
free( sst->seq[i].s );
free(sst);
}
void erase_fib ( uintstruct *fs )
{
free(fs->fib);
free(fs);
}
void output(seq *st)
{
int64_t i;
for ( i=0; i<st->m; i++ )
{
printf("%5"PRId64" ", st->s[i]);
}
puts("");
}
void soutput(sseq *sst, seq *st)
{
int64_t i;
for ( i=0; i < sst->n; i++ )
{
printf("%6"PRId64": ", st->s[i]);
output(sst->seq+i);
}
}
int64_t max(seq *st)
{
uint64_t i;
int64_t max = st->s[0];
for ( i=1; i<st->m; i++ )
{
if ( max < st->s[i] )
max=st->s[i];
}
return max;
}
uintstruct* gen_fib(int64_t max)
{
uint64_t i, j;
int64_t tmp0 = 0, tmp1 = 1, tmp2 = 0, tmpcur = 0;
for ( i=2; tmp1<max; tmpcur=tmp0 + tmp1, tmp0=tmp1, tmp1=tmpcur, i++ /*, printf("tmp=%"PRId64"/%"PRId64"\n", tmpcur, max)*/ );
int64_t *fib = malloc(sizeof(int64_t)*i);
fib[0]=0;
fib[1]=1;
for ( j=2; j<i; j++ )
{
fib[j]=fib[j-1]+fib[j-2];
}
uintstruct *fs = malloc ( sizeof(uintstruct) );
fs->fib = fib;
fs->n = j;
return fs;
}
sseq* make_matrix (seq *st, uintstruct *fs)
{
int64_t i, j;
sseq *sst;
sst = malloc( sizeof(sseq) );
sst->n = st->m;
sst->seq = malloc ( sizeof(seq) * st->m );
for ( j=0; j<st->m; j++ )
{
int64_t count = st->s[j];
uint64_t k;
for ( i=fs->n-1, k=0; count>=0 && i>0; i-- )
{
if ( count - fs->fib[i] >= 0 )
{
count -= fs->fib[i];
k++;
}
}
sst->seq[j].s = malloc (sizeof(int64_t) * k);
count = st->s[j];
sst->seq[j].m = k;
for ( i=fs->n-1, k=0; count>=0 && i>0; i-- )
{
if ( count - fs->fib[i] >= 0 )
{
count -= fs->fib[i];
sst->seq[j].s[k] = fs->fib[i];
k++;
}
}
}
return sst;
}
void action(seq *st, sseq **sst)
{
int64_t mmax = max(st);
uintstruct *fs = gen_fib(mmax);
sst[0] = make_matrix(st, fs);
erase_fib (fs);
}
int main()
{
seq *st = NULL;
sseq *sst = NULL;
input (&st);
action (st, &sst);
printf("input numbers\n");
output (st);
printf("output matrix\n");
soutput (sst, st);
erase_seq (st);
erase_sseq (sst);
}
|
C
|
//2:最长公共子序列
#include<stdio.h>
int main(){
int data[100];
int i,j;
int Max[100];
int n,t,k;
printf("请输入n个数");
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&data[i]);
}
for( i=0;i<100;i++){
Max[i]=1; //给每一个序列点作为右端时的最大序列长度为1
}
for( i=1;i<n;i++){
t=1;
for( j=0;j<i;j++){//与其前面的每一个进行比较
if(data[i]>data[j]){//如果数据比前面的某一个的值大
if(Max[i]+Max[j]>t){//找出该点的最大子序列长度
t=Max[i]+Max[j];
}
}
}
Max[i]=t;
}
t=Max[0];
for(i=1;i<n;i++){
if(Max[i]>t){
t=Max[i];
}
}
printf("最长单调递增子序列的长度为:%d",t);
return 0;
}
|
C
|
// Calculating aggregate and percentage marks
#include <stdio.h>
int main()
{
float ben, eng, cms, phys, math, avg, per, tol;
printf("Enter the marks in Bengali\n");
scanf("%f", &ben);
printf("Enter the marks obtained in English\n");
scanf("%f", &eng);
printf("Entered the marks obtained in Physics\n");
scanf("%f", &phys);
printf("Entered the marks obtained in Math\n");
scanf("%f", &math);
printf("Entered the marks obtained in Computer Sci.\n");
scanf("%f", &cms);
tol = ben+eng+phys+math+cms; // Calculating total marks obtained
avg = tol/5; // Calculating avg.
per = (tol/500)*100; // Calculating percentage
printf("The aggregate and percentage marks is %f and %f\n", avg, per);
return 0;
}
|
C
|
/*
* main.c
*
* Created on: Sep 13, 2019
* Author: DR. ADEL
*/
#include "keypad.h"
int main(void)
{
DDRC |= 0x0F; /*PORTB first 4 pins are output pins*/
PORTC &= (0xF0); /*PORTB first 4 pins are cleared at the beginning of the program*/
while(1)
{
uint8 ch = KEYPAD_getKeyPressed();
if(ch >= 0 && ch <= 9)
PORTC = (PORTC & 0xF0) | (ch & 0x0F);
else if(ch == '+' || ch == '-' || ch == '/' || ch == '*' || ch == 13 || ch == '=' || ch == '#')
PORTC = (PORTC & 0xF0) | 0x09;
}
return 0;
}
|
C
|
/*
* i2c_eeprom.c
*
* Created: 11.05.2017 08:41:07
* Author: Stud
*/
#include "i2c_eeprom.h"
#include <avr/io.h>
#include <util/delay.h>
/*
MAKRO ersetzt einen Text
*/
#define TWI_BAUD(F_SYS, F_TWI) ((F_SYS / (2*F_TWI)) - 5)
#define TWI_BAUDRATE 100000
#define TWI_BAUDSETTING TWI_BAUD(F_CPU, TWI_BAUDRATE)
// Makro zum warten, bis das Interrupt Flag vom TWI wieder freigegeben wird
#define TWI_WAIT_RW_COMPLETE() while(!(TWIC.MASTER.STATUS & TWI_MASTER_WIF_bm) && !(TWIC.MASTER.STATUS & TWI_MASTER_RIF_bm))
#define TWI_ACK_RECEIVED() !(TWIC.MASTER.STATUS & TWI_MASTER_RXACK_bm)
// If a bus error occours WIF *and* BUSERR flag are set
#define TWI_BUSERR() ((TWIC.MASTER.STATUS & TWI_MASTER_BUSERR_bm) && (TWIC.MASTER.STATUS & TWI_MASTER_WIF_bm))
// static: ist nur innerhalb der Datei sichtbar (Verhindert den Aufruf der Funktion von auen
static bool send_start_and_address(uint8_t addr, bool write)
{
addr <<= 1; // ist das gleiche wie Scheieben des Registers um eins nach links; addr = addr << 1
TWIC.MASTER.ADDR = write ? addr : addr | 0x01; // ?-Operator, wenn write true dann vor dem Doppelpunkt ausgefhrt, falls false dann hinterer Teil
TWI_WAIT_RW_COMPLETE();
return TWI_ACK_RECEIVED();
}
static void send_stop_condition()
{
TWIC.MASTER.CTRLC = TWI_MASTER_CMD_STOP_gc;
}
static void send_nack_and_stop_condition()
{
TWIC.MASTER.CTRLC = TWI_MASTER_ACKACT_bm | TWI_MASTER_CMD_STOP_gc;
}
static void ack_and_received()
{
TWIC.MASTER.CTRLC = TWI_MASTER_CMD_RECVTRANS_gc;
}
static bool send_byte(uint8_t byte)
{
TWIC.MASTER.DATA = byte;
TWI_WAIT_RW_COMPLETE();
return TWI_ACK_RECEIVED();
}
static bool receive_byte(uint8_t* data)
{
TWI_WAIT_RW_COMPLETE();
*data = TWIC.MASTER.DATA;
return !TWI_BUSERR();
}
static uint8_t recieve()
{
TWI_WAIT_RW_COMPLETE();
return TWIC.MASTER.DATA;
}
void i2c_eeprom_init()
{
// Raise pullups
PORTC.PIN0CTRL = (PORTC.PIN0CTRL & ~PORT_OPC_gm) | PORT_OPC_PULLUP_gc;
PORTC.PIN1CTRL = (PORTC.PIN1CTRL & ~PORT_OPC_gm) | PORT_OPC_PULLUP_gc;
TWIC.MASTER.BAUD = TWI_BAUDSETTING;
TWIC.MASTER.CTRLA = TWI_MASTER_ENABLE_bm;
TWIC.MASTER.STATUS = TWI_MASTER_BUSSTATE_IDLE_gc;
}
void i2c_wind_read(uint8_t i2c_addr, uint8_t* buffer, size_t len)
{
size_t num = 0;
if (!send_start_and_address(i2c_addr,false))
{
send_stop_condition();
return false;
}
while (num < len)
{
if (!receive_byte(&buffer[num]))
{
break;
}
ack_and_received();
num++;
}
send_nack_and_stop_condition();
}
|
C
|
/*
* server.c
*
* Created on: 17 ott 2016
* Author: Federico De Laurentiis
*/
#if defined WIN32
#include <winsock.h>
#else
#define closesocket close
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#endif
#include <stdio.h>
#include <stdlib.h>
void ErrorHandler(char[]);
void ClearWinSock() ;
int main() {
#if defined WIN32
// Initialize Winsock
WSADATA wsaData;
int iResult =WSAStartup(MAKEWORD(2,2),&wsaData);
if (iResult != 0) {
printf("Error at WSAStartup()\n");
return 0;
}
#endif
// INIZIO CODICE SOCKET
//DEFINIZIONE STRUCT PER MODELLARE INDIRIZZO IP E PORTA
struct sockaddr_in {
short sin_family;
u_short sin_port;// u_short , presente in Winsock
struct in_addr sin_addr;// in_addr, presente in Winsock
char sin_zerp[8];
};
struct sockaddr_in cad;
int clientSocket; //id della socket_client
int clientLen; //dimensione indirizzo socket client
int MySocket;// id socket
int qlen=6; // massimo numero di socket accettabili dalla socket
// ***CREAZIONE SOCKET***
MySocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (MySocket < 0) {
printf("socket creation failed.\n");
return 0;
}
struct sockaddr_in sad;
sad.sin_family = AF_INET;// valore costante Winsock"2"
sad.sin_addr.s_addr = inet_addr( "127.0.0.1" );//localHost
sad.sin_port = htons( 27015 );//conversione per la rete
//***ASSEGNAZIONE INDIRIZZO ALLA SOCKET ***
//bind( id_socket , puntatore a sockaddr_in , byte indirizzo );
if ( bind(MySocket, (struct sockaddr*) &sad, sizeof(sad)) <0) {
ErrorHandler("bind() failed.\n");
closesocket(MySocket);
return 0;
}
//***SETTAGGIO SOCKET IN ASCOLTO ***
if (listen (MySocket, qlen) < 0) {
ErrorHandler("listen() failed.\n");
closesocket(MySocket);
return 0;
}
printf(" serverSocket in ascolto ....");
//***CICLO PER ACCETTARE LE SOCKET DEI CLIENT***
while (1) {
clientLen = sizeof(cad); // set the size of the client address
if ((clientSocket = accept(MySocket, (struct sockaddr *)&cad,&clientLen)) < 0)
{
ErrorHandler("accept() failed .\n");
// CHIUSURA DELLA CONNESSIONE
closesocket(MySocket);
ClearWinSock();
return 0;
}
printf("Handling client %s\n", inet_ntoa(cad.sin_addr));
}
// CHIUSURA SOCKET
closesocket(MySocket);
#if defined WIN32
WSACleanup();
#endif
return 0;
} // main end
void ErrorHandler(char *errorMessage) {
printf(errorMessage);
}
void ClearWinSock() {
#if defined WIN32
WSACleanup();
#endif
}
|
C
|
#include<stdio.h>
int gcd(int a, int b)
{
return b==0?a:gcd(b, a%b);
}
int main()
{
int a, b;
while(scanf("%d%d", &a, &b)!=EOF){
printf("%d\n", gcd(a, b));
}
return 0;
}
|
C
|
/******************************************************************************
*
* Module: ADC
*
* File Name: adc.c
*
* Description: Source file for the ADC driver
*
* Author: Kyrillos Tharwat
*
*******************************************************************************/
#include "adc.h"
void ADC_Init(void)
{
ADMUX = 0 ;
ADCSRA |= (1<<ADEN) | (1<<ADPS0) | (1<<ADPS1);
ADCSRA &= ~(1<<ADIE);
}
uint16 ADC_readChannel(uint8 channel)
{
ADMUX = (ADMUX & 0xE0) | (channel & 0x073);
ADCSRA |= (1<<ADSC);
while (BIT_IS_CLEAR(ADCSRA,ADIF));
ADCSRA |= (1<<ADIF);
return ADC;
}
|
C
|
// _sense.c
// Monk/Kataan ability
// created by Descartes 21 October 1992
// slightly modified by Bohemund 14 January 1994
#include <std.h>
inherit DAEMON;
int cmd_sense(string str) {
object ob;
object *inv;
int i, skip, which, faith;
string what, Class;
mixed *arr;
if(!str) {
notify_fail("Sense what?\n");
return 0;
}
Class = (string)this_player()->query_class();
if(Class != "monk" && Class != "kataan") {
notify_fail("Your mind swirls in chaos.\n");
return 0;
}
if(Class == "monk") {
if((int)this_player()->query_alignment() < 200) {
notify_fail("You fail to sense anything special about it.\n");
return 0;
}
}
if(Class == "kataan") {
if((int)this_player()->query_alignment() > -200) {
notify_fail("You fail to sense anything special about it.\n");
return 0;
}
}
ob = present(str, this_player());
if(!ob) {
inv = all_inventory(this_player());
if(sscanf(str, "%s %d", what, which) != 2) {
notify_fail("You don't have that!\n");
return 0;
}
for(i=0, skip = 0; i<sizeof(inv) && !ob; i++) {
if(inv[i]->id(what)) {
skip ++;
if(skip == which) ob = inv[i];
}
}
if(!ob) {
notify_fail("You don't have that!\n");
return 0;
}
}
faith = (int)this_player()->query_skill("faith");
if((int)this_player()->query_mp() < 13) {
notify_fail("Too low on magic power.\n");
return 0;
}
say(this_player()->query_cap_name()+" mutters a prayer as "+this_player()->query_subjective()+" concentrates on the "+(string)ob->query_name()+".", this_player());
this_player()->set_magic_round();
if(faith < random(101)) {
this_player()->add_mp(-13);
this_player()->add_skill_points("faith", random(13));
write("You fail to sense anything special about it.");
return 1;
}
else {
this_player()->add_mp(-13);
this_player()->add_skill_points("faith", 13);
arr = (string *)ob->query_property("magic item");
if(!arr) write("You fail to sense anything special about it.");
else if(arr == ({})) write("You fail to sense anything special about it.");
else write("You sense magic about it...\nYou sense the "
"word \"%^BOLD%^"+arr[random(sizeof(arr))]+"%^RESET%^\".");
return 1;
}
}
void help() {
write("Syntax: <sense [item]>\n\n"
"Allows a monk or a kataan to sense any magic powers "
"inherent in an object. "
"There is no way to tell the difference between a failure to sense "
"magic in the object and the lack of magic in an object.\n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MYPORT 9023 // the port users will be connecting to
#define MAXBUFLEN 512
int main(void)
{
int sockfd;
struct sockaddr_in my_addr; // my address information
struct sockaddr_in their_addr; // connector's address information
socklen_t addr_len;
int numbytes;
char buf[MAXBUFLEN];
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
perror("socket");
exit(1);
}
my_addr.sin_family = AF_INET; // host byte order
my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP
my_addr.sin_port = htons(MYPORT); // short, network byte order
memset(&(my_addr.sin_zero), '\0', 8); // zero the rest of the struct
if (bind(sockfd, (struct sockaddr *)&my_addr,
sizeof(struct sockaddr)) == -1) {
perror("bind");
exit(1);
}
for (;;) {
addr_len = sizeof(struct sockaddr);
if ((numbytes = recvfrom(sockfd, buf, MAXBUFLEN-1 , 0,
(struct sockaddr *)&their_addr, &addr_len)) == -1) {
perror("recvfrom");
continue;
}
printf("got packet from %s\n",inet_ntoa(their_addr.sin_addr));
printf("packet is %d bytes long\n",numbytes);
buf[numbytes] = '\0';
printf("packet contains \"%s\"\n",buf);
if (0 == strcmp(buf, "HELL0")) {
sendto(sockfd, "OK!", 3, 0, (struct sockaddr *)&their_addr, addr_len);
}
}
close(sockfd);
return 0;
}
|
C
|
#include "matrix.h"
const uint8_t keyboard[4][4] PROGMEM = { {'1', '2', '3', 'F'},
{'4', '5', '6', 'E'},
{'7', '8', '9', 'D'},
{'A', '0', 'B', 'C'}};
#ifdef INTERRUPT
volatile uint8_t led = 0;
ISR(PCINT0_vect)
{
if(!TST_BIT(PINC,PB0))
led = 2;
else if(!TST_BIT(PINC,PB1))
led = 4;
else if(!TST_BIT(PINC,PB2))
led = 8;
}
void extIRQ_config() {
PCICR = 1 << PCIE0;
PCMSK0 = 0xFF;
}
#endif
void keyboard_config() {
MATRIX_KEYBOARD->DDR = 0x0F;
MATRIX_KEYBOARD->PORT = 0xFF;
#ifdef INTERRUPT
extIRQ_config();
#endif
}
uint8_t read_keyboard() {
uint8_t n, j, key=0xFF, line;
for(n=0;n<4;n++) {
CLR_BIT(COLLUM,n);
_delay_ms(10);
line = LINE >> 4;
for(j=0;j<4;j++) {
if(!TST_BIT(line,j)) {
key = pgm_read_byte(&keyboard[j][n]);
while(!TST_BIT(LINE >> 4,j));
}
}
SET_BIT(COLLUM,n);
}
return key;
}
|
C
|
/* ************************************************************************** */
/* */
/* :::::::: */
/* ps_get_dest_distances.c :+: :+: */
/* +:+ */
/* By: jdunnink <marvin@codam.nl> +#+ */
/* +#+ */
/* Created: 2019/08/14 15:49:26 by jdunnink #+# #+# */
/* Updated: 2019/08/14 17:02:17 by jdunnink ######## odam.nl */
/* */
/* ************************************************************************** */
#include "push_swap.h"
static int find_place_rev(t_list *stack, int value)
{
int dis;
int highest;
int high_dis;
t_list *iter;
dis = 1;
highest = get_highest(stack, &high_dis);
if (value > highest)
return (high_dis);
iter = stack;
while (iter->next)
{
if (*(int *)iter->content > value &&
*(int *)iter->next->content < value)
return (dis);
else if (*(int *)iter->content > value &&
*(int *)iter->next->content > value &&
*(int *)iter->next->content == highest)
return (dis);
dis++;
iter = iter->next;
}
return (0);
}
static int find_place(t_list *stack, int val, int *low_dis)
{
int dis;
int highest;
int high_dis;
int lowest;
t_list *iter;
dis = 1;
highest = get_highest(stack, &high_dis);
lowest = get_lowest(stack, low_dis);
if (val > highest)
return (high_dis + 1);
iter = stack;
while (iter->next)
{
if (*(int *)iter->content < val && *(int *)iter->next->content > val)
return (dis);
else if (val < *(int *)iter->content &&
val < *(int *)iter->next->content &&
*(int *)iter->next->content == lowest)
return (dis);
dis++;
iter = iter->next;
}
return (0);
}
void get_dest_distances(t_list **distances, t_list *stack, char c)
{
t_list *iter;
t_pos *curr;
int low_dis;
low_dis = 0;
iter = *distances;
while (iter)
{
curr = (t_pos *)iter->content;
if (c == 'a')
curr->dest_r_dis = find_place_rev(stack, curr->value);
else
curr->dest_r_dis = find_place(stack, curr->value, &low_dis);
curr->dest_rr_dis = ft_listlen(stack) - curr->dest_r_dis;
iter = iter->next;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
void error(const char *msg) { perror(msg); exit(1); } // Error function used for reporting issue
int main(int argc, char *argv[]){
//declare variables for network and fork use
int listenSocketFD, establishedConnectionFD, portNumber, charsRead, client_address_len, pid;
socklen_t sizeOfClientInfo;
char plain_key[1000]; //variable to hold the data sent by client
char self_name[256]; //variable to hold the name of the executed program
memset(self_name, '\0', sizeof(self_name)); //clear out self name array
strcpy(self_name, argv[0]); //fill self name array with first cmd line arg
struct sockaddr_in serverAddress, clientAddress;
if (argc < 2) { fprintf(stderr,"USAGE: %s port\n", argv[0]); exit(1); } // Check usage & args
// Set up the address struct for this process (the server)
memset((char *)&serverAddress, '\0', sizeof(serverAddress)); // Clear out the address struct
portNumber = atoi(argv[1]); // Get the port number, convert to an integer from a string
serverAddress.sin_family = AF_INET; // Create a network-capable socket
serverAddress.sin_port = htons(portNumber); // Store the port number
serverAddress.sin_addr.s_addr = INADDR_ANY; // Any address is allowed for connection to this process
// Set up the socket
listenSocketFD = socket(AF_INET, SOCK_STREAM, 0); // Create the socket
if (listenSocketFD < 0) perror("ERROR opening socket");
// Enable the socket to begin listening
if (bind(listenSocketFD, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0) // Connect socket to port
perror("ERROR on binding");
listen(listenSocketFD, 5); // Flip the socket on - it can now receive up to 5 connections
//this is the main while loop, acts like a multiserver that forks each new connection
while(1) {
// Accept a connection, blocking if one is not available until one connects
sizeOfClientInfo = sizeof(clientAddress); // Get the size of the address for the client that will connect
establishedConnectionFD = accept(listenSocketFD, (struct sockaddr *)&clientAddress, &sizeOfClientInfo); // Accept
if (establishedConnectionFD < 0) perror("ERROR on accept");
pid = fork(); //create new forked process
if(pid == 0){ //if child, do all of the following
//clear plain_key array
memset(plain_key, '\0', sizeof(plain_key));
charsRead = recv(establishedConnectionFD, plain_key, 999, 0); // Read the client's message from the socket
//following block grabs the plaintext file from the client
int count = 0;
char plaintext[256]; //this variable will hold plaintext file name
memset(plaintext, '\0', sizeof(plaintext)); //clear out the array
while(plain_key[count] != '$'){ //keep adding characters until $ is hit
plaintext[count] = plain_key[count];
count++;
}
plaintext[count] = '\0'; //null terminate the array
//following block grabs the key file from the client
char key[256]; //this will hold the name of the key file
memset(key, '\0', sizeof(key)); //clear out the array
count++;
int i = 0;
while(plain_key[count] != '$'){ //kepp adding characters until & is hit
key[i] = plain_key[count];
i++;
count++;
}
//following block grabs the name of the connecting client
char name[256]; //this will hold the name
memset(name, '\0', sizeof(name)); //clear out the array
count++;
int g = 0;
while(plain_key[count] != '$'){ //keep adding characters until $ is hit
name[g] = plain_key[count];
g++;
count++;
}
key[count] = '\0'; //null terminate key
//open both the key and plaintext files for read only
FILE* fp1 = fopen(plaintext, "r");
FILE* fp2 = fopen(key, "r");
//check to see if keygen file is long enough
fseek(fp1, 0, SEEK_END);
int byteCount1 = ftell(fp1); //length of plaintext file
fseek(fp2, 0, SEEK_END);
int byteCount2 = ftell(fp2); //length of key file
if(byteCount2 < byteCount1){ //if the key is smaller than the plaintext, refuse
perror("Key too small");
exit(1);
}
//rewind the filepoints back to the beginning of the files
rewind(fp1);
rewind(fp2);
char cipher_char; //this will hold the current cipher character
char cipher_str[1000]; //this will hold the complete cipher string
int j = 0;
int k = 0;
//grab the first characters of each file
int p_char = fgetc(fp1);
int k_char = fgetc(fp2);
//encrypt the plaintext, keep going until end of plaintext file
while(p_char != EOF){
if(strcmp(name, "otp_enc") != 0){ //if something other than otp_enc is trying to connect, refuse
perror("Only opt_enc can connect to opt_enc_d");
exit(1);
break;
}
if(p_char == '\n') // if a newline is encounterd, break the loop
break;
if(((int)p_char < 65 || (int)p_char > 91) && p_char != ' ' && p_char){ //if an invalid character is encountered, break the loop
perror("Invalid character encountered\n");
break;
}
//if a space is encounterd, turn it into a [, which the ascii char after Z
if(p_char == ' ')
p_char = '[';
if(k_char == ' ')
k_char = '[';
//calculate the value of the cipher character
cipher_char = (p_char+k_char-130)%27+65;
//if the cipher character is a [, add a space to the cipher string
if(cipher_char == '['){
cipher_str[k] = ' ';
}
else{ //otherwise just add the cipher character to the cipher string
cipher_str[k] = cipher_char;
}
//get the next characters from the files
p_char = fgetc(fp1);
k_char = fgetc(fp2);
k++;
}
cipher_str[k] = '\0'; //null terminate the cipher string
//close the files
fclose(fp2);
fclose(fp1);
if (charsRead < 0) perror("ERROR reading from socket");
charsRead = send(establishedConnectionFD, cipher_str, sizeof(cipher_str), 0); // Send cipher string to client
if (charsRead < 0) perror("ERROR writing to socket");
exit(0); // exit the forked process
}
else
close(establishedConnectionFD); // Close the existing socket which is connected to the client
}
close(listenSocketFD); // Close the listening socket
return 0;
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
int main(){
int a = 10;
double b = 10.5;
printf("%lu\n", sizeof(b)); // double : 64 bits
float c = 10.5;
printf("%lu\n", sizeof(c)); // float : 32 bits
char d = 'a';
char e[] = "Easy way to define string";
bool f = false;
int zero = .9999; // 0
printf("zero is %d\n", zero);
int slices = 17;
int people = 2;
double slicesPerPerson = (double) slices / people; //
printf("%lf\n", slicesPerPerson);
double test1 = 25 / 2 * 2; //24.0
double test2 = 25 / 2 * 2.0; //24.0
double test3 = 25.0 / 2 * 2; //25.0
double test4 = (double) 25 / 2 * 2; //25.0
printf("test1: %lf, test2: %lf, test3: %lf, test4: %lf\n", test1, test2, test3, test4);
return 0;
}
|
C
|
struct student
{
int num;
int yu;
int shu;
int sum;
} stu[100000];
int main()
{
int n,i;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d %d %d",&stu[i].num, &stu[i].yu, &stu[i].shu);
stu[i].sum=stu[i].shu+stu[i].yu;
}
int k,e;
for(k=0;k<3;k++){
for(i=n-2;i>=k;i--){
if(stu[i].sum<stu[i+1].sum){
e=stu[i].sum;
stu[i].sum=stu[i+1].sum;
stu[i+1].sum=e;
e=stu[i].num;
stu[i].num=stu[i+1].num;
stu[i+1].num=e;
}
}
}
for(i=0;i<3;i++){
printf("%d %d\n",stu[i].num,stu[i].sum);
}
return 0;
}
|
C
|
#include "../../includes/math_functions_float.h"
#include "../../includes/verify.h"
#include "float_fmod.h"
int main() {
/* REQ-BL-1130:
* The fmod and fmodf procedures shall return x ,
* if the argument x is +-0 and the argument y is not zero.
*/
float x = 0.0f;
float y = __VERIFIER_nondet_float();
if ((y < 0.0f || y > 0.0f)) {
__VERIFIER_precond_reach();
float res = fmod_float(x, y);
// x is +0, y is not 0, result shall be +0
if (!(res == 0.0f && __signbit_float(res) == 0)) {
__VERIFIER_error();
return 1;
}
}
return 0;
}
|
C
|
#ifndef _RATING_C_
#define _RATING_C_
#include "conn4.h"
#include "rating.h"
#include <stdio.h> /* printf(), fprintf(), scnaf(), fscanf(), FILE */
#include <string.h> /* strcmp() */
#include <stdlib.h> /* malloc() */
#define MAX_NAME_LENGTH 32
/* Use rentry structure */
typedef struct {
char* name;
unsigned int wins;
unsigned int losses;
unsigned int draws;
} user_t;
/* List of rated users. */
user_t* rated = NULL;
/* Number of rates users. */
unsigned int countRated = 0;
/* Maximal number of rated users. */
unsigned int maxRated = 0;
/* Function: find_user */
/* Searches for a user given his/hr name. */
/* Parameter(s): */
/* name - name of searched user (case sensitive) */
/* Returns: */
/* Index of user in score table if found, or -1 if not found. */
int find_user(const char* name) {
int i;
for (i = 0; i < countRated; ++i) {
if (strcmp(name, rated[i].name) == 0) {
return i;
}
}
return -1;
}
/* Function: add_user */
/* Adds user entry to score table. */
/* Parameter(s): */
/* user - new user entry */
void add_user(user_t* user) {
user_t* old;
if (countRated == maxRated) {
if (maxRated == 0) {
maxRated = 1;
rated = malloc(sizeof(*rated));
} else {
old = rated;
rated = malloc(2 * maxRated * sizeof(*rated));
for (countRated = 0; countRated < maxRated; ++countRated) {
rated[countRated] = old[countRated];
}
free(old);
maxRated *= 2;
}
}
rated[countRated++] = *user;
return;
}
/* Function: create_user */
/* Creates a new user entry for a given name. */
/* Returns: */
/* New user entry. */
user_t* create_user(const char* name) {
user_t* user = malloc(sizeof(*user));
user->name = malloc(MAX_NAME_LENGTH+1);
strcpy(user->name, name);
user->wins = 0;
user->losses = 0;
user->draws = 0;
return user;
}
/* Function: choose_name */
/* Asks user for a name and creates a new entry in score table if name is */
/* new. After successful choosing, printf current rating of user. */
/* Returns: */
/* Name selected by user. This string mustn't be freed by the caller. */
/* It will be automatically freed after calling save_raings() function. */
char* choose_name(void) {
char name[MAX_NAME_LENGTH+1];
int ok = 0; /* Status of name creation */
int i;
user_t* user;
/* Ask for a name until valid name is entered */
do {
printf("Pick a name: ");
scanf("%32s", name);
if ((ok = strcmp(name, COMPUTER_NAME)) == 0) {
printf("This name is reserved for computer AI.\n");
}
} while (!ok);
/* If user is new - create new entry in score table */
if ((i = find_user(name)) < 0) {
i = countRated;
add_user(create_user(name));
}
/* Print current rating */
printf("\nYour current rating:\n %d wins, %d losses, %d draws.\n\n",
rated[i].wins, rated[i].losses, rated[i].draws);
return rated[i].name;
}
/* Function: save_result */
/* Saves result of a game. */
/* Parameter(s): */
/* playerX - name of player who played with disks of X type */
/* playerO - name of player who playe with disks of O type */
/* winner - type of disks of winner (X or O) or any other symbol if a draw */
void save_result(const char* playerX, const char* playerO, char winner) {
/* Find users */
int iX = find_user(playerX);
int iO = find_user(playerO);
/* Udate ratings of two players */
if (winner == CELL_X) {
rated[iX].wins++;
rated[iO].losses++;
} else if (winner == CELL_O) {
rated[iO].wins++;
rated[iX].losses++;
} else {
rated[iX].draws++;
rated[iO].draws++;
}
return;
}
/* Function: load_ratings */
/* Loads ratings of registered users from file. Call this function once at */
/* start up. */
void load_ratings(void) {
char name[MAX_NAME_LENGTH+1];
unsigned int wins, losses, draws;
user_t* user;
int i;
/* Read users from file */
FILE* file = fopen(FILENAME, "r");
if (file != NULL) {
while (!feof(file)) {
if (fscanf(file, "%32s %u %u %u", name,
&wins, &losses, &draws) == 4) {
user = create_user(name);
user->wins = wins;
user->losses = losses;
user->draws = draws;
add_user(user);
} else {
break;
}
}
fclose(file);
}
/* Make sure that computer is rated as well */
if (find_user(COMPUTER_NAME) < 0) {
add_user(create_user(COMPUTER_NAME));
}
/* Output all ratings */
printf(" *** Score table ***\n");
for (i = 0; i < countRated; ++i) {
printf(" %s: %d wins, %d losses, %d draws\n",
rated[i].name, rated[i].wins, rated[i].losses, rated[i].draws);
}
return;
}
/* Function: save_ratings */
/* Saves ratings of registered users to file. Call this function once at */
/* exit because it will remove all ratings and free memory. */
void save_ratings(void) {
int i;
/* Write users to file */
FILE* file = fopen(FILENAME, "w");
if (file == NULL) {
printf("\nError: cannot save ratings.\n\n");
} else {
for (i = 0; i < countRated; ++i) {
fprintf(file, "%s\t%u\t%u\t%u\n", rated[i].name, rated[i].wins,
rated[i].losses, rated[i].draws);
free(rated[i].name);
}
fclose(file);
/* Remove all ratings */
free(rated);
rated = NULL;
countRated = maxRated = 0;
}
return;
}
#endif /* _RATING_C_ */
|
C
|
#include <stdio.h>
//structure outside main (like global variable)
struct student
{
//shchar name [10];
char *name;
int ID;
char dept[10];
float CGPA;
};
int main ()
{
//struct student st1 = {"nil shagor", 1234, "CSE", 4.00};
struct student st1;
printf ("\nEnter name, id, department and cgpa: \n");
scanf ("%s %d %s %f", st1.name, &st1.ID, st1.dept,&st1.CGPA);
printf ("You have entered: %s %d %s %.2f\n", st1.name,st1.ID,st1.dept,st1.CGPA);
return 0;
}
|
C
|
#include "json_common.h"
#include <stdlib.h>
#include <string.h>
/*
return string from (*b_i)[0] to delimiter,
setup *b_i to next symbol
*/
char* get_msg_from_stream(char** b_i, char* msg_delimiter)
{
char* r_code = NULL;
char* f_i = strstr(*b_i, msg_delimiter);
if (f_i) {
r_code = (char*)calloc(1, f_i-(*b_i)+1+1);
//*f_i = 0;
memcpy(r_code, *b_i, (f_i-(*b_i)+1));
*b_i = f_i+1;
}
return r_code;
}
|
C
|
//2016115572
//Kwon Hyeon Su
//https://www.zerocho.com/category/Algorithm/post/584b9033580277001862f16c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int arr_index=0;
typedef struct vertex{
int x;
int y;
int city;
double distance;
struct vertex* next[99];
struct vertex* prev;
}Vertex;
void printarr(Vertex* arr){
int i;
for(i=0;i<100;i++){
//if(arr[i].distance != 0)
printf("(%2d,%2d) dist: %.1f city : %d- %d\n",
arr[i].x, arr[i].y, arr[i].distance,arr[i].city , i);
}
}
void CreateVertex(Vertex* arr, int x, int y){
Vertex vertex;
int i;
vertex.x = x;
vertex.y = y;
vertex.city = 1;
vertex.distance = 0.0f;
vertex.prev = NULL;
for(i=0;i<100;i++){
vertex.next[i] = (Vertex*)malloc(sizeof(Vertex));
vertex.next[i] = NULL;
}
arr[arr_index++] = vertex;
}
double dist(Vertex a, Vertex b){
double dist;
dist = sqrt(pow(a.x-b.x,2)+pow(a.y-b.y,2));
return dist;
}
double min(double a, double b){
if(a>b || a == 0) return b;
else return b;
}
void addEdge(Vertex* a, Vertex* b){
int i;
Vertex *vertex = (Vertex*)malloc(sizeof(Vertex));
*vertex = *b;
vertex->prev = a;
vertex->city = 1;
vertex->distance = a->distance + dist(*a, *vertex);
i=0;
a->next[i] = vertex;
//printf("edge added %d to %d in %d\n", a->x, vertex->x, i);
}
void insertNode(Vertex* arr, Vertex* IndexNode, int index, int fuel, Vertex* result_vertex){
int i, j=0;
Vertex* Node = (Vertex*)malloc(sizeof(Vertex));
for(i=0;i<100;i++){
Node->next[i] = (Vertex*)malloc(sizeof(Vertex));
Node->next[i] = NULL;
}
Node->prev = (Vertex*)malloc(sizeof(Vertex));
double offset;
//printf("insert node start\n");
if(index == 99){
//printf("end\n");
return;
}
for(i=index;i<index+5;i++){
if(i==99) break;
*Node = arr[i+1];
while(arr[i].next[j] != NULL){
j++;
}
offset = dist(*Node, arr[99]);
Node->distance = IndexNode->distance + dist(*Node, *IndexNode);
Node->city = IndexNode->city+1;
IndexNode->next[j] = Node;
Node->prev = IndexNode;
if(Node->distance+offset > fuel){
//printf("over !\n");
IndexNode->next[j] = NULL;
//free(IndexNode->next[j]);
break;
}
else if(result_vertex->city <= Node->city){
*result_vertex = *Node;
//printf("overwrittnd\n");
insertNode(arr,IndexNode->next[j], i+1, fuel, result_vertex);
}
}
}
void simulate_overwrite_distance(Vertex* arr, int fuel){
int i, j;
double test;
char** result_coor;
char* temp;
temp = (char*)malloc(sizeof(char)*10);
result_coor = (char**)malloc(sizeof(char*)*1000);
for(i=0;i<1000;i++){
result_coor[i] = (char*)malloc(sizeof(char)*10);
}
Vertex* result_vertex = (Vertex*)malloc(sizeof(Vertex));
Vertex* searchNode = (Vertex*)malloc(sizeof(Vertex));
//result_vertex = &(arr[0]);
for(i=1;i<100;i++){
addEdge(&(arr[0]), &(arr[i]));
//printf("debug\n");
insertNode(arr, &(arr[i]), i, fuel, result_vertex);
}
printf("%d %.1f\n", fuel, result_vertex->distance+ dist(*result_vertex, arr[99]));
searchNode = result_vertex;
i=0;
while(searchNode->prev != NULL){
//printf("%d %d ",searchNode->x, searchNode->y);
memset(result_coor[i],0,5);
itoa(searchNode->x, temp, 10);
strcat(result_coor[i], temp);
//printf("%s ",temp);
strcat(result_coor[i], " ");
itoa(searchNode->y, temp, 10);
//printf("%s ",temp);
strcat(result_coor[i], temp);
strcat(result_coor[i], " ");
i++;
searchNode = searchNode->prev;
}
printf("0 0 ");
for(j=0;j<i;j++){
printf("%s ", result_coor[i-j-1]);
}
printf("100 100\n\n");
result_vertex = NULL;
free(result_vertex);
searchNode = NULL;
free(searchNode);
}
void swap(Vertex* a, Vertex* b){
Vertex temp;
temp = *a;
*a = *b;
*b = temp;
}
int Partition(Vertex* arr, int l, int r){
int pivot=arr[l].x;
int low = l+1;
int high = r;
while(low <= high){
while(low <= r && pivot >= arr[low].x) low++;
while(high >= (l+1) && pivot <= arr[high].x) high--;
if(low<=high) swap(&(arr[low]), &(arr[high]));
}
swap(&(arr[l]), &(arr[high]));
return high;
}
void QuickSort(Vertex* arr, int l, int r){
int pivot;
if(l < r){
pivot = Partition(arr, l, r);
QuickSort(arr, l, pivot-1);
QuickSort(arr, pivot+1, r);
}
}
int main(void){
Vertex *arr;
Vertex trash;
int garbage;
int i, j;
int x, y;
FILE *fp;
trash.x = 0;
trash.y = 0;
trash.city = 0;
trash.distance = -1.0f;
arr = (Vertex*)malloc(sizeof(Vertex)*100);
if(arr == NULL){
perror("malloc error : ");
exit(1);
}
fp = fopen("hw5-3_ex1.txt", "r");
if(fp == NULL){
perror("fopen error : ");
exit(1);
}
fscanf(fp, "%d", &garbage);
for(i=0;i<100;i++){
fscanf(fp, "%d %d", &x, &y);
CreateVertex(arr, x, y);
}
for(i=1;i<100;i++){
arr[i].distance = dist(arr[i],arr[0]);
}
QuickSort(arr, 0, 99);
simulate_overwrite_distance(arr, 300);
simulate_overwrite_distance(arr, 700);
simulate_overwrite_distance(arr, 1100);
simulate_overwrite_distance(arr, 1500);
//printarr(arr);
fclose(fp);
return 0;
}
|
C
|
#include "declaracoes.h"
/*------------------------------------------------------------------*/
/* FUNCOES AUXILIARES */
/*------------------------------------------------------------------*/
int calcula_pos_matriz(int NT, int p, int t){
return (p*NT)+t;
}
void le_argumentos(int argc, char **argv, parametros *param) {
if (argc-1 != 7){
printf("PARAMETROS INVALIDOS!\n");
printf("Use: %s <ARQ_SERIE_ENTRADA> <ARQ_MATRIZ_ENTRADA> <ARQ_SAIDA> <NX> <NY> <NT> <UNDEF>\n",argv[0]);
exit(1);
}
param->arq_serie_entrada=argv[1];
param->arq_matriz_entrada=argv[2];
param->arq_saida=argv[3];
param->NP=atoi(argv[4])*atoi(argv[5]); //NP = NX * NY
param->NT=atoi(argv[6]);
param->UNDEF=atof(argv[7]);
}
void imprime_argumentos(parametros param){
printf("\n");
printf("ARGUMENTOS:\n");
printf("-> ARQ_SERIE_ENTRADA: %s\n",param.arq_serie_entrada);
printf("-> ARQ_MATRIZ_ENTRADA: %s\n",param.arq_matriz_entrada);
printf("-> ARQ_SAIDA: %s\n",param.arq_saida);
printf("-> DIMENSOES: %d x %d\n",param.NP,param.NT);
printf("-> UNDEF: %f\n",param.UNDEF);
printf("\n");
}
void le_serie_entrada(parametros param, float **s){
FILE *arq;
arq=fopen(param.arq_serie_entrada,"rb");
if (!arq){
printf("Erro na abertura do arquivo da serie de entrada : \"%s\".\n",param.arq_serie_entrada);
exit (1);
}
(*s)=(float*)malloc((param.NT)*sizeof(float));
fread((*s),sizeof(float),param.NT,arq);
fclose(arq);
}
void le_matriz_entrada(parametros param, float **d){
int p,t,pos;
FILE *arq;
float *buffer;
arq=fopen(param.arq_matriz_entrada,"rb");
if (!arq){
printf("Erro na abertura do arquivo da serie de entrada : \"%s\".\n",param.arq_matriz_entrada);
exit (1);
}
buffer=(float*)malloc(param.NP*sizeof(float));
(*d)=(float*)malloc((param.NP*param.NT)*sizeof(float));
/*
O arquivo binario esta organizado da seguinte maneira:
[1,1,1][2,1,1][3,1,1],...,[NX,1,1]
[1,2,1][2,2,1][3,2,1],...,[NX,2,1]
[1,3,1][2,3,1][3,3,1],...,[NX,3,1]
...
[1,NY,1][2,NY,1][3,NY,1],...,[NX,NY,1]
[1,1,2][2,1,2][3,1,2],...,[NX,1,2]
[1,2,2][2,2,2][3,2,2],...,[NX,2,2]
[1,3,2][2,3,2][3,3,2],...,[NX,3,2]
...
[1,NY,2][2,NY,2][3,NY,2],...,[NX,NY,2]
[1,1,3][2,1,3][3,1,3],...,[NX,1,3]
[1,2,3][2,2,3][3,2,3],...,[NX,2,3]
[1,3,3][2,3,3][3,3,3],...,[NX,3,3]
...
[1,NY,2][2,NY,2][3,NY,NT-2],...,[NX,NY,NT-1]
[1,1,3][2,1,3][3,1,NT-1],...,[NX,1,NT-1]
[1,2,3][2,2,3][3,2,NT-1],...,[NX,2,NT-1]
[1,3,3][2,3,3][3,3,NT-1],...,[NX,3,NT-1]
...
[1,NY,NT][2,NY,NT][3,NY,NT],...,[NX,NY,NT]
Ou seja, varia varia primeiro o X, depois o Y, e por ultimo o T.
*/
for (t=0;t<param.NT;t++){
fread(buffer,sizeof(float),param.NP,arq);
for(p=0;p<param.NP;p++){
pos=calcula_pos_matriz(param.NT,p,t);
(*d)[pos]=buffer[p];
}
}
free(buffer);
fclose(arq);
}
void salva_arq_saida(parametros param, float *s){
FILE *arq;
arq=fopen(param.arq_saida,"wb");
if (!arq){
printf("Erro na abertura do arquivo de saida.\n");
exit (1);
}
fwrite(s,sizeof(float),param.NP,arq);
fclose(arq);
}
void shuffle(float *array, size_t n){
if (n > 1) {
size_t i;
for (i = 0; i < n - 1; i++) {
size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
float t = array[j];
array[j] = array[i];
array[i] = t;
}
}
}
/*------------------------------------------------------------------*/
/*------------------------------------------------------------------*/
float correlacao_serie_serie(float *vA, float *vB, int nt, float undef){
int i,k;
float *vA_aux, *vB_aux;
double E_cov, E_anm2_A, E_anm2_B, div;
double med_A, med_B;
vA_aux=(float *)malloc(nt*sizeof(float));
vB_aux=(float *)malloc(nt*sizeof(float));
//CRIA DOIS VETORES AUXILIARES APENAS COM AS "DUPLAS" DE
//DADOS ONDE AMBOS OS VALORES NAO SEJAM INDEFINIDOS.
//ALEM DISSO JA FAZ O SOMATORIO DAS SERIES FINAIS PARA DEPOIS
//CALCULAR A MEDIA;
//*** k = Numero de duplas validas e tamanho total das series auxiliares ***
med_A=0.0;
med_B=0.0;
k=0;
for (i=0;i<nt;i++){
if ((vA[i] != undef) && (vB[i] != undef)){
vA_aux[k]=vA[i];
vB_aux[k]=vB[i];
med_A=med_A+(double)vA[i];
med_B=med_B+(double)vB[i];
k++;
}
}
if (k < 2) {
free(vA_aux);
free(vB_aux);
return (double)undef;
}
med_A=med_A/(double)k;
med_B=med_B/(double)k;
E_cov=0.0;
E_anm2_A=0.0;
E_anm2_B=0.0;
for (i=0;i<k;i++){
E_cov = E_cov + (((double)vA_aux[i]-med_A)*((double)vB_aux[i]-med_B));
E_anm2_A = E_anm2_A + (((double)vA_aux[i]-med_A)*((double)vA_aux[i]-med_A));
E_anm2_B = E_anm2_B + (((double)vB_aux[i]-med_B)*((double)vB_aux[i]-med_B));
}
free(vA_aux);
free(vB_aux);
div=sqrt(E_anm2_A * E_anm2_B);
if (div == 0) return undef;
else return (float)(E_cov/div);
}
float sig_mcarlo_serie_serie(float *vA, float *vB, int nt, float undef, int total_perm){
int i, cont;
float correl_orig, correl;
correl_orig=correlacao_serie_serie(vA,vB,nt,undef);
if (correl_orig == undef) return undef;
srand(time(NULL));
for (i=0;i<total_perm;i++){
shuffle(vB,nt);
correl=correlacao_serie_serie(vA,vB,nt,undef);
if (fabs(correl) >= fabs(correl_orig)) cont++;
}
return ((float)cont/(float)total_perm)*(correl_orig*fabs(correl_orig));
}
/*------------------------------------------------------------------*/
/*------------------------------------------------------------------*/
int main(int argc, char **argv){
int p, pos;
//LE OS ARGUMENTOS E OS DADOS DE ENTRADA
le_argumentos(argc,argv,¶m);
le_serie_entrada(param,&h_serie_entrada);
le_matriz_entrada(param,&h_matriz_entrada);
h_saida=(float*)malloc(param.NP*sizeof(float));
for (p=0; p<param.NP; p++){
pos=calcula_pos_matriz(param.NT, p, 0);
h_saida[p]=sig_mcarlo_serie_serie(h_serie_entrada, &(h_matriz_entrada[pos]),param.NT, param.UNDEF, TOTAL_PERM);
}
salva_arq_saida(param, h_saida);
free(h_matriz_entrada);
free(h_serie_entrada);
free(h_saida);
return 1;
}
|
C
|
#include <stdio.h>
int main(void){
int n;
int cnt=1, temp=1;
scanf("%d", &n);
if(n==1){
cnt=1;
}
else{
for(int i=2; i<=n; i++){
if(temp+(cnt-1)*6<i){
cnt++;
temp=i-1;
}
}
}
printf("%d", cnt);
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
#include <time.h>
#include "pow.h"
#include "sha256.h"
#define START 25
#define COUNT 5
void check_hash(char *hash, struct proof *proofs, int sequence, int c, clock_t start) {
for (int i = 0; i < c; i++) {
if (proofs[i].found) continue;
int n = proofs[i].length;
clock_t time = clock() - start;
double time_taken = ((double) time) / CLOCKS_PER_SEC;
if (check_pow(hash, n)) {
proofs[i].time = time_taken;
proofs[i].found = true;
proofs[i].sequence = sequence;
proofs[i].hash = hash;
print_proof(proofs[i]);
return;
}
}
}
int main(int argc, char *argv[]) {
struct proof samples[COUNT];
init_proofs(samples, START, COUNT);
clock_t start = clock();
bool random = argc == 1 && argv[0] == "--random";
int nonce = 0;
while (true) {
char macondo[] = "Muchos años después, frente al pelotón de fusilamiento, el Coronel Aureliano Buendía había de "
"recordar aquella tarde remota en que su padre lo llevó a conocer el hielo. Macondo era entonces una "
"aldea de %d";
if (random) nonce = 0; //TODO: Get nonce randomly
else nonce++;
int length_nonce = (int) floor(log10(fabs(nonce))) + 1;
int n = sizeof(macondo) + length_nonce;
char plain[n];
sprintf(plain, macondo, nonce);
char hash[65];
sha256(plain, hash);
check_hash(hash, samples, nonce, COUNT, start);
if (proofs_completed(samples, COUNT)) break;
}
return 0;
}
|
C
|
/*
Copyright (C) HWPORT.COM.
All rights reserved.
Author: JAEHYUK CHO <mailto:minzkn@minzkn.com>
*/
#include "hwport_ftpd.h"
static void hwport_ftpd_break_signal(int s_signal);
static void hwport_ftpd_dummy_signal(int s_signal);
static void hwport_ftpd_install_signal(void);
static int hwport_ftpd_load_system_account(hwport_ftpd_t s_handle);
static int hwport_ftpd_load_default_account(hwport_ftpd_t s_handle);
int main(int s_argc, char **s_argv);
static int g_ftpd_break = 0;
static void hwport_ftpd_break_signal(int s_signal)
{
g_ftpd_break = 1;
/* reinstall signal */
(void)signal(s_signal, hwport_ftpd_break_signal);
}
static void hwport_ftpd_dummy_signal(int s_signal)
{
/* reinstall signal */
(void)signal(s_signal, hwport_ftpd_dummy_signal);
}
static void hwport_ftpd_install_signal(void)
{
#if defined(def_hwport_ftpd_windows)
(void)signal(SIGINT, hwport_ftpd_break_signal);
(void)signal(SIGTERM, hwport_ftpd_break_signal);
#else
(void)signal(SIGPIPE, hwport_ftpd_dummy_signal);
(void)signal(SIGINT, hwport_ftpd_break_signal);
(void)signal(SIGQUIT, hwport_ftpd_break_signal);
(void)signal(SIGTERM, hwport_ftpd_break_signal);
(void)signal(SIGHUP, hwport_ftpd_break_signal);
#endif
}
static int hwport_ftpd_load_system_account(hwport_ftpd_t s_handle)
{
#if 1L /* all system user */
(void)hwport_ftpd_add_user(s_handle, (hwport_ftpd_account_t **)0, def_hwport_ftpd_account_flag_none | def_hwport_ftpd_account_flag_system_user, (const char *)0, (const char *)0, (const char *)0);
#elif 0L /* specific system user only */
(void)hwport_ftpd_add_user(s_handle, (hwport_ftpd_account_t **)0, def_hwport_ftpd_account_flag_none | def_hwport_ftpd_account_flag_system_user, "root", (const char *)0, (const char *)0);
#else
(void)s_handle;
#endif
return(0);
}
static int hwport_ftpd_load_default_account(hwport_ftpd_t s_handle)
{
#if 1L /* OPTION: allow for guest user account */
(void)hwport_ftpd_add_user(s_handle, (hwport_ftpd_account_t **)0, def_hwport_ftpd_account_flag_none | def_hwport_ftpd_account_flag_guest_user, "test", (const char *)0, (const char *)0 /* "/home/ftp" */);
(void)hwport_ftpd_add_user(s_handle, (hwport_ftpd_account_t **)0, def_hwport_ftpd_account_flag_none | def_hwport_ftpd_account_flag_guest_user, "ftp", (const char *)0, (const char *)0 /* "/home/ftp" */);
(void)hwport_ftpd_add_user(s_handle, (hwport_ftpd_account_t **)0, def_hwport_ftpd_account_flag_none | def_hwport_ftpd_account_flag_guest_user, "anonymous", (const char *)0, (const char *)0 /* "/home/ftp" */);
#else
(void)s_handle;
#endif
return(0);
}
int main(int s_argc, char **s_argv)
{
hwport_ftpd_t s_handle;
(void)s_argc;
(void)s_argv;
hwport_ftpd_install_signal();
s_handle = hwport_ftpd_open();
if(hwport_ftpd_builtin_expect(s_handle == ((hwport_ftpd_t)0), 0)) {
/* can not open ftpd */
return(EXIT_FAILURE);
}
(void)hwport_ftpd_load_system_account(s_handle);
(void)hwport_ftpd_load_default_account(s_handle);
while(g_ftpd_break == 0) {
(void)hwport_ftpd_do(s_handle, 1000 /* (-1)=suspend */);
}
s_handle = hwport_ftpd_close(s_handle);
return(EXIT_SUCCESS);
}
/* vim: set expandtab: */
/* End of source */
|
C
|
#include<stdio.h>
#define N 10
int main() {
static int a[N]= {5,4,3,2,1,9,8,7,6,0};
printf("\nThe array is:\n");
for(int i=0; i<N; i++)printf("%5d",a[i]);
for(int i=0; i<N-1; i++) {
int min=i,j;
for(int j=i+1; j<N; j++)
if(a[min]>a[j])min=j;
int tmp=a[min];
a[min]=a[i];
a[i]=tmp;
}
printf("\n The sorted numbers: \n");
for(int i=0; i<N; i++)printf("%5d",a[i]);
putchar('\n');
return 0;
}
|
C
|
int glob_a;
int glob_b = glob_c;
int A() {
int c = 2;
a = c + 2;
c = c + 1;
c = a + 3;
return c;
}
int B() {
int c, s = 0;
for (c = 0; c < 10; c = c + 1) {
if (c == 3) {
int t = c + 1;
s = s + t;
c = c + a + t;
}
}
return s;
}
void C() {
typedef int a;
typedef a c;
typedef b d;
}
void D() {
int a;
if (1) {
typedef a e;
}
}
void E() {
AA(1,
1);
}
void F() {
int a;
a();
}
int Gx() {
return 1;
}
int G() {
int c[3];
float a = Gx;
return c[1];
}
void H(not_exist a) {}
|
C
|
//conversion of infix to postfix
#include<stdio.h>
int prec(char);
int main()
{
char stack[15],postfix[30],exp[30];
int i,top=-1,j=0;
printf("Enter the expression in infix:");
scanf("%s",&exp);
for(i=0;exp[i]!='\0';i++)
{
if((exp[i]>=65 && exp[i]<=90) || (exp[i]>=97 && exp[i]<=122))
postfix[j++]=exp[i];
else
{
if(exp[i]=='(')
stack[++top]='(';
else if(exp[i]==')')
{
while(stack[top]!='(')
{
postfix[j++]=stack[top--];
}
stack[top--];
}
else
{
while(stack[top]>-1 && (prec(stack[top])>=prec(exp[i])))
{
postfix[j++]=stack[top--];
}
stack[++top]=exp[i];
}
}
}
while(stack[top]!=-1)
postfix[j++]=stack[top--];
postfix[j]='\0';
printf("\n the postfix expression is:\n");
puts(postfix);
return 0;
}
int prec(char a)
{
if(a=='*' || a=='/')
return 2;
else if(a=='+' || a=='-')
return 1;
else if(a=='^')
return 3;
else
return -1;
}
/* INPUT:-(a+b*c-d/e)
output:-abc*+de/-
*/
|
C
|
/*
========== licence begin LGPL
Copyright (C) 2002 SAP AG
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
========== licence end
*/
#ifdef RELIANT
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int strcasecmp (char *str0, char *str1) {
int rc;
char *ptr;
char *mystr0;
char *mystr1;
mystr0 = malloc (strlen (str0) + 1);
mystr1 = malloc (strlen (str1) + 1);
strcpy (mystr0, str0);
strcpy (mystr1, str1);
for (ptr = mystr0; *ptr != '\0'; ptr++) {
*ptr = toupper (*ptr);
}
for (ptr = mystr1; *ptr != '\0'; ptr++) {
*ptr = toupper (*ptr);
}
rc = strcmp (mystr0, mystr1);
free (mystr0);
free (mystr1);
return (rc);
}
#endif
|
C
|
/* Name: Philip Hoddinott
Section: 4
Side: A
Date: 2/29/2016
Gain: 2
Port pin: 1.4
File name: hw7.c
Description: This program reads an analog input, it prints the digital value of the A/D conversion and print the input voltage (in millivolts).
The gain is 2, so the max voltage it can measure is 1.2 volts. It has an if statment that warns the user if they are approching an overflow value
The specific requirements are:
Read the analog input on Port 1.4
Set a gain value of 2
Print the A/D value
Print the input voltage in millivolts (as an integer). Remember to include the gain term when calculating voltage.
*/
#include <c8051_SDCC.h>// include files. This file is available online
#include <stdio.h>
//-----------------------------------------------------------------------------
// Function Prototypes
//-----------------------------------------------------------------------------
void Timer_Init(void); // Initialize Timer 0
void Interrupt_Init(void); //Initialize interrupts
void Timer0_ISR(void) __interrupt 1; //Initalize interupts
void ADC_Init(void);//Initalize ADC
void Port_Init(void);//Initalize Ports
unsigned char read_AD_input(unsigned char pin_number);//reads AD input
//-----------------------------------------------------------------------------
// Global Variables
//-----------------------------------------------------------------------------
unsigned int counts1;//given not used
unsigned int counts2;//given not used
unsigned char AD_value;//AD value
unsigned char input;//used in main for AD value
unsigned char result;//Given, not used
unsigned long millivolts;//used in main to display milivolts
//***************
void main(void) {
Sys_Init(); // System Initialization
putchar(' '); // the quote fonts may not copy correctly into SiLabs IDE
Interrupt_Init();//Initalize interurrupt
Timer_Init(); // Initialize Timer 0
Port_Init(); //Initalzie ports
ADC_Init(); //Initalize ADC stuff
printf("Start \r\n");
while (1) {
printf("press enter to read A/D input \r\n");
input = getchar();//user presses enter to check voltage
input = read_AD_input(4);// set port 4
millivolts = ((long) 1000*input * 24) / (10*256 * 2);// from page 56, multiply by 1000 to get miivoles
if(input>=250){
printf("\nWARNING! This circut cannot handle more than 2.4 volts of input.\r\n");
printf("Program has detected that circut is at or over 2.4 volts.\r\n");
printf("The gain is 2 so program cannot handle an input value of morethan 1.2V\r\n");
printf("The following values may be incorrect due to overflow.\r\n");
}//end if overflow starment
printf("\n\rInput value is %u\r\n", input);
printf("\n\rIn millivolts the value is %lu (remember gain is 2)\r\n", millivolts);//Print statments to display AD input and voltage
}//end while loop
}//end main
//
// the initialization code needed for the ADC1
//
void ADC_Init(void) {
REF0CN = 0x03; //code from page 61
ADC1CN = 0x80; //code from page 61 in book
ADC1CF |= 0x02; //gain is 2
}//end ADC INIT
//
// function that completes an A/D conversion
//
unsigned char read_AD_input(unsigned char pin_number) {
AMX1SL = pin_number;//set it to pin numer
ADC1CN = ADC1CN & ~0x20; // Clear “Conversion Completed” flag
ADC1CN = ADC1CN | 0x10; // Initiate A/D Conversion
while ((ADC1CN & 0x20) == 0x00); // Wait for conversion to finish
return ADC1; // Return digital value from ADC1
}//end read_AD_INPUT
//
// Port initialization code
//
void Port_Init(void){
P1MDIN &= ~0x04; // Configure P1.4 as analoug input
P1MDOUT &= ~0x04; // P1.4 open-drain input
P1 |= 0x04; // set logic 1 to P1.4
}//end port init
//
// the following functions can be used if needed, no edits required
// They are not used in the program
void Interrupt_Init(void){
IE |= 0x82; // enable Timer0 Interrupt request
}//end inerupt init
void Timer_Init(void){
CKCON |= 0x08; // Timer0 uses SYSCLK
TMOD &= 0xF0; // clear the 4 least significant bits
TMOD |= 0x01; // Timer0 mode 16
TR0 = 0; // Stop Timer0
TL0 = 0; // Clear low byte of register T0
TH0 = 0; // Clear high byte of register T0
}//end timer init
void Timer0_ISR(void) __interrupt 1
{
counts1++;
counts2++;
}//end timer0
|
C
|
//there is an array a with 10 elements,
//and the number is put in order from small to big.
//input x and find it in a,print its index;if none ,print not found.
#include <stdio.h>
int main()
{
int a[10]={0,1,2,3,4,5,6,7,8,9};
int low,high,mid,x,n=10;
printf("input x:\n");
scanf("%d",&x);
low = 0;
high = n-1;
while (low <= high)
{
mid = ( low + high )/2;
if (x == a[mid])
{
break;
}
else if ( x < a[mid])
{
high = mid -1;
}
else
{
low = mid +1;
}
}
if ( low <= high)
{
printf("index of the number is %d\n",mid );
}
else
{
printf("not found\n");
}
return 0;
}
|
C
|
#ifndef __DIJKSTRA_ARRAY__
#define __DIJKSTRA_ARRAY__
#include "graph.h"
#define INFINITY 1000000000
#define NIL -1
typedef struct queue{
int * array;
unsigned int size;
}queue;
/**
* Initialization of the queue.
*
* This function initializes the queue, adding all nodes
* to the queue.array member, according to the size.
*
* @param size of the queue.
*/
queue * build_queue(unsigned int size);
/**
* Check on the dimension of the queue.
*
* This function checks if the queue is empty.
*
* @param Q queue to be checked.
*/
int is_empty(queue * Q);
/**
* Swapping of two elements in the queue.
*
* This function is an auxiliary method used by the extract_min
* function to swap two elements in the queue.
*
* @param Q queue that contains the two nodes to be swapped.
* @param node_a first node to be swapped.
* @param node_b second node to be swapped.
*/
void swap(queue * Q, unsigned int node_a, unsigned int node_b);
/**
* Extraction of the node with minimum distance from the queue.
*
* This function extract the node with minimum candidate distance
* from the queue, using the auxiliary function swap to put the
* selected node at the end of the queue and reducing the queue size.
*
* @param G graph that contains the vector of vertices with the respective candidate distances
* @param Q queue that contains the nodes
* @return the index of the queue that contains the extracted value.
*/
int extract_min_queue(graph * G, queue * Q); //maybe const int const * distance???
/**
* Update of the candidate distance from the source.
*
* This function updates the candidate distance from the source of a given
* node. Auxiliary function for the relax method.
*
* @param G graph that contains the nodes.
* @param index of the node whose distance will be updated.
* @param new_distance new value of the candidate distance.
*/
void update_distance(graph * G, const int index, int new_distance);
/**
* Relax function for the candidate distances from the source.
*
* This function updates the distance and predecessor of a node
* in vector V of graph G, when necessary.
*
* @param G graph containing the vector of vertices.
* @param u candidate predecessor for node v.
* @param v node whose distance and predecessor could be updated.
*/
void relax(graph * G, const int u, const int v);
/**
* Initialization of the single source shortest path problem.
*
* This function sets, for each vertex of the graph,
* all distances to INFINITY and all predecessors to NIL.
*
* @param G is the graph to which the vertices belongs.
*/
void init_sssp(graph * G);
/**
* Execution of the Dijkstra algorithm for the single
* source shortest path problem.
*
* This function performs the execution modifying the values
* of vector of vertices V, member of the struct graph.
*
* @param G is the graph involved in the execution.
* @param source is the source node for the algorithm.
*/
void dijkstra_array(graph * G, int source);
#endif
|
C
|
#ifndef _GRAPH_H_
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define GRAPH_INFINITY 65535 /* 65535 */
#define Default_Vertex_Size 10 /*ĬϵĶ*/
#define MAXSIZE 10 /* 洢ռʼ */
typedef int Status; /* StatusǺ,ֵǺ״̬룬OK */
typedef char VertexType; /* Ӧû */
typedef int EdgeType; /* ϵȨֵӦû */
typedef int Boolean; /* BooleanDz,ֵTRUEFALSE */
/*======================ڽӾṹ뺯======================*/
typedef struct GraphMtx GraphMtx; /*ڽӾ*/
void InitGraph(GraphMtx* g); /*ڽӾʼ*/
int GetVertexPos(GraphMtx* g, VertexType v); /*ڽӾȡλ*/
void ShowGraph(GraphMtx g); /*ڽӾӡͼϢ*/
void InsertVertex(GraphMtx* g, VertexType v); /*ڽӾ붥*/
void RemoveEdge(GraphMtx* g, VertexType v1, VertexType v2); /*ڽӾɾ*/
void RemoveVertex(GraphMtx* g, VertexType v); /*ڽӾɾ*/
int GetFirstNeighbor(GraphMtx* g, VertexType v); /*ڽӾȡvһڽӶ*/
int GetNextNeighbor(GraphMtx* g, VertexType v, VertexType w);/*ڽӾȡһڽӶ(±)ȡvһڽӶwڽӶ*/
void DestroyGraph(GraphMtx* g); /*ڽӾ*/
VertexType GetVertexValue(GraphMtx* g, int v); /*ʶȡֵ*/
/*======================ڽӱṹ뺯======================*/
//typedef struct EdgeNode EdgeNode; //߽ṹ
//typedef struct VerNode VerNode, * Vertex; //ṹ
//typedef struct AdjGraph AdjGraph; //ڽӱ(ͼ)
//void InitAdjGraph(AdjGraph* g); /*ڽӱʼ*/
//߽ṹ
typedef struct EdgeNode {
int dest;//Ŷ±
struct EdgeNode* next; //ָ¸߽ṹָ
//EdgeType weight; //Ȩ,
}EdgeNode;
//ṹ
typedef struct VerNode {
VertexType data; //
EdgeNode* firstArc; //ָ߽ṹָ
}VerNode, * Vertex;
//ڽӱ(ͼ)
typedef struct AdjGraph {
int MaxVertices; //
int NumVertices; //ʵʶ
int NumEdges; //ߵ
Vertex adjList; //ָṹ
}AdjGraph;
int GetVerNodePos(AdjGraph* g, VertexType v); /*ȡλ*/
void ShowAdjGraph(AdjGraph g); /*ӡͼ*/
void InsertAdjVertex(AdjGraph* g, VertexType v); /*붥*/
void InsertAdjEdge(AdjGraph* g, VertexType v1, VertexType v2); /*ߣڶvertex1vertex2֮һ*/
void removeAdjEdge(AdjGraph* g, VertexType v1, VertexType v2); /*ɾ,ɾv1Ͷv2֮ı*/
int GetFirstAdjNeighbor(AdjGraph* g, VertexType v); /*ȡһڽӶ*/
int GetNextAdjNeighbor(AdjGraph* g, VertexType v1, VertexType v2); /*ȡڽӶһ㣺ȡv1ڽӶ㣬ڽӶv1ڽӶv2һ*/
void DestroyAdjGraph(AdjGraph* g); /*ͼ*/
VertexType GetVerNodeValue(AdjGraph* g, int v); /*ȡֵ*/
/* ****************************************************** */
/*======================ȱ(ͨͼ)======================*/
void DFS(GraphMtx* g, int v, Boolean visited[]); //ڽӾȱ: g:ͼ v:ʼ visited:
void BFS(GraphMtx* g, int v, Boolean visited[]); //ڽӾȱg:ͼ v:ʼ visited:
void DFS_adj(AdjGraph* g, int v, Boolean visited[]); //ڽӱȱͼgʼv
void BFS_adj(AdjGraph* g, int v, Boolean visited[]); //ڽӱȱg:ͼ v:ʼ visited:
/*======================ȱ(ͨͼ)======================*/
void NonUnicomDFS(GraphMtx* g, int v, Boolean visited[]);
void NonUnicomBFS(GraphMtx* g, int v, Boolean visited[]);
void NonUnicomDFS_adj(AdjGraph* g, int v, Boolean visited[]);
void NonUnicomBFS_adj(AdjGraph* g, int v, Boolean visited[]);
/*======================нṹ뺯======================*/
/* ѭе˳洢ṹ */
typedef struct Queue
{
int data[MAXSIZE];
int front; /* ͷָ */
int rear; /* βָ룬вգָβԪصһλ */
}Queue;
typedef struct Queue Queue;
Status InitQueue(Queue* Q); /* ʼһնQ */
Status QueueEmpty(Queue Q); /* QΪն,TRUE,FALSE */
Status EnQueue(Queue* Q, int e); /* δԪeΪQµĶβԪ */
Status DeQueue(Queue* Q, int* e); /* вգɾQжͷԪأeֵ */
#endif // !_GRAPH_H_
|
C
|
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
int lena,lenb,i,j,k,t=0;
char a[100500],b[100500];
int aa[100500],bb[100500],c[200500];
memset(c,0,sizeof(c));
scanf("%s %s",a,b);
lena=strlen(a);
lenb=strlen(b);
c[lena+lenb]=10000;
for(i=0;i<lena;i++)
aa[i]=a[i]-'0';
for(i=0;i<lenb;i++)
bb[i]=b[i]-'0';
for(i=0;i<lena;i++)
{
for(j=0;j<lenb;j++)
{
c[i+j+1]+=aa[i]*bb[j];//b*a
}
}
for(k=lena+lenb-1;k>0;k--)
{
c[k-1]+=(c[k]/10);
c[k]=c[k]%10;
}
if(c[0]==0)
t++;
while(c[t]==0&&c[t+1]==0)
t++;//跳过头部为0元素
for(i=t;i<lena+lenb;i++)
printf("%d",c[i]);
return 0;
}
|
C
|
//
// main.c
// Cow Beauty
//
// Created by Freddy Roman Cepeda on 11/13/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#include <stdio.h>
#include <limits.h>
#define path "pageant"//"/Users/Freddy/Desktop/USACO/Cow Beauty/Cow Beauty/pageant"
#define MAXSIZE 50
#define MAXQUEUE 10000
typedef struct {
int x, y;
} Point;
Point makePoint(int x, int y);
Point makePoint(int x, int y){
Point point = {x, y};
return point;
}
typedef struct {
int width, height;
} Size;
int map[MAXSIZE][MAXSIZE];
Size mapSize;
#define pointInMap(p) map[p.x][p.y]
#define isValidPoint(p) (p.x >= 0 && p.x < mapSize.width && p.y >= 0 && p.y < mapSize.height)
#define MOVCOUNT 4
Point movs[MOVCOUNT] = {{0,1}, {0,-1}, {1,0}, {-1,0}};
#define nextPoint(p,i) makePoint(p.x + movs[i].x, p.y + movs[i].y)
Point queue[MAXQUEUE];
int qs, qe;
#define push(p) queue[qe++ % MAXQUEUE] = p;
#define pop() queue[qs++ % MAXQUEUE];
#define queueIsNotEmpty (qs < qe)
#define resetQueue() qs = qe = 0
FILE *in;
FILE *out;
#define test -1
#define EMPTY 1 * test
#define SPOT 2 * test
#define SPOTA 3 * test
#define SPOTB 4 * test
void color(Point start, int col);
void color(Point start, int col){
push(start);
while (queueIsNotEmpty) {
Point curr = pop();
pointInMap(curr) = col;
int i;
for (i = 0; i < MOVCOUNT; i++) {
Point next = nextPoint(curr, i);
if (isValidPoint(next) && pointInMap(next) == SPOT) {
push(next);
}
}
}
resetQueue();
}
#define printMap() for (y = 0; y < mapSize.height; y++) {for (x = 0; x < mapSize.width; x++)\
{fprintf(out, "%d ", map[x][y]);} fprintf(out, "\n");}fprintf(out, "\n");
Point startPoint(void);
Point startPoint(void){
int x, y;
for (y = 0; y < mapSize.height; y++) {
for (x = 0; x < mapSize.width; x++) {
if (map[x][y] == SPOTA) {
return makePoint(x, y);
}
}
}
return makePoint(0, 0);
}
int doSearch(Point start);
int doSearch(Point start){
int minDist = INT_MAX;
pointInMap(start) = 0;
push(start)
while (queueIsNotEmpty) {
Point curr = pop();
int i;
for (i = 0; i < MOVCOUNT; i++) {
Point next = nextPoint(curr, i);
if (isValidPoint(next)) {
if (pointInMap(next) == SPOTB && minDist > pointInMap(curr)) {
minDist = pointInMap(curr);
} else if (pointInMap(next) == SPOTA) {
pointInMap(next) = 0;
push(next);
} else if (pointInMap(next) == EMPTY) {
pointInMap(next) = pointInMap(curr) + 1;
push(next);
} else if (pointInMap(next) > pointInMap(curr) + 1) {
pointInMap(next) = pointInMap(curr) + 1;
push(next);
}
}
}
}
return minDist;
}
int main (int argc, const char * argv[])
{
in = fopen(path".in", "r");
out = fopen(path".out", "w");
fscanf(in, "%d %d", &mapSize.height, &mapSize.width);
int x, y;
for (y = 0; y < mapSize.height; y++) {
for (x = 0; x < mapSize.width; x++) {
char c;
do{
fscanf(in, "%c", &c);
} while (c != 'X' && c != '.');
map[x][y] = c == 'X' ? SPOT : EMPTY;
}
}
int col = SPOTA;
for (y = 0; y < mapSize.height; y++) {
for (x = 0; x < mapSize.width; x++) {
if (map[x][y] == SPOT) {
color(makePoint(x, y), col);
col = SPOTB;
}
}
}
//printMap();
Point start = startPoint();
int result = doSearch(start);
fprintf(out, "%d\n", result);
return 0;
}
|
C
|
/**
* \defgroup unixsimulator Simulation of the Borg API for UNIX like platforms.
*/
/*@{*/
/**
* @file main.c
* @brief Simulator for Unix like platforms.
* @author Martin Ongsiek, Peter Fuhrmann, Christian Kroll
*/
#ifdef OSX_
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include <pthread.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <setjmp.h>
#include "../config.h"
#include "../display_loop.h"
#include "trackball.h"
/** Number of bytes per row. */
#define LINEBYTES (((NUM_COLS - 1) / 8) + 1)
/** Fake port for simulating joystick input. */
volatile unsigned char fakeport;
/** Flag which indicates if wait should jump to the menu if fire is pressed. */
volatile unsigned char waitForFire;
/** The simulated frame buffer of the borg. */
volatile unsigned char pixmap[NUMPLANE][NUM_ROWS][LINEBYTES];
/** Jump buffer which leads directly the menu. */
extern jmp_buf newmode_jmpbuf;
/** Width of the window. */
int WindWidth;
/** Height of the window. */
int WindHeight;
/** Rotation of the x-axis of the scene. */
float view_rotx = 0;
/** Rotation of the y-axis of the scene. */
float view_roty = 0;
/** Rotation of the z-axis of the scene. */
float view_rotz = 0;
/** GLUT window handle. */
int win;
/**
* Simple wait function.
* @param ms The requested delay in milliseconds.
*/
void wait(unsigned int ms) {
if (waitForFire) {
if (fakeport & 0x01) {
longjmp(newmode_jmpbuf, 43);
}
}
usleep(ms * 1000);
}
/**
* Draw a LED in the given color (which is a list).
* @param color List which contains a sphere.
* @param pos_x x-coordinate
* @param pos_y y-coordinate
* @param pos_z z-coordinate
*/
void drawLED(int color, float pos_x, float pos_y, float pos_z) {
glPushMatrix();
glTranslatef(pos_x, pos_y, pos_z);
glCallList(color);
glPopMatrix();
}
/**
* Draws the LED matrix.
*/
void display(void) {
int x, y, z, level, color;
tbReshape(WindWidth, WindHeight);
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
glTranslatef(NUM_COLS * 2., 0., NUM_ROWS * 2.);
tbMatrix();
glRotatef(view_rotx, 1.0, 0.0, 0.0);
glRotatef(view_roty, 0.0, 1.0, 0.0);
glRotatef(view_rotz, 0.0, 0.0, 1.0);
glTranslatef(-NUM_COLS * 2, 0., -NUM_ROWS * 2.);
for (x = 0; x < 1; x++) {
for (y = 0; y < NUM_COLS; y++) {
for (z = 0; z < NUM_ROWS; z++) {
color = 0;
for (level = 0; level < NUMPLANE; level++) {
if (pixmap[level][z % NUM_ROWS][y / 8] & (1 << y % 8)) {
color = level + 1;
}
}
drawLED(color, (float) y * 4.0, (float) x * 4.0,
(float) (NUM_ROWS - 1 - z) * 4.0);
}
}
}
glPopMatrix();
glutSwapBuffers();
usleep(20000);
}
/**
* Handler for processing key presses.
* @param key The pressed key encoded in ASCII.
* @param x X-position of the mouse pointer.
* @param y Y-position of the mouse pointer.
*/
void keyboard(unsigned char key, int x, int y) {
switch (key) {
case 'q':
printf("Quit\n");
glutDestroyWindow(win);
exit(0);
break;
case ' ':
fakeport |= 0x01;
break;
case 'a':
fakeport |= 0x02;
break;
case 'd':
fakeport |= 0x04;
break;
case 's':
fakeport |= 0x08;
break;
case 'w':
fakeport |= 0x10;
break;
}
}
/**
* Handler for processing key releases.
* @param key The released key encoded in ASCII.
* @param x X-position of the mouse pointer.
* @param y Y-position of the mouse pointer.
*/
void keyboardup(unsigned char key, int x, int y) {
switch (key) {
case ' ':
fakeport &= ~0x01;
break;
case 'a':
fakeport &= ~0x02;
break;
case 'd':
fakeport &= ~0x04;
break;
case 's':
fakeport &= ~0x08;
break;
case 'w':
fakeport &= ~0x10;
break;
}
}
/**
* Relays mouse position and button state to the trackball implementation.
* @param button Currently monitored button.
* @param state State of that button.
* @param x X-position of the mouse pointer.
* @param y Y-position of the mouse pointer.
*/
void mouse(int button, int state, int x, int y) {
tbMouse(button, state, x, y);
}
/**
* Relays motion request to the trackball implementation.
* @param x X-position for the motion direction.
* @param y Y-position for the motion direction.
*/
void motion(int x, int y) {
tbMotion(x, y);
}
/**
* Updating the window size.
* @param width Width of the window.
* @param height Height of the window.
*/
void reshape(int width, int height) {
tbReshape(width, height);
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0, (float) WindWidth / (float) WindWidth, 5., 1000.);
gluLookAt(NUM_ROWS * 2., NUM_ROWS * 2. + 50., NUM_COLS * 2., NUM_ROWS * 2.,
NUM_ROWS * 2., NUM_COLS * 2., 0.0, 0.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
WindWidth = width;
WindHeight = height;
}
/**
* Handler for special keys (the arrow keys in particular) for adjusting the
* view angle of the scene.
* @param k The pressed special key using GLUT's nomenclature.
* @param x X-position of the mouse pointer.
* @param y Y-position of the mouse pointer.
*/
static void special(int k, int x, int y) {
switch (k) {
case GLUT_KEY_UP:
view_rotx += 5.0;
break;
case GLUT_KEY_DOWN:
view_rotx -= 5.0;
break;
case GLUT_KEY_LEFT:
view_rotz += 5.0;
break;
case GLUT_KEY_RIGHT:
view_rotz -= 5.0;
break;
default:
return;
}
glutPostRedisplay();
}
/**
* Entry point for starting the display loop thread.
* @param unused Not used. Only here to satisfy signature constraints.
*/
void *display_loop_run(void * unused) {
display_loop();
return 0;
}
/**
* Main function for the simulator.
* @param argc The argument count.
* @param argv Command line arguments.
* @return Exit codem, always zero.
*/
int main(int argc, char **argv) {
WindHeight = 700;
WindWidth = 700;
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
glutInitWindowSize(WindHeight, WindWidth);
win = glutCreateWindow("16x16 Borg Simulator");
// callback
glutDisplayFunc(display);
glutIdleFunc(display);
glutSetKeyRepeat(GLUT_KEY_REPEAT_OFF);
glutKeyboardFunc(keyboard);
glutKeyboardUpFunc(keyboardup);
glutSpecialFunc(special);
glutMouseFunc(mouse);
glutMotionFunc(motion);
// clearcolor & main loop
glClearColor(0, 0, 0, 1.0);
gluPerspective(60.0, (float) WindWidth / (float) WindWidth, 5., 1000.);
gluLookAt(NUM_COLS * 2., NUM_COLS * 2. + 50., NUM_ROWS * 2., NUM_COLS * 2.,
NUM_COLS * 2., NUM_ROWS * 2., 0.0, 0.0, 1.0);
// init Call List for LED
GLUquadric* quad = gluNewQuadric();
glNewList(0, GL_COMPILE);
glColor4f(0.8, 0.0, 0.0, 1.);
gluSphere(quad, 1.0, 12, 12);
glEndList();
glNewList(1, GL_COMPILE);
glColor4f(0.5, 0.0, 0.0, 1.);
gluSphere(quad, 1.4, 12, 12);
glEndList();
glNewList(2, GL_COMPILE);
glColor4f(0.7, 0.0, 0.0, 1.);
gluSphere(quad, 1.55, 12, 12);
glEndList();
glNewList(3, GL_COMPILE);
glColor4f(1.00, 0.0, 0.0, 1.);
gluSphere(quad, 1.7, 12, 12);
glEndList();
tbInit(GLUT_LEFT_BUTTON);
tbAnimate(GL_FALSE);
pthread_t simthread;
pthread_create(&simthread, NULL, display_loop_run, NULL);
glutMainLoop();
return 0;
}
/*@}*/
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_lst_planes_to_tab.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: grivalan <grivalan@student.42lyon.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/02/05 08:57:40 by grivalan #+# #+# */
/* Updated: 2021/05/22 15:39:23 by grivalan ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "cub3d.h"
static t_list **ft_planes_top_to_tab(t_game *game)
{
int size;
t_list **tab;
t_list *list;
t_plane *plane;
int i;
size = game->file.height_map;
tab = ft_calloc(sizeof(t_plane *), size + 1);
if (!tab)
return (NULL);
i = -1;
while (++i <= size)
tab[i] = NULL;
list = game->lst_planes_top;
while (list)
{
plane = list->content;
tab[(int)ft_abs(plane->d) - 1] = list;
list = list->next;
}
return (tab);
}
static t_list **ft_planes_bottom_to_tab(t_game *game)
{
int size;
t_list **tab;
t_list *list;
t_plane *plane;
int i;
size = game->file.height_map;
tab = ft_calloc(sizeof(t_plane *), size + 1);
if (!tab)
return (NULL);
i = -1;
while (++i <= size)
tab[i] = NULL;
list = game->lst_planes_bottom;
while (list)
{
plane = list->content;
tab[(int)plane->d] = list;
list = list->next;
}
return (tab);
}
static t_list **ft_planes_right_to_tab(t_game *game)
{
int size;
t_list **tab;
t_list *list;
t_plane *plane;
int i;
size = game->file.width_map;
tab = ft_calloc(sizeof(t_plane *), size + 1);
if (!tab)
return (NULL);
i = -1;
while (++i <= size)
tab[i] = NULL;
list = game->lst_planes_right;
while (list)
{
plane = list->content;
tab[(int)plane->d] = list;
list = list->next;
}
return (tab);
}
static t_list **ft_planes_left_to_tab(t_game *game)
{
int size;
t_list **tab;
t_list *list;
t_plane *plane;
int i;
size = game->file.width_map;
tab = ft_calloc(sizeof(t_plane *), size + 1);
if (!tab)
return (NULL);
i = -1;
while (++i <= size)
tab[i] = NULL;
list = game->lst_planes_left;
while (list)
{
plane = list->content;
tab[(int)ft_abs(plane->d) - 1] = list;
list = list->next;
}
return (tab);
}
int ft_lst_planes_to_tab(t_game *game)
{
game->tab_planes.left = ft_planes_left_to_tab(game);
game->tab_planes.right = ft_planes_right_to_tab(game);
game->tab_planes.top = ft_planes_top_to_tab(game);
game->tab_planes.bottom = ft_planes_bottom_to_tab(game);
if (!game->tab_planes.left)
return (ft_trash_game(game, allocation_fail, -1, "\n"));
if (!game->tab_planes.right)
return (ft_trash_game(game, allocation_fail, -1, "\n"));
if (!game->tab_planes.top)
return (ft_trash_game(game, allocation_fail, -1, "\n"));
if (!game->tab_planes.bottom)
return (ft_trash_game(game, allocation_fail, -1, "\n"));
return (0);
}
|
C
|
#include <stdio.h>
long long mem[51];
long long foo(long long i){
if(i == 1)
return 1;
if(i == 2){
return 2;
}
if(mem[i] != -1)
return mem[i];
mem[i] = foo(i-1) + foo(i-2);
return mem[i];
}
int main(){
int j;
for(j=0;j<51;j++)
mem[j] = -1;
long long i;
while(1){
scanf("%lli",&i);
if(i == 0){
return 0;
}
printf("%lli\n",foo(i));
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include "ial.h"
int lenght(string *str) //Funkce, která vrací délu řetězce.
{
return str->length; //Vracíme délku řetězce ze struktury string.
}
string copy(string *str, int i, int j) //Funkce vrací podřetězec z řetězce str od i o délce j.
{
string strback; //Pomocná proměnná typu string.
int p; //Řídící proměnná for cyklu.
if (i < 1) //Pokud je i menší než 1, přiřadíme mu hodnotu 1, aby jsme nepřistupovali mimo string.
{
i=1;
}
if ((i+j-1) > str->length) //Pokud je j větší než délka řetězce, upravíme jej, aby jsme nekopírovali prvky za rozsahem stringu.
{
j=str->length-i+1;
}
strInit(&strback); //Inicializace stringu.
for (p = 0; p < j; p++) //For cyklus o j opakováních.
{
strAddChar(&strback,str->str[i+p-1]); //Jednotlivé znaky přidáváme do strback.
}
return strback; //Vracíme string.
}
int find(string *str, string *vzorek) //Funkce která najde vzorek v str.
{
int Fail[str->length]; //Pole Fail o délce str->lenght.
int TInd = 0; //Index prvku v str.
int PInd = 0; //Index prvku ve vzorku.
int k,r; //Pomocné proměnné.
Fail[0] = -1; //Do prvního prvku pole si přiřadíme -1.
for (k = 1; k <= vzorek->length; k++)
{
r = Fail[k-1]; //Do r si přiřadíme hodnotu z prvku k-1.
while ((r > -1) && (vzorek->str[r] != vzorek->str[k-1])) //Procházíme vzorek a zjišťujeme na kterou pozici se můžeme vrátit při neshodě na každé pozici.
{
r = Fail[r];
}
Fail[k] = r+1;
}
while ((TInd < str->length) && (PInd < vzorek->length)) //Samotné vyhledávání podřetězce.
{
if ((PInd == -1) || (str->str[TInd] == vzorek->str[PInd])) //Pokud se str na indexu TInd rovná vzorku na indexu PInd..
{
TInd++; //Inkrementujeme obě počítadla.
PInd++;
}
else
{
PInd = Fail[PInd]; //Pokud se nerovná, vracíme se na index, který je uložem v poli Fail.
}
}
if (PInd > vzorek->length-1) //Ppokud je PInd větší než délka vzorku -1, prošli jsme vzorek až na konec a mám eshodu.
{
return TInd-vzorek->length+1; //Vracíme index, na kterém jsme našli podřetězec.
}
else
return 0; //Nenašli jsme podřetězec, vracíme 0.
}
string sort(string *str)
{
int step = str->length / 2; //Proměnná v které máme uložený krok, pro procházení řetězce.
int i, j; //Pomocné proměnné pro průchod.
char c;
while (step > 0) //Procházíme, dokud je krok větší než 0.
{
for (i = step; i < str->length; i++)
{
j = i-step; //Posun na další prvek.
while ((j >= 0) && (str->str[j] > str->str[j+step])) //Bubble sort pro prvky vzdálené o step.
{
c=str->str[j]; //Výměna dvou prvku.
str->str[j] = str->str[j+step];
str->str[j+step] = c;
j=j-step; //Snížení indexu o krok.
}
}
step = step / 2; //Po všech průchodech vždy rozpůlíme krok.
}
return *str; //Vracíme seřazený string.
}
void GlobTableInit(tGlobSymbolTable *T,Tridic *ridic)/*inicializace globalni tabilky*/
{
string pom;
sGlobTableItem *novy;
Rfirst=NULL;/* zasobnik ramcu je prazdny*/
T->first = NULL;/*globalni tabulka je prazdna*/
ridic->aktiv= NULL;/*ukazatel na aktivni uzel globalni tabulky*/
ridic->pomlog = 0;/*pomocna promenna*/
ridic->pocet_argumentu=0;/*pocet argumentu fce je nula*/
ridic->deklaration=0;/*pomocna promenna pro definici funkci*/
strInit(&pom);
strAddStr(&pom,"length");
GlobItemInsert(T,&pom,FUNCTION_HEADER,ridic,&novy);
strAddStr(&(novy->arg),"si");
strClear(&pom);
strAddStr(&pom,"copy");
GlobItemInsert(T,&pom,FUNCTION_HEADER,ridic,&novy);
strAddStr(&(novy->arg),"siis");
strClear(&pom);
strAddStr(&pom,"find");
GlobItemInsert(T,&pom,FUNCTION_HEADER,ridic,&novy);
strAddStr(&(novy->arg),"ssi");
strClear(&pom);
strAddStr(&pom,"sort");
GlobItemInsert(T,&pom,FUNCTION_HEADER,ridic,&novy);
strAddStr(&(novy->arg),"ss");
}
void GlobItemInsert(tGlobSymbolTable *T,string *nazev, int typ,Tridic *ridic, sGlobTableItem **novy){
int koren=0;
if (((*novy) = (sGlobTableItem*) malloc(sizeof(sGlobTableItem)))==NULL) error(T,OTHER_RUNN_ERR,ridic);/*alokovani mista pro novy globálni uzel*/
sGlobTableItem *pomglob;
strInit(&((*novy)->data.nazev));/*plneni uzlu*/
strCopyString(&((*novy)->data.nazev), nazev);
(*novy)->data.typ = typ;
(*novy)->lptr=NULL;
(*novy)->rptr=NULL;
(*novy)->data.def=1;
strInit(&((*novy)->arg));
//strInit(&((*novy)->hodnota->stringh));
ridic->aktivG=(*novy);
ridic->aktivG->link=NULL;
if (T->first==NULL){/*pokud je strom prazdny*/
T->first=(*novy);/*pridame novy uzel na vrchol stromu*/
}else{
pomglob=T->first;/*nastavime pomocny ukazatel na vrchol stromu*/
koren=tableSearchGlob(ridic,&pomglob,&((*novy)->data.nazev));/*projdeme strom*/
}
if (koren==1){
pomglob->lptr=(*novy);/*uzel vlozime nalevo*/
}else if (koren==2) {
pomglob->rptr=(*novy);/*uzel vlozime napravo*/
}
}
int GlobTableInsert(tGlobSymbolTable *T, string *nazev, int typ,Tridic *ridic){/*vlozeni noveho uzlu do glob table*/
if (typ==FUNCTION_END){/*pokud je konec tela funkce*/
ridic->aktivG->data.def=1;/*definuj danou funkci*/
ridic->aktiv=NULL;/*uzel ztraci aktivitu*/
ridic->pomlog = 0;/*vynulovani ridicich promennych*/
ridic->pocet_argumentu=0;
ridic->deklaration=0;
// ridic->aktivG->link=NULL;
return 1;
}
if (typ==FUNCTION_FORWARD){/*pokud se jedna o doprednou deklaraci funkce*/
sGlobTableItem *pomg;
pomg=ridic->aktivG;
ridic->pomlog = 0;/*vynulování ridicich promennych*/
ridic->pocet_argumentu=0;
ridic->deklaration=0;
if (pomg->data.def==1){/*pokud jiz byla funkce definovana, plati i pro dvakrat deklarovanou funkci*/
error(T,TAB_ERR,ridic);/*chyba v ramci tabulky*/
}
return 1;
}
int koren=0;
struct GlobTabItem *novy;
sGlobTableItem *pomglob;
if ((novy = (sGlobTableItem*) malloc(sizeof(sGlobTableItem)))==NULL) error(T,OTHER_RUNN_ERR,ridic);/*alokovani mista pro novy globálni uzel*/
strInit(&(novy->data.nazev));/*plneni uzlu*/
strCopyString(&(novy->data.nazev), nazev);
novy->data.typ = typ;
pomglob=NULL;
novy->lptr=NULL;
novy->rptr=NULL;
strInit(&(novy->arg));
// strInit(&(novy->hodnota->stringh));
ridic->aktivG=novy;
ridic->aktivG->link=NULL;
pomglob=T->first;/*nastavime pomocny ukazatel na vrchol stromu*/
koren=tableSearchGlob(ridic,&pomglob,&(novy->data.nazev));/*projdeme strom*/
if (koren==0){/*uzel se stejnym klicem jiz byl nalezen*/
if (typ==FUNCTION_HEADER){/*pridavany prvek je funkce*/
if (pomglob->data.typ==FUNCTION_HEADER){/*nalezeny prvek je funkce*/
if (pomglob->data.def==0){/*funkce jeste nebyla definována*/
pomglob->data.def=1;/*nadefinujeme funkci*/
ridic->aktivG=pomglob;/*nastavime aktivitu na nas prvek*/
ridic->aktiv=ridic->aktivG->link;/*jako aktivni lokalni tabulku nastavime ukazatel na lok tabulku aktivni globalni tabullky*/
ridic->deklaration=1;/*nastavime, že budeme cist první argument fce*/
ItemFreeAktu(novy,NULL);/*uvolnime pripravovany uzel glob. tabulky*/
return 1;
}else {ItemFreeAktu(novy,NULL);error(T,TAB_ERR,ridic);}/*chyba v ramci tabulky*/
}else {ItemFreeAktu(novy,NULL);error(T,TAB_ERR,ridic);}/*chyba v ramci tabulky*/
}else {ItemFreeAktu(novy,NULL);error(T,TAB_ERR,ridic);}/*chyba v ramci tabulky*/
}else
if (koren==1){
pomglob->lptr=novy;/*uzel vlozime nalevo*/
}else if (koren==2) {
pomglob->rptr=novy;/*uzel vlozime napravo*/
}
novy->link=NULL;
novy->data.def=0;/*novy prvek neni definovany*/
if(typ == FUNCTION_HEADER) {/*pokud se jedna o funkci*/
ridic->aktivG=novy;/*nastavime jako aktivni*/
ridic->pomlog = 1;/*jsme v hlavicce fce*/
} else {novy->link = NULL;}/*neobsahuje lokalni tabulku*/
return 1;
}
int LokTableInsert(tGlobSymbolTable *T, string *nazev, int typ,Tridic *ridic){/*vlození noveho uzlu do lok table*/
sLokTableItem *novy;
sLokTableItem *pomloka;
int koren=0;
if ((novy = (sLokTableItem*) malloc(sizeof(sLokTableItem)))==NULL) error(T,OTHER_RUNN_ERR,ridic);/*alokace mista na novy lokalni prvek*/
ridic->aktiv=novy;/*nastaveni aktivity na novy prvek*/
novy->data.def=1;/*plneni prvku*/
strInit(&(novy->data.nazev));
novy->data.typ=typ;
novy->lptr=NULL;
novy->rptr=NULL;
if ( ridic->pomlog || ridic->deklaration){/*pokud se jedna o hlavicku fce*/
ridic->pocet_argumentu++;
novy->data.def=1;/*argument je inicialyzovany*/
novy->poradi_argumentu=ridic->pocet_argumentu;/*poradí argumentu*/
}else {
novy->data.def=0;/*lokalni promenna neni inicializovana*/
novy->poradi_argumentu=0;/*nejedna se o argument funkce*/
}
if (nazev!=NULL){/*pokud se nejedna o navratovy typ*/
strCopyString((&novy->data.nazev), nazev);/*naplnim nazev*/
}else {
strCopyString((&novy->data.nazev), &(ridic->nazev_func));/*jinak ziskam nazev z globalni tabulky z aktualniho prvku*/
novy->data.def=3;
}
sGlobTableItem *pomgl;
koren=0;
pomgl = T->first;/*nastavime koren stromu*/
koren= tableSearchGlob(ridic,&pomgl,&(novy->data.nazev));/*prohledame glob tabulku kvuli shodnym nazvum fci*/
if (koren==0 && nazev!=NULL){/*pokud byl prvek nalezen a lok promenna neni navratovy typ*/
if (pomgl->data.typ==FUNCTION_HEADER){/*pokud byla nalezena glob uzel ktery je funkce*/
ItemFreeAktu(NULL, novy);/*uvolni pridavany prvek*/
error(T,TAB_ERR,ridic);/*chyba v ramci tabulky*/
}
}
if (ridic->deklaration>0){/*pokud jsme v hlavicce funkce*/
sLokTableItem *poml;
sGlobTableItem *pomgl;
pomgl = ridic->aktivG;/*jako pomocný glob uzel nastavime aktivni glob uzel*/
poml=pomgl->link;/*jako pomocnou lok. tabulku nastavime odkaz z aktivniho glob uzlu*/
koren=0;
koren=tableSearchLok(ridic,&poml,&(novy->data.nazev));
if (koren){
ItemFreeAktu(NULL, novy);/*uvolnime pridávany prvek*/
error(T,TAB_ERR,ridic);/*chyba v ramci tabulky*/
}
ridic->deklaration++;/*kontrola poctu argumentu*/
if (ridic->deklaration==strGetLength(&(pomgl->arg))+1) {ridic->deklaration=0;}/*pocet prvku deklrovane a definovane funkce je jiny*/
if (poml->data.typ==typ){/*pokud sedi typ argumentu deklarovane a definovane funkce*/
if (poml->poradi_argumentu==novy->poradi_argumentu){/*pokud je na stejnem miste*/
if (nazev!=NULL){/*pokud se nejedna o navratovy parametr*/
if ((strCmpString(&(poml->data.nazev), nazev)==0)) {/*pokud sedi nazvy*/
ItemFreeAktu(NULL, novy);/*uvolnime vkladany argument*/
return 1;/*agrumnet je totozny*/
}else {
ItemFreeAktu(NULL, novy);/*uvolnime vkladany argument*/
error(T,TAB_ERR,ridic);/*error v ramci tabulky*/
}
}else{/*pokud se jedna o navratovy parametr*/
if (ridic->deklaration==strGetLength(&(ridic->aktivG->arg))) {/*pokud neni stejny pocet argumentu*/
ItemFreeAktu(NULL, novy);/*uvolnime vkladany argument*/
error(T,TAB_ERR,ridic);/*error v ramci tabulky*/
}
ridic->aktivG=pomgl;/*uvolnime vkládaný argument*/
ItemFreeAktu(NULL,novy);/*error v ramci tabulky*/
return 1;/*agrumnet je totozny*/
}
}else {/*nejedna se o stejny typ*/
ItemFreeAktu(NULL, novy);/*uvolníme vkladany argument*/
error(T,TAB_ERR,ridic);/*error v ramci tabulky*/
}
}
}
else{/*pokud pridavame lokalni promennou*/
if (ridic->aktivG->link==NULL){/*pokud je strom prazdny*/
ridic->aktivG->link=novy;/*pridame jako koren*/
}else{
pomloka=ridic->aktivG->link;
koren=0;
koren=tableSearchLok(ridic,&pomloka,&(novy->data.nazev));
if (koren==0){/*pokud jiz prvek se stejnym klicem existuje*/
ItemFreeAktu(NULL, novy);/*uvolnime vkladany argument*/
error(T,TAB_ERR,ridic);/*error v ramci tabulky*/
}
if (koren==1){/*pridame do leveho podstromu*/
pomloka->lptr=novy;
}else if (koren==2) {pomloka->rptr=novy;}/*pridáme do praveho podstromu*/
}
if ( (ridic->pomlog ) || (nazev==NULL) ){/*pokud jsme v hlavicce funkce*/
switch(typ){/*pridame typ argumnetu do glob tabulky*/
case TP_INT:
if (strAddChar(&(ridic->aktivG->arg),'i'));
break;
case TP_REAL:
if (strAddChar(&(ridic->aktivG->arg),'r'));
break;
case TP_STRING:
if (strAddChar(&(ridic->aktivG->arg),'s'));
break;
case BOOLEAN:
if (strAddChar(&(ridic->aktivG->arg),'b'));
break;
}
}
if (nazev==NULL) {/*pokud uz byl predan i navratovy typ*/
ridic->pocet_argumentu=0; /*nasleduji lok promenne*/
ridic->pomlog=0;/*nejsme jiz v hlavicce funkce*/
}
return 1;
}
return 0;
}
int tableSearch(tGlobSymbolTable *T, string *nazev, int def,Tridic *ridic){/*hledani v glob i lok table*/
struct GlobTabItem *Gpom;
sLokTableItem *poml;
int nenasel = 1;
if (T->first!=NULL){
if (ridic->aktiv!=NULL){/*pokud existuje aktivni lok tabulka*/
poml=ridic->aktivG->link;
nenasel=tableSearchLok(ridic,&poml,nazev);/*hledame v lok tabulce*/
if (!nenasel) {/*pokud jsme nasli*/
return poml->data.typ;
}
}
if(!nenasel) {return poml->data.typ;}
else {
if (nenasel){/*pokud stale nenasel*/
Gpom = T->first;/*hledame v glob tabulce*/
nenasel=tableSearchGlob(ridic,&Gpom,nazev);
}
if(!nenasel) return Gpom->data.typ; else error(T,TAB_ERR,ridic);
}
}
return 0;
}
void GlobVypis(tGlobSymbolTable *T,Tridic *ridic,sGlobTableItem *koren){
// printf(" a dany prvek **** %s\n",strGetStr((ptr->arg)));
if (koren!=NULL){
printf("\n\nVYPIS - globalni tabulka\n");
printf("Pridany prvek ma nazev %s\n",strGetStr(&(koren->data.nazev)));
printf(" a dany prvek ma typ %i\n",koren->data.typ);
printf(" a dany prvek **** %s\n",strGetStr(&(koren->arg)));
if (koren->link!=NULL){
LokVypis(T,ridic,koren->link);
}
GlobVypis(T,ridic,koren->lptr);
GlobVypis(T,ridic,koren->rptr);
}
}
void LokVypis(tGlobSymbolTable *T,Tridic *ridic,sLokTableItem *koren){
if (koren!=NULL){
printf(" lokalni prvek ma nazev %s\n",strGetStr(&(koren->data.nazev)));
printf(" argument je %i\n",koren->poradi_argumentu);
printf(" lokalni typ je %i\n",koren->data.typ);
LokVypis(T,ridic,koren->lptr);
LokVypis(T,ridic,koren->rptr);
}
}
int tableSearchLok(Tridic *ridic,sLokTableItem **poml,string *nazev){/*hledání v lok table*/
int koren=0;
while(!koren){/*dokud neni nalezeno misto nebo shoda*/
if (key(nazev,&((*poml)->data.nazev))==2){/*pokud je vkladany vetsí nez vlozeny*/
if ((*poml)->rptr!=NULL){/*pokud je vpravo jeste uzel*/
(*poml)=(*poml)->rptr;/*jdu vpravo*/
}else{/*jinak vracim ze je vpravo misto*/
return 2;
}
}else if (key(nazev,&((*poml)->data.nazev))==1){/*pokud je vkladany mensi nez vlozeny*/
if ((*poml)->lptr!=NULL){/*pokud je vlevo jeste uzel*/
(*poml)=(*poml)->lptr;/*jdu vlevo*/
}else{/*jinak vracim ze je vlevo misto*/
return 1;
}
}else if (key((nazev),&((*poml)->data.nazev))==0){/*shoda*/
return 0;
}
}
return 0;
}
int tableSearchGlob(Tridic *ridic,sGlobTableItem **pomgl,string *nazev){/*hledani v glob table*/
int koren=0;
while (!koren){/*dokud není nalezeno místo nebo shoda*/
if (key(nazev,&((*pomgl)->data.nazev))==2){/*pokud je vkladany vetsi nez vlozeny*/
if ((*pomgl)->rptr!=NULL){/*pokud je vpravo ještì uzel*/
(*pomgl)=(*pomgl)->rptr;/*jdu vpravo*/
}else {/*jinak vracím že je vpravo místo*/
return 2;
}
} else if (key(nazev,&((*pomgl)->data.nazev))==1){/*pokud je vkládaný menší než vložený*/
if ((*pomgl)->lptr!=NULL){/*pokud je vlevo ještì uzel*/
(*pomgl)=(*pomgl)->lptr;/*jdu vlevo*/
}else {/*jinak vracím že je vlevo místo*/
return 1;
}
}else if (key(nazev,&((*pomgl)->data.nazev))==0){/*shoda*/
return 0;
}
}
return 0;
}
void TableFree(tGlobSymbolTable *T,Tridic *ridic,sGlobTableItem *koren,int *in){/*rekurzivni mazani tabulek*/
if((koren)!= NULL) {/*pokud neni globalni tabulka prazdna*/
if(koren->data.typ == FUNCTION_HEADER){/*pokud je glob. prvek funkce*/
if(koren->data.def == 0 ) *in=0;/*pokud neni definovana*/
TableFreeLok(T,ridic,(koren->link));/*zavolam mazani lokalni tabulky*/
}
TableFree(T,ridic,(koren->lptr),in);/*posouvam se vlevo*/
TableFree(T,ridic,(koren->rptr),in);/*posouvam se vpravo*/
//strFree(&(koren->hodnota->stringh));
strFree(&(koren->data.nazev));/*mazu*/
strFree(&(koren->arg));
free(koren);
koren = NULL;
}
return ;
}
void TableFreeLok(tGlobSymbolTable *T,Tridic *ridic,sLokTableItem *koren){/*uvolneni lokalni tabulky*/
if(koren != NULL){/*pokud neni lokalni prazdna*/
TableFreeLok(T,ridic,(koren->lptr));/*posouvam se vlevo*/
TableFreeLok(T,ridic,(koren->rptr));/*posouvam se vpravo*/
strFree(&(koren->data.nazev));/*mazu*/
free(koren);
koren = NULL;
}
}
void ItemFreeAktu(sGlobTableItem *pomg,sLokTableItem *poml){/*mazani alokovaneho prvku pri chybe*/
if (pomg!=NULL){/*pokud mazu globalni prvek*/
strFree(&(pomg->data.nazev));/*smaz*/
strFree(&(pomg->arg));
free(pomg);
}else
if (poml!=NULL){/*pokud mazu lokalni prvek*/
strFree(&(poml->data.nazev));/*smaz*/
free(poml);
}
}
sRamec* RamecInit(){/*inicializace prvniho prvku noveho ramce*/
sRamec *novy;
if ((novy = (sRamec*) malloc(sizeof(sRamec)))==NULL) error(NULL,OTHER_RUNN_ERR,NULL);/*malokuje misto pro nove vytvoreny ramec*/
novy->lptr = NULL; /*nastavi ukazatele prvniho prvku na NULL*/
novy->rptr = NULL;
PushR(novy); /*ulozi odkaz na ramec do zasobniku*/
return novy;
}
sRamec* GlobRamecInit(){ /*inicializace prvniho prvku noveho globalniho ramce*/
sRamec *novy;
if ((novy = (sRamec*) malloc(sizeof(sRamec)))==NULL) error(NULL,OTHER_RUNN_ERR,NULL);/*malokuje misto pro nove vytvoeeny ramec*/
novy->lptr = NULL;/*nastavi ukazatele prvniho prvku na NULL*/
novy->rptr = NULL;
GlobRamec = novy;/*globalni ramec je jenom jeden, proto ho staci ulozit do globalni promene*/
return novy;
}
void VytvorRamec(sLokTableItem *koren, sRamec *novy){
if(koren != NULL){
novy->lptr = NULL; /*nastavi defaultne kazdemu novemu prvku ukazatele na NULL*/
novy->rptr = NULL;
sRamec *pom;/*vytvori si pomocnou promenou*/
strInit(&(novy->nazev));
strCopyString((&novy->nazev), (&koren->data.nazev));/*kopiruje informace z tabulky symbolu*/
novy->typ = koren->data.typ;
novy->hodnota.def = 0; /*nastavi definovanost prvku na 0 (tzn. neobsahuje hodnotu)*/
novy->hodnota.porarg = koren->poradi_argumentu;
if(koren->lptr != NULL){ /*kdyz ma ukazatel na levy podstrom, tak:*/
if((pom = (sRamec*) malloc(sizeof(sRamec)))==NULL) error(NULL,OTHER_RUNN_ERR,NULL); /*malokuje misto pro novy prvek ramce*/
novy->lptr = pom; /*a aktualnimu prvku nastavi ukazatel na novy levy podstrom*/
VytvorRamec(koren->lptr, novy->lptr); /*a dale rekurzivne vola funkci VytvorRamec*/
} else novy->lptr = NULL; /*kdyz nema levy podstrom, pta se na pravy podstrom u ktereho postupuje obdobne jako u leveho*/
if(koren->rptr != NULL){
if((pom = (sRamec*) malloc(sizeof(sRamec)))==NULL) error(NULL,OTHER_RUNN_ERR,NULL);
novy->rptr = pom;
VytvorRamec(koren->rptr, novy->rptr);
} else novy->rptr = NULL;
} /*v pripade, ze nema ani jeden podstrom, tak se funkce ukonci a vraci se do rekurzivni funkce, v ktere byla predtim volana*/
}
void VytvorRamecGlob(sGlobTableItem *koren, sRamec *novy){
if(koren != NULL){/*postup je zde obdobny, jako u funkce VytvorRamec pro lokalni tabulky symbolu, ktera se nachazi nad touto funkci*/
novy->lptr = NULL;
novy->rptr = NULL;
sRamec *pom;
strInit(&(novy->nazev));
strCopyString((&novy->nazev), (&koren->data.nazev));
novy->typ = koren->data.typ;
novy->hodnota.def = 0;
novy->hodnota.porarg = 0;
if(koren->lptr != NULL){
if((pom = (sRamec*) malloc(sizeof(sRamec)))==NULL) error(NULL,OTHER_RUNN_ERR,NULL);
novy->lptr = pom;
VytvorRamecGlob(koren->lptr, novy->lptr);
} else novy->lptr = NULL;
if(koren->rptr != NULL){
if((pom = (sRamec*) malloc(sizeof(sRamec)))==NULL) error(NULL,OTHER_RUNN_ERR,NULL);
novy->rptr = pom;
VytvorRamecGlob(koren->rptr, novy->rptr);
} else novy->rptr = NULL;
}
}
void SearchRamecPoradi(sRamec *ramec, sRamec **hledanyramec, double poradi){ /*slouzi pro hledani prvku ramce se stejnou hodnotou parametru porarg s argumentem poradi*/
if(ramec != NULL){ /*zkontroluje, zda mame spravny ukazatel na ramec*/
if(poradi != ramec->hodnota.porarg){ /*pokud prvek nema stejne poradi argumentu jako je hledane poradi, tak:*/
if(ramec->lptr != NULL) SearchRamecPoradi(ramec->lptr, hledanyramec, poradi);/*kdyz obsahuje levy podstrom, tak volame rekurzivne funkci s ukazatelem na levy podstrom*/
if(ramec->rptr != NULL) SearchRamecPoradi(ramec->rptr, hledanyramec, poradi);/*kdyz obsahuje pravy podstrom, tak volame rekurzivne funkci s ukazatelem na levy podstrom*/
}else{
*(hledanyramec) = ramec;
}
}
}
int SearchRamec(sRamec **ramec, string *nazev){ /*funkce, ktera zjistuje, zda se hledany prvek nachazi v ramcich*/
if(SearchRamecPom(ramec, nazev) == 0) {/*pomoci funkce SearchRamecPom prohleda aktualni lokalni ramec*/
(*ramec) = GlobRamec;
if(SearchRamecPom(ramec, nazev) == 0) {/*kdyz neobjevi nic v lokalnim ramci, tak prohleda globalni ramec*/
return 0;
}
else {
return 1;
}
} else {
return 1;}
}
int SearchRamecPom(sRamec **ramec, string *nazev){ /*funkce, ktera je volana z funkce SearchRamec a slouzi k prohledani jednoho ramce podle nazvu (klice)*/
int koren=0;
while(!koren){/*dokud nezjistime, jestli jsme nasli a nebo konecny podstrom u nikam neukazuje, tak cyklime*/
if (key(nazev,&((*ramec)->nazev))==2){ /*rozhodne, zda mame jit do praveho podstromu*/
if ((*ramec)->rptr!=NULL){ /*kdyz ma pravy podstrom, tak se do nej presune, jinak ukonci cyklus*/
(*ramec)=(*ramec)->rptr;
}else{
return 0;
}
}else if (key(nazev,&((*ramec)->nazev))==1){/*rozhodne, zda mame jit do leveho podstromu*/
if ((*ramec)->lptr!=NULL){ /*kdyz ma levy podstrom, tak se do nej presune, jinak ukonci cyklus*/
(*ramec)=(*ramec)->lptr;
}else{
return 0;
}
}else if (key((nazev),&((*ramec)->nazev))==0){/*kdyz jsme prvek nalezli, ukonci cyklus s 1*/
if(((*ramec)->typ == TP_INT)||((*ramec)->typ == TP_REAL)||((*ramec)->typ == BOOLEAN))
(*ramec)->typ=TP_DOUBLE;
return 1;
}
}
return 0;
}
void VypisRamce(sRamec *ramec){
if(ramec != NULL){
printf("Vypis ramce********************************\n");
printf("RAMEC -jeho nazev je: %s\n",strGetStr(&(ramec->nazev)));
if(ramec->lptr != NULL) VypisRamce(ramec->lptr);
if(ramec->rptr != NULL) VypisRamce(ramec->rptr);
}
}
void PridatHodnotu(sRamec *ramec, int typ, double cisloh, string *stringh){
ramec->typ = typ; /*priradi prvku v ramci typ*/
if(typ == TP_STRING) { /*kdyz je typ string, tak preda retezec*/
strInit(&ramec->hodnota.stringh);/*kdyz je bool, int, nebo real, tak pouze priradi double*/
strCopyString(&(ramec->hodnota.stringh),stringh);/*nastavi definovanost prvku na 1*/
}
else {
ramec->hodnota.cisloh = cisloh;
}
ramec->hodnota.def = 1;
return;
}
void PridatPom(sRamec *ramec, string *nazev, int typ, double cisloh, string *stringh){
int koren=0;
sRamec *novy;
while (!koren){/*dokud nezjistime kam podle nazvu novou pomocnou zaradit, tak cyklime*/
if( key(nazev, &ramec->nazev) == 2) {/*rozhodne, zda mame jit do praveho podstromu*/
if(ramec->rptr != NULL) ramec = ramec->rptr;/*kdyz neni pravy podstrom prazdny, tak opakujeme dalsi cyklus pro novy ramec*/
else {
if((novy = (sRamec*) malloc(sizeof(sRamec)))==NULL) error(NULL,OTHER_RUNN_ERR,NULL);/*kdyz je pravy podstrom prazdny, tak malokujeme novy prvek a nastavime pravy ukazatel aktualniho prvku na novy*/
strInit(&novy->nazev);
strCopyString(&(novy->nazev),nazev);
ramec->rptr = novy;
PridatHodnotu(novy, typ, cisloh, stringh); /*pomoci funkce PridatHodnotu vyplnime hodnotu prvku*/
return; /*ukoncime funkci*/
}
}
if( key(nazev, &ramec->nazev) == 1){/*rozhodne, zda mame jit do leveho podstromu*/
if(ramec->lptr != NULL) ramec = ramec->lptr; /*kdyz neni levy podstrom prazdny, tak opakujeme dalsi cyklus pro novy ramec*/
else {
if((novy = (sRamec*) malloc(sizeof(sRamec)))==NULL) error(NULL,OTHER_RUNN_ERR,NULL);/*kdyz je levy podstrom prazdny, tak malokujeme novy prvek a nastavime levy ukazatel aktualniho prvku na novy*/
strInit(&novy->nazev);
strCopyString(&(novy->nazev),nazev);
ramec->lptr = novy;
PridatHodnotu(novy, typ, cisloh, stringh); /*pomoci funkce PridatHodnotu vyplnime hodnotu prvku*/
return; /*ukoncime funkci*/
}
}
if( key(nazev, &ramec->nazev) == 0){ /*v pripade, ze se prvek shoduje, tak pouze nahradime jeho hodnotu volanim funkce PridatHodnotu*/
PridatHodnotu(ramec, typ, cisloh, stringh);
return; /*ukoncime funkci*/
}
}
}
void FreeRamec(sRamec *ramec){
if(ramec != NULL){
FreeRamec(ramec->lptr);
FreeRamec(ramec->rptr);
strFree(&(ramec->nazev));
free(ramec);
ramec = NULL;
}
}
void PushR(sRamec *Ritem){/*vlozeni ramce do zasobniku*/
tRamec *pom;
if((pom=(tRamec*) malloc(sizeof(tRamec ) ))==NULL) error(NULL,OTHER_RUNN_ERR,NULL);/*alukuji prostor*/
pom->Ritem=Ritem;/*pridani ramce do zasobniku*/
pom->next=Rfirst;
Rfirst=pom;
//novy = (sLokTableItem*) malloc(sizeof(sLokTableItem));
}
void PopTopR(sRamec **Ritem){/*vybrani ramce ze zasobniku*/
tRamec *pom;
if (Rfirst!=NULL){/*pokud zasobnik neni prazdny*/
pom=Rfirst;/*vybereme vrchol*/
Rfirst=Rfirst->next;/*jako vrchol dame nasledovnika prvniho*/
*Ritem=pom->Ritem;/*do promenne volane odkazem vlozime vrchol*/
FreeRamec(pom->Ritem);
}
}
|
C
|
/**
* Copyright (c) 2012-2013, Mattias Frånberg
* All rights reserved.
*
* This file is distributed under the Modified BSD License. See the COPYING file
* for details.
*/
#ifndef __BED_H__
#define __BED_H__
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
#include <plinkio/status.h>
#include <plinkio/bed_header.h>
/**
* Integral type used for storing a single SNP.
*/
typedef unsigned char snp_t;
/**
* Contains the information about a bed file. On opening the file
* header is read and the information stored in this structure.
*/
struct pio_bed_file_t
{
/**
* File pointer of bed file
*/
FILE *fp;
/**
* Header of the bed file.
*/
struct bed_header_t header;
/**
* Temporary buffer for each row.
*/
unsigned char *read_buffer;
/**
* Index of the current row.
*/
size_t cur_row;
};
/**
* Opens the bed file and reads the header, the data is
* not read until explicitly asking for it.
*
* @param bed_file Bed file.
* @param path Path to the bed file.
* @param num_loci The number loci.
* @param num_samples The number of samples.
*
* @return PIO_OK if the file could be opened, PIO_ERROR otherwise.
*/
pio_status_t bed_open(struct pio_bed_file_t *bed_file, const char *path, size_t num_loci, size_t num_samples);
/**
* Creates a bed file.
*
* @param bed_file Bed file.
* @param path Path to the bed file.
* @param num_samples The number of samples that the .bed file will include.
*
* @return PIO_OK if the file could be created, PIO_ERROR otherwise.
*/
pio_status_t bed_create(struct pio_bed_file_t *bed_file, const char *path, size_t num_samples);
/**
* Writes a single row of samples to the bed file, assuming that the size of
* the buffer is at least as big as specified when created.
*
* @param bed_file Bed file.
* @param buffer List of SNPs to write to file.
*/
pio_status_t bed_write_row(struct pio_bed_file_t *bed_file, const snp_t *buffer);
/**
* Reads a single row from the given bed_file. Each element in the buffer
* will contain a SNP. The SNP will be encoded as follows:
* 0 - Homozygous major
* 1 - Hetrozygous
* 2 - Homozygous minor
* 3 - Missing value
*
* @param bed_file Bed file.
* @param buffer The buffer to read into. It is asssumed that it
* is big enough, e.g.:
* SNPS_IN_ROWS: Number of individuals
* SNPS_IN_COLUMNS: Number of loci.
*
* @return PIO_OK if a row could be read,
* PIO_END if there are no more rows,
* PIO_ERROR otherwise.
*/
pio_status_t bed_read_row(struct pio_bed_file_t *bed_file, snp_t *buffer);
/**
* Skips a single row from the given bed_file.
*
* @param bed_file Bed file.
*
* @return PIO_OK if a row could be skipped,
* PIO_END if there are no more rows,
* PIO_ERROR otherwise.
*/
pio_status_t bed_skip_row(struct pio_bed_file_t *bed_file);
/**
* Returns the number of bytes required to store a row from
* the given bed file.
*
* @param bed_file Bed file.
*
* @return The number of bytes required to store a row from
* the given bed file.
*/
size_t bed_row_size(struct pio_bed_file_t *bed_file);
/**
* Returns the number of snps stored in a row for the
* given bed file.
*
* @param bed_file Bed file.
*
* @return The number of snps stroed in a row.
*/
size_t bed_num_snps_per_row(struct pio_bed_file_t *bed_file);
/**
* Returns the SNP order for the given bed file.
*
* @param bed_file Bed file.
*
* @return the SNP order for the given bed file.
*/
enum SnpOrder bed_snp_order(struct pio_bed_file_t *bed_file);
/**
* Restarts the reading at the first row.
*
* @param bed_file Bed file.
*/
void bed_reset_row(struct pio_bed_file_t *bed_file);
/**
* Closes the bed file.
*
* @param bed_file Bed file.
*/
void bed_close(struct pio_bed_file_t *bed_file);
/**
* Transposes the given file to the given output file.
*
* @param original_path The file to transpose.
* @param transposed_path The file where the transposed data
* will be stored.
* @param num_loci The number of loci.
* @param num_samples The number of samples.
*
*/
pio_status_t bed_transpose(const char *original_path, const char *transposed_path, size_t num_loci, size_t num_samples);
#ifdef __cplusplus
}
#endif
#endif /* End of __BED_H__ */
|
C
|
#include<stdio.h>
#include<string.h>
int main()
{
char a[100][100];
int i,now = 0, max = 0;
char temp[100];
strcpy(a[0],"http://www.acm.org/");
while(1)
{
scanf("%s",temp);
if(strcmp(temp,"VISIT")==0)
{
scanf("%s",temp);
printf("%s\n",temp);
now++;
strcpy(a[now],temp);
max=now;
}
else if(strcmp(temp,"FORWARD")==0)
{
i=now+1;
if(i<=max)
{
printf("%s\n",a[i]);
now=i;
}
else
printf("Ignored\n");
}
else if(strcmp(temp,"BACK")==0)
{
i=now-1;
if(i>=0)
{
printf("%s\n",a[i]);
now=i;
}
else
printf("Ignored\n");
}
else if(strcmp(temp,"QUIT")==0)
{
break;
}
}
return 0;
}
|
C
|
// CIS565 CUDA Raytracer: A parallel raytracer for Patrick Cozzi's CIS565: GPU Computing at the University of Pennsylvania
// Written by Yining Karl Li, Copyright (c) 2012 University of Pennsylvania
// This file includes code from:
// Yining Karl Li's TAKUA Render, a massively parallel pathtracing renderer: http://www.yiningkarlli.com
#ifndef INTERACTIONS_H
#define INTERACTIONS_H
#include "intersections.h"
struct Fresnel {
float reflectionCoefficient;
float transmissionCoefficient;
};
struct AbsorptionAndScatteringProperties{
glm::vec3 absorptionCoefficient;
float reducedScatteringCoefficient;
};
//forward declaration
__host__ __device__ bool calculateScatterAndAbsorption(ray& r, float& depth, AbsorptionAndScatteringProperties& currentAbsorptionAndScattering, glm::vec3& unabsorbedColor, material m, float randomFloatForScatteringDistance, float randomFloat2, float randomFloat3);
__host__ __device__ glm::vec3 getRandomDirectionInSphere(float xi1, float xi2);
__host__ __device__ glm::vec3 calculateTransmission(glm::vec3 absorptionCoefficient, float distance);
__host__ __device__ glm::vec3 calculateTransmissionDirection(glm::vec3 normal, glm::vec3 incident, float incidentIOR, float transmittedIOR);
__host__ __device__ glm::vec3 calculateReflectionDirection(glm::vec3 normal, glm::vec3 incident);
__host__ __device__ Fresnel calculateFresnel(glm::vec3 normal, glm::vec3 incident, float incidentIOR, float transmittedIOR, glm::vec3 reflectionDirection, glm::vec3 transmissionDirection);
__host__ __device__ glm::vec3 calculateRandomDirectionInHemisphere(glm::vec3 normal, float xi1, float xi2);
//TODO (OPTIONAL): IMPLEMENT THIS FUNCTION
__host__ __device__ glm::vec3 calculateTransmission(glm::vec3 absorptionCoefficient, float distance) {
return glm::vec3(0,0,0);
}
//TODO (OPTIONAL): IMPLEMENT THIS FUNCTION
__host__ __device__ bool calculateScatterAndAbsorption(ray& r, float& depth, AbsorptionAndScatteringProperties& currentAbsorptionAndScattering,
glm::vec3& unabsorbedColor, material m, float randomFloatForScatteringDistance, float randomFloat2, float randomFloat3){
return false;
}
//TODO (OPTIONAL): IMPLEMENT THIS FUNCTION
__host__ __device__ glm::vec3 calculateTransmissionDirection(glm::vec3 normal, glm::vec3 incident, float incidentIOR, float transmittedIOR) {
return glm::vec3(0,0,0);
}
//TODO (OPTIONAL): IMPLEMENT THIS FUNCTION
__host__ __device__ glm::vec3 calculateReflectionDirection(glm::vec3 normal, glm::vec3 incident) {
//nothing fancy here
return glm::vec3(0,0,0);
}
//TODO (OPTIONAL): IMPLEMENT THIS FUNCTION
__host__ __device__ Fresnel calculateFresnel(glm::vec3 normal, glm::vec3 incident, float incidentIOR, float transmittedIOR, glm::vec3 reflectionDirection, glm::vec3 transmissionDirection) {
Fresnel fresnel;
fresnel.reflectionCoefficient = 1;
fresnel.transmissionCoefficient = 0;
return fresnel;
}
//LOOK: This function demonstrates cosine weighted random direction generation in a sphere!
__host__ __device__ glm::vec3 calculateRandomDirectionInHemisphere(glm::vec3 normal, float xi1, float xi2) {
//crucial difference between this and calculateRandomDirectionInSphere: THIS IS COSINE WEIGHTED!
float up = sqrt(xi1); // cos(theta)
float over = sqrt(1 - up * up); // sin(theta)
float around = xi2 * TWO_PI;
//Find a direction that is not the normal based off of whether or not the normal's components are all equal to sqrt(1/3) or whether or not at least one component is less than sqrt(1/3). Learned this trick from Peter Kutz.
glm::vec3 directionNotNormal;
if (abs(normal.x) < SQRT_OF_ONE_THIRD) {
directionNotNormal = glm::vec3(1, 0, 0);
} else if (abs(normal.y) < SQRT_OF_ONE_THIRD) {
directionNotNormal = glm::vec3(0, 1, 0);
} else {
directionNotNormal = glm::vec3(0, 0, 1);
}
//Use not-normal direction to generate two perpendicular directions
glm::vec3 perpendicularDirection1 = glm::normalize(glm::cross(normal, directionNotNormal));
glm::vec3 perpendicularDirection2 = glm::normalize(glm::cross(normal, perpendicularDirection1));
return ( up * normal ) + ( cos(around) * over * perpendicularDirection1 ) + ( sin(around) * over * perpendicularDirection2 );
}
// Given the refractive indices of the materials at intersection, cosine of the incident angle and
// a random number uniformly distributed between 0 and 1, this function returns true if the Fresnel
// reflectance term is greater than or equal to the random number, signifying reflection. Otherwise,
// it will return false, signifying refraction/transmittance.
__host__ __device__ bool calculateFresnelReflectance (float outsideRefIndex, float insideRefIndex, float cosineIncidentAngle,
float uniformRandomBetween01)
{
float RF0 = (insideRefIndex - outsideRefIndex) / (insideRefIndex + outsideRefIndex);
RF0 = RF0 * RF0;
//if (cosineIncidentAngle < 0) // External Reflection
//{
float fresnelRefl = RF0 + (1-RF0)*pow ((1-abs(cosineIncidentAngle)), 5);
if (uniformRandomBetween01 <= fresnelRefl)
return true; // reflectance
return false; // refraction
//}
//else // Internal Reflection.
//{
// float sinCritAngle = insideRefIndex / outsideRefIndex;
// float sinIncidentAngle = sqrt (1 - (cosineIncidentAngle * cosineIncidentAngle));
// if (sinIncidentAngle > sinCritAngle)
// return true; // reflection
// return false; // refraction
//}
}
//TODO: Done!
//Now that you know how cosine weighted direction generation works, try implementing non-cosine (uniform) weighted random direction generation.
//This should be much easier than if you had to implement calculateRandomDirectionInHemisphere.
__host__ __device__ glm::vec3 getRandomDirectionInSphere(float xi1, float xi2) {
float cosTheta = 2*xi1 - 1; // Spread out xi1 in [0,1] to [-1, 1].
float sinTheta = sqrt (1 - cosTheta*cosTheta);
float phi = TWO_PI * xi2;
return glm::vec3(sinTheta*cos(phi), sinTheta*sin(phi), cosTheta);
}
__host__ __device__ glm::vec3 calculateDirectionInLobeAroundNormal (glm::vec3 normal, thrust::default_random_engine rng)
{
float piBy16 = PI / 16.0;
thrust::uniform_real_distribution<float> angleTheta(0, TWO_PI);
thrust::uniform_real_distribution<float> anglePhi(-piBy16, piBy16);
glm::vec3 someDirNotNormal;
if ((normal.x < normal.y) && (normal.x < normal.z))
someDirNotNormal = glm::vec3(1, 0, 0);
else if (normal.y < normal.z)
someDirNotNormal = glm::vec3(0, 1, 0);
else
someDirNotNormal = glm::vec3(0, 0, 1);
//Use not-normal direction to generate two perpendicular directions
glm::vec3 perpendicularDirection1 = glm::normalize(glm::cross(normal, someDirNotNormal));
glm::vec3 perpendicularDirection2 = glm::normalize(glm::cross(normal, perpendicularDirection1));
return ( cos(anglePhi(rng)) * normal ) + ( sin(anglePhi(rng))*cos(angleTheta(rng)) * perpendicularDirection1 ) +
( sin(anglePhi(rng))*sin(angleTheta(rng)) * perpendicularDirection2 );
}
//TODO (PARTIALLY OPTIONAL): IMPLEMENT THIS FUNCTION
//returns 0 if diffuse scatter, 1 if reflected, 2 if transmitted.
__host__ __device__ int calculateBSDF(ray& r, glm::vec3 intersect, glm::vec3 normal, glm::vec3 emittedColor,
AbsorptionAndScatteringProperties& currentAbsorptionAndScattering,
float randomSeed, glm::vec3& color, glm::vec3& unabsorbedColor,
material m)
{
int retVal = 0;
r.origin = intersect-0.01f*r.direction; //slightly perturb along normal to avoid self-intersection.
thrust::default_random_engine rng(hash(randomSeed));
thrust::uniform_real_distribution<float> u01(0, 1);
thrust::uniform_real_distribution<float> u02(0, 1);
if (m.hasReflective >= 1.0) // specular reflectance
{
r.direction = glm::normalize (reflectRay (r.direction, normal));
retVal = 1;
}
else if (m.hasRefractive) // Fresnel refractance.
{
float cosIncidentAngle = glm::dot (r.direction, normal);
float insideRefIndex = m.indexOfRefraction; float outsideRefIndex = 1.0;
if (cosIncidentAngle > 0) // If ray going from inside to outside.
{
outsideRefIndex = m.indexOfRefraction;
insideRefIndex = 1.0;
normal = -normal;
}
if (calculateFresnelReflectance (outsideRefIndex, insideRefIndex, cosIncidentAngle, u01(rng)))
{
// if (cosIncidentAngle > 0) // If ray going from inside to outside.
// normal = -normal; // Flip the normal for reflection.
r.direction = glm::normalize (reflectRay (r.direction, normal));
retVal = 1;
}
else
{
// As given in Real-Time Rendering, Third Edition, pp. 396.
/*float w = (outsideRefIndex / insideRefIndex) * glm::dot (lightDir, normal);
float k = sqrt (1 + ((w + (outsideRefIndex / insideRefIndex)) * (w - (outsideRefIndex / insideRefIndex))));
r.direction = (w - k)*normal - (outsideRefIndex / insideRefIndex)*lightDir;*/
r.direction = glm::normalize (glm::refract (r.direction, normal, outsideRefIndex/insideRefIndex));
r.origin = intersect+0.01f*r.direction;
retVal = 2;
}
}
else if (m.hasReflective) // m.hasReflective between 0 and 1 signifies diffuse reflectance.
{
r.direction = glm::normalize (calculateDirectionInLobeAroundNormal (normal, rng));
retVal = 1;
}
else
{
float xi1, xi2;
r.direction = glm::normalize (calculateRandomDirectionInHemisphere (normal, u01 (rng), u02 (rng)));
}
return retVal;
};
#endif
|
C
|
/*
* C H 9 Q 3
* A program contains the following lines. What does it print?
*/
#include <stdio.h>
/* My guess is that it prints Z. */
int main() {
char ch = 'M', *cp;
cp = &ch;
*cp = 'Z';
putchar(ch);
}
/* It prints Z. */
|
C
|
#include <stdio.h>
#include <math.h>
int main()
{
int i,j,input,sum;
scanf("%d",&input);
for(i=6; i<=input; i+=2)
{
for(j=2,sum=0; j<sqrt(i); j++)
{
if(i%j==0)
sum+=(j+i/j);
}
sum++;
if(sum == i)
printf("%d\n",sum);
}
return 0;
}
|
C
|
/*
* PRACTICA 3 - ejercicio 09
* Realiza un programa que reciba un número y llame a una función que calcule el
* factorial de ese número, posteriormente con el resultado del paso anterior, debe llamar
* a la función fibonacci que calcule la sucesión de números hasta ese. (realizarlo de dos
* formas, una usando funciones que devuelvan los valores y otra simulando el paso de
* parámetros por referencia).
*/
#include <stdio.h>
void factorial(int*, int*);
void fibonacci(int*);
int main(){
int num, fact;
printf("Introduce un numero: ");
scanf("%d", &num);
factorial(&num, &fact);
printf("El factorial de %d es %d y la sucesion de fibonacci hasta ese numero es\n", num, fact);
fibonacci(&fact);
return 0;
}
//cabecera void factorial(int*, int*);
//precondicion debe recibir 2 parametros por referencia, n es un puntero a entero inicializado
//postcondicion modifica el contenido de factorial
void factorial (int* n, int* f){
int i;
*f=1;
for(i=1 ; i <= *n ; i++)
*f = *f * i;
}
//cabecera int fibonacci(int);
//precondicion n es un puntero a entero enteno inicializado
//postcondicion muestra la sucesión de fibonacci hasta n
void fibonacci(int* n){
int ant=1, fib=0, aux;
while(fib<=*n){
aux = fib;
printf("%d ", fib);
fib += ant;
ant = aux;
}
}
|
C
|
/** @file array.h
* @brief Array C function prototypes
*
* This file contains prototpyes of functions written
* for Array C/C++ practice problems using C language
* from GeeksForGeeks.
*
* @author Tropical Sun
* @bug No known bugs.
*/
#ifndef _ARRAY_H
#define _ARRAY_H
/** @brief Find sum of elements in a given array.
*
* @param inputArray input array.
*
* @param number of elements in input array.
*
* @return Sum of elements in the input array.
*/
int Array_Sum(int inputArray[], size_t size);
#endif /* _ARRAY_H */
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "funcs.h"
#include <math.h>
#define PI2 6.28
#ifdef _OPENMP
#include <omp.h>
#else
#define omp_get_thread_num() 0
#endif
void dofilt(ImageF * in_re, ImageF * out_re,ImageF * in_im, ImageF * out_im, ImageF * mask) {
int i,j;
#pragma omp parallel private(i,j)
{
#pragma omp for
for (i=0; i<out_re->rows; i++) {
for(j=0; j<out_re->cols; j++) {
out_re->data[i*out_re->cols+j]= in_re->data[i*in_re->cols+j] * mask->data[i*mask->cols+j]; //multiplica parte real por mask data
out_im->data[i*out_im->cols+j]= in_im->data[i*in_im->cols+j] * mask->data[i*mask->cols+j]; //multiplica parte imaginaria por mask data
//parte dentro de data[*] foi a lógica usada pelo professor em baixo
}
}
}
}
Image * imageFtoImage( ImageF * F) {
Image * image;
int i, j;
image= NULL;
image->rows = F->rows;
image->cols = F->cols;
image->widthStep = F->rows * F->cols;
image->data=(unsigned char*)malloc(image->rows*image->cols);
#pragma omp parallel private(i,j)
{
#pragma omp for
for (i=0; i<F->rows; i++) {
for(j=0; j<F->cols; j++) {
double val;
val=F->data[i*F->cols+j];
if (val<0)
val=0.0;
else if (val>255)
val=255.0;
image->data[i*image->cols+j]=(unsigned char)val;
}
}
}
return image;
}
ImageF * genlpfmask(int rows,int cols) {
ImageF * filter;
int i,j;
/* allocating image*/
filter=(ImageF*)malloc(sizeof(ImageF));
filter->cols= cols;
filter->rows=rows;
filter->widthStep=cols*sizeof(double);
filter->data=(double *)malloc(filter->rows*filter->cols*sizeof(double));
// i= rows, linhas j= colunas
int Cesq=cols/4;
int Cdir=3*cols/4;
int Lcima= rows/4;
int Lbaixo= 3*rows/4;
#pragma omp parallel private(i,j)
{
#pragma omp for
for (i=0; i<rows; i++) {
for(j=0; j<cols; j++) {
if( (i<Lcima && j<Cesq) || (i<Lcima && j>Cdir) ||(i<Lbaixo && j<Cesq) || (i<Lbaixo && j>Cdir)) {
filter->data[i*filter->cols+j]= 1;
}
else {
filter->data[i*filter->cols+j]=0;
}
}
}
}
return filter;
}
void fti (ImageF * in_re, ImageF * in_img, ImageF * out_re, ImageF * out_img, int inverse) {
double arg;
if (inverse == 0) {
arg = -PI2;
}
else {
arg = PI2;
}
int i,k,n,j;
ImageF * aux_re;
ImageF * aux_img;
aux_re=(ImageF*)malloc(sizeof(ImageF));
aux_re->cols= in_re->cols;
aux_re->rows= in_re->rows;
aux_re->widthStep= in_re->cols*sizeof(double);
aux_re->data=(double *)malloc(in_re->rows*in_re->cols*sizeof(double));
aux_img=(ImageF*)malloc(sizeof(ImageF));
aux_img->cols= in_re->cols;
aux_img->rows= in_re->rows;
aux_img->widthStep= in_re->cols*sizeof(double);
aux_img->data=(double *)malloc(in_re->rows*in_re->cols*sizeof(double));
/* Calcular a FFT por linhas */
for (i = 0; i <= in_re->rows; i++) {
for (k = 0; k < in_re->cols; k++) {
aux_re->data [i*in_re->cols] = 0.0;
aux_img->data [i*in_re->cols] = 0.0;
for(n = 0; n < in_re->cols; n++) {
aux_re->data [i*in_re->cols+k] += in_re->data [i*in_re->cols+n] * cos (n * k * arg / in_re->cols);
aux_img->data [i*in_re->cols+k] -= in_img->data [i*in_re->cols+n] * sin (n * k * arg / in_re->cols);
}
}
}
/* Calcular a FFT por colunas */
for (i = 0; i <= in_re->cols; i++) {
for (k = 0; k < in_re->rows; k++) {
out_re->data [i*in_re->rows] = 0.0;
out_img->data [i*in_re->rows] = 0.0;
for(n = 0; n < in_re->cols; n++) {
out_re->data [i*in_re->cols+k] += aux_re->data [i*in_re->cols+n] * cos (n * k * arg / in_re->cols);
out_img->data [i*in_re->cols+k] += aux_img->data [i*in_re->cols+n] * cos (n * k * arg / in_re->cols);
}
}
}
/* multiplicar! */
for (i=0; i<out_re->rows; i++) {
for(j=0; j<out_re->cols; j++) {
out_re->data[i*out_re->cols+j]= in_re->data[i*in_re->cols+j] * out_re->data[i*in_re->cols+j]; //multiplica parte real por mask data
out_img->data[i*out_img->cols+j]= in_img->data[i*in_img->cols+j] * out_img->data[i*in_img->cols+j]; //multiplica parte imaginaria por mask data
//parte dentro de data[*] foi a lógica usada pelo professor em baixo
}
}
}
int main(int argc, char**argv){
char fnamein[255];
char fnameout[255];
Image * imgin=NULL;
Image * imgout=NULL;
ImageF *imginf=NULL;
ImageF * imgoutf=NULL;
if (argc!=3){
printf("Uso: %s <imagem_in.bmp> <imagem_flt.bmp>\n",argv[0]);
exit(1);
}
strcpy(fnamein,argv[1]);
strcpy(fnameout,argv[2]);
imgin=loadPBM(fnamein);
imgout=(Image *)malloc(sizeof(Image));
imgout->rows=imgin->rows;
imgout->cols=imgin->cols;
imgout->widthStep=imgin->widthStep;
imgout->data=(unsigned char*)malloc(imgout->rows*imgout->cols);
imginf=(ImageF*)malloc(sizeof(ImageF));
imginf->rows=imgin->rows;
imginf->cols=imgin->cols;
imginf->widthStep=imginf->cols*sizeof(double);
imginf->data=(double *)malloc(imginf->rows*imginf->cols*sizeof(double));
imgoutf=(ImageF*)malloc(sizeof(ImageF));
imgoutf->rows=imgin->rows;
imgoutf->cols=imgin->cols;
imgoutf->widthStep=imgoutf->cols*sizeof(double);
imgoutf->data=(double *)malloc(imgoutf->rows*imgoutf->cols*sizeof(double));
int i,j;
// copiar imagem para uma nova em formato double
for (i=0;i<imgin->rows;i++){
for(j=0;j<imgin->cols;j++)
imginf->data[i*imginf->cols+j]=imgin->data[i*imgin->cols+j];
}
/** processamento **/
ImageF *in_re = (ImageF *)malloc(sizeof(ImageF)),
*in_img = (ImageF *)malloc(sizeof(ImageF)),
*out_re = (ImageF *)malloc(sizeof(ImageF)),
*out_img = (ImageF *)malloc(sizeof(ImageF));
// in_re
in_re->rows = imgin->rows;
in_re->cols = imgin->cols;
in_re->widthStep = in_re->cols * sizeof(double);
in_re->data = (double *)malloc(in_re->rows * in_re->cols * sizeof(double));
// in_img
in_img->rows = imgin->rows;
in_img->cols = imgin->cols;
in_img->widthStep = in_img->cols * sizeof(double);
in_img->data = (double *)malloc(in_img->rows * in_img->cols * sizeof(double));
// out_re
out_re->rows = imgout->rows;
out_re->cols = imgout->cols;
out_re->widthStep = out_re->cols * sizeof(double);
out_re->data = (double *)malloc(out_re->rows * out_re->cols * sizeof(double));
// out_img
out_img->rows = imgout->rows;
out_img->cols = imgout->cols;
out_img->widthStep = out_img->cols * sizeof(double);
out_img->data = (double *)malloc(out_img->rows * out_img->cols * sizeof(double));
for (i = 0; i < in_re->rows; i++)
{
for (j = 0; j < in_re->cols; j++)
{
in_re->data[i * in_re->cols + j] = imginf->data[i * imginf->cols + j];
in_img->data[i * in_re->cols + j] = 0.0;
}
}
/** cria mascara **/
ImageF *mask = genlpfmask(in_re->rows, in_re->cols);
printf("1\n");
/** calcula dft da imagem */
fti(in_re, in_img, out_re, out_img, 0);
printf("2\n");
/** multiplica pela mascara */
dofilt(out_re, out_img, mask, out_re, out_img);
printf("3\n");
/** calcula dft inversa da imagem filtrada */
fti(out_re, out_img, in_re, in_img, 1);
printf("4\n");
/** copia para imagem de saida imgout */
for (i = 0; i < in_re->rows; i++)
{
for (j = 0; j < in_re->cols; j++)
{
imgout->data[i * imgout->cols + j] = in_re->data[i * in_re->cols + j];
}
}
printf("5\n");
/*#pragma parallel
#pragma omp sections
#pragma section
{ // criar mascara chamar função
}
#pragma section
{ // dft imagem chamar função
}
*/
/** A seguir é apenas um exemplo que deve ser retirado e substituido pela chamadas às funções a escrever */
/* Só para testar. Comentar quando incluir o seu código*/
teste(imginf, imgoutf);
for (i=0;i<imgoutf->rows;i++){
for(j=0;j<imgoutf->cols;j++){
double val;
val=imgoutf->data[i*imgoutf->cols+j];
if (val<0)
val=0.0;
else if (val>255)
val=255.0;
imgout->data[i*imgout->cols+j]=(unsigned char)val;
}
}
savePBM(fnameout,imgout);
return 0;
}
|
C
|
#include "holberton.h"
/**
* _sqrt_recursion - return the natural square root of a number
* @n: the number to be square rooted
* Return: the value of n square rooted
*/
int _sqrt_recursion(int n)
{
int x = 1, ans;
ans = _sqrt_helper(n, x);
return (ans);
}
/**
* _sqrt_helper - help return the square root of a number
* @n: the number to be square rooted
* @x: the eventual square root of n
* Return: the square root of n
*/
int _sqrt_helper(int n, int x)
{
if ((x * x) == n)
return (x);
else if ((x * x) > n)
return (-1);
return (_sqrt_helper(n, (x + 1)));
}
|
C
|
#include <stdio.h>
typedef struct data {
unsigned int day: 5;
unsigned int month: 4;
unsigned int year: 7;
} date;
int main() {
unsigned int day, month, year;
scanf("%d", &day);
scanf("%d", &month);
scanf("%d", &year);
date Date = {day, month, year % 100};
printf("%d.%d.%d", Date.day, Date.month, Date.year);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_all_info_we_can_into_array_of_tlines. :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bsemchuk <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/12 15:37:44 by bsemchuk #+# #+# */
/* Updated: 2018/03/20 18:05:06 by bsemchuk ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/asm.h"
/*
** Спочатку line обрізається зі сторін, потім видаляються
** коми, після чого розбивається на двувимірний масив
** Якщо режим дебагу увімкнений, виводиться інформація
** (line, deintegrated)Після чого треба зробити вибір,
** якщо перший елемент NAME_COMMAND || COMMENT_COMMAND,
** то обробляємо як сказано, якщо немає нульового елементу,
** то вважаємо її пустою, в іншому випадку спробуємо обробити
** її як інструкцію після чого видаляємо виділену память,
** окрім line -- він видаляється там де і виділяється
*/
int get_all_info_we_can_into_array_of_tlines(t_line *tline)
{
deintegrate_split_trim(tline);
get_label_if_present(tline);
get_command_index_and_label_args_pointer(tline);
get_parg_and_pparg(tline);
if (get_bytes_needed(tline) == EXIT_FAILURE)
{
ft_printf("Can not count size of id %d line: %s\n",
tline->id, tline->line_content);
return (EXIT_FAILURE);
}
print_debug(tline);
return (EXIT_SUCCESS);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//#include "adjacent.h"
//Global Declarations
typedef struct list
{
int node;
int x;
int y;
struct list * next;
} Node;
Node * insert_node(Node * head, int n_Val, int x_val, int y_val);
Node * make_node(int n_val, int x_val, int y_val);
void destroy_list(Node * tn);
int main(int argc, char ** argv)
{
if(argc < 2)
{
printf("Error, please provide input file\n");
return 0;
}
FILE * fptr;
fptr = fopen(argv[1], "r");
if(fptr == NULL)
{
printf("Error reading input file\n");
return 0;
}
int num_vertex;
int num_edges;
fscanf(fptr, "%d %d\n", &num_vertex, &num_edges);
int adj_matrix[num_vertex][num_vertex];
int k;
int l;
for(k = 0; k < num_vertex; k++) //initialize entire adjacency matrix to 0
{
for(l = 0; l < num_vertex; l++)
{
adj_matrix[k][l] = 0;
}
}
int i = 0;
Node * list = NULL; //list of vertex numbers
while(i < num_vertex)
{
int t_vnum; //temporary vertex number
int t_x; //temp x coordinate
int t_y; //temp y coordinate
fscanf(fptr, "%d %d %d\n", &t_vnum, &t_x, &t_y);
list = insert_node(list, t_vnum, t_x, t_y);
i++;
}
int t_n1; //temp node 1
int t_n2; //temp node 2
int j = 0;
while(j <= num_edges){
fscanf(fptr, "%d %d\n", &t_n1, &t_n2);
for(k = 0; k < num_vertex; k++)
{
if(k == t_n1)
{
for(l = 0; l < num_vertex; l++)
{
if(l == t_n2)
{
adj_matrix[k][l] = 1; //1 represents adjacency
adj_matrix[l][k] = 1;
}
}
}
}
j++;
}
for(k = 0; k < num_vertex; k++)
{
printf("%d:", k);
for(l = 0; l < num_vertex; l++)
{
if(adj_matrix[k][l] == 1)
{
printf(" %d", l);
}
}
printf("\n");
}
destroy_list(list);
return 0;
}
Node* insert_node(Node * head, int n_val, int x_val, int y_val)
{
Node * curr;
Node * temp;
if(head == NULL)
{
curr = make_node(n_val, x_val, y_val);
return(curr);
}
curr = head;
while(curr->next != NULL)
{
curr = curr->next;
}
temp = make_node(n_val, x_val, y_val);
curr->next = temp;
return head;
}
Node * make_node(int n_val, int x_val, int y_val)
{
Node * ln;
ln = malloc(sizeof(Node));
ln->node = n_val;
ln->x = x_val;
ln->y = y_val;
ln->next = NULL;
return ln;
}
void destroy_list(Node * tn)
{
if(tn->next != NULL)
{
destroy_list(tn->next);
}
free(tn);
}
|
C
|
#include<stdio.h>
void f(int b)
{
static int a;
if(b==1)
a += 10;
else
a = 2;
printf("%d\n", a);
}
int main(void)
{
static int a = 1;
f(0);
f(1);
f(1);
}
|
C
|
/*
* main.c
*
* Created: 2018-03-05 8:33:44 PM
* Author : anssk
*/
#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include "uart.h"
#include "irsensor.h"
#include "Motor.h"
#include "MACROS.h"
/* **************** FUN PROTOTYPES **************** */
/* NORMAL MOTION */
void Stop();
void Forward();
void Backward();
void Right();
void Left();
void setSpeed(uint8_t A, uint8_t B);
/* LINE FOLLOWER */
void Line();
volatile uint8_t data; /* RECIEVED DATA FROM UART */
int main(void)
{
/* **************** INITIALIZATIONS **************** */
sei();
UART_init();
/* SET MOTORS PINS TO BE OUTPUT */
SetMotor(DDRC,PC0,PC1); /* MOTOR A */
SetMotor(DDRC,PC2,PC3); /* MOTOR B */
setSpeed(0,0); /* initialize speed by 0 */
/* SET IR PINS TO BE INPUT */
SET_IR_PINS(DDRC,PC4); /* LEFT IR */
SET_IR_PINS(DDRC,PC5); /* MID IR */
SET_IR_PINS(DDRC,PC6); /* RIGHT IR */
/* **************** USED VARIABLES **************** */
char carState = 'W'; /* W -> NORMAL STATE ----- w -> LINE FOLLOWER STATE */
while(1)
{
/* **************** CAR STATE SELECT **************** */
if( data == 'W')
{
carState = 'W';
}
else if(data == 'w')
{
carState = 'w' ;
}
/* **************** CAR SPEED SELECT **************** */
if( (data >= '0' && data <= '9') || data == 'q')
{
if(data == 'q')
{
setSpeed(255,255);
}
else
{
uint8_t x = 28 * data;
setSpeed(x,x);
}
}
/* **************** MOTION BASED ON CAR STATE **************** */
if(carState == 'w')
{
Line();
}
else
{
/* **************** AVOID OBSTACLES **************** */
if( IS_BIT_CLEAR(PINC,PC4) || IS_BIT_CLEAR(PINC,PC5) )
{
Backward();
}
/* **************** NORMAL MOTION **************** */
else
{
if(data == 'F')
{
Forward();
}
else if(data == 'B')
{
Backward();
}
else if(data == 'R')
{
Right();
}
else if(data == 'L')
{
Left();
}
else if(data == 'S')
{
Stop();
}
}
}
/* **************** ULTRASONIC & SERVO CODE HERE **************** */
} /* while */
} /* main */
/* MOTION STATES */
void Stop(){
Motor_Stop(PORTC,PC0,PC1);
Motor_Stop(PORTC,PC2,PC3);
}
void Forward(){
Motor_Forward(PORTC,PC0,PC1);
Motor_Forward(PORTC,PC2,PC3);
}
void Backward(){
Motor_Backward(PORTC,PC0,PC1);
Motor_Backward(PORTC,PC2,PC3);
}
void Left(){
Motor_Forward(PORTC,PC0,PC1);
Motor_Backward(PORTC,PC2,PC3);
}
void Right(){
Motor_Backward(PORTC,PC0,PC1);
Motor_Forward(PORTC,PC2,PC3);
}
void setSpeed(uint8_t A, uint8_t B){
analogWrite(1,A);
analogWrite(2,B);
}
/* LINE FOLLOWER STATE */
void Line(){
if(IR_Read(PC4,PC5,PC6) == 2){
setSpeed(150,150);
Left();
}
else if(IR_Read(PC4,PC5,PC6) == 1){
setSpeed(150,150);
Right();
}
else{
setSpeed(200,200);
Forward();
}
}
/* **************** INTERRUPTS **************** */
/* UART */
ISR(USART_RXC_vect)
{
data = UDR;
}
|
C
|
/* LVB
* (c) Copyright 2003-2012 by Daniel Barker.
* (c) Copyright 2013, 2014 by Daniel Barker and Maximilian Strobl.
* Permission is granted to copy and use this program provided that no fee is
* charged for it and provided that this copyright notice is not removed. */
#include <lvb.h>
/* check pow_wrapper crashes verbosely on domain error if first
* parameter is negative and second parameter is non-integral */
int main(void)
{
lvb_initialize();
pow_wrapper(-3, 1.5); /* should cause domain error */
/* if we get this far, pow_wrapper() has failed to crash so the
* test has failed */
printf("test failed\n");
exit(EXIT_SUCCESS); /* we want failure: so program success
* indicates test failed */
}
|
C
|
/** @file */
#ifndef __CCL_UTILS_H_INCLUDED__
#define __CCL_UTILS_H_INCLUDED__
#include <gsl/gsl_spline.h>
#define CCL_MIN(a, b) (((a) < (b)) ? (a) : (b))
#define CCL_MAX(a, b) (((a) > (b)) ? (a) : (b))
CCL_BEGIN_DECLS
/**
* Compute bin edges of N-1 linearly spaced bins on the interval [xmin,xmax]
* @param xmin minimum value of spacing
* @param xmax maximum value of spacing
* @param N number of bins plus one (number of bin edges)
* @return x, bin edges in range [xmin, xmax]
*/
double * ccl_linear_spacing(double xmin, double xmax, int N);
/**
* Compute bin edges of N-1 logarithmically and then linearly spaced bins on the interval [xmin,xmax]
* @param xminlog minimum value of spacing
* @param xmin value when logarithmical ends and linear spacing begins
* @param xmax maximum value of spacing
* @param Nlin number of linear bins plus one (number of bin edges)
* @param Nlog number of logarithmic bins plus one (number of bin edges)
* @return x, bin edges in range [xminlog, xmax]
*/
double * ccl_linlog_spacing(double xminlog, double xmin, double xmax, int Nlin, int Nlog);
/**
* Compute bin edges of N-1 logarithmically spaced bins on the interval [xmin,xmax]
* @param xmin minimum value of spacing
* @param xmax maximum value of spacing
* @param N number of bins plus one (number of bin edges)
* @return x, bin edges in range [xmin, xmax]
*/
double * ccl_log_spacing(double xmin, double xmax, int N);
//Returns array of N logarithmically-spaced values between xmin and xmax
double ccl_j_bessel(int l,double x);
//Spherical Bessel function of order l (adapted from CAMB)
/**
* Spline wrapper
* Used to take care of evaluations outside the supported range
*/
typedef struct {
gsl_spline *spline;
double x0,xf; //Interpolation limits
double y0,yf; //Constant values to use beyond interpolation limit
} SplPar;
SplPar *ccl_spline_init(int n,double *x,double *y,double y0,double yf);
double ccl_spline_eval(double x,SplPar *spl);
void ccl_spline_free(SplPar *spl);
CCL_END_DECLS
#endif
|
C
|
#include <stdlib.h>
#include <assert.h>
size_t CountSetBits(int num)
{
size_t counter = 0;
while (0 < num)
{
num = (num & (num -1));
++counter;
}
return counter;
}
int main()
{
assert(2 == CountSetBits(12));
assert(1 == CountSetBits(8));
assert(1 == CountSetBits(4));
assert(2 == CountSetBits(5));
assert(2 == CountSetBits(6));
assert(3 == CountSetBits(7));
return 0;
}
|
C
|
#include "dispatcher.h"
VOID BuildRequestW(LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR *lplpszAcceptTypes, LPCWSTR lpszReferrer, DWORD flags) {
int i = 0;
WCHAR tmp[MAX_PATH*sizeof(WCHAR)];
ZeroMemory(tmp, MAX_PATH*sizeof(WCHAR));
if(flags & 0x00800000) //INTERNET_FLAG_SECURE
wsprintfW(tmp, L"%s https://%s%s HTTP/1.1", lpszVerb, whost, lpszObjectName);
else
wsprintfW(tmp, L"%s http://%s%s HTTP/1.1", lpszVerb, whost, lpszObjectName);
while(lplpszAcceptTypes[i] != NULL) {
if(!i) {
wcscat(tmp, L"\r\n\0");
wcscat(tmp, L"Accept: \0");
}
wcscat(tmp, (LPCWSTR) lplpszAcceptTypes[i]);
wcscat(tmp, L",\0");
i++;
}
if(lpszReferrer) {
wcscat(tmp, L"\r\nReferrer: \0");
wcscat(tmp, lpszReferrer);
}
if(flags & 0x00400000) //INTERNET_FLAG_KEEP_CONNECTION
wcscat(tmp, L"\r\nConnection: Keep-Alive\n\0");
wrequest = (LPWSTR) malloc(wcslen(tmp)*sizeof(WCHAR));
wcsncpy(wrequest, tmp, wcslen(tmp));
return;
}
VOID addVerbW(LPCWSTR verb) {
wrequest = (LPWSTR) malloc((wcslen(verb) + 1)*sizeof(WCHAR));
wsprintfW(wrequest, L"%s", verb);
}
VOID addHostW(DWORD flags) {
WCHAR tmp[MAX_PATH*sizeof(WCHAR)];
ZeroMemory(tmp, MAX_PATH*sizeof(WCHAR));
if(flags & 0x00800000) //INTERNET_FLAG_SECURE
wsprintfW(tmp, L"%s https://%s", wrequest, whost);
else
wsprintfW(tmp, L"%s http://%s", wrequest, whost);
wrequest = (LPWSTR) realloc(wrequest, (wcslen(tmp) + 1)*sizeof(WCHAR));
wsprintfW(wrequest, L"%s", tmp);
}
VOID addObjectW(LPCWSTR object) {
LPWSTR tmp;
tmp = (LPWSTR) malloc(((wcslen(wrequest)*3) + wcslen(object))*sizeof(WCHAR));
wrequest = (LPWSTR) realloc(wrequest, (wsprintfW(tmp, L"%s%s HTTP/1.1\r\n", wrequest, object) + 1)*sizeof(WCHAR));
wsprintfW(wrequest, L"%s", tmp);
free(tmp);
}
VOID addAcceptTypesW(LPCWSTR *types) {
WCHAR tmp[MAX_PATH*sizeof(WCHAR)];
int i = 0;
ZeroMemory(tmp, MAX_PATH*sizeof(WCHAR));
while(types[i]) {
if(!i)
wsprintfW(tmp, L"Accept: ");
wcscat(tmp, types[i]);
wcscat(tmp, L",");
i++;
}
tmp[wcslen(tmp) - 1] = NULL;
wrequest = (LPWSTR) realloc(wrequest, (wcslen(wrequest) + wcslen(tmp) + 5)*sizeof(WCHAR));
wcscat(wrequest, tmp);
wcscat(wrequest, L"\r\n");
}
VOID addReferrerW(LPCWSTR referrer) {
LPWSTR tmp;
if(referrer) {
tmp = (LPWSTR) malloc(((wcslen(wrequest)*2) + wcslen(referrer))*sizeof(WCHAR));
wsprintfW(tmp, L"%s\r\nReferrer: %s\r\n", wrequest, referrer);
wrequest = (LPWSTR) realloc(wrequest, (wcslen(tmp) + 1)*sizeof(WCHAR));
wsprintfW(wrequest, L"%s", tmp);
free(tmp);
}
else
return;
}
VOID addKeepAliveW(VOID) {
wrequest = (LPWSTR) realloc(wrequest, (wcslen(wrequest) + (wcslen(L"Connection: Keep-Alive\r\n")) + 1)*sizeof(WCHAR));
wcscat(wrequest, L"Connection: Keep-Alive\r\n");
}
VOID addHeadersW(LPCWSTR headers) {
wrequest = (LPWSTR) realloc(wrequest, (wcslen(wrequest) + wcslen(headers) + 5)*sizeof(WCHAR));
wcscat(wrequest, headers);
wcscat(wrequest, L"\r\n");
}
VOID addOptionalW(LPVOID optional, DWORD length){
LPWSTR uni;
WCHAR tmp[MAX_PATH];
uni = (LPWSTR) malloc(length*sizeof(WCHAR));
MultiByteToWideChar(CP_OEMCP, 0, (LPCSTR) optional, length, uni, length);
ZeroMemory(tmp, MAX_PATH);
wsprintfW(tmp, L"Content-Length: %d ---> %d\r\n\r\n", wcslen(uni), length);
wrequest = (LPWSTR) realloc(wrequest, (wcslen(wrequest) + wcslen(tmp) + wcslen(uni) + 100)*sizeof(WCHAR));
wcscat(wrequest, tmp);
wcscat(wrequest, uni);
wcscat(wrequest, L"\r\n\r\n");
}
VOID addOptionalA(LPVOID optional){
LPWSTR uni;
size_t len = strlen((LPCSTR) optional);
uni = (LPWSTR) malloc((len + 1) * sizeof(WCHAR));
MultiByteToWideChar(CP_OEMCP, 0, (LPCSTR) optional, -1, uni, len + 1);
OutputDebugStringA("+++");
OutputDebugStringW((LPCWSTR) uni);
//OutputDebugStringA((LPCSTR) optional);
OutputDebugStringA("+++");
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct Node{
int num;
struct Node *prox
}node;
int cont,contador=0;
void inicia(node *TO, node *T1);
int compara(char op[]);
node *aloca();
void insereD(node *T);
void insereE(node *T);
node *retiraD(node *T);
node *retiraE(node *T);
void contagem(node *T);
int main(){
char op[3];
int opt;
node *T0=(node*)malloc(sizeof(node));
if(!T0){
exit(1);
}
node *T1=(node*)malloc(sizeof(node));
if(!T1){
exit(1);
}
inicia(T0, T1);
while(scanf(" %s", op) == 1){
fflush(stdin);
opt=compara(op);
node *tmp=NULL;
switch(opt){
case 1:
insereD(T0);
break;
case 2:
tmp=retiraD(T0);
printf("%d\n", tmp->num);
break;
case 3:
insereE(T1);
break;
case 4:
insereD(T1);
break;
case 5:
tmp=retiraE(T1);
printf("%d\n", tmp->num);
break;
case 6:
tmp=retiraD(T1);
printf("%d\n", tmp->num);
break;
case 7:
contador=0;
contagem(T0);
contador=0;
contagem(T1);
printf("\n");
inicia(T0,T1);
break;
}
}
free(T0);
free(T1);
return 0;
}
void inicia(node *TO, node *T1){
TO->prox= NULL;
T1->prox= NULL;
cont= -1;
}
int compara(char op[]){
if((strcmp(op,"E0")==0))
return 1;
else{
if((strcmp(op,"S0"))==0)
return 2;
else{
if((strcmp(op,"E1E"))==0)
return 3;
else{
if((strcmp(op,"E1D"))==0)
return 4;
else{
if((strcmp(op,"S1E"))==0)
return 5;
else{
if((strcmp(op,"S1D"))==0)
return 6;
else{
if((strcmp(op,"FIM"))==0)
return 7;
else
return 8;
}
}
}
}
}
}
}
node *aloca(){
node *novo=(node*)malloc(sizeof(node));
if(!novo)
exit(1);
else
return novo;
}
void insereD(node *T){
if(T->prox == NULL){
node *novo=aloca();
novo->prox=NULL;
cont++;
novo->num=cont;
T->prox=novo;
}
else{
insereD(T->prox);
}
}
void insereE(node *T){
node *novo=aloca();
cont++;
novo->num=cont;
node *oldHead= T->prox;
T->prox=novo;
novo->prox= oldHead;
}
node *retiraD(node *T){
if(T->prox == NULL)
return NULL;
else{
node *ultimo=T->prox, *penultimo=T;
while(ultimo->prox !=NULL){
penultimo=ultimo;
ultimo=ultimo->prox;
}
penultimo->prox=NULL;
return ultimo;
}
}
node *retiraE(node *T){
if(T->prox == NULL)
return NULL;
else{
node *tmp=T->prox;
T->prox= tmp->prox;
return tmp;
}
}
void contagem(node *T){
if(T->prox != NULL){
contador++;
contagem(T->prox);
}
else
printf("%d\n", contador);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_env_utils2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: seunkim <seunkim@student.42seoul.kr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/09/03 16:09:27 by seunkim #+# #+# */
/* Updated: 2020/09/03 16:09:29 by seunkim ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
void ft_add_new_env(char *new_arg)
{
extern char **environ;
int i;
i = 0;
while (environ[i])
i++;
environ[i] = new_arg;
i++;
environ[i] = 0;
}
void ft_add_envs(char *new_arg)
{
int i;
int j;
char key[1024];
char value[1024];
char new_value[1024];
i = -1;
j = 0;
while (new_arg[++i] && new_arg[i] != '=')
key[j++] = new_arg[i];
key[j] = 0;
j = 0;
while (new_arg[++i])
new_value[j++] = new_arg[i];
new_value[j] = 0;
ft_get_env(key, value);
if (value[0] == 0)
ft_add_new_env(new_arg);
else
ft_set_env(key, new_value);
}
void ft_print_new_envs(char **new_arg)
{
int idx;
idx = 1;
while (new_arg[idx])
{
ft_putstr_fd(new_arg[idx], STDOUT);
ft_putchar_fd('\n', STDOUT);
idx++;
}
}
int ft_validate_key_value(char *arg)
{
int idx;
idx = 0;
while (arg[idx])
{
if (arg[idx] == '=')
return (1);
idx++;
}
return (0);
}
|
C
|
#include <stdio.h>
int main(void) {
int s[4][5];
int i, j, cnt = 0;
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++) {
/*
if (i == 0)s[i][j] = i + 1 + j;
else if (i == 1) s[i][j] = 6 + j;
else if (i == 2) s[i][j] = 11 + j;
else s[i][j] = 16 + j;
*/
s[i][j] = ++cnt;
}
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++) {
printf("%5d", s[i][j]);
}
printf("\n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "slice.h"
//resize resizes slices that need to grow, or that should be shrunk
//
//Slices that are at max capacity are expanded.
//Slices that are less than half full are shrunk.
int resize(struct Slice *slice, unsigned int valueSize) {
if(slice->used == slice->allocated) {
if(!slice->allocated) { //Initial allocation
slice->values = malloc(valueSize);
if(slice->values == NULL) {
perror("Unable to get a memory allocation for our slice");
return 101;
}
slice->allocated = 1;
} else { //Subsequent allocations
slice->values = realloc(slice->values, slice->allocated * valueSize * 2);
if(slice->values == NULL) {
perror("Unable to get a memory reallocation for our slice");
return 102;
}
slice->allocated = slice->allocated * 2;
}
} else if(slice->used < (slice->allocated / 2)) {
slice->values = realloc(slice->values, (slice->allocated / 2) * valueSize);
if(slice->values == NULL) {
perror("Unable to get a memory reallocation for our slice");
return 103;
}
}
return 0;
}
//append adds "value" to "slice". Array memory
//reallocations are handled automatically, if needed
int append(struct Slice *slice, void* value, unsigned int valueSize) {
resize(slice, valueSize); //Call "resize" to prevent segfaults
(void)memcpy((void*)((char*)(slice->values) + (valueSize * slice->used)), value, valueSize);
slice->used++;
return 0;
}
//delete removes the first instance of "value" from "slice"
int delete(struct Slice *slice, void* value, unsigned int valueSize) {
for(int index = 0; index < slice->used; index++) {
int err = memcmp((void*)((char*)(slice->values) + (valueSize * index)), value, valueSize);
if(err == 0) {
if(valueSize * (slice->used - (index + 1)) != 0) { //There are no elements to copy if we're deleting the last element
(void)memcpy((void*)((char*)(slice->values) + (valueSize * index)),
(void*)((char*)(slice->values) + (valueSize * (index + 1))),
valueSize * (slice->used - (index + 1))); //Copy all elements after "index" to "slice"
}
slice->used--;
return resize(slice, valueSize);
}
}
perror("Couldn't find value in slice");
return 104;
}
//pop "pops" the last x values off the end of "slice"
int pop(struct Slice *slice, unsigned int valueCount, unsigned int valueSize) {
slice->used = slice->used - valueCount;
return resize(slice, valueSize);
}
|
C
|
#include"LinkList.h"
//ʼ
LinkList Init_LinkList(){
LList* list = (LList*)malloc(sizeof(LList));
if (list == NULL){
return NULL;
}
list->header.next = NULL;
list->size = 0;
return list;
}
//ָλò
void Insert_LinkList(LinkList list, int pos, LinkNode* data){
if (list == NULL){
return;
}
LList* mlist = (LList*)list;
if (pos < 0 || pos > mlist->size){
pos = mlist->size;
}
if (data == NULL){
return;
}
#if 0
//²ͲЧʣûԾظԪ
//жַָǷظ
LinkNode* pTest = mlist->header.next;
while (pTest != NULL){
if (pTest == data){
printf("ָظ!\n");
return;
}
pTest = pTest->next;
}
#endif
//ָ
LinkNode* pCurrent = &(mlist->header);
int i = 0;
for (; i < pos;i++){
pCurrent = pCurrent->next;
}
//
data->next = pCurrent->next;
pCurrent->next = data;
mlist->size++;
}
//ͷ
void PushFront_LinkList(LinkList list, LinkNode* data){
if (list == NULL){
return;
}
if (data == NULL){
return;
}
Insert_LinkList(list, 0, data);
}
//β
void PushBack_LinkList(LinkList list, LinkNode* data){
if (list == NULL){
return;
}
if (data == NULL){
return;
}
LList* mlist = (LList*)list;
Insert_LinkList(list, mlist->size, data);
}
//ָλɾ
void RemoveByPos_LinkList(LinkList list, int pos){
if (list == NULL){
return;
}
LList* mlist = (LList*)list;
if (pos < 0 || pos > mlist->size - 1){
return;
}
if (mlist->size == 0){
return;
}
//ָ
LinkNode* pCurernt = &(mlist->header);
int i = 0;
for (; i < pos;i++){
pCurernt = pCurernt->next;
}
//±ɾڵ
LinkNode* pDel = pCurernt->next;
//ɾڵǰڵĺָָɾڵĺ̽ڵ
pCurernt->next = pDel->next;
mlist->size--;
}
//ͷλɾ
void PopFront_LinkList(LinkList list){
if (list == NULL){
return;
}
LList* mlist = (LList*)list;
if (mlist->size == 0){
return;
}
RemoveByPos_LinkList(list, 0);
}
//βλɾ
void PopBack_LinkList(LinkList list){
if (list == NULL){
return;
}
LList* mlist = (LList*)list;
if (mlist->size == 0){
return;
}
RemoveByPos_LinkList(list, mlist->size - 1);
}
//ֵɾ
void RemoveByVal_LinkList(LinkList list, LinkNode* data, DATA_COMPARE compare){
if (list == NULL){
return;
}
if (data == NULL){
return;
}
if (compare == NULL){
return;
}
LList* mlist = (LList*)list;
if (mlist->size == 0){
return;
}
//ָ
LinkNode* pPrev = &(mlist->header);
LinkNode* pCurrent = pPrev->next;
while (pCurrent != NULL){
if (compare(pCurrent,data)){
pPrev->next = pCurrent->next;
mlist->size--;
break;
}
pPrev = pCurrent;
pCurrent = pPrev->next;
}
}
//С
int Size_LinkList(LinkList list){
if (list == NULL){
return -1;
}
LList* mlist = (LList*)list;
return mlist->size;
}
//ӡ
void Print_LinkList(LinkList list, DATA_PRINT print){
if (list == NULL){
return;
}
if (print == NULL){
return;
}
LList* mlist = (LList*)list;
//ָ
LinkNode* pCurrent = mlist->header.next;
while (pCurrent != NULL){
print(pCurrent);
pCurrent = pCurrent->next;
}
}
//
void Destroy_LinkList(LinkList list){
if (list == NULL){
return;
}
free(list);
}
|
C
|
#include <stdio.h>
#include <malloc.h>
#include "Database.h"
#include "../Util/ScanUtil.h"
/*
* Description: lists the manufacturers in the database
* Returns: void
*/
void listManufacturers(DataBase* database) {
for(int i = 0; i < database->amountOfManufacturers; i++){
Manufacturer* manufacturer = database->manufacturers[i];
printf("%s\n" "Description: %s\n", manufacturer->name,manufacturer->description);
}
}
/*
* Description: lists the providers in the database
* Returns: void
*/
void listProviders(DataBase* database) {
for(int i = 0; i < database->amountOfProviders; i++){
Provider* provider = database->providers[i];
printf("%s\n" "Description: %s\n", provider->name,provider->description);
}
}
/*
* Description: lists the appliances in the database
* Returns: void
*/
void listAppliances(DataBase* database) {
for(int i = 0; i < database->amountOfAppliances; i++){
Appliance* appliance = database->appliances[i];
printf("%s\n", appliance->name);
}
}
/*
* Description: asks for the details of a manufacturer, creates one and adds them to the database
* Returns: void
*/
void addManufacturerMenu(DataBase* database){
printf("Add Manufacturer:\n");
printf("Name:\n");
char* name = scanChar();
printf("Description:\n");
char* description = scanChar();
printf("Address:\n");
char* address = scanChar();
printf("City:\n");
char* city = scanChar();
printf("Web:\n");
char* web = scanChar();
printf("Phone:\n");
char* phone = scanChar();
Manufacturer* manufacturer = createManufacturer(name, description, address, city, phone, web);
addManufacturer(database, manufacturer);
free(name);
free(description);
free(address);
free(city);
free(web);
free(phone);
}
/*
* Description: removes a manufacturer from the database
* Returns: void
*/
void removeManufacturerMenu(DataBase *database){
printf("Name of the manufacturer to remove:\n");
if(removeManufacturer(database,scanChar())) printf("Manufacturer removed successfully\n");
else printf("Manufacturer not found\n");
}
/*
* Description: asks the user what he wants to do and calls a method accordingly
* Returns: void
*/
void manufacturersMenu(DataBase *database){
while(1) {
printf("\n");
printf("----------------------\n");
printf("Manufacturers\n");
printf("1. Add manufacturer\n");
printf("2. Remove manufacturer\n");
printf("3. List manufacturers\n");
printf("-1. Exit\n");
int choice = scanInt();
switch (choice) {
case 1:
addManufacturerMenu(database);
break;
case 2:
removeManufacturerMenu(database);
break;
case 3:
listManufacturers(database);
break;
case -1:
return;
default:
printf("Please enter a valid number\n");
}
}
}
/*
* Description: asks the user what he wants to do and calls a method accordingly
* Returns: void
*/
void addProviderMenu(DataBase *database){
printf("Add provider:\n");
printf("Name:\n");
char* name = scanChar();
printf("Description:\n");
char* description = scanChar();
printf("Address:\n");
char* address = scanChar();
printf("City:\n");
char* city = scanChar();
printf("Web:\n");
char* web = scanChar();
printf("Phone:\n");
char* phone = scanChar();
Provider* provider = createProvider(name, description, address, city, phone, web);
addProvider(database, provider);
free(name);
free(description);
free(address);
free(city);
free(web);
free(phone);
}
void removeProviderMenu(DataBase* database){
printf("Name of the provider to remove:\n");
if(removeProvider(database,scanChar())) printf("Provider removed successfully\n");
else printf("Provider not found\n");
}
void providersMenu(DataBase *database){
while(1) {
printf("\n");
printf("----------------------\n");
printf("Providers\n");
printf("1. Add provider\n");
printf("2. Remove provider\n");
printf("3. List providers\n");
printf("-1. Exit\n");
int choice = scanInt();
switch (choice) {
case 1:
addProviderMenu(database);
break;
case 2:
removeProviderMenu(database);
break;
case 3:
listProviders(database);
break;
case -1:
return;
default:
printf("Please enter a valid number\n");
}
}
}
void addApplianceMenu(DataBase* database){
printf("Add appliance:\n");
//name
printf("Name:\n");
char* name = scanChar();
printf("\n");
//model
printf("Model:\n");
char* model = scanChar();
printf("\n");
//price
printf("Price:\n");
int price = scanInt();
printf("\n");
//id
printf("id:\n");
char* id = scanChar();
printf("\n");
//list, check and save manufacturer
listManufacturers(database);
char* manufacturer;
while (1){
printf("Name of the Manufacturer:\n");
char* manufacturerName = scanChar();
if(manufacturerExist(database, manufacturerName)){
manufacturer = manufacturerName;
break;
}
}
printf("\n");
//list, check and save provider
listProviders(database);
char* provider;
while (1){
printf("Name of the Provider:\n");
char* providerName = scanChar();
if(providerExist(database, providerName)){
provider = providerName;
break;
}
}
printf("\n");
//create appliance and add it to the database
Appliance* appliance = createAppliance(name,model,price,id);
addAppliance(database,appliance,manufacturer,provider);
//free variables used
free(name);
free(model);
free(id);
free(manufacturer);
free(provider);
}
void removeApplianceMenu(DataBase* database) {
printf("Name of the appliance to remove:\n");
if(removeAppliance(database,scanChar())) printf("Appliance removed successfully\n");
else printf("Appliance not found\n");
}
void appliancesMenu(DataBase* database){
while(1) {
printf("\n");
printf("----------------------\n");
printf("Appliances:\n");
printf("1. Add appliance\n");
printf("2. Remove appliance\n");
printf("3. List appliances\n");
printf("-1. Exit\n");
int choice = scanInt();
switch (choice) {
case 1:
addApplianceMenu(database);
break;
case 2:
removeApplianceMenu(database);
break;
case 3:
listAppliances(database);
break;
case -1:
return;
default:
printf("Please enter a valid number\n");
}
}
}
void adminMenu(DataBase* database){
while(1) {
printf("\n");
printf("********************\n");
printf("Admin Menu\n");
printf("1. Manufacturers\n");
printf("2. Providers\n");
printf("3. Appliances\n");
printf("-1. Exit\n");
int choice = scanInt();
switch (choice) {
case 1:
manufacturersMenu(database);
break;
case 2:
providersMenu(database);
break;
case 3:
appliancesMenu(database);
break;
case -1:
return;
default:
printf("Please enter a valid number\n");
}
}
}
|
C
|
#include <stdio.h>
// count number of spaces, tabs and newlines
main() {
int nc = 0;
char c;
c = getchar();
while( c != EOF ) {
if(c == '\n' || c == ' ' || c == '\t') {
nc++;
printf("The number of each breaks is %d", nc);
c = getchar();
} else {
printf("You entered something different!");
c = getchar();
}
}
}
|
C
|
#include <xc.h>
#include <delays.h>
#include <plib/timers.h>
#include "buttons.h"
#include "lcd.h"
#define _XTAL_FREQ 8000000
unsigned char pwm_value = 50;
// void PWM1_setDC(unsigned int dutycycle)
// {
// CCPR1L = dutycycle >> 2; // PWM duty cycle - first 8-bits (MSb)
// CCP1CON &= 0xCF; // 5,4 bits zeroed (DC1B1:DC1B0 = 00)
// CCP1CON |= ((dutycycle << 4) & 0x30); // PWM duty cycle - last 2-bits (LSb) in CCP1CON 5,4 bits
// }
void regulate_temperature(int temperature , int normal_temperature){
if (temperature > normal_temperature && pwm_value > 10)
{
pwm_value--;
CCPR1L = pwm_value;
FAN_CIRCULACION = 1;
}
if (temperature < normal_temperature && pwm_value < 110)
{
pwm_value++;
CCPR1L = pwm_value;
FAN_CIRCULACION = 0;
}
if(temperature > 395 || temperature < 360){
BUZZER = 1;
LCD_clr();
LCD_out(1,0," RANGO DE TEMP ");
LCD_out(2,0," EXCEDIDO ");
__delay_ms(100);
}else {
BUZZER = 0;
FAN_EXTRACION = 0;
}
if(temperature > 390){
pwm_value = 10;
CCPR1L = pwm_value;
FAN_EXTRACION = 1;
}
}
|
C
|
#include <conf.h>
#include <kernel.h>
#include <proc.h>
#include <stdio.h>
#include <lock.h>
#include <sleep.h>
int priority_insert(int lock_index,int pid,int pri,int type)
{
/*if (isbadlock_no(lock_index))
{
kprintf("\nBad Lock ID");
return(SYSERR);
}*/
order_list_t *list = lock_tab[lock_index].head;
order_list_t *new = NULL;
order_list_t *prev = NULL;
//kprintf("\nIn priority insert <%d>", list == NULL);
if(list == NULL)
{
new = (order_list_t *)getmem(sizeof(order_list_t));
new->pid = pid;
new->pri = pri;
new->time = ctr1000;
new->lock_type = type;
//kprintf("\nFirst Entry in Q");
new->next = list;
list = new;
lock_tab[lock_index].head = list;
//print_list(lock_index);
return OK;
}
while(list != NULL)
{
//kprintf("\nIn While loop<%d>",list->lock_type);
if(pri >= list->pri)
{
//kprintf("\nNot First in Q");
new = (order_list_t *)getmem(sizeof(order_list_t));
new->pid = pid;
new->pri = pri;
new->lock_type = type;
new->time = ctr1000;
if((pri == list->pri && type == WRITE && (ctr1000 - new->time) < 1000) || pri > list->pri)
{
//kprintf("\nInserting");
if(prev == NULL)
{
new->next = list;
list = new;
lock_tab[lock_index].head = list;
}
else
{
prev->next = new;
new->next = list;
}
}
else
{
new->next = list->next;
list->next = new;
}
return OK;
}
//kprintf("\nDoing next");
prev = list;
list = list->next;
}
/* Insert at the last element */
new = (order_list_t *)getmem(sizeof(order_list_t));
new->pid = pid;
new->pri = pri;
new->lock_type = type;
new->time = ctr1000;
new->next = NULL;
prev->next = new;
//kprintf("\nAfter while loop");
//print_list(lock_tab[lock_index].head);
return OK;
}
void print_list(int lock_index)
{
kprintf("\nprint_list\n");
order_list_t *list = lock_tab[lock_index].head;
while(list != NULL)
{
kprintf("<%d|%d>-",list->pid,list->lock_type);
list = list->next;
}
}
int is_write_pres(int lock_index)
{
order_list_t *list = lock_tab[lock_index].head;
while(list != NULL)
{
if(list->lock_type == WRITE)
{
//kprintf("\nPRESENT");
return PRESENT;
}
list = list->next;
}
//kprintf("\nEMPTY");
return EMPTY;
}
order_list_t* get_first_write(int lock_index)
{
order_list_t *list = lock_tab[lock_index].head;
while(list != NULL)
{
if(list->lock_type == WRITE)
{
//kprintf("\nPRESENT");
return list;
}
}
//kprintf("\nEMPTY");
return NULL;
}
int is_present(int lock_index)
{
order_list_t *head;
head = lock_tab[lock_index].head;
if(head == NULL)
{
return EMPTY;
}
else
{
return PRESENT;
}
}
order_list_t* remove_first(int lock_index)
{
if(lock_tab[lock_index].head == NULL)
{
return NULL;
}
order_list_t *first = lock_tab[lock_index].head;
lock_tab[lock_index].head = lock_tab[lock_index].head->next;
return first;
}
order_list_t* get_first(int lock_index)
{
return lock_tab[lock_index].head;
}
int getfirst_ll(int lock_index)
{
if(lock_tab[lock_index].head == NULL)
return EMPTY;
return lock_tab[lock_index].head->pid;
}
void putin_proc_list(int ldes1,int pid)
{
if(ldes1 < NLOCKS)
{
proctab[pid].lock_list[ldes1] = 1;
proctab[pid].lock_counter++;
//kprintf("\nSetting the Process <%d> with ldesc<%d><%d>",pid,ldes1,proctab[pid].lock_list[ldes1]);
}
}
int is_proc_hold(int lk_index,int pid)
{
//kprintf("\nCalled Process <%d> with ldesc<%d><%d>",pid,lk_index,proctab[pid].lock_list[lk_index]);
if(proctab[pid].lock_list[lk_index] == 1)
{
proctab[pid].lock_list[lk_index] = 0;
proctab[pid].lock_counter--;
return YES;
}
else
{
return NO;
}
}
void lock_init(int index)
{
if(index < NLOCKS)
{
lock_tab[index].head = NULL;
lock_tab[index].curr_status = FREE;
lock_tab[index].curr_proc = -1;
lock_tab[index].read_count = 0;
}
}
|
C
|
#include <stdio.h>
// #include <string.h>
int main()
{
char st1[15];
char st2[15];
char c;
int i = 0;
printf("input WHOLE string= \n");
scanf("%s", st1);
printf("input string CHARACTER BY CHARACTER = \n");
while (c != '\n')
{
fflush(stdin); //to refresh or flush address before next scanf entry
scanf("%c", &c);
st2[i] = c;
i++;
}
st2[i] = '\0';
printf("the value of st1= %s\n", st1);
printf("the value of st2= %s\n", st2);
return 0;
}
|
C
|
/*
============================================================================
Name : Clase_05.c
Author :
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include <stdio.h>
#include <stdio_ext.h>
#include <stdlib.h>
#define QTY_EDADES 5
int initArrayInt(int *pArray , int limite, int valor);
int printArrayInt(int *pArray , int limite);
int getArrayInt( int *pArray,
int limite,
char *pMensaje,
char *pMensajeError,
int minimo,
int maximo,
int reintentos);
int getInt( int *pResultado,
char *pMensaje,
char *pMensajeError,
int minimo,
int maximo,
int reintentos);
int main(void)
{
int edades[QTY_EDADES] = {100,200,300,400,500};
int cantidadUsuario;
initArrayInt(edades,QTY_EDADES,22);
cantidadUsuario = getArrayInt(edades,QTY_EDADES,"Edad?\n","Error\n",0,200,2);
printArrayInt(edades,cantidadUsuario);
return EXIT_SUCCESS;
}
int initArrayInt(int *pArray , int limite, int valor)
{
int retorno = -1;
int i;
if(pArray != NULL && limite > 0)
{
for(i=0;i<limite;i++)
{
pArray[i]=valor;
}
retorno = 0;
}
return retorno;
}
int printArrayInt(int *pArray , int limite)
{
int retorno = -1;
int i;
printf("\nDEBUG\n");
if(pArray != NULL && limite > 0)
{
for(i=0;i<limite;i++)
{
printf("\n\t%i",pArray[i]);
}
retorno = 0;
}
return retorno;
}
int getArrayInt( int *pArray,
int limite,
char *pMensaje,
char *pMensajeError,
int minimo,
int maximo,
int reintentos)
{
int retorno = -1;
int buffer;
int i=0;
char respuesta;
printf("\nDEBUG\n");
if(pArray != NULL && limite > 0)
{
do
{
if( getInt( &buffer,
pMensaje,
pMensajeError,
minimo,
maximo,
reintentos) == 0)
{
pArray[i] = buffer;
i++;
if(i == limite)
{
break;
}
}
printf("Continuar (s/n)? \n");
__fpurge(stdin); // fflush(stdin)
scanf("%c",&respuesta);
}while(respuesta != 'n');
retorno = i;
}
return retorno;
}
int getInt( int *pResultado,
char *pMensaje,
char *pMensajeError,
int minimo,
int maximo,
int reintentos)
{
int retorno = -1;
int buffer;
do
{
printf("%s",pMensaje);
__fpurge(stdin);
if(scanf("%d",&buffer)==1 && buffer >= minimo && buffer <= maximo)
{
*pResultado = buffer;
retorno = 0;
break;
}
printf("%s",pMensajeError);
reintentos--;
}while(reintentos >= 0);
return retorno;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int A,B,sum=0,i=0,num=0,rest=0,suma=0,opcion=0,c;
printf("Ingrese dos numeros:\n");
scanf("%d",&A);
scanf("%d",&B);
if (A<B)
{
printf("\nQuiere que se realice una multiplicacion? (Eliga un numero)\n\n");
printf("1: Si\n2: No\n\n\n");
scanf("%d",&opcion);
if(opcion=1)
{
for(c=1;c<=B;c++)
{
suma=A+suma;
}
printf("La multiplicacion de %d y %d es: %d",A,B,suma);
}
else
{
if(opcion=2)
{
return 1;
}
}
}
if (A>B || A==B)
{
printf("\nQuiere que se realice una multiplicacion o una division\n\n");
printf("1: Multiplicacion\n2: Division\n3: No quiero que se realice ninguna operacion\n\n\n");
scanf("%d",&opcion);
if(opcion==1)
{
for(c=1;c<=B;c++)
{
suma=A+suma;
}
printf("La multiplicacion de %d y %d es: %d",A,B,suma);
}
else
{
if(opcion==2)
{
while (num+B<=A)
{
num=B+num;
i++;
rest=A-num;
}
printf("\nEl resultado entre %d y %d es: %d\n",A,B,i);
printf("El resto de esta division es: %d",rest);
}
else
{
if(opcion==3)
{
return 2;
}
}
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/acct.h>
#include <unistd.h>
#include <fcntl.h>
#include "ssp.h"
#define ACCT_FILE "/var/adm/pacct"
static unsigned long compt2ulong (comp_t num);
int main (void)
{
int fd;
int n;
struct acct acct_data;
if ((fd = open (ACCT_FILE, O_RDONLY)) == -1)
err_msg ("Can't open %s", ACCT_FILE);
while ((n = read (fd, &acct_data, sizeof (struct acct))) != 0) {
if (n == -1)
err_msg ("read failed");
printf ("%-8s %c%c etime = %6ld, io = %8ld, stat = %3u\n",
acct_data.ac_comm, (acct_data.ac_flag & AFORK) ? 'F': ' ',
(acct_data.ac_flag & ASU) ? 'S' : ' ',
compt2ulong (acct_data.ac_etime), compt2ulong (acct_data.ac_io),
(unsigned char) acct_data.ac_stat);
}
return (0);
}
static unsigned long compt2ulong (comp_t num)
{
unsigned long val;
int exp;
val = num & 017777; /* 13-bit mantissa */
exp = (num >> 13) & 7; /* 3-bit exponent */
printf ("val = %lu, exp = %d\n", val, exp);
while (exp-- > 0)
val *= 8;
return (val);
}
|
C
|
#include "mylib.h"
int sum(int *array, int size){
/*********************************
* Sum the Contents of the Array *
*********************************/
int sum=0;
int index;
for(index=0;index<size;index++){
sum =sum + array[index];
}
return sum;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
struct ds2780_device_info {int dummy; } ;
typedef int s16 ;
/* Variables and functions */
int /*<<< orphan*/ DS2780_VOLT_MSB_REG ;
int ds2780_read16 (struct ds2780_device_info*,int*,int /*<<< orphan*/ ) ;
__attribute__((used)) static int ds2780_get_voltage(struct ds2780_device_info *dev_info,
int *voltage_uV)
{
int ret;
s16 voltage_raw;
/*
* The voltage value is located in 10 bits across the voltage MSB
* and LSB registers in two's compliment form
* Sign bit of the voltage value is in bit 7 of the voltage MSB register
* Bits 9 - 3 of the voltage value are in bits 6 - 0 of the
* voltage MSB register
* Bits 2 - 0 of the voltage value are in bits 7 - 5 of the
* voltage LSB register
*/
ret = ds2780_read16(dev_info, &voltage_raw,
DS2780_VOLT_MSB_REG);
if (ret < 0)
return ret;
/*
* DS2780 reports voltage in units of 4.88mV, but the battery class
* reports in units of uV, so convert by multiplying by 4880.
*/
*voltage_uV = (voltage_raw / 32) * 4880;
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int num;
printf("Enter a integer: ");
scanf_s("%d", &num);
if (num % 2 == 0)
printf("%d is even.\n", num);
else
printf("%d is odd.\n", num);
system("pause");
return 0;
}
|
C
|
#include "helper.h"
int mem_dump(uint8_t *src, int size)
{
int inc=0;
printf("memdump sz%d: \n", size);
while (inc < size) {
printf("%.2x ", *src & 0xff);
if (!((inc+1) % 16)) {
printf(" %d \n", inc+1);
}
inc++;
src++;
}
printf("\n");
return inc;
}
int readfile(char *filename, uint8_t **data)
{
int ret=0, len=0;
FILE *fin=0;
uint8_t *datain=0;
fin = fopen(filename, "r");
if (!fin) {
printf("file [%s] does not exist\n", filename);
return -1;
}
ret = fseek(fin, 0, SEEK_END);
if(ret) {
printf("input seek end failed ret: %d\n", ret);
fclose(fin);
return -2;
}
len = ftell(fin);
printf("file len of input file is %d \n", len);
datain = malloc(len);
if (!datain) {
printf("memory allocate failed size: %d \n", len);
fclose(fin);
return -3;
}
ret = fseek(fin, 0, SEEK_SET);
if(ret) {
printf("input seek begin failed ret: %d\n", ret);
fclose(fin);
return -4;
}
ret = fread(datain, 1, len, fin);
printf("file read size %d ret: %d \n", len, ret);
fclose(fin);
*data = datain;
return len;
}
int print2file(char *filename, struct data_linklist_s *max32list, int size, uint16_t *last32)
{
int ix=0, len=0, cnt=0, rst=0, base=0;
FILE *fout=0;
char str[128]={0};
struct data_linklist_s *tmplist=0;
cnt = size;
fout = fopen(filename, "w+");
if (!fout) {
printf("file [%s] can't open\n", filename);
return -1;
}
sprintf(str,"--Sorted Max 32 Values--\n");
len = strlen(str);
fwrite(str, 1, len, fout);
tmplist = max32list;
while (tmplist) {
sprintf(str, "%d\n", tmplist->spayload);
len = strlen(str);
fwrite(str, 1, len, fout);
tmplist = tmplist->next;
}
sprintf(str,"--Last 32 Values--\n");
len = strlen(str);
fwrite(str, 1, len, fout);
rst = cnt % 32;
if (cnt > 32) {
base = 32;
} else {
base = cnt;
}
for (ix=0; ix < base; ix++) {
sprintf(str,"%d\n", last32[(ix+rst)%base]);
len = strlen(str);
fwrite(str, 1, len, fout);
}
return 0;
}
|
C
|
#include <stdio.h>
void Cross(int size, char simbol) {
int x, y;
for(y = 0; y < size; y++) {
for(x = 0; x < size; x++) {
if(x == y || x == (size - y - 1))
printf("%c", simbol);
else
printf(" ");
}
printf("\n");
}
return;
}
void EmptyDiamond(int size, char simbol) {
int x, y;
for(y = 0; y < size; y++) {
for(x = 0; x < size; x++) {
if(x == size/2 - y || x == size/2 + y || x == y - size/2 || x == 1.5 *(size - size%2) - y)
printf("%c", simbol);
else
printf(" ");
}
printf("\n");
}
return;
}
void FilledDiamond(int size, char simbol) {
int x, y;
for(y = 0; y < size; y++) {
for(x = 0; x < size; x++) {
if(x >= size/2 - y && x <= size/2 + y && x >= y - size/2 && x <= 1.5 *(size - size%2) - y)
printf("%c", simbol);
}
printf("\n");
}
return;
}
typedef void (*funcForDrawing_t)(int, char);
int main(void) {
funcForDrawing_t funcForDrawing[3];
funcForDrawing[0] = Cross;
funcForDrawing[1] = EmptyDiamond;
funcForDrawing[2] = FilledDiamond;
int size, n;
char simbol;
printf("Enter simbol : ");
scanf("%c", &simbol);
printf("Chose your figure : \n");
printf("1) Cross\n2) Empty Diamond\n3) FilledDiamond\nEnter num : ");
scanf("%d", &n);
printf("Enter size : ");
scanf("%d", &size);
funcForDrawing[n-1](size, simbol);
return 0;
}
|
C
|
#include <stdio.h>
#define MAX 10000
int inpt(char s[], int lim);
void rmc(char s[], char cln[], int len);
int main () {
int len;
char str[MAX];
// Get input
len = inpt(str, MAX);
// Remove comments
char cln[len];
rmc(str, cln, len);
// Test
printf("\n-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-\n%s\n+-+-+-+-+-+-+-+-++-+-+-+-+-+-+-+\n", cln);
return 0;
}
int inpt (char s[], int lim) {
int c, p, in_str;
p = 0;
while ((c = getchar()) != EOF && p <= lim) {
s[p] = c;
++p;
}
s[p] = '\0';
return p;
}
void rmc(char s[], char cln[], int len) {
int p, i, state;
i = p = 0;
state = 1;
while (p <= len) {
if ((s[p] == '/' && s[p+1] == '/') || (s[p] == '/' && s[p+1] == '*'))
state = 0;
else if ( s[p] == '\n' && state == 0)
state = 1;
else if ( s[p] == '*' && s[p+1] == '/') {
state = 1;
p += 2;
}
if (state == 1) {
cln[i] = s[p];
++i;
}
++p;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.