language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include "defn.h"
#include "AM.h"
char empName[40];
char empAge[40];
char empSal[40];
char dnameAge[40];
void insertEntries(int fd, char * name, int recid) {
char errStr[140];
strcpy(errStr, "Error in AM_InsertEntry");
if (AM_InsertEntry(fd, name, &recid) != AME_OK) {
sprintf(errStr, "Error in AM_InsertEntry called on %s \n", empSal);
AM_PrintError(errStr);
printf("record id : %d\n", recid);
AM_CloseIndex(fd);
AM_DestroyIndex("TestDb3");
exit(0);
}
}
int main()
{
int scan1;
int eNentry;
int eAentry;
int eSentry;
int dAentry;
int eage;
float esal;
char edname[40];
empName[9] = '\0';
char fltname[40];
int recordid = 1;
char errStr[200];
int* ivalue = NULL;
char* cvalue = NULL;
AM_Init();
strcpy(empAge, "TestDb3");
if (AM_CreateIndex(empAge, STRING, sizeof(empName) - 1, INTEGER, sizeof(int)) != AME_OK) {
sprintf(errStr, "Error in AM_CreateIndex called on %s \n", empAge);
AM_PrintError(errStr);
return 1;
}
if ((eAentry = AM_OpenIndex(empAge)) < 0) {
sprintf(errStr, "Error in AM_OpenIndex called on %s \n", empAge);
AM_PrintError(errStr);
return 1;
}
srand(time(NULL));
int i, j;
recordid = 0;
int count = 0;
for (i = 1; i <= 100000; ++i) {
for (j = 0; j < 9; ++j) {
empName[j] = (char) abs(rand()%(122-97) + 97);
}
if(empName[0] == 'a')
count++;
insertEntries(eAentry, empName, ++recordid);
// printf("record id : %d\n", recordid);
}
strcpy(empName, "bla");
insertEntries(eAentry, empName, ++recordid);
printf("names starting with a : %d\n", count);
empName[0] = 'b';
empName[1] = '\0';
int scan = AM_OpenIndexScan(eAentry, LESS_THAN, empName);
i = 0;
while(AM_FindNextEntry(scan) != NULL)
i++;
printf("Names with less than b : %d\n", i);
AM_CloseIndexScan(scan);
empName[0] = 'b';
empName[1] = '\0';
scan = AM_OpenIndexScan(eAentry, GREATER_THAN, empName);
i = 0;
while(AM_FindNextEntry(scan) != NULL)
i++;
printf("Names with more than b : %d\n", i);
AM_CloseIndexScan(scan);
strcpy(empName, "bla");
scan = AM_OpenIndexScan(eAentry, EQUAL, empName);
i = 0;
int * kappa = NULL;
while((kappa = (int *) AM_FindNextEntry(scan) )!= NULL)
{
printf("%d\n", *kappa);
i++;
}
printf("Names equal with bla : %d\n", i);
AM_CloseIndexScan(scan);
printf("record id : %d\n", recordid);
AM_CloseIndex(eAentry);
AM_DestroyIndex(empAge);
return 0;
}
|
C
|
#pragma once
BENC_ENTITY_TYPE benc_entity_type(char* buf){
int i;
switch(buf[0]){
case 'd':
return T_DICT;
case 'l':
return T_LIST;
case 'i':
return T_INT;
default:
for(i=0;isdigit(buf[i]);i++){//there are dependencies on this
} //guaranteeing there is no \0 before ':' when returning T_STRING
if(buf[i]==':'&&i>0){
return T_STRING;
}
}
return T_FAIL;
}
int benc_list_item_offset(char* buf, int item){
int offset=0,cur_item=0;
if(item<0||benc_entity_type(buf)!=T_LIST){
return -1;
}
while(buf[offset+1]!='e'&&buf[offset+1]!=0){
if(cur_item==item){
return offset+1;
}
offset+=benc_entity_length(buf+offset+1,0);//FIXME errhandling
cur_item++;
}
return -1;
}
int benc_dict_value_offset(char* buf, char* key){
int offset=0,current_item=0;
if(!key||benc_entity_type(buf)!=T_DICT){
return -1;
}
while(buf[offset+1]!='e'&&buf[offset+1]!=0){
if(current_item%2==0){
//key
if(benc_entity_type(buf+offset+1)!=T_STRING){
return -1;
}
if(strlen(key)==benc_string_length(buf+offset+1)){
if(!strncmp(key,buf+offset+1+benc_string_data_offset(buf+offset+1),strlen(key))){
//find value entity
return offset+1+benc_entity_length(buf+offset+1,0);
}
}
}
offset+=benc_entity_length(buf+offset+1,0);
current_item++;
}
return -1;
}
int benc_dict_key_offset(char* buf, int index){
int offset=0,current_item=0;
if(index<0||benc_entity_type(buf)!=T_DICT){
return -1;
}
while(buf[offset+1]!='e'&&buf[offset+1]!=0){
if(current_item%2==0){
//key
if(benc_entity_type(buf+offset+1)!=T_STRING){
return -1;
}
if(current_item==index*2){
return offset+1;
}
}
offset+=benc_entity_length(buf+offset+1,0);
current_item++;
}
return -1;
}
int benc_int_value(char* buf, int defval){
int i;
if(benc_entity_type(buf)!=T_INT){
return defval;
}
i=0;
if(buf[i+1]=='-'){
i++;
}
for(;isdigit(buf[i+1]);i++){
}
if(i<=1||buf[i+1]!='e'){
return defval;
}
return strtol(buf+1,NULL,10);
}
int benc_string_length(char* buf){
if(benc_entity_type(buf)!=T_STRING){
return -1;
}
return strtoul(buf,NULL,10);
}
int benc_string_data_offset(char* buf){
int i;
if(benc_entity_type(buf)!=T_STRING){
return -1;
}
for(i=0;buf[i]!=':';i++){
}
return i+1;
}
int benc_entity_length(char* buf, int initial_offset){
int i,offset=0,item_length,item_index=0;
long conv;
switch(benc_entity_type(buf)){
case T_DICT:
BENC_PARSER_DEBUG(printf("Dictionary start @ %d\n",initial_offset));
while(buf[offset+1]!='e'&&buf[offset+1]!=0){
if(item_index%2==0&&benc_entity_type(buf+offset+1)!=T_STRING){
BENC_PARSER_DEBUG(printf("Invalid dict key type @ %d\n",initial_offset+offset+1));
return -1;
}
item_length=benc_entity_length(buf+offset+1,initial_offset+offset+1);
if(item_length==-1){
BENC_PARSER_DEBUG(printf("Inner dict element at %d failed to parse, cascading back\n",initial_offset+offset+1));
return -1;
}
offset+=item_length;
item_index++;
}
if(buf[offset+1]=='e'&&(item_index%2)==0){
BENC_PARSER_DEBUG(printf("Dictionary[%d] inner length was %d, end @ %d\n",initial_offset,offset,initial_offset+offset+1));
return offset+2;
}
else{
BENC_PARSER_DEBUG(printf("End of stream (%d) reached while parsing dictionary @ %d\n",initial_offset+offset+1,initial_offset));
return -1;
}
case T_LIST:
BENC_PARSER_DEBUG(printf("List start @ %d\n",initial_offset));
while(buf[offset+1]!='e'&&buf[offset+1]!=0){
item_length=benc_entity_length(buf+offset+1,initial_offset+offset+1);
if(item_length==-1){
BENC_PARSER_DEBUG(printf("List item @ %d was invalid\n",initial_offset+offset+1));
return -1;
}
offset+=item_length;
}
if(buf[offset+1]=='e'){
BENC_PARSER_DEBUG(printf("List[%d] inner length was %d, end at %d\n",initial_offset,offset,initial_offset+offset+1));
return offset+2;
}
else{
BENC_PARSER_DEBUG(printf("End of stream (%d) reached while parsing list @ %d\n",initial_offset+offset+1,initial_offset));
return -1;
}
case T_INT:
i=1;
if(buf[i]=='-'){
i++;
}
for(;isdigit(buf[i]);i++){
}
if(buf[i]=='e'){
BENC_PARSER_DEBUG(printf("Integer with length %d @ %d\n",i+1,initial_offset));
return i+1;
}
BENC_PARSER_DEBUG(printf("Integer @ %d not properly terminated\n",initial_offset));
break;
case T_STRING:
for(i=0;isdigit(buf[i]);i++){
}
if(buf[i]==':'&&i>0){
conv=strtol(buf,NULL,10);
BENC_PARSER_DEBUG(printf("String with length %d @ %d\n",i+conv+1,initial_offset));
return i+conv+1;
}
BENC_PARSER_DEBUG(printf("Unknown entity type (this should not have been reached)\n"));
break;
case T_FAIL:
//ignore
break;
}
BENC_PARSER_DEBUG(printf("Entity length calculation failed @ %d\n",initial_offset));
return -1;
}
|
C
|
//binary search
#include<stdio.h>
int bsearch(int arr[],int lower,int higher,int key)
{
int mid=lower+(higher-lower)/2;
if(arr[mid]==key) return mid;
if(arr[mid]>key) return bsearch(arr,lower,mid-1,key);
else return bsearch(arr,mid+1,higher,key);
}
int main()
{
int n,key;
printf("Enter element value:-");
scanf("%d",&n);
int i,arr[n];
printf("Enter array element");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
printf("Enter key search in array:-");
scanf("%d",&key);
int index=bsearch(arr,0,n-1,key);
printf("%d",index);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include<time.h>
void cria_triangulacao (float *vetor, int i, int f){
int auxiliar = vetor[i]; // definindo vetor auxiliar como a primeira posição do vetor (posição inicial)
int j = i * 2 + 1; // primeiro ramo
while(j <= f){ // enquanto o valor final for maior ou iagual ao primeiro ramo
if(j<f){ // quando o primeiro ramo form menor que o valor final
if(vetor[j] < vetor[j+1]){ // o primeiro ramo tem mais dois ramos ? qual o meior ?
j = j+1;
}
}
if(auxiliar < vetor[j]){ // ramo secundário maior que o ramo prioncipal ?
vetor[i] = vetor[j]; // então o ramo secundário se torna o ramo principal
i = j; // (...)
j= 2*i+1; // Repetir o processo
}else{
j= f +1;
}
}
vetor[i] = auxiliar; // antigo ramo principal ocupa o lugar do último ramo analizado
}
void triangular (float *vetor, int n){
int i, auxiliar;
for(i= (n-1)/2; i>=0; i--){
cria_triangulacao(vetor, i, n-1);
}
for(i = n-1; i>=1; i--){
auxiliar = vetor[0]; // Pegar o maior elemento
vetor[0]= vetor[i] ; // e colar na sua devida posição
vetor[i] = auxiliar; // no vetor
cria_triangulacao(vetor, 0, i-1); // Refazendo a triangulação
}
}
int main() {
int i,n; //vairáveis da alocação de vetores
float *x, (*ordena_ai)();
ordena_ai = triangular;
clock_t Ticks[2];
Ticks[0] = clock();
printf("Digite aqui o valor que desejas para n:"); // Interação com usuário para descobrir o tamano do vetor desejado
scanf("%d", &n);
x = malloc(n * sizeof(float)); //alocando vetor
for (i = 0; i < n; i++) { //Processo de inserção dos valores que desejam ser alocados
printf("Digite o valor de numero %d\n",i+1);
scanf("%f", &x[i]);
}
for (i = 0; i < n; i++) { // Impressão na tela do vetor em seu estado original
printf("[%.1f] ",x[i]);
}
printf("\n");// apenas para estética de apresentação
ordena_ai(x,n);
for (i=0; i<n; i++){
printf ("[%.1f] ", x[i]);
}
free(x);
Ticks[1] = clock();
double Tempo = (Ticks[1] - Ticks[0]) * 1000.0 / CLOCKS_PER_SEC;
printf("\nTempo gasto: %g ms.", Tempo);
getchar();
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#define BUF_LEN 50
int func() __attribute__ ((noinline));
void parse(int* ) __attribute__ ((noinline));
int compare(int*, int*) __attribute__ ((noinline));
void parse(int* p) {
int a = 0x11111;
printf("unused a = %d", a);
*p = 123456;
}
int compare(int* p1, int* p2) {
return *p1 < *p2;
}
int func(int* input) {
int ret = 0, a, b;
a = *input;
parse(&b);
if (compare(&a, &b)) {
ret = 1;
}
out:
return ret;
}
int main(int argc, char* argv[])
{
int input;
FILE *file = fopen(argv[1], "r");
if (file != NULL) {
fscanf(file, "%d", &input);
fclose(file);
}
printf("Input address: %p\n", &input);
int ret = func(&input);
if (ret == 1) {
printf("Yes!\n");
} else {
printf("No!\n");
}
return 0;
}
|
C
|
#include <stdio.h>
int main() {
int i,N,num, check, count=0;
scanf("%d", &N);
while (N--)
{
check = 0;
scanf("%d", &num);
if (num == 1) {
check = 1;
}
for (i = 2; i*i <= num; i++) {
if (num%i == 0) {
check = 1;
break;
}
}
if (check == 0)
count++;
}
printf("%d", count);
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int f(int n)
{
if (n > 1)
{
return n * f(n - 1);
}
return 1;
}
int fa(int n)
{
int m = 1;
while (n > 1)
{
m = m * n;
n--;
}
return m;
}
int main()
{
int n = 0;
int a;
printf("Ҫ֣");
scanf("%d", &n);
a = f(n);
printf("%d\n", a);
a = fa(n);
printf("%d\n", a);
return 0;
}
|
C
|
/* K4-7̉ */
#include <stdio.h>
/*--- ̕s1s2 ---*/
void swap_str(char s1[], char s2[])
{
char *temp;
while (*s1 && *s2) { /* Zق̖܂ŕ */
char t = *s1; *s1++ = *s2; *s2++ = t;
}
if (*s1) { /* s1̂ق */
temp = s1;
while (*s1) { *s2++ = *s1++; } /* s1̎cs2ɃRs[ */
*temp = *s2 = '\0';
} else if (*s2) { /* s2̂ق */
temp = s2;
while (*s2) { *s1++ = *s2++; } /* s2̎cs1ɃRs[ */
*temp = *s1 = '\0';
} else {
*s1 = *s2 = '\0';
}
}
int main(void)
{
char s1[80], s2[80];
printf("S1F"); scanf("%s", s1);
printf("S2F"); scanf("%s", s2);
swap_str(s1, s2); /* s1s2 */
printf("̕܂B\n");
printf("S1F%s\n", s1);
printf("S2F%s\n", s2);
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <string.h>
#include "matrix.h"
void benchmark_mul(int n, int repeats) {
double *a = random_matrix(n);
double *b = random_matrix(n);
double *res = alloc_matrix(n);
clock_t start, end;
int i;
double basic = 0.0;
if(n < 1000) {
start = clock();
for(i = 0; i < repeats; ++i) {
matrix_mul_basic(res, a, b, n);
}
end = clock();
basic = (double)(end - start) / CLOCKS_PER_SEC / (double)repeats;
}
start = clock();
for(i = 0; i < repeats; ++i) {
matrix_mul_transposed(res, a, b, n);
}
end = clock();
double transposed = (double)(end - start) / CLOCKS_PER_SEC / (double)repeats;
start = clock();
for(i = 0; i < repeats; ++i) {
matrix_mul_blocked(res, a, b, n, 128);
}
end = clock();
double blocked = (double)(end - start) / CLOCKS_PER_SEC / (double)repeats;
printf("%d basic: %.5lf, transposed: %.5lf, blocked: %.5lf\n", n, basic, transposed, blocked);
free(a);
free(b);
free(res);
}
int main(int argc, char**argv) {
int size_inc = 100;
int reps = 10;
int i;
for(i = 1; i < 21; ++i) {
benchmark_mul(i * size_inc, reps);
}
return 0;
}
|
C
|
#ifndef _ALFA_H
#define _ALFA_H
#define MAX_LONG_ID 100
#define MAX_TAMANIO_VECTOR 64
#define TRUE 1
#define FALSE 0
#define ERROR -1
#define MAX_VAR 200 /* Numero maximo de variables que puede tener un programa */
/* Categorias */
#define VARIABLE 0
#define PARAMETRO 1
#define FUNCION 2
/* Tipos */
#define INT 0
#define BOOLEAN 1
/* Clases */
#define ESCALAR 0
#define VECTOR 1
typedef struct {
char lexema[MAX_LONG_ID+1]; /* guarda el lexema de los identificadores */
int tipo; /* tipo de una expresion */
int valor_entero; /* valor entero */
int es_direccion; /* indica si un simbolo es una dirección de memoria o es un valor constante */
int etiqueta; /* necesario gestion de sentencias condicionales e iterativas */
} tipo_atributos;
#endif
|
C
|
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
int conversion = atoi(argv[1]);
printf("Number of blocks to be passed to malloc(): %i\n", conversion);
printf("Passing blocks to malloc().\n");
int counter = 0;
sleep(3);
while (counter < conversion)
{
char* pointer = malloc(1024);
printf("Blocks passed to malloc(): %p\n", pointer);
if (counter % 2 == 0)
{
free(pointer);
}
counter++;
}
sleep(3);
printf("Allocation complete, program terminated.\n");
return 0;
}
/*
The program does indeed reallocate the memory that was released by calling free(). Whenever a block of memory was released to the operating system, it was used as the address returned from malloc().
*/
|
C
|
#include "construct.h"
#include <stdlib.h>
int balance(int t[], int l, int r) {
long long mtot = 0, rxm = 0;
for ( int i = l, j = 0; i <= r; i++, j++) {
mtot += t[i];
rxm += t[i] * j;
}
if ( rxm % mtot == 0 )
return l + rxm / mtot;
return -1;
}
Node *new_node(int value) {
Node *ret = (Node *)malloc(sizeof(Node));
ret->value = value;
ret->left = ret->right = NULL;
return ret;
}
Node *link(int t[], int l, int r) {
Node *ret = new_node(t[r]), *tail = ret;
for ( int i = r - 1; i >= l; i--)
tail = tail->left = new_node(t[i]);
return ret;
}
Node *build(int t[], int l, int r, int N) {
if ( l > r )
return NULL;
if ( r - l + 1 < 3 )
return link(t, l, r);
int bp = balance(t, l, r);
if ( bp < 0 )
return link(t, l, r);
Node *ret = new_node(t[bp]);
ret->left = build(t, l, bp - 1, N);
ret->right = build(t, bp + 1, r, N);
return ret;
}
Node *ConstructTree(int T[], int N) {
return build(T, 0, N - 1, N);
}
|
C
|
/*ANGELA GABRIELA PESINA DE LOS SANTOS - 1947576
RESTAURANT MENU */
//library
#include <stdio.h>
#include <stdlib.h>
#include "res.h"
//principal function
int main (){
int op, rep;
do { //open do
printf("\t\t***WELCOME TO FIME-STAURANT***\n");
printf("-----------------------------------------------\n");
printf("\tChoose an option: (only numbers)\n ");
//principal menu
printf("\t1. Customer order. \n");
printf("\t2. Employee options. \n");
printf("-----------------------------------------------\n");
scanf("%i", &op);
if(op==1){ //open if
custo_order();
} //close if
else {
if(op==2) {//open 2 if
em_options();
} //close 2 if
else {
printf("TRY AGAIN\nOnly accepts numbers from 1 to 2\n");
}
}
printf("\n\nRETURN TO THE PRINCIPAL MENU\n 1. YES, 2. NO\n");
scanf("%i", &rep);
} //close do
while (rep == 1);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////CUSTOMER ORDER SECTION //////////////////////////////////////////////////////////////////////////////////////////
void custo_order(){
int op, repetir;
do { //open do
printf("\t\t***WELCOME TO THE CUSTOMER ORDER SECTION***\n ");
printf("-----------------------------------------------\n");
printf("\tChoose an option: (only numbers)\n");
printf("\t1. Breakfast menu.\n");
printf("\t2. Lunch menu.\n");
printf("\t3. Dinner menu.\n");
printf("\t4. Drinks menu.\n");
printf("\t5. Delivery options.\n");
printf("\t6. Generate final ticket.\n");
printf("\t7. Give your opinion about the restaurant.\n");
printf("-----------------------------------------------\n");
scanf("%i", &op);
//CUSTOMER OPTIONS
switch(op){
case 1:
b_menu();
break;
case 2:
l_menu();
break;
case 3:
di_menu();
break;
case 4:
d_menu();
break;
case 5:
deli_menu();
break;
case 6:
ticket();
break;
case 7:
opinion();
break;
default:
printf("\n\nTry again\nOnly accepts numbers from 1 to 6\n");
break;
}
printf("\n\n\nRETURN TO THE CUSTOMER OPTIONS\n 1. YES, 2. NO\n");
scanf("%i", &repetir);
}//close do
while (repetir == 1);
return;
}
//BREAKFAST MENU
void b_menu(){
int bmen, bplatos;
bpago = 0;
printf("\t\t***WELCOME TO THE BREAKFAST MENU***\n");
printf("-----------------------------------------------\n");
printf("\tThis is the menu: \n");
printf("\t1. Eggs (2) with bacon \t $120\n");
printf("\t2. French toasts (2) \t $100\n");
printf("\t3. Pancakes (4) \t $110\n");
printf("-----------------------------------------------\n");
printf("Which one would you like to eat?\n");
scanf("%i", &bmen);
printf("How many orders wold you like to have?\n");
scanf("%i", &bplatos);
switch(bmen) {
case 1:
printf("\n\nYou order: Eggs with bacon\n");
bpago = bplatos * 120;
break;
case 2:
printf("\n\nYou order: French toasts\n");
bpago = bplatos * 100;
break;
case 3:
printf("\n\nYou order: Pancakes\n");
bpago = bplatos * 110;
break;
default:
printf("\n\nTry again\nOnly accepts numbers from 1 to 3\n");
}
printf("Your payment for breakfast is: $%i\n", bpago);
printf("\n\n\t***If you finish your order go to the delivery section\n\tin the customer options, if you don't keep buying in customer options'***\n");
}
//LUNCH MENU
void l_menu(){
int lmen, lplatos;
lpago = 0;
printf("\t\t***WELCOME TO THE LUNCH MENU***\n");
printf("-----------------------------------------------\n");
printf("\tThis is the menu: \n");
printf("\t1. Pizza \t\t $200\n");
printf("\t2. Cheese sandwich \t $100\n");
printf("\t3. House salad \t $150\n");
printf("-----------------------------------------------\n");
printf("Which one would you like to eat?\n");
scanf("%i", &lmen);
printf("How many orders wold you like to have?\n");
scanf("%i", &lplatos);
switch(lmen) {
case 1:
printf("\n\nYou order: pizza\n");
lpago = lplatos * 200;
break;
case 2:
printf("\n\nYou order: Cheese sandwich\n");
lpago = lplatos * 100;
break;
case 3:
printf("\n\nYou order: House salad \n");
lpago = lplatos * 150;
break;
default:
printf("\n\nTry again\nOnly accepts numbers from 1 to 3\n");
}
printf("Your payment for lunch is: $%i\n", lpago);
printf("\n\n\t***If you finish your order go to the delivery section\n\tin the custuomer options, if you don't keep buying in customer options'***\n");
}
//DINNER MENU
void di_menu(){
int dimen, diplatos;
dipago = 0;
printf("\t\t***WELCOME TO THE DINNER MENU***\n");
printf("-----------------------------------------------\n");
printf("\tThis is the menu: \n");
printf("\t1. Hamburger \t\t $110\n");
printf("\t2. Tacos (5) \t\t $100\n");
printf("\t3. Buffalo Wings (12) \t $110\n");
printf("-----------------------------------------------\n");
printf("Which one would you like to eat?\n");
scanf("%i", &dimen);
printf("How many orders wold you like to have?\n");
scanf("%i", &diplatos);
switch(dimen) {
case 1:
printf("\n\nYou order: hamburger\n");
dipago = diplatos * 100;
break;
case 2:
printf("\n\nYou order: Tacos\n");
dipago = diplatos * 100;
break;
case 3:
printf("\n\nYou order: Buffalo Wings \n");
dipago = diplatos * 110;
break;
default:
printf("\n\nTry again\nOnly accepts numbers from 1 to 3\n");
}
printf("Your payment for dinner is: $%i\n", dipago);
printf("\n\n\t***If you finish your order go to the delivery section\n\tin the custuomer options, if you don't keep buying in customer options'***\n");
}
//DRINKS MENU
void d_menu(){
int dmen, dplatos;
dpago = 0;
printf("\t\t***WELCOME TO THE DRINKS MENU***\n");
printf("-----------------------------------------------\n");
printf("\tThis is the menu: \n");
printf("\t1. Limonade \t\t $70\n");
printf("\t2. Coke \t\t $60\n");
printf("\t3. Water \t\t $30\n");
printf("-----------------------------------------------\n");
printf("Which one would you like to eat?\n");
scanf("%i", &dmen);
printf("How many orders wold you like to have?\n");
scanf("%i", &dplatos);
switch(dmen) {
case 1:
printf("\n\nYou order: Limonade\n");
dpago = dplatos * 70;
break;
case 2:
printf("\n\nYou order: Coke\n");
dpago = dplatos * 60;
break;
case 3:
printf("\n\nYou order: Water \n");
dpago = dplatos * 30;
break;
default:
printf("\n\nTry again\nOnly accepts numbers from 1 to 3\n");
}
printf("Your payment for drinks is: $%i\n", dpago);
printf("\n\n\t***If you finish your order go to the delivery section\n\tin the custuomer options, if you don't keep buying in customer options'***\n");
}
//DELIVERY MENU
void deli_menu(){
int delimen;
delipago = 0;
printf("\t\t***WELCOME TO THE DELIVERY***\n");
printf("-----------------------------------------------\n");
printf("\tChoose your zone to calculate the delivery price: \n");
printf("\t1. Eat in the restaurant \t$0\n");
printf("\t2. San Nicolas\t\t\t$30\n");
printf("\t3. Escobedo \t\t\t$40\n");
printf("\t4. Santa Catarina \t\t$60\n");
printf("\t5. Apodaca \t\t\t$45\n");
printf("\t6. San Pedro \t\t\t$70\n");
printf("-----------------------------------------------\n");
printf("Select your option\n");
scanf("%i", &delimen);
switch(delimen) {
case 1:
printf("You are going to eat in the restaurant\n");
delipago = 0;
break;
case 2:
printf("Your zone is: San Nicolas \n");
delipago = 30;
break;
case 3:
printf("Your zone is: Escobedo \n");
delipago = 40;
break;
case 4:
printf("Your zone is: Santa Catarina \n");
delipago = 60;
break;
case 5:
printf("Your zone is: Apodaca \n");
delipago = 45;
break;
case 6:
printf("Your zone is: San Pedro \n");
delipago = 70;
break;
default:
printf("\n\nTry again\nOnly accepts numbers from 1 to 6\n");
}
printf("Your payment for delivery is: $%i\n", delipago);
printf("\n\n\t***If you finish your order go to the ticket section in customer options \n");
}
//TICKET MENU
void ticket(){
pagototal = bpago + lpago + dipago + dpago + delipago;
printf("\t\t***YOUR FINAL TICKET IS: ***\n");
printf("-----------------------------------------------\n");
printf("Breakfast menu---------------------$%i\n", bpago);
printf("Lunch muenu------------------------$%i\n", lpago);
printf("Dinner menu------------------------$%i\n", dipago);
printf("Drinks menu------------------------$%i\n", dpago);
printf("Delivery---------------------------$%i\n", delipago);
printf("Total:-----------------------$%i\n", pagototal);
return;
}
//OPINION MENU
void opinion() {
FILE *pf;
int r;
char op[500];
if((pf = fopen("opinion.txt", "w")) != NULL) {
printf("\t***Welcome to the opinion section, This section is completely anonymous, write your opinion about the restaurant and its service***\n\n\n ");
printf("Would you like to give your opinion about the restaurant?\n 1. YES, 2. NO\n\n\n");
scanf("%i", &r);
if (r == 1){
fflush(stdin);
printf("Write your opinion: \n\n");
gets(op);
fputs(op, pf);
}
fclose(pf);
printf("\n\n\tSuccessfully created!\n\n");
}
else {
printf("\n TRY AGAIN LATER\n\n");
}
return;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////EMPLOYEE OPTIONS SECTION //////////////////////////////////////////////////////////////////////////////////////////
void em_options(){
int op, repetir;
do { //open do
printf("\t\t***WELCOME TO THE EMPLOYEE OPTIONS***\n ");
printf("-----------------------------------------------\n");
printf("\tChoose an option: (only numbers)\n");
printf("\t1. Check my salary.\n");
printf("\t2. Review employee discounts.\n");
printf("-----------------------------------------------\n");
scanf("%i", &op);
//EMPLOYEE OPTIONS
switch(op){
case 1:
salary();
break;
case 2:
em_disco();
break;
default:
printf("\n\nTry again\nOnly accepts numbers from 1 to 2\n");
break;
}
printf("\n\n\nRETURN TO THE EMPLOYEE OPTIONS\n 1. YES, 2. NO\n");
scanf("%i", &repetir);
}//close do
while (repetir == 1);
return;
}
//SALARY SECTION
void salary(){
int op, hor;
float sal, pago;
printf("\t\t***SALARY***\n ");
printf("-----------------------------------------------\n");
printf("\tSelect your workstation : (only numbers)\n");
printf("\t1. Cashier.\n");
printf("\t2. Chef.\n");
printf("\t3. Waiter.\n");
printf("\t4. Janitor.\n");
printf("-----------------------------------------------\n");
scanf("%i", &op);
printf("\n\tYou have to answer a few questions to calculate your week salary.\n\n");
printf("How many hours have you worked in the week: \n");
scanf("%i", &hor);
//start calculating the salary
switch(op){
case 1:
sal = 21.40;
pago = hor * sal;
break;
case 2:
sal = 24.5;
pago = hor * sal;
break;
case 3:
sal= 20.50;
pago= hor * sal;
break;
case 4:
sal = 17.30;
pago = hor * sal;
break;
default:
printf("\n\nTry again\nOnly accepts numbers from 1 to 2\n");
break;
}
printf("Your hourly pay is: %.2f\n", sal);
printf("Your worked: %i", hor);
printf(" hours \n");
printf("\t Your total payment is: %.2f\n\n", pago );
}
//DISCOUNTS
void em_disco() {
float mon;
printf("\t\t***EMPLOYEE DISCOUNTS***\n ");
printf("-----------------------------------------------\n\n\n\n");
printf("How many time have you been working in the restaurant? (in months) ");
scanf("%f", &mon);
if(mon>=1 && mon<6){
printf("You can have free delivery to to all available areas once a year,\n Keep working hard!\n\n\n");
} else {
if(mon>=6 && mon<12){
printf("You can have one free meal once a year (including the drink),\n Keep working hard!\n\n\n");
}
else {
printf("You can haave free delivery to to all available areas and a free meal twice a year,\n Keep working hard!\n\n\n");
}
}
}
|
C
|
#ifndef _UTILITIES_H
#define _UTILITIES_H
// Needed to sort array of points according to X coordinate.
int compare_x(const void *a, const void *b);
// Needed to sort array of points according to Y coordinate.
int compare_y(const void* a, const void* b);
// A utility function to find the distance between two points.
double dist(struct Point p1, struct Point p2);
/*
* Brute Force method to find minimal distance between two points in an
* array p of size n.
*/
double brute_force(struct Point *p, int n);
// Return smallest of two double values
double min(double x, double y);
/*
* Find the distance between the closest points of array strip of size d.
* All points in array strip are sorted according to y coordinate. They all
* have an upper bound on minimum distance as d. Note that this method
* seems to be a O(n^2) method, but it's a O(n) method as the inner loop
* runs at most 6 times.
*/
double strip_closest(struct Point *strip, int size, double d);
/*
* Return the total number of points stored in the specified file.
*/
int total_points(char *f_name);
/*
* Return all input points from the specified file and populate *n with the
* number of points read.
*/
void read_points(char *f_name, struct Point *points_arr);
#endif /* _UTILITIES_H */
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* rgb.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jbaringo <jbaringo@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/09/14 19:49:06 by jbaringo #+# #+# */
/* Updated: 2021/10/27 18:38:12 by jbaringo ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/fdf.h"
int rgb_progressive(int i, int initial_c, int final_c, int n)
{
if (n > 0)
return (initial_c + (i * (final_c - initial_c) / n));
return (0);
}
int choose_color(float z, float z1, unsigned int *color, t_all *all)
{
if (all->color == 0 && *color == 0)
*color = 0x7CFF00;
if (all->color != 0)
*color = 0xFFFFFF;
if (all->color > 0)
{
if (z > 0 && z1 > 0)
*color = 0xFF0000;
else if (z < 0 && z1 <= 0)
*color = 0x00FF00;
if (z > z1 && z1 == 0)
return (2);
if (z1 > z && z == 0)
return (3);
if (z > z1 && z == 0 && z1 < 0)
return (4);
if (z1 > z && z1 == 0 && z < 0)
return (5);
if (z > 0 && z1 < 0)
return (6);
if (z < 0 && z1 > 0)
return (7);
return (1);
}
return (all->color);
}
unsigned int get_color(int i, int n, t_all *all)
{
if (all->color == 2)
return (65536 * rgb_progressive(i, 255, 0, n) + 256 * \
rgb_progressive(i, 0, 0, n) + rgb_progressive(i, 0, 255, n));
else if (all->color == 3)
return (65536 * rgb_progressive(i, 0, 255, n) + 256 * \
rgb_progressive(i, 0, 0, n) + rgb_progressive(i, 255, 0, n));
else if (all->color == 4)
return (65536 * rgb_progressive(i, 0, 0, n) + 256 * \
rgb_progressive(i, 0, 255, n) + rgb_progressive(i, 255, 0, n));
else if (all->color == 5)
return (65536 * rgb_progressive(i, 0, 0, n) + 256 * \
rgb_progressive(i, 255, 0, n) + rgb_progressive(i, 0, 255, n));
else if (all->color == 6 && i <= (n / 2))
return (65536 * rgb_progressive(i, 255, 0, n / 2) + 256 * \
rgb_progressive(i, 0, 0, n / 2) + rgb_progressive(i, 0, 255, n / 2));
else if (all->color == 6 && i >= (n / 2))
return (65536 * rgb_progressive(i, 0, 0, n / 2) + 256 * \
rgb_progressive(i, 0, 255, n / 2) + rgb_progressive(i, 255, 0, n / 2));
else if (all->color == 7 && i <= (n / 2))
return (65536 * rgb_progressive(i, 0, 0, n / 2) + 256 * \
rgb_progressive(i, 255, 0, n / 2) + rgb_progressive(i, 0, 255, n / 2));
else if (all->color == 7 && i >= (n / 2))
return (65536 * rgb_progressive(i, 0, 255, n) + 256 * \
rgb_progressive(i, 0, 0, n) + rgb_progressive(i, 255, 0, n));
return (0);
}
|
C
|
//The code format should be as below. Excessive commenting and documentations is encouraged as this
//project is multi-year. In the future a new group of students will need to pick this project up as
//quickly as possible.
//***PLEASE NOTE*** the Max line width should be 100 characters. In most IDEs you can set up a guide
//line to help you conform to this.
/*
* formatting.c
*
* Author : Adam Parlane (adam.parlane@outlook.com) Github: AdamParlane
* Created: 15/04/2017 3:31:20 PM
*
* Project Repository: https://github.com/wittsend/aut-swarm-robotics
*
* SPI driver for optical mouse sensor ADNS-7530 used for navigation
* in the 2017 swarm robotics project for Mark Beckerleg, AUT
*
* Functions:
* int functionName(char paramOne, int paramTwo, unsigned int paramThree)
* void registerAccess(void)
*
*/
//\/ \/ \/ \/Template file header\/ \/ \/ \/
/*
* filename.c/h
*
* Author : name (email)
* Created: time date
*
* Project Repository: https://github.com/wittsend/aut-swarm-robotics
*
* 1 or 2 liner on the purpose of the file
*
* More Info:
* Atmel SAM 4N Processor Datasheet:http://www.atmel.com/Images/Atmel-11158-32-bit%20Cortex-M4-Microcontroller-SAM4N16-SAM4N8_Datasheet.pdf
* Relevant reference materials or datasheets if applicable
*
* Functions:
* void funcName(void)
*
*/
//////////////[Includes]////////////////////////////////////////////////////////////////////////////
#include <libHeader1>
//////////////[Defines]/////////////////////////////////////////////////////////////////////////////
//Tabs keep values in line and easy to read
#define macroOne (REG_PIOB_CODR |= (1<<12)) //Macros camelCase because they are executing code
#define macroTwo (REG_PIOB_SODR |= (1<<12))
//Constant values should be decimal or hex form. Not binary.
//Values can be converted with programmer mode in windows calculator quite easily.
#define CONST_ONE 0x00 //Constants use CAPS_UNDERSCORE_SPACE_FORMAT
//////////////[Functions]///////////////////////////////////////////////////////////////////////////
/*
* Function:
* [function declaration]
*
* [brief purpose of function]
*
* Inputs:
* [input arguments and any relevant explanation]
*
* Returns:
* [return values and any relevant explanation]
*
* Implementation:
* [explain key steps of function]
* [use heavy detail for anything complicated]
* Template c file function header. H file function header will be the same without the
* implementation/improvement section
*
* Improvements:
* [Ideas for improvements that are yet to be made](optional)
*
*/
/*
* Function:
* int functionName(char paramOne, int paramTwo, unsigned int paramThree)
*
* Details code style for robot C code. Function names in camelCase.
*
* Inputs:
* paramOne does this, paramTwo does that and paramThree does the other.
*
* Returns:
* always returns 1
*
* Implementation:
* States variable definitions, and switch statement structure.
*
* Improvements:
* no doubt there will be. Hit us up (Adam or Matt)
*/
int functionName(char paramOne, int paramTwo, unsigned int paramThree)
{
//Single spacing. Every variable should have its own definition. Variable names use camelCase.
unsigned char varOne = 1;
int varTwo = 0;
unsigned int varThree = 100;
//Switch statement example
switch state
{
case 1
//Code here
break:
case 2
//Code here
break;
}
return varOne;
}
/*
* Function:
* void registerAccess(void)
*
* Format for writing to registers. Use macros where ever possible to increase
* readability
*
* Inputs:
* none
*
* Returns:
* none
*
* Implementation:
* Outlines code structure for manipulating system registers with macros
*
* Improvements:
* no doubt there will be. Hit us up (Adam or Matt)
*/
void registerAccess(void)
{
//Register names begin with REG. The second part is the peripheral and the third is the name
//of the specific register being accessed (separated by underscores).
//Register name is on the first line, then subsequent bitfields being set are on following lines.
//Tabs are used to space things out evenly to keep them neat and readable.
REG_PMC_PCER0
|= (1<<ID_TWI1); //Sometimes there isn't a macro for a bit field
//Bit field macros are as follows: The first part of the name is the peripheral catergory.
//The second part is the register name, and the last part is the bitfield within that register.
REG_TWI1_CWGR
|= TWI_CWGR_CLDIV(126) //Atmel studio has macros that allow numbers to be written
| TWI_CWGR_CHDIV(56) //to specific bitfields within registers
| TWI_CWGR_CKDIV(0);
REG_TWI1_CR
= TWI_CR_MSEN //These will turn specific bits on and off
| TWI_CR_SVDIS;
//Inline comments kept straight in a row with tabs
//By keeping them in line they become easier to read
}
|
C
|
#include<stdio.h>
#define max(a,b) (a>b)?a:b
void knapsack(int m,int n,int w[],int p[])
{
int v[100][200],x[10],i,j,sum=0;
for(i=0;i<=n;i++)
v[i][0]=0;//first column all elements=0
for(j=0;j<=m;j++)
v[0][j]=0;//first row all elements=0
/*Here, we assume all the given item weights are always lesser than the max capacity of the sack, and therefore j (along knapsack capacity)
can be subtracted with w[i] ie. j-w[i]
We dont have to subtract and compare for each step. Only when a new item can be accomodated (ie. when the current leftover capacity can fit
w[i])*/
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
if(j>=w[i])
v[i][j]=max(v[i-1][j],v[i-1][j-w[i]]+p[i]);
else
v[i][j]=v[i-1][j];
for(i=1;i<=n;i++)
x[i]=0;
//x[] is a binary array to store if the item will be taken or not (0->not taken, 1->taken)
i=n;
j=m;
while(i>0 && j>0)
{
if(v[i][j]!=v[i-1][j])
{
x[i]=1;//taken, because the previous value isn't carried over
j=j-w[i];//subtract the weight of current item from capacity.
}
i--;
}
printf("\n The optimal set of items are :\n");
for(i=1;i<=n;i++)
{
if(x[i]==1)
{
printf("%d \t ",i);
sum=sum+p[i];//add all sums to print the net profit
}
}
printf("\n Total profit is %d",sum);
}
int main()
{
int w[10],p[10],m,n,j,i;
printf("Enter the number of items:");
scanf("%d",&n);//n = no. of items
printf("Enter the weights of the items:\n ");
for(i=1;i<=n;i++)
scanf("%d",&w[i]);//w[] = weights
printf("Enter profit of items: \n");
for(i=1;i<=n;i++)
scanf("%d",&p[i]);//p[] = profits of individual items
printf("Enter capacity: \n");
scanf("%d",&m);//m = capacity
knapsack(m,n,w,p);
return 0;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void my_fprintf(char *path)
{
FILE *fp = NULL;
//дʽ
fp = fopen(path, "w+");
if (fp == NULL)
{
perror("my_fprintf fopen");
return;
}
//printf("hello, i am pig, mike = %d\n", 250);
//fprintf(stdout, "hello, i am pig, mike = %d\n", 250);
fprintf(fp, "%d %d %d\n", 1, 2, 3);
if (fp != NULL)
{
fclose(fp);
fp = NULL;
}
}
void my_fscanf(char *path)
{
FILE *fp = NULL;
//дʽ
fp = fopen(path, "r+");
if (fp == NULL)
{
perror("my_fprintf fopen");
return;
}
//printf("hello, i am pig, mike = %d\n", 250);
//fprintf(stdout, "hello, i am pig, mike = %d\n", 250);
int a = 0;
int b = 0;
int c = 0;
fscanf(fp, "%d %d %d\n", &a, &b,&c);
printf("a = %d, b = %d, c = %d\n", a, b, c);
if (fp != NULL)
{
fclose(fp);
fp = NULL;
}
}
int main(void)
{
my_fprintf("../06.txt");
my_fscanf("../06.txt");
printf("\n");
system("pause");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("%-10d\n", 10000);//false
printf("%c\n", "This is a string");//false
printf("%*.*lf\n", 8, 3, 1024.987654);//true
printf("% ld\n%+ld\n", 1000000, 1000000);//true
printf("%10.2E\n", 444.93738);//true
printf("%d\n", 10.987);//false
}
|
C
|
#include <stdio.h>
#include "sorting.h"
#include <stdlib.h>
int main()
{
FILE *file = fopen("/Users/alexandrasyabrenko/Documents/Programming/Lab2/Lab2/test.txt", "r");
int arrayLength = getSymbolsAmout(file);
char *array = getFromFileToArray(file);
printf("Unsorted array: \n");
printArrayToScreen(array, arrayLength);
printf("Choose sorting algorithm:\n 1 - bubble\n 2 - selection sort\n 3 - inserting sort\nEnter here: ");
int numberOfAlgorithm = 0;
scanf("%d", &numberOfAlgorithm);
while(numberOfAlgorithm != 1 && numberOfAlgorithm != 2 && numberOfAlgorithm != 3)
{
printf("Incorrect value. Enter again: ");
scanf("%d", &numberOfAlgorithm);
}
switch(numberOfAlgorithm)
{
case 1:
bubbleSort(array, arrayLength);
printArrayToFile(array, arrayLength);
break;
case 2:
selectionSort(array, arrayLength);
printArrayToFile(array, arrayLength);
break;
case 3:
insertionSort(array, arrayLength);
printArrayToFile(array, arrayLength);
break;
}
printf("Sorted array: \n");
printArrayToScreen(array, arrayLength);
fclose(file);
free(array);
return 0;
}
|
C
|
#include "requete.h"
#include "envoi.h"
/**
* Converti un char* en un entier.
* Le char* doit représenter un nombre entre -1 et la taille max
* d'un int non signé.
*/
int parseInt(char* entier) {
if(strcmp(entier, "-1") == 0) {
return -1;
}
int res = 0;
int i;
for(i = 0; entier[i] != '\0'; i++) {
char c = entier[i];
if(isdigit(c)) {
res = res*10+(c-'0');
} else {
return PARSE_ERROR;
}
}
return res;
}
void initReq(struct requete* req) {
req->type = NON_DEFINI;
req->isOver = 0;
req->imgId = -2;
req->listenPort = -1;
req->fragmentSize = -1;
req->inWord = 0;
req->space = 0;
req->crlfCounter = 0;
req->mot = 0;
req->motPosition = 0;
req->reqPosition = 0;
}
void traiteRequete(struct requete* req, struct videoClient* videoClient, int epollfd, int sock) {
videoClient->lastAlive = getTime();
switch(req->type) {
case BAD_REQUEST:
break;
case GET:
if(req->fragmentSize != -1)
{
memset(&videoClient->dest_addr,0,sizeof(&videoClient->dest_addr));
memcpy(&videoClient->dest_addr, &videoClient->orig_addr, sizeof(&videoClient->orig_addr));
videoClient->dest_addr.sin_port = htons(req->listenPort);
videoClient->envoi = malloc(sizeof(struct envoi));
if(videoClient->infosVideo->type == UDP_PUSH)
{
videoClient->etat = RUNNING;
videoClient->envoi->curFile = fopen(videoClient->infosVideo->images[0], "r");
if(videoClient->envoi->curFile == NULL)
{
puts("E: ouverture du fichier");
}
}
else
{
videoClient->etat = PAUSE;
}
videoClient->envoi->posDansImage = 0;
videoClient->envoi->tailleMaxFragment = req->fragmentSize - 128;
videoClient->id = 0;
videoClient->dernierEnvoi = getTime();
videoClient->envoi->state = NOTHING_SENT;
} else if(req->listenPort != -1)
{
videoClient->clientSocket = connectDataTCP(epollfd, sock, req->listenPort, videoClient->infosVideo->type);
videoClient->envoi = malloc(sizeof(struct envoi));
if(videoClient->infosVideo->type == TCP_PUSH)
{
videoClient->etat = RUNNING;
videoClient->envoi->curFile = fopen(videoClient->infosVideo->images[0], "r");
if(videoClient->envoi->curFile == NULL)
{
puts("E: ouverture du fichier");
}
}
else
{
videoClient->etat = PAUSE;
}
videoClient->dernierEnvoi = getTime();
videoClient->envoi->state = NOTHING_SENT;
videoClient->id = 0;
} else
{
videoClient->etat = RUNNING;
if (req->imgId == -1)
{
videoClient->id = (videoClient->id < videoClient->infosVideo->nbImages ? videoClient->id+1 : 1);
}
else
{
videoClient->id = req->imgId;
}
videoClient->envoi->more = 0;
videoClient->envoi->posDansImage = 0;
videoClient->envoi->state = NOTHING_SENT;
videoClient->envoi->curFile = fopen(videoClient->infosVideo->images[videoClient->id-1], "r");
if(videoClient->envoi->curFile == NULL)
{
puts("E: ouverture du fichier");
}
sendImage(videoClient, epollfd, sock);
}
break;
case START:
if(videoClient->etat == PAUSED)
{
if(videoClient->infosVideo->type != UDP_PULL && videoClient->infosVideo->type != UDP_PUSH)
{
struct epoll_event ev;
ev.events = EPOLLOUT;
ev.data.fd = videoClient->clientSocket;
FAIL(epoll_ctl(epollfd, EPOLL_CTL_ADD, videoClient->clientSocket, &ev));
}
videoClient->etat = RUNNING;
}
sendImage(videoClient, epollfd, sock);
break;
case PAUSE:
if(videoClient->etat == RUNNING)
{
if(videoClient->infosVideo->type != UDP_PULL && videoClient->infosVideo->type != UDP_PUSH)
{
struct epoll_event ev;
ev.events = 0;
ev.data.fd = videoClient->clientSocket;
FAIL(epoll_ctl(epollfd, EPOLL_CTL_DEL, videoClient->clientSocket, &ev));
}
videoClient->etat = PAUSED;
}
break;
case END:
decoClient(videoClient, sock, epollfd, videoClient->infosVideo->type);
break;
case ALIVE:
videoClient->lastAlive = time(NULL);
break;
default:
break;
}
}
void traiteChaine(char* chaine, struct requete* req, struct videoClient* videoClient, int epollfd, int sock) {
if(req->mot == 0) {
req->mot = malloc(MAX_TOCKEN*sizeof(char));
}
int i;
for(i=0; chaine[i] != '\0' && !req->isOver; i++) {
char c = chaine[i];
//est-ce que le caractère est un espace ?
req->space = (c == ' ' || c == '\n' || c == '\r');
if(req->inWord && req->space) { //Le mot est fini, on peut le traiter
req->mot[req->motPosition] = '\0';
req->inWord = 0;
//Traitement du mot lu
if(req->reqPosition == 0) {
if(strcmp(req->mot, "GET") == 0) {
req->type = GET;
} else if(strcmp(req->mot, "START") == 0) {
req->type = START;
} else if(strcmp(req->mot, "PAUSE") == 0) {
req->type = PAUSE;
} else if(strcmp(req->mot, "END") == 0) {
req->type = END;
} else if(strcmp(req->mot, "ALIVE") == 0) {
req->type = ALIVE;
} else {
req->type = BAD_REQUEST;
}
} else if(req->reqPosition == 1) {
int numero = parseInt(req->mot);
if(numero == PARSE_ERROR) {
req->imgId = 0;
} else {
req->imgId = numero;
}
} else if(req->reqPosition == 2 && strcmp(req->mot, "LISTEN_PORT") != 0) {
//req->type = BAD_REQUEST;
} else if(req->reqPosition == 3) {
int numero = parseInt(req->mot);
if(numero == PARSE_ERROR) {
req->type = BAD_REQUEST;
} else {
req->listenPort = numero;
}
} else if(req->reqPosition == 4) {
if(req->type == ALIVE || strcmp(req->mot, "FRAGMENT_SIZE") != 0) {
//req->type = BAD_REQUEST;
}
} else if(req->reqPosition == 5) {
int numero = parseInt(req->mot);
if(numero == PARSE_ERROR) {
req->type = BAD_REQUEST;
} else {
req->fragmentSize = numero;
}
} else if(req->reqPosition == 6) {
//req->type = BAD_REQUEST;
}
req->reqPosition++;
} else if(req->inWord && !req->space) { //Le mot continue
req->mot[req->motPosition] = c;
req->motPosition++;
} else if(!req->inWord && !req->space) { //Le mot commence
req->crlfCounter = 0;
req->motPosition = 0;
req->inWord = 1;
req->mot[req->motPosition] = c;
req->motPosition++;
} else { //Sinon les espaces continuent
if(c == '\n') {
req->crlfCounter++;
}
if(req->crlfCounter == 2) {
req->isOver = 1;
//puts(req->mot);
}
}
}
if(req->isOver) {
free(req->mot);
req->mot = NULL;
if(req->type == GET && req->imgId == -2) {
req->type = BAD_REQUEST;
}
if(req->type == ALIVE && req->imgId == -2) {
req->type = BAD_REQUEST;
}
traiteRequete(req, videoClient, epollfd, sock);
initReq(req);
}
}
|
C
|
#include <stdio.h>
#include "arbol.h"
#include "pila.h"
#define TAM 100
void imprimeAlgo() {
}
int main(void) {
Pila *p;
NodoArb *a, *b, *c, *d;
char cad[TAM];
int i;
p = creaPila(TAM);
printf("Introduce una operación\n");
for (i = 0; i < TAM; i++) {
scanf("%[^\n]", &cad[i]);
}
for (i = 0; cad[i]; i++) {
a = creaNodoArb(creaChar(cad[i]), NULL, NULL);
if(cad[i] != '+' && cad[i] != '-' && cad[i] != '*' && cad[i] != '/') {
push(p, a);
}
else {
b = pop(p);
c = pop(p);
d = creaNodoArb(creaChar(cad[i]), b, c);
push(p, d);
}
}
printf("%d\n", eval(d));
return 0;
}
|
C
|
//
// main.c
// 11【了解】条件编译的概念及优点
//
// Created by 高明辉 on 16/2/15.
// Copyright © 2016年 itcast. All rights reserved.
//
#include <stdio.h>
#define M 0
#if M == 1
void gm_log(){
printf("这是日志输出");
}
#else
void gm_log(){
printf("不输出日志");
}
#endif
int main(int argc, const char * argv[]) {
/*
#if defined M
特定代码块;
#endif
表示如果前面定义过宏M则可以将特定的代码块编译进源文件,可以调用执行。
#if 常量表达式
程序段1
#else
程序段2
#endif
*/
gm_log();
return 0;
}
|
C
|
#include<stdio.h>
void swap (int *a, int x, int y) /*swap method it will be used by qSortHelper
and takes as parameters an array and two integers that
will be used as indexes for the swap*/
{
int temp=a[x]; //setting the value of temp to the first number to be swapped, so the value is not lost
a[x]=a[y];//setting the value of that same position to the number that it is being swapped with
a[y]=temp;//setting the value of the second position to the first position's old value
}
void print (int *a, int n)/*print method is responsible to print the values of an array
and receives as parameters an array and its size*/
{
for (int i=0; i<n; i++){ //for loop to go through all the arrays positions
printf("%d ",a[i]); //printing each element of the array
}
printf("\n");//skipping to the next line
}
void qSortHelper(int *a, int left, int right, int n) /*qSortHelper is method that essentially sorts the array trhough quicksort
and receives as parameters an array and three integers that corresopond respectively to
where the partition should start, where should it finish and the size of the array*/
{
if (right <= left) return;//base case when the two indices cross each other the array is sorted
int pivot = a[left];//setting the pivot
int l = left+1;// setting the index of the the left subarray
int r = right;//setting the index of the right subarray
while(l<=r){ /*inside this loop the subarrays are formed*/
while(a[l]<=pivot){//left subarray
l++;
}
if(l>r) break;//exit condition in which the array is already sorted
while(a[r]>pivot){//right subarray
r--;
}
if(l>r) break;//exit condition in which the array is already sorted
swap(a,l,r);//makes the swap when necessary
}
swap(a,left,r);//put the pivot in the right place
print(a,n);//prints the iteractions
qSortHelper(a,left,r-1, n);//calls qSortHelper recursively with the left subarray
qSortHelper(a,l,right, n);//calls qSortHelper recursively with the right subarray
}
void qSort (int *a, int n)//quicksort method
{
qSortHelper(a, 0, n-1, n);//calls qSortHelper offering and array, the initial position, the end position and the size.
}
int main()
{
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};//declaring the array a
qSort(a,10);//calling the method qSort with array a and its size
printf("sorted:\n");
print(a,10);//prints the sorted array
}
|
C
|
/*
* watches.h
*
* Memory watch definitions
*/
#ifndef _LIBUM_WATCHES_H
#define _LIBUM_WATCHES_H
#include <stdint.h>
#ifndef LITE
#define WATCHES_MAX 10
#else
#define WATCHES_MAX 5
#endif
struct watch_info {
uint8_t type : 4;
uint8_t floating : 4;
};
enum watch_type {
WATCH_TYPE_S8,
WATCH_TYPE_U8,
WATCH_TYPE_X8,
WATCH_TYPE_S16,
WATCH_TYPE_U16,
WATCH_TYPE_X16,
WATCH_TYPE_S32,
WATCH_TYPE_U32,
WATCH_TYPE_X32,
WATCH_TYPE_FLOAT
};
typedef struct {
void *address;
enum watch_type type;
int16_t x;
int16_t y;
uint8_t floating;
char *label;
} watch_t;
void watch_printf (watch_t *watch, uint32_t color);
void clear_watches (void);
void init_watch_rows (void);
#endif
|
C
|
/*
Lily has a chocolate bar consisting of a row of n squares where each square
has an integer written on it. She wants to share it with Ron for his birthday,
which falls on month m and day d. Lily wants to give Ron a piece of chocolate
only if it contains m consecutive squares whose integers sum to d.
Given m, d, and the sequence of integers written on each square of Lily's
chocolate bar, how many different ways can Lily break off a piece of chocolate
to give to Ron?
Input Format
The first line contains an integer denoting n (the number of squares in the chocolate bar).
The second line contains n space-separated integers describing the respective values of s[i] (the numbers written on each consecutive square of chocolate).
The third line contains two space-separated integers describing the respective values of d (Ron's birth day) and m (Ron's birth month).
Print an integer denoting the total number of ways that Lily can give a piece of chocolate to Ron.
Sample Input
5
1 2 1 3 2
3 2
Sample Output
2
Sample Input 1
6
1 1 1 1 1 1
3 2
Sample Output 1
0
Sample Input 2
1
4
4 1
Sample Output 2
1
*/
#include <stdio.h>
#include <stdlib.h>
int chocoCombos(int n, int *chocVals, int target, int bracket_size){
int count = 0;
int current_sum = 0;
for(int i = 0; i < bracket_size; i++){
current_sum = current_sum + chocVals[i];
}
if(current_sum == target){
count++;
}
for(int i = 1; i <= (n - bracket_size); i++){
current_sum = ((current_sum - chocVals[i-1]) + chocVals[(i-1) + bracket_size]);
if(current_sum == target){
count++;
}
}
return count;
}
int main(){
int chocSize;
scanf("%d", &chocSize);
int *chocVals = malloc(sizeof(int) * chocSize);
for(int i = 0; i < chocSize; i++){
scanf("%d", &chocVals[i]);
}
int month, day;
scanf("%d %d", &day, &month);
int solutionCount = chocoCombos(chocSize, chocVals, day, month);
printf("%d\n", solutionCount);
return 0;
}
|
C
|
#include <stdio.h>
int main() {
int i = 0xDAEDBEAF;
int *pi = &i;
size_t size = sizeof(pi) * 8;
printf("size: %lu bit(s)\n", size);
printf("value: %p\n", pi);
printf("memory: %X\n", *pi);
}
|
C
|
#include<stdio.h>/*2009.9.25晚 写于白鹿原*/
#include <malloc.h>
typedef int DataType;
typedef struct Node {
DataType data;
struct Node *LChild;
struct Node *RChild;
}BitNode,*BitTree;
void CreatBiTree(BitNode * BT) {
char ch;
ch = getchar();
if(ch == '#') {
BT = NULL;
}
else {
BT = (BitNode *)malloc(sizeof(BitNode));
BT->data = ch;
CreatBiTree((BT->LChild));
CreatBiTree((BT->RChild));
}
}
void Visit(char ch) {
printf("%c ",ch);
}
void PreOrder(BitNode * root) {
if (root!=NULL) {
Visit(root ->data); /*访问根结点*/
PreOrder(root ->LChild); /*先序遍历左子树*/
PreOrder(root ->RChild); /*先序遍历右子树*/
}
}
void main()
{
BitNode * T;
int h;
int layer;
int treeleaf;
layer=0;
printf("请输入二叉树中的元素(以扩展先序遍历序列输入,其中.代表空子树):\n");
CreatBiTree(T);
printf("先序遍历序列为:");
PreOrder(T);
}
|
C
|
#include <stdio.h>
#include <math.h>
int bit_liczby (int numer, int liczba)
{
if( (liczba & (int)pow(2, numer)) > 0) return 1;
else return 0;
}
int main()
{
int a, b;
printf("Podaj liczbe\n");
scanf("%i", &a);
printf("Podaj numer bitu\n");
scanf("%i", &b);
printf("rezultat - %i\n", bit_liczby(b,a));
return 0;
}
|
C
|
#include "transport.h"
#include "skyline.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
df_transport null_dft = {0};
//Condition au bord gauche
double g(double t)
{
return exp(-t);
}
int main(void){
df_transport dft = null_dft;
int nx = 1000;
double Lx = 1;
init_df_transport(&dft, nx, Lx);
//printf("%f\n",compute_mass(&dft));
double tmax = 0.6;
double beta = 0.1;// On prend c=1, donc beta=dt/dx
compute_df(&dft, tmax, beta);
compute_exact(&dft, dft.tnow);
//printf("%f\n",compute_mass(&dft));
plot_data(&dft);
return 0;
}
void init_df_transport(df_transport *dft, int nx, double Lx){
dft->nx = nx;// (*dft).nx = nx
dft->Lx = Lx;
dft->dx = Lx / nx;
dft->xx = malloc(nx * sizeof(double));
dft->un = malloc(nx * sizeof(double));
dft->unp1 = malloc(nx * sizeof(double));
dft->uex = malloc(nx * sizeof(double));
for(int i = 0; i < nx; i++){
dft->xx[i] = (i + 1) * dft->dx;
exact_sol(dft->xx[i], 0, &(dft->un[i]));
dft->unp1[i] = dft->un[i];
dft->uex[i] = 0;
}
}
void exact_sol(double x, double t, double *u){
if (x >= t)
*u = 0;
else
*u = g(t-x);
}
void plot_data(df_transport *dft){
double err_sup = 0;
double err_L2 = 0;
double err_L1 = 0;
double errloc = 0;
FILE *plotfile;
plotfile = fopen("plot.dat", "w");
fprintf(plotfile, "x un us");
for(int i = 0; i < dft->nx; i++){
fprintf(plotfile, "%f %f %f\n", dft->xx[i], dft->un[i], dft->uex[i]);
errloc= fabs(dft->uex[i] - dft->un[i]);
err_sup = errloc > err_sup ? errloc : err_sup;
err_L2 += dft->dx * errloc * errloc;
err_L1 += dft->dx * errloc;
}
err_L2 = sqrt(err_L2);
printf("erreur L2=%f L1=%f\n", err_L2, err_L1);
fclose(plotfile);
system("gnuplot plotcom");
}
void compute_df(df_transport *dft, double tmax, double beta){
double dx = dft->dx;
double dt = beta * dx;
int nx = dft->nx;
dft->dt = dt;
dft->tmax = tmax;
dft->tnow = 0;
while(dft->tnow < tmax){
dft->unp1[0] = exp(- dft->tnow);
for(int i = 1; i < nx; ++i){
dft->unp1[i] = (1 - beta)*dft->un[i] + beta*dft->un[i-1];
}
for(int i=0; i<nx; ++i){
dft->un[i] = dft->unp1[i];
}
dft->tnow += dt;
}
}
void compute_exact(df_transport *dft, double tmax)
{
for (int i = 0; i < dft->nx; i++){
exact_sol(dft->xx[i], tmax, &(dft->uex[i]));
}
}
|
C
|
#include <stdio.h>
#define NO_OUT 1
#if NO_OUT == 1
#define ERROUT0(fmt)
#else
#define ERROUT0(fmt) vce_errout((fmt))
#endif
void vce_errout( char *hoge )
{
fprintf( stderr, "%s aho \n", hoge );
}
int main()
{
ERROUT0( "aho\n");
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main(void)
{
int n;
int fd[2];
pid_t pid;
char line[100];
if (pipe(fd) < 0)
printf("pip error");
if ((pid = fork()) < 0)
printf("fork error");
else if (pid > 0){
close(fd[0]);
write(fd[1], "hello world\n", 12);
} else {
close(fd[1]);
n = read(fd[0], line, 100);
printf("%d", n);
read(STDOUT_FILENO, line, n);
}
exit(0);
}
|
C
|
#include<stdio.h>
int main(void)
{
int numbers[] = {9,8,7,6,5,4,3,2,1,0};
int sort[10];
int swapc = 1,i = 0;
while(swapc != 0)
{
swapc = 0;
if(i > 9)
i = 0;
if (numbers[i] > numbers[i+1])
{
sort[i] = numbers[i+1];
sort[i+1] = numbers[i];
swapc++;
}
i++;
}
for(int i = 0; i < 10; i++)
{
printf("%d\n", sort[i]);
}
}
|
C
|
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
//void (*signal(int signo, void (*func )(int)))(int);
//typedef void sigfunc(int);
//sigfunc *signal(int, sigfunc *);
void my_assert()
{
kill(getpid(), SIGSEGV);
}
void signal_handler(int signo)
{
if (signo == SIGINT) {
printf("SIGINT received \n");
}
return;
}
int main()
{
if (signal(SIGINT, signal_handler) == SIG_ERR) {
printf("Can't catch signal \n");
}
while(1) {
sleep(1);
}
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int num;
scanf_s("%d", &num);
while (num >= 1200)
{
num -= 1200;
printf("%d\n", num);
}
}
|
C
|
#include <xinu.h>
#include <stdio.h>
void printPacket(struct netpacket * );
shellcmd xsh_sendpkt(int nargs, char * args[]) {
printf("\nSending packet...\n");
if (nargs != 3) {
//print usage
printf("USAGE: sendpkt <destination> <message>\n");
return 0;
}
//TODO: sanity check for input
uint32 strlength, maclength = 0;
char * string = args[2];
//printf("msg: %s\n", string);
while(*string != 0) {
string++;
strlength++;
if (strlength > 1500) {
printf("Payload too large! Only 1500 octets allowed!\n");
return 1;
}
}
string = args[1];
while(*string != 0) {
string++;
maclength++;
}
if (maclength != 17) {
printf("Invalid destination MAC length\n");
return 1;
}
struct netpacket * packet = (struct netpacket *) getmem(PACKLEN);
memset((char *) packet, NULLCH, PACKLEN);
if (charToHex(packet->net_dst, args[1])) {
printf("Unknown characters in destination MAC\n");
return 1;
}
//printf("ETH_ADDR_LEN: %d\n", ETH_ADDR_LEN);
//memcpy(&packet->net_dst, args[1], ETH_ADDR_LEN);
memcpy(&packet->net_src, if_tab[0].if_macucast, ETH_ADDR_LEN);
packet->net_type = ETH_IP;
//printf("ETH_IP: %x\n", ETH_IP);
memcpy(&packet->net_payload, args[2], strlength);
//printf("packet size = %d\n", PACKLEN);
write(ETHER0, (char *) packet, PACKLEN);
//printPacket(packet);
return 0;
}
void printPacket(struct netpacket * packet) {
printf("Printing packet...\n");
printf("Dest: %02x:%02x:%02x:%02x:%02x:%02x\n",
packet->net_dst[0], 0xff & packet->net_dst[1], 0xff & packet->net_dst[2],
0xff & packet->net_dst[3], 0xff & packet->net_dst[4], 0xff & packet->net_dst[5]);
printf("Source: %02x:%02x:%02x:%02x:%02x:%02x\n",
packet->net_src[0], 0xff & packet->net_src[1], 0xff & packet->net_src[2],
0xff & packet->net_src[3], 0xff & packet->net_src[4], 0xff & packet->net_src[5]);
printf("Type: 0x%04x\n", packet->net_type);
printf("Payload: %s\n", packet->net_payload);
}
|
C
|
/*
Find PI using Monte Carlo algoritm.
Total CPU processes: 4.
References:
https://www.geeksforgeeks.org/estimating-value-pi-using-monte-carlo/
https://www.tutorialspoint.com/c-program-to-demonstrate-fork-and-pipe
https://tldp.org/LDP/lpg/node11.html
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
time_t t;
typedef unsigned long long points_t;
double calculatePI(int, points_t);
void parentProcess(int, points_t, int[]);
void childProcess(int, points_t, int[]);
void writeResult(int, int[], double);
void processTask(int, int[], points_t);
int main(void) {
printf("\n");
printf("\n -> Calculating PI using Monte Carlo Method using distributed processes.\n");
points_t pointCount = 100000000;
int taskResults1[2];
int taskResults2[2];
int taskResults3[2];
// Create pipeline to allow each task to send back the results to the main process.
if (pipe(taskResults1) == -1 || pipe(taskResults2) == -1 || pipe(taskResults3) == -1) {
fprintf(stderr, "Falied to create pipe");
return 1;
}
// Distribute the number of points per task.
points_t pointsPerProcess = (points_t) (pointCount / 4);
points_t remainingPoints = (points_t) (pointCount % 4);
int taskID = -1;
// Create separated processes
pid_t id1;
pid_t id2;
id1 = fork();
id2 = fork();
if (id1 == 0 && id2 == 0) {
// Task branch: Main(id1) -> child -> child(id2)
processTask(3, taskResults3, pointsPerProcess);
} else if (id1 == 0 && id2 > 0) {
// Task branch: Main(id1) -> child -> parent(id2)
processTask(2, taskResults2, pointsPerProcess);
} else if (id1 > 0 && id2 == 0) {
// Task branch: Main(id1) -> parent -> child(id2)
processTask(1, taskResults1, pointsPerProcess);
} else if (id1 > 0 && id2 > 0) {
// MAIN PROCESS
// Task branch: Main(id1) -> parent -> parent(id2)
wait(NULL);
printf("\n Task (%d) - pID: %ld \t pPID: %ld", 0, (long)getpid(), (long)getppid());
wait(NULL);
double result1;
close(taskResults1[1]);
read(taskResults1[0], &result1, sizeof(double));
double result2;
close(taskResults2[1]);
read(taskResults2[0], &result2, sizeof(double));
double result3;
close(taskResults3[1]);
read(taskResults3[0], &result3, sizeof(double));
double result4 = calculatePI(taskID, pointsPerProcess);
double PI = (result1 + result2 + result3 + result4) / 4.0;
printf("\n\n-----------------------\n");
printf("FINAL RESULT \n");
printf("-----------------------\n");
printf("-> PI (aprox.) = %1.7f\n", PI);
printf("\n");
}
return(EXIT_SUCCESS);
}
void processTask(int taskID, int taskPipe[], points_t pointsPerProcess) {
printf("\nTask (%d) - pID: %ld \t pPID: %ld", taskID, (long)getpid(), (long)getppid());
double PI = calculatePI(taskID, pointsPerProcess);
close(taskPipe[0]);
write(taskPipe[1], &PI, sizeof(double));
}
double calculatePI(int taskID, points_t numOfPoints) {
srand((unsigned) time(&t) + (long) getpid());
unsigned long long pointsInCircle = 0;
unsigned long long pointsInSquare = 0;
for (; pointsInSquare < numOfPoints; pointsInSquare++) {
double x = (rand() % 101) / (double)100;
double y = (rand() % 101) / (double)100;
double p = (x * x) + (y * y);
if (p <= 1) {
pointsInCircle += 1;
}
}
double PI = 4.0 * (pointsInCircle / (double)pointsInSquare);
printf("\n Task ID: %d\n", taskID);
printf(" Points in circle: %llu \t Total points: %llu \t PI = %1.7f\n\n", pointsInCircle, pointsInSquare, PI);
return PI;
}
|
C
|
#include <stdio.h>
#include <climits>
int main(){
long long unsigned int shelf = 0;
int book;
while(scanf("%d", &book) != EOF){
//from shelf
int inshelf = 0;
int index;
long long unsigned int tmp = 255;
//on shelf and which position
for(int i=0; i<8; i++){
if(((shelf >> 8*i) & tmp) == book){
inshelf = 1;
index = i+1;
break;
}
}
long long unsigned int long_book = book;
if(inshelf){
long long unsigned int front = shelf >> index*8 << index*8;
long long unsigned int later = shelf << (8-index+1)*8 >> (8-index+1)*8;
later = later << 8;
shelf = long_book | front | later;
}
else{
shelf = shelf<< 8;
shelf = shelf | long_book;
}
}
//print shelf
long long unsigned int tmp = ULLONG_MAX;
char cur;
for(int i = 7; i>=0; i--){
char cur = (tmp & shelf)>>(i*8);
tmp = tmp >> 8;
printf("%d", cur);
if(i >= 1)
printf(" ");
}
return 0;
}
|
C
|
/* driver for enorm example. */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <minpack.h>
#define real __minpack_real__
#ifdef __cminpack_double__
#define N1 3
#define N2 367
#define SQRTFAC 1.5
#define FAC 10.
#endif
#ifdef __cminpack_long_double__
#define N1 3
#define N2 367
#define SQRTFAC 1.5
#define FAC 10.
#endif
#ifdef __cminpack_float__
#define N1 3
#define N2 367
#define SQRTFAC 1.5
#define FAC 10.
#endif
#ifdef __cminpack_half__
#define N1 2
#define N2 2
#define SQRTFAC 1.
#define FAC 2.
#endif
int main()
{
int i;
int n;
real* x;
real norm;
real agiant;
real rdwarf = sqrt(__cminpack_func__(dpmpar)(2)*SQRTFAC) * FAC;
real rgiant = sqrt(__cminpack_func__(dpmpar)(3)) / FAC;
#ifdef __cminpack_long_double__
printf ("dpmpar(2) = %18.7Lg, dpmpar(3) = %18.7Lg\n", __cminpack_func__(dpmpar)(2), __cminpack_func__(dpmpar)(3));
printf ("rdwarf = %.19Lg, rgiant = %.19Lg\n", rdwarf, rgiant);
#else
printf ("dpmpar(2) = %15.7g, dpmpar(3) = %15.7g\n", (double)__cminpack_func__(dpmpar)(2), (double)__cminpack_func__(dpmpar)(3));
printf ("rdwarf = %.16g, rgiant = %.16g\n", (double)rdwarf, (double)rgiant);
#endif
n = N1*N1*N2*N2*2+2;
x = (real*)malloc(n*sizeof(real));
for (i = 0; i < n; ++i) {
if (i < 2) {
x[i] = rdwarf * N1;
} else {
x[i] = rdwarf / N2;
}
}
norm = 0;
for (i = 0; i < n; ++i) {
norm += x[i]*x[i];
}
norm = sqrt(norm) / rdwarf / N1 / 2;
#ifdef __cminpack_long_double__
printf( "norm/rdwarf (naive) = %.18Lg\n", norm);
#else
printf( "norm/rdwarf (naive) = %.15g\n", (double)norm);
#endif
norm = __minpack_func__(enorm)(&n, x);
norm = norm / rdwarf / N1 / 2;
#ifdef __cminpack_long_double__
printf( "norm/rdwarf (enorm) = %.18Lg\n", norm);
#else
printf( "norm/rdwarf (enorm) = %.15g\n", (double)norm);
#endif
agiant = rgiant / (real)n;
for (i = 0; i < n; ++i) {
if (i < 2) {
x[i] = agiant * N1;
} else {
x[i] = agiant / N2;
}
}
norm = 0;
for (i = 0; i < n; ++i) {
norm += x[i]*x[i];
}
norm = sqrt(norm) / agiant / N1 / 2;
#ifdef __cminpack_long_double__
printf( "norm/agiant (naive) = %.18Lg\n", norm);
#else
printf( "norm/agiant (naive) = %.15g\n", (double)norm);
#endif
norm = __minpack_func__(enorm)(&n, x);
norm = norm / agiant / N1 / 2;
#ifdef __cminpack_long_double__
printf( "norm/agiant (enorm) = %.18Lg\n", norm);
#else
printf( "norm/agiant (enorm) = %.15g\n", (double)norm);
#endif
free (x);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void lireArrangement( FILE * flujo, int tailleArrangement ){
int array [ tailleArrangement ];
fread( array, sizeof( int ), tailleArrangement, flujo );
fclose( flujo );
printf( "Leyendo el archivo\n" );
for (int i =0 ; i < tailleArrangement; i++ ){
printf( "Arreglo en la posicion %d con valor %d\n", i, array[ i ] );
}
}
int main(){
FILE * flujo = fopen ("1000000datos.dat", "rb" );
lireArrangement( flujo, 1000000 );
return 0;
}
|
C
|
/***************************************************************************//**
@file listtest.c
@author Stephen Brennan
@date Friday, 6 March 2015
@brief Libstephen: Generic list tests.
@copyright Copyright (c) 2013-2016, Stephen Brennan. Released under the
Revised BSD License. See the LICENSE.txt file for details.
*******************************************************************************/
#include <string.h>
#include "libstephen/base.h"
#include "libstephen/list.h"
#include "libstephen/ll.h"
#include "libstephen/al.h"
#include "libstephen/ut.h"
#include "tests.h"
/*******************************************************************************
Test Setup
*******************************************************************************/
smb_list (*get_list)(void);
/*******************************************************************************
Tests
*******************************************************************************/
int test_append()
{
smb_status status = SMB_SUCCESS;
DATA d;
smb_list list = get_list();
for (d.data_llint = 0; d.data_llint < 200; d.data_llint++) {
// Put a small, 200 item load on it. This tests appending on
// empty and general appending.
list.append(&list, d);
TA_LLINT_EQ((long long)list.length(&list), d.data_llint + 1);
// Test that the data is correct.
for (int i = 0; i < list.length(&list); i++) {
TA_LLINT_EQ(list.get(&list, i, &status).data_llint, (long long) i);
TA_INT_EQ(status, SMB_SUCCESS);
}
}
list.delete(&list);
return 0;
}
int test_prepend()
{
smb_status status = SMB_SUCCESS;
DATA d;
smb_list list = get_list();
// Test prepend about 200 times...
for (d.data_llint = 0; d.data_llint < 200; d.data_llint++) {
list.prepend(&list, d);
TA_LLINT_EQ((long long)list.length(&list), d.data_llint + 1);
for (int i = 0; i < list.length(&list); i++) {
TA_LLINT_EQ(list.get(&list, i, &status).data_llint, d.data_llint - i);
TA_INT_EQ(status, SMB_SUCCESS);
}
}
list.delete(&list);
return 0;
}
int test_set()
{
smb_status status = SMB_SUCCESS;
DATA d;
smb_list list = get_list();
const int length = 30;
// Create the data
for (d.data_llint = 0 ; d.data_llint < length; d.data_llint++) {
list.append(&list, d);
}
// Verify the data
for (d.data_llint = 0 ; d.data_llint < length; d.data_llint++) {
TA_LLINT_EQ(list.get(&list, d.data_llint, &status).data_llint, d.data_llint);
TA_INT_EQ(status, SMB_SUCCESS);
}
// Test that the length is correct
TA_INT_EQ(list.length(&list), length);
// Test set
for (int i = 0; i < list.length(&list); i++) {
d.data_llint = length - i;
list.set(&list, i, d, &status);
TA_INT_EQ(status, SMB_SUCCESS);
TA_LLINT_EQ(list.get(&list, i, &status).data_llint, d.data_llint);
TA_INT_EQ(status, SMB_SUCCESS);
}
// Test that the length is still correct
TA_INT_EQ(list.length(&list), length);
list.set(&list, list.length(&list), d, &status);
TA_INT_EQ(status, SMB_INDEX_ERROR);
status = SMB_SUCCESS;
list.get(&list, list.length(&list), &status);
TA_INT_EQ(status, SMB_INDEX_ERROR);
list.delete(&list);
return 0;
}
int test_remove()
{
smb_status status = SMB_SUCCESS;
DATA d;
smb_list list = get_list();
const int length = 20;
// Create the data
for (d.data_llint = 0 ; d.data_llint < length; d.data_llint++) {
list.append(&list, d);
}
// Verify the data
for (d.data_llint = 0 ; d.data_llint < length; d.data_llint++) {
TA_LLINT_EQ(list.get(&list, d.data_llint, &status).data_llint, d.data_llint);
TA_INT_EQ(status, SMB_SUCCESS);
}
// Remove first element
list.remove(&list, 0, &status);
TA_INT_EQ(status, SMB_SUCCESS);
TA_INT_EQ(list.length(&list), length - 1);
TA_LLINT_EQ(list.get(&list, 0, &status).data_llint, (long long) 1);
TA_INT_EQ(status, SMB_SUCCESS);
// Remove middle element
list.remove(&list, 10, &status); // list[10] == 11 before
TA_INT_EQ(status, SMB_SUCCESS);
TA_INT_EQ(list.length(&list), length - 2);
TA_LLINT_EQ(list.get(&list, 10, &status).data_llint, (long long) 12);
TA_INT_EQ(status, SMB_SUCCESS);
// Remove last element
list.remove(&list, list.length(&list) - 1, &status);
TA_INT_EQ(status, SMB_SUCCESS);
TA_INT_EQ(list.length(&list), length - 3);
// Remove invalid element
list.remove(&list, list.length(&list), &status);
TA_INT_EQ(status, SMB_INDEX_ERROR);
status = SMB_SUCCESS;
list.remove(&list, -1, &status);
TA_INT_EQ(status, SMB_INDEX_ERROR);
status = SMB_SUCCESS;
// Test all elements values
int value = 1;
for (int i = 0; i < length - 3; i++) {
if (i == 10) value++;
TA_LLINT_EQ(list.get(&list, i, &status).data_llint, (long long)value);
TA_INT_EQ(status, SMB_SUCCESS);
value++;
}
list.delete(&list);
return 0;
}
int test_insert()
{
smb_status status = SMB_SUCCESS;
DATA d;
smb_list list = get_list();
const int length = 20;
// Create the data
for (d.data_llint = 0 ; d.data_llint < length; d.data_llint++) {
list.append(&list, d);
}
// Verify the data
for (d.data_llint = 0 ; d.data_llint < length; d.data_llint++) {
TA_LLINT_EQ(list.get(&list, d.data_llint, &status).data_llint, d.data_llint);
TA_INT_EQ(status, SMB_SUCCESS);
}
// Here are the insertions for the test:
d.data_llint = 100;
list.insert(&list, 0, d);
TA_INT_EQ(list.length(&list), length + 1);
d.data_llint = 101;
list.insert(&list, 10, d);
TA_INT_EQ(list.length(&list), length + 2);
d.data_llint = 102;
list.insert(&list, list.length(&list), d);
TA_INT_EQ(list.length(&list), length + 3);
d.data_llint = 101;
list.insert(&list, -1, d);
TA_INT_EQ(list.length(&list), length + 4);
d.data_llint = 102;
list.insert(&list, list.length(&list) + 1, d);
TA_INT_EQ(list.length(&list), length + 5);
int value = 0;
for (int i = 0; i < list.length(&list); i++) {
if (i == 0) {
TA_LLINT_EQ(list.get(&list, i, &status).data_llint, (long long)101);
TA_INT_EQ(status, SMB_SUCCESS);
} else if (i == 1) {
TA_LLINT_EQ(list.get(&list, i, &status).data_llint, (long long)100);
TA_INT_EQ(status, SMB_SUCCESS);
} else if (i == 11) {
TA_LLINT_EQ(list.get(&list, i, &status).data_llint, (long long) 101);
TA_INT_EQ(status, SMB_SUCCESS);
} else if (i == list.length(&list) - 2) {
TA_LLINT_EQ(list.get(&list, i, &status).data_llint, (long long) 102);
TA_INT_EQ(status, SMB_SUCCESS);
} else if (i == list.length(&list) - 1) {
TA_LLINT_EQ(list.get(&list, i, &status).data_llint, (long long) 102);
TA_INT_EQ(status, SMB_SUCCESS);
} else {
TA_LLINT_EQ(list.get(&list, i, &status).data_llint, (long long) value);
TA_INT_EQ(status, SMB_SUCCESS);
value++;
}
}
list.delete(&list);
return 0;
}
int test_front(void)
{
smb_list list = get_list();
smb_status status = SMB_SUCCESS;
DATA d;
const int length = 5;
// Push test data to get 0, 1, 2, 3, 4
for (d.data_llint = length-1; d.data_llint >= 0; d.data_llint--) {
list.push_front(&list, d);
}
// Test that peek works correctly with data.
TA_LLINT_EQ(list.peek_front(&list, &status).data_llint, (long long) 0);
TA_INT_EQ(status, SMB_SUCCESS);
// Check that pop works correctly.
for (d.data_llint = 0; d.data_llint < length; d.data_llint++) {
TA_LLINT_EQ(list.pop_front(&list, &status).data_llint, d.data_llint);
TA_INT_EQ(status, SMB_SUCCESS);
}
// Check that peek and pop will fail correctly.
list.peek_front(&list, &status);
TA_INT_EQ(status, SMB_INDEX_ERROR);
status = SMB_SUCCESS;
list.pop_front(&list, &status);
TA_INT_EQ(status, SMB_INDEX_ERROR);
// Cleanup
list.delete(&list);
return 0;
}
int test_back(void)
{
smb_list list = get_list();
smb_status status = SMB_SUCCESS;
DATA d;
const int length = 5;
// Push test data to get 0, 1, 2, 3, 4
for (d.data_llint = 0; d.data_llint < length; d.data_llint++) {
list.push_back(&list, d);
}
// Test that peek works correctly with data.
TA_LLINT_EQ(list.peek_back(&list, &status).data_llint, (long long)4);
TA_INT_EQ(status, SMB_SUCCESS);
// Check that pop works correctly.
for (d.data_llint = length-1; d.data_llint >= 0; d.data_llint--) {
TA_LLINT_EQ(list.pop_back(&list, &status).data_llint, d.data_llint);
TA_INT_EQ(status, SMB_SUCCESS);
}
// Check that peek and pop will fail correctly.
list.peek_back(&list, &status);
TA_INT_EQ(status, SMB_INDEX_ERROR);
status = SMB_SUCCESS;
list.pop_back(&list, &status);
TA_INT_EQ(status, SMB_INDEX_ERROR);
// Cleanup
list.delete(&list);
return 0;
}
int test_index_of(void)
{
smb_list list = get_list();
smb_status status = SMB_SUCCESS;
DATA d, d2;
char *t1 = "I'm a string";
char *t2;
int strsize = strlen(t1) + 1;
const int length = 20;
// Make a copy of the test string so pointer comparison won't work.
t2 = (char*)smb_new(char, strsize);
strncpy(t2, t1, strsize);
d.data_ptr = t1;
// Check that the string won't be found in an empty list.
TA_INT_EQ(list.index_of(&list, d, &data_compare_string), -1);
// Now add the copy to the list.
d2.data_ptr = t2;
list.append(&list, d2);
// Now assert that the string will be found in the list.
TA_INT_EQ(list.index_of(&list, d, &data_compare_string), 0);
smb_free(t2);
list.pop_back(&list, &status);
// Push test data to get 0, 1, 2, 3, 4, ..., 20
for (d.data_llint = 0; d.data_llint < length; d.data_llint++) {
list.push_back(&list, d);
}
// Check that it finds the data.
for (d.data_llint = 0; d.data_llint < length; d.data_llint++) {
TA_LLINT_EQ((long long)list.index_of(&list, d, NULL), d.data_llint);
}
list.delete(&list);
return 0;
}
/*******************************************************************************
Test Runner
*******************************************************************************/
/**
@brief Run the tests in this file with a specified description.
This allows you to set the setup and tear down functions to different values
and run the tests again with a different name.
@param desc The description for this run through.
*/
void run_list_tests(char *desc)
{
smb_ut_group *group = su_create_test_group(desc);
smb_ut_test *append = su_create_test("append", test_append);
su_add_test(group, append);
smb_ut_test *prepend = su_create_test("prepend", test_prepend);
su_add_test(group, prepend);
smb_ut_test *set = su_create_test("set", test_set);
su_add_test(group, set);
smb_ut_test *remove = su_create_test("remove", test_remove);
su_add_test(group, remove);
smb_ut_test *insert = su_create_test("insert", test_insert);
su_add_test(group, insert);
smb_ut_test *front = su_create_test("front", test_front);
su_add_test(group, front);
smb_ut_test *back = su_create_test("back", test_back);
su_add_test(group, back);
smb_ut_test *index_of = su_create_test("index_of", test_index_of);
su_add_test(group, index_of);
su_run_group(group);
su_delete_group(group);
}
/**
@brief Run the tests on lists.
*/
void list_test(void)
{
get_list = &ll_create_list;
run_list_tests("ll: test/listtest.c");
get_list = &al_create_list;
run_list_tests("al: test/listtest.c");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "storage_mgr.h"
#include "dberror.h"
#include <sys/stat.h>
#include <string.h>
//File header contains total number of pages
#define PAGELEN 4
//We need a global variable to reset values if a file is closed or destroyed
SM_FileHandle *sm_fileHandle;
void initStorageManager (){
//Not being used in this code
}
RC createPageFile (char *fileName){
//create the file
FILE *file = fopen(fileName, "w");
if(file == NULL)
return RC_WRITE_FAILED;
//Add a page with the size same as PAGE_SIZE
char *page = (char *) malloc(PAGE_SIZE);
memset(page, '\0', PAGE_SIZE);
int pages = 1;
//Write page nos first and then add an empty block having all '\0'
fwrite(&pages, sizeof(int), 1, file);
fwrite(page, sizeof(char), PAGE_SIZE, file);
//Close file
fclose(file);
free(page);
return RC_OK;
}
RC openPageFile (char *fileName, SM_FileHandle *fHandle){
//Check if the file exists, the structure help prevent memory faults
struct stat buffer;
if (stat (fileName, &buffer) != 0)
return RC_FILE_NOT_FOUND;
//check if the file is already open
if (fHandle->fileName == fileName)
return RC_OK ;
//Open the page file in r+ because we need to perform read+write
FILE *file = fopen(fileName, "r+");
int pages;
//read the page nos put at the beginning of the file
fread(&pages, sizeof(int), 1, file);
//set the file handle to current file
fHandle->fileName = fileName;
fHandle->totalNumPages = pages;
fHandle->curPagePos = 0;
fHandle->mgmtInfo = file;
//We need a global variable to reset values if a file is closed or destroyed
sm_fileHandle = fHandle;
return RC_OK;
}
RC closePageFile (SM_FileHandle *fHandle){
//If file is not open
if (fHandle->fileName == NULL)
return RC_FILE_NOT_FOUND;
//Close file
fclose(fHandle->mgmtInfo);
//Reset all the values in the global file handle
fHandle->fileName = NULL;
fHandle->totalNumPages = 0;
fHandle->curPagePos = 0;
fHandle->mgmtInfo = NULL;
return RC_OK;
}
RC destroyPageFile (char *fileName){
//Remove the file if we get a 0 then the file is removed
int rem=remove(fileName);
if (rem == 0){
//reset all the values in the file handle
sm_fileHandle->fileName = NULL;
sm_fileHandle->totalNumPages = 0;
sm_fileHandle->curPagePos = 0;
sm_fileHandle->mgmtInfo = NULL;
return RC_OK;
}
return RC_WRITE_FAILED;
}
RC readBlock (int pageNum, SM_FileHandle *fHandle, SM_PageHandle memPage){
//If the file is open or not
if (fHandle->fileName == NULL)
return RC_FILE_NOT_FOUND;
//If the page does not exist
if(pageNum < 0 || pageNum > fHandle->totalNumPages - 1)
return RC_READ_NON_EXISTING_PAGE;
//Calculate the location of the pointer
long int point = ((pageNum) * PAGE_SIZE) + PAGELEN;
fseek(fHandle->mgmtInfo, point, SEEK_SET);
//Reading the page
fread(memPage, sizeof(char), PAGE_SIZE, fHandle->mgmtInfo);
//Updating the file handle
fHandle->curPagePos = pageNum;
return RC_OK;
}
int getBlockPos (SM_FileHandle *fHandle){
//Check if file is open
if (fHandle->fileName == NULL)
return -1;
return fHandle->curPagePos;
}
RC readFirstBlock (SM_FileHandle *fHandle, SM_PageHandle memPage){
return readBlock(0,fHandle, memPage);
}
RC readPreviousBlock (SM_FileHandle *fHandle, SM_PageHandle memPage){
return readBlock(fHandle->curPagePos - 1, fHandle, memPage);
}
RC readCurrentBlock (SM_FileHandle *fHandle, SM_PageHandle memPage){
return readBlock(fHandle->curPagePos,fHandle, memPage);
}
RC readNextBlock (SM_FileHandle *fHandle, SM_PageHandle memPage){
//If current page is the last page
if ((fHandle->curPagePos) == fHandle->totalNumPages)
return RC_READ_NON_EXISTING_PAGE;
return readBlock(fHandle->curPagePos + 1, fHandle, memPage);
}
RC readLastBlock (SM_FileHandle *fHandle, SM_PageHandle memPage){
return readBlock(fHandle->totalNumPages - 1, fHandle, memPage);
}
RC writeBlock (int pageNum, SM_FileHandle *fHandle, SM_PageHandle memPage){
//If file is open
if (fHandle->fileName == NULL)
return RC_FILE_NOT_FOUND;
//If memPage is not NULL
if (memPage == NULL)
return RC_RM_NO_PRINT_FOR_DATATYPE;
//If page does not exist in the file
if(pageNum < 0 || pageNum > fHandle->totalNumPages - 1)
return RC_READ_NON_EXISTING_PAGE;
//Calculate location of the pointer from where to write
long int point = ((pageNum) * PAGE_SIZE) + PAGELEN;
fseek(fHandle->mgmtInfo, point, SEEK_SET);
//Write to the file
fwrite(memPage, sizeof(char), PAGE_SIZE, fHandle->mgmtInfo);
//Updating the file handle
fHandle->curPagePos = pageNum;
return RC_OK;
}
RC writeCurrentBlock (SM_FileHandle *fHandle, SM_PageHandle memPage){
return writeBlock(fHandle->curPagePos,fHandle, memPage);
}
RC appendEmptyBlock (SM_FileHandle *fHandle){
//check if file is open
if (fHandle->fileName == NULL)
return RC_FILE_NOT_FOUND;
//add a new page of the size of PAGE_SIZE
char *page = (char *) malloc(PAGE_SIZE);
memset(page, '\0', PAGE_SIZE);
fHandle->totalNumPages++;
//update no of pages
fseek (fHandle->mgmtInfo, 0, SEEK_SET);
fwrite(&fHandle->totalNumPages, sizeof(int), 1, fHandle->mgmtInfo);
//write an empty page to the file
fseek (fHandle->mgmtInfo, 0, SEEK_END);
fwrite(page, sizeof(char), PAGE_SIZE, fHandle->mgmtInfo);
fHandle->curPagePos = fHandle->totalNumPages-1;
free(page);
return RC_OK;
}
RC ensureCapacity (int numberOfPages, SM_FileHandle *fHandle){
//If file is open
if (fHandle->fileName == NULL)
return RC_FILE_NOT_FOUND;
int i;
//Calculate the required no of pages to be added, if less value is given we ignore
int change = numberOfPages - fHandle->totalNumPages;
if (change > 0){
for ( i = 0; i < change; i++){
appendEmptyBlock(fHandle);
}
}
printf("File capacity is ensured");
return RC_OK;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
typedef struct _nodo
{
int dato;
struct _nodo* sx;
struct _nodo* dx;
} nodo;
typedef struct _cercaprof
{
int profond;
int trovato;
} cercaprof;
nodo* Inserisci(nodo* radice, int input)
{
if(radice == NULL)
{
nodo* nuovo = malloc(sizeof(nodo));
(*nuovo).dato = input;
(*nuovo).sx = NULL;
(*nuovo).dx = NULL;
return nuovo;
}
else
{
if(input <= (*radice).dato) (*radice).sx = Inserisci((*radice).sx, input);
else (*radice).dx = Inserisci((*radice).dx, input);
return radice;
}
}
cercaprof* Profondita(nodo* radice, int cercato, int prof)
{
if(radice == NULL)
{
cercaprof* valore = malloc(sizeof(cercaprof));
(*valore).trovato = 0;
(*valore).profond = prof;
return valore;
}
else
{
cercaprof* valore = malloc(sizeof(cercaprof));
if((*radice).dato == cercato)
{
(*valore).profond = prof;
(*valore).trovato = 1;
}
else
{
cercaprof* valoreSX = Profondita((*radice).sx, cercato, prof+1);
cercaprof* valoreDX = Profondita((*radice).dx, cercato, prof+1);
(*valore).profond = prof;
(*valore).trovato = 0;
if((*valoreSX).trovato) { (*valore).trovato = 1; (*valore).profond = (*valoreSX).profond; }
if((*valoreDX).trovato) { (*valore).trovato = 1; (*valore).profond = (*valoreDX).profond; }
free(valoreSX); free(valoreDX);
}
return valore;
}
}
int main()
{
int n;
scanf("%d", &n);
nodo* radice = NULL;
int i;
int input;
for(i=0; i<n; i++)
{
scanf("%d", &input);
radice = Inserisci(radice, input);
}
scanf("%d", &input);
while(input >= 0)
{
cercaprof* risp = Profondita(radice, input, 0);
if((*risp).trovato == 1) printf("%d\n", (*risp).profond);
else printf("NO\n");
free(risp);
scanf("%d", &input);
}
return 0;
}
|
C
|
#include "flow.h"
#include "imu.h"
#include "imath.h"
#include "math.h"
_FLOW flow = {0};
//光流数据包接收
void flow_parse(u8 data_packet)
{
u8 sum = 0;
switch(flow.step)
{
case 0:
//帧头
if(data_packet==0xFE)
{
flow.step = 1;
flow.packet[flow.dat_cnt++] = data_packet;
}
else
flow.step = 0;
break;
case 1:
//数据长度
if(data_packet==0x04)
{
flow.step = 2;
flow.packet[flow.dat_cnt++] = data_packet;
}
else
flow.step = 0;
break;
case 2:
//数据接收
flow.packet[flow.dat_cnt++] = data_packet;
if(flow.dat_cnt==9)
{
flow.step = 0;
flow.dat_cnt = 0;
//有效数据累加和
sum = (flow.packet[2] + flow.packet[3] + flow.packet[4] + flow.packet[5]);
if((0xAA == data_packet) && (sum == flow.packet[6])&&(0x30 == flow.packet[7]))
{
flow.x = ( (int16_t)(*(flow.packet+3)<<8)|*(flow.packet+2) );
flow.y = ( (int16_t)(*(flow.packet+5)<<8)|*(flow.packet+4) );
}
}
break;
default:
flow.step = 0;
flow.dat_cnt = 0;
break;
}
}
//光流串口接收中断函数
void USART3_IRQHandler(void)
{
if(USART_GetITStatus(USART3, USART_IT_RXNE) != RESET)
{
flow.dat = USART_ReceiveData(USART3);
flow_parse(flow.dat);
}
USART_ClearITPendingBit(USART3, USART_IT_RXNE);
}
void flow_iir_lpf(_XY_F *_flow_in,_XY_F *_flow_out,float lpf_factor)
{
_flow_out->x = _flow_out->x + lpf_factor*(_flow_in->x - _flow_out->x);
_flow_out->y = _flow_out->y + lpf_factor*(_flow_in->y - _flow_out->y);
}
//光流数据处理
void flow_handle(void)
{
//光流数据积分得出位移
flow.pos.x += flow.x;
flow.pos.y += flow.y;
//倾角位移补偿
flow.att.x = 2450.0f*tan(att.rol*deg_to_rad);
flow.att.y = 2450.0f*tan(att.pit*deg_to_rad);
//倾角补偿后的位移输出
flow.fix_pos.x = (flow.pos.x - flow.att.x)*0.08f;
flow.fix_pos.y = (flow.pos.y - flow.att.y)*0.08f;
//求微分速度
flow.vel.x = (flow.fix_pos.x - flow.last_pos.x)*30.0f;
flow.vel.y = (flow.fix_pos.y - flow.last_pos.y)*30.0f;
// flow.nav_pos.y = -flow.pos.x*sin_yaw + flow.pos.y*cos_yaw;
// flow.nav_pos.x = flow.pos.x*cos_yaw + flow.pos.y*sin_yaw;
//// flow.vel.x = (flow.pos.x - flow.last_pos.x)/0.005f;
//// flow.vel.y = (flow.pos.y - flow.last_pos.y)/0.005f;
////
//// flow.last_pos.x = flow.pos.x;
//// flow.last_pos.y = flow.pos.y;
flow.last_pos.x = flow.fix_pos.x;
flow.last_pos.y = flow.fix_pos.y;
//光流速度低通滤波
flow_iir_lpf(&flow.vel,&flow.fix_vel,flow.vel_lpf_factor);
}
|
C
|
void main()
{
char intonumber(char x);
char intochar(int y);
char str[N];
gets(str);
int i=0,c1=0;
while(str[i]!=' ')
{
c1=c1*10+intonumber(str[i++]);
}
while(str[i]==' ')
i++;
unsigned long n1=0;
while(str[i]!=' ')
{
n1=n1*c1+intonumber(str[i++]);
}
while(str[i]==' ')
i++;
int l1=0;
while(str[i]!='\0')
{
l1=l1*10+intonumber(str[i++]);
}
int f;
char yu[M];
for(f=0;n1>0;f++)
{
yu[f]=intochar(n1%l1);
n1=n1/l1;
}
if (f==0) printf("%d",0);
for(f--;f>=0;f--)
printf("%c",yu[f]);
}
char intonumber(char x)
{
if(x>='a'&&x<='z')
x=x-87;
else if(x>='A'&&x<='Z')
x=x-55;
else if(x>=48&&x<=57)
x=x-48;
return(x);
}
char intochar(int y)
{
if(y>=0&&y<=9)
y=y+48;
else if(y>9&&y<=35)
y=y+55;
return(y);
}
|
C
|
/*
* main.c
*
* 20493-02 Computer Architecture
* Term Project on Implentation of Cache Mechanism
*
* Skeleton Code Prepared by Prof. HyungJune Lee
* Nov 13, 2017
*
*/
#include <stdio.h>
#include <math.h>
#include "cache_impl.h"
int num_cache_hits = 0;
int num_cache_misses = 0;
int num_bytes = 0;
int num_access_cycles = 0;
int global_timestamp = 0;
int retrieve_data(void* addr, char data_type) {
int value_returned = -1; /* accessed data */
/* Invoke check_cache_data_hit() */
value_returned = check_cache_data_hit(addr, data_type);
/* In case of the cache miss event, access the main memory by invoking access_memory() */
if (value_returned == -1) {
value_returned = access_memory(addr, data_type);
}
return value_returned;
}
int main(void) {
FILE* ifp = NULL, * ofp = NULL;
unsigned long int access_addr; /* byte address (located at 1st column) in "access_input.txt" */
char access_type; /* 'b'(byte), 'h'(halfword), or 'w'(word) (located at 2nd column) in "access_input.txt" */
int accessed_data; /* This is the data that you want to retrieve first from cache, and then from memory */
init_memory_content(); /*initialize memory_array content*/
init_cache_content(); /*initialize cache_array content*/
ifp = fopen("access_input2.txt", "r"); /*open input file*/
if (ifp == NULL) {
printf("Can't open input file\n");
return -1;
}
ofp = fopen("access_output2-3.txt", "w"); /*open output file*/
if (ofp == NULL) {
printf("Can't open output file\n");
fclose(ifp);
return -1;
}
fprintf(ofp, "[Accessed Data]\n");
while (1) {
fscanf(ifp, "%d %c", &access_addr, &access_type); /*read access_address and access_type from input file*/
if (feof(ifp)) /*until file ends*/
break;
else {
accessed_data = retrieve_data(access_addr, access_type); /*invoke retrieve_data and save the value of accessed_data*/
fprintf(ofp, "%d %c %#x\n", access_addr, access_type, accessed_data); /*print it on the output file*/
global_timestamp++; /*increase global timestamp*/
}
}
int num_access = num_cache_hits + num_cache_misses; /*total access number is sum of num_cache_hits and num_cache_misses*/
double hit_ratio = (double)num_cache_hits / num_access; /*hit ratio is the value of num_cache_hits divide into num_access*/
double bandwidth = (double)num_bytes / num_access_cycles; /*bandwidth is the value of num_bytes divide into num_access_cycles*/
fprintf(ofp, "-----------------------------------------------\n");
if (DEFAULT_CACHE_ASSOC == 1) { /*if it is direct mapped cache*/
fprintf(ofp, "[Direct mapped cache performance]\n");
}
else if (DEFAULT_CACHE_ASSOC == 4) { /*if it is fully associative cache*/
fprintf(ofp, "[Fully associative cache performance]\n");
}
else { /*otherwise, n-way set associative cache*/
fprintf(ofp, "[%d-way set associative cache performance]\n", DEFAULT_CACHE_ASSOC);
}
fprintf(ofp, "Hit ratio = %.2f (%d/%d)\n", hit_ratio, num_cache_hits, num_access);
fprintf(ofp, "Bandwidth = %.2f (%d/%d)\n", bandwidth, num_bytes, num_access_cycles);
fclose(ifp);
fclose(ofp);
return 0;
}
|
C
|
#include<stdio.h>
//not working
int main(){
int x , y , i , n ;
y = 1;
scanf("%d%d",&x,&n);
while(1<=n){
y = x*n;
printf("%d",y);
i++;
}
printf("%d",y);
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
int i, index, k, n, temp;
int a[10];
scanf("%d", &n);
for(i=0; i<n; i++)
scanf("%d", &a[i]);
for(k=0; k<n-1; k++){
index=k;
for(i=k+1; i<n; i++)
if(a[i]>a[index])
index=i;
temp=a[index];
a[index]=a[k];
a[k]=temp;
}
printf("%d", a[0]);
for(i=1; i<n; i++)
printf(" %d", a[i]);
return 0;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <string.h>
//在一个「平衡字符串」中,'L' 和 'R' 字符的数量是相同的。
//给出一个平衡字符串 s,请你将它分割成尽可能多的平衡字符串。
//返回可以通过分割得到的平衡字符串的最大数量。
int balancedStringSplit(char * s)
{
int len = strlen(s);
int i = 0;
int count = 0;
int a = 0;
int b = 0;
for (i = 0; i < len; i++)
{
if (s[i] == 'L')
{
a++;
}
else
{
b++;
}
if (a == b)
{
count++;
}
}
return count;
}
int main()
{
char s[] = "RLRRLLRLRL";
int ret = 0;
ret = balancedStringSplit(s);
printf("%d\n", ret);
return 0;
}
|
C
|
// һУظĽ㣬ɾظĽ㣬ظĽ㲻ͷָ롣
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
// Ϊ ֻһڵʱֱӷ
if (pHead == NULL || pHead->next == NULL)
{
return pHead;
}
ListNode *prev = NULL;
ListNode *cur = pHead;
ListNode *next = pHead->next;
while (next)
{
if (cur->val != next->val)
{
prev = cur;
cur = next;
next = next->next;
}
else
{
while (cur->val == next->val && next != NULL)
{
next = next->next;
}
if (prev == NULL) // еprev=NULL˵ǰͬ
{
pHead = next; // ͷΪnext
}
else
{
prev->next = next; // Խ磬ȫΪ3еprev=NULLûnext,Ҫж
}
cur = next;
if (next)
next = next->next;
}
}
return pHead;
}
};
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <ctype.h>
#include <string.h>
#include <time.h>
#include "funciones.h"
int igresoCadenaChar(char texto[],char dato[])
{
int flag=-1;
if(texto!=NULL&&dato!=NULL)
{
flag=0;
printf("%s",texto);
fflush(stdin);
gets(dato);
}
return flag;
}
int validarSiSonLetra(char nombre[])
{
int i;
int flag=-1;
if(nombre!=NULL)
{
flag=0;
for(i=0; nombre[i]!='\0'; i++)
{
nombre[i]=toupper(nombre[i]);
if(validarLetra(nombre[i]))
{
printf("\nSOLO PUEDE INGRESAR LETRAS LETRAS Y SIN DEJAR ESPACIO!!!!!\n");
flag=-2;
break;
}
}
}
return flag;
}
int validarLetra(char dato)
{
int flag=-1;
if((dato>='A'&&dato<='Z')||(dato>='a'&&dato<='z'))
{
flag=0;
}
return flag;
}
int ingresoInt(char texto[])
{
int dato=-1;
char auxChar[200];
if(texto!=NULL)
{
printf("%s",texto);
fflush(stdin);
gets(auxChar);
dato=validarNumeroInt(auxChar);
if(dato==-1)
{
dato=-2;
}
}
return dato;
}
int validarNumeroInt(char dato[])
{
int num;
int flag=-1;
int i;
if(dato!=NULL)
{
for(i=0; dato[i]!='\0'; i++)
{
flag=esUnNumero(dato[i]);
if(flag)
{
flag=-2;
break;
}
}
if(flag)
{
printf("NO PUEDE INGRESRAR LETRAS!!!!!\n");
num=flag;
}
else
{
num = atof(dato);
}
}
return num;
}
int esUnNumero(char dato)
{
int flag=-1;
if(dato>='0'&&dato<='9')
{
flag=0;
}
return flag;
}
int devolverHorasEstadia()
{
int horas;
srand(time(NULL));
horas = (rand()%24)+1;
return horas ;
}
float multiplicacion(float num1,float num2)
{
float total;
total=num1*num2;
return total;
}
|
C
|
#include<stdio.h>
void main()
{
int a,b,ch;
printf("1.add\n2.subtract\n3.multiply\n4.division\n5.square of number\n");
printf("enter your choice: ");
scanf("%d",&ch);
if (ch==1 || ch==2 || ch==3 || ch==4)
{
scanf("%d %d",&a,&b);
if (ch==1)
{
printf("the sum of %d and %d is %d\n",a,b,a+b);
}
else if (ch==2)
{
printf("the difference of %d and %d is %d\n",a,b,a-b);
}
else if (ch==3)
{
printf("the product of %d and %d is %d\n",a,b,a*b);
}
else if (ch==4)
{
printf("the quotient of %d and %d is %d\n",a,b,a/b);
printf("the remainder is %d\n",a%b);
}
}
else
{
printf("enter the a number: ");
scanf("%d",&a);
printf("the square of %d is %d\n",a,a*a);
}
}
|
C
|
#include<stdio.h>
#include<errno.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
int main(void)
{
pid_t pid_fils;
do {
pid_fils = fork();
} while ((pid_fils == -1) && (errno == EAGAIN));
if (pid_fils == -1) {
fprintf(stderr, "forfk() impossible, errno=%d\n",errno);
return 1;
}
if (pid_fils == 0) { /*Processus fils*/
fprintf(stdout,"Fils : PID=%ld, PPID=%ld\n",(long)getpid(),(long)getppid());
return 0;
} else { /*Processus Père*/
fprintf(stdout,"Père : PID=%ld, PPID=%ld, PID fils=%ld\n",(long)getpid(),(long)getppid(),(long)pid_fils);
wait(NULL);
return 0;
}
}
|
C
|
/***
*heapsrch.c - search the heap for a free block
*
* Copyright (c) 1989-1997, Microsoft Corporation. All rights reserved.
*
*Purpose:
* Defines the _heap_search() function.
*
*******************************************************************************/
#ifndef WINHEAP
#include <cruntime.h>
#include <heap.h>
#include <stddef.h>
#define LOOP_FOREVER while(1)
/***
*_PBLKDESC _heap_search(unsigned size) - Find a free block of a least size
* bytes.
*
*Purpose:
* Finds a free block of at least size bytes. Searches the list of block
* descriptors from *proverdesc to the end (marked by the sentinel). The
* search is strictly first fit. Adjacent free blocks are coalesced as
* they are encountered during the search.
*
*Entry:
* unsigned size - size of block requested
*
*Exit:
* Success: Pointer to descriptor for free memory block of at least size
* bytes
* Failure: NULL
*
*Uses:
*
*Exceptions:
*
*******************************************************************************/
_PBLKDESC __cdecl _heap_search (
unsigned size
)
{
REG1 _PBLKDESC pdesc;
REG2 _PBLKDESC pdesc2;
_PBLKDESC pretdesc = NULL;
/* search from proverdesc thru plastdesc, looking for free block of
* at least size bytes. coalesce adjacent free blocks during the
* search. the search is strictly first fit. that is, it terminates
* when the first block is found of adequate size.
*/
for ( pdesc = _heap_desc.proverdesc ; pdesc != &(_heap_desc.sentinel) ;
pdesc = pdesc->pnextdesc )
/* is pdesc free?
*/
if ( _IS_FREE(pdesc) )
/* coalesce loop
*/
LOOP_FOREVER {
/* if pdesc is big enough, return it
*/
if ( _BLKSIZE(pdesc) >= size ) {
pretdesc = pdesc;
goto searchdone;
}
/* see if the next block is free and, if so,
* coalesce it with pdesc
*/
pdesc2 = pdesc->pnextdesc;
if ( _IS_FREE(pdesc2) ) {
/* coalesce pdesc2 with pdesc
*/
pdesc->pnextdesc = pdesc2->pnextdesc;
_PUTEMPTY(pdesc2);
}
else
break;
} /* end LOOP_FOREVER */
for ( pdesc = _heap_desc.pfirstdesc ; pdesc != _heap_desc.proverdesc ;
pdesc = pdesc->pnextdesc )
/* is pdesc free?
*/
if ( _IS_FREE(pdesc) )
/* coalesce loop
*/
LOOP_FOREVER {
/* if pdesc is big enough, return it
*/
if ( _BLKSIZE(pdesc) >= size ) {
pretdesc = pdesc;
goto searchdone;
}
/* see if the next block is free and, if so,
* coalesce it with pdesc
*/
pdesc2 = pdesc->pnextdesc;
if ( _IS_FREE(pdesc2) ) {
/* coalesce pdesc2 with pdesc
*/
pdesc->pnextdesc = pdesc2->pnextdesc;
_PUTEMPTY(pdesc2);
/* special handling for the case where
* the rover has been coalesced (search
* ends)
*/
if ( _heap_desc.proverdesc == pdesc2 )
{
_heap_desc.proverdesc = pdesc;
if ( _BLKSIZE(pdesc) >= size )
pretdesc = pdesc;
goto searchdone;
}
}
else
break;
} /* end LOOP_FOREVER */
searchdone:
/* common exit for all code paths. win, lose or draw, this is the
* only code path back to the caller.
*/
return(pretdesc);
}
#endif /* WINHEAP */
|
C
|
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/stat.h>
#include <sys/shm.h>
#include <semaphore.h>
#include "../helpers/alert_helpers.h"
int main(){
sem_t *sem;
char *mem_pointer;
int memory_handle;
memory_handle = shmget(18011970, 100, 0600);
if(memory_handle == -1){
get_error_alert("Cannot find shared memory\n");
exit(1);
}
get_success_alert("\nShared memory opened\n");
mem_pointer = shmat(memory_handle, NULL, SHM_RDONLY);
if(mem_pointer == -1){
get_error_alert("Error getting pointer");
exit(1);
}
get_success_alert("\nMemory pointer is %d\n", mem_pointer);
sem = sem_open("memory_sem", 0);
get_warning_alert("\nWaiting for semaphore...\n");
sem_wait(sem);
printf("Readed from memory: %s", mem_pointer);
sem_post(sem);
sem_close(sem);
getchar();
return 0;
}
|
C
|
#include<stdio.h>
int scan(int *a,int,int);
int print(int *c,int ,int);
int main()
{
int m,n,x,y;
printf("Enter the dimensions of matrix A");
scanf("%d %d", &m,&n);
printf("Enter the dimensions of matrix B");
scanf("%d %d", &x,&y);
int a[m][n], b[x][y] ,c[m][n];
int *p=a[m][n],*q=b[x][y];
scan(p,m,n);
scan(q,x,y);
if(m==x && n==y)
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
int *r=c[m][n];
print(r,m,n);
}
else
{
printf("Sum cannot be determined, no of rows and columns should be equal for addition to be viable");
}
}
int scan(int *a,int m,int n)
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
}
int print(int *c,int m, int n)
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
printf("%d",c[i][j]);
}
}
}
|
C
|
/*
* File: Random.c
* Author: abutel
*
* Created on January 03, 2016, 02:04 PM
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include "Random.h"
#include "Memory.h"
#include "Math.h"
#include "PrintManage.h"
/**************************************************************/
/* PUBLIC DATA */
/**************************************************************/
/**************************************************************/
/* PRIVATE DATA */
/**************************************************************/
/**************************************************************/
/* PRIVATE FUNCTIONS */
/**************************************************************/
static void FreeBuffer(buffer_s buffer)
{
free(buffer.p);
if ( buffer.p != NULL)
{
fprintf(stdout, "\nError 05 : Free pointer fail\n");
exit(0);
}
}
static buffer_s FillBuffer(buffer_s buffer) // Par exemple place le nombre 203 dans un buffer => buf[0]=2 buf[1]=0 buf[2]=3
{
int randomNumber;
randomNumber = rand() % (power(BASE_TWO, SIZE_OF_WORDS) - 1);
buffer.size = 0;
buffer = MemoryAdd(buffer);
while(buffer.size <= DecimalNumber())
{
buffer.p[buffer.size] = randomNumber / power(BASE_TEN, (DecimalNumber() - buffer.size)); //BASE_TEN ^ (DecimalNumber() - buffer.size)
randomNumber = randomNumber - (buffer.p[buffer.size] * power(BASE_TEN, (DecimalNumber() - buffer.size)));
buffer.size++;
}
while(buffer.p[0] == 0)
{
buffer.p[0] = buffer.p[1];
buffer.p[1] = buffer.p[2];
buffer.p[2] = 0;
buffer.size--;
}
return (buffer);
}
static counter_s InitCounters(counter_s counter)
{
counter.countRandomNumber = 0;
counter.countNumberDisplay = 0;
counter.nbZeroAfterDiv = 0;
counter.countBeforeToGoTheLine = 0;
return (counter);
}
static buffer_s InitBuffer(buffer_s buffer)
{
buffer.p = (int*)calloc(ALLOCATION_STEP, sizeof(int));
MemoryCheck(buffer);
buffer.size = 0;
return (buffer);
}
/**************************************************************/
/* PUBLIC FUNCTIONS */
/**************************************************************/
void Random(FILE *fp)
{
counter_s counter;
buffer_s bufferInteger;
buffer_s bufferBinary;
counter = InitCounters(counter);
bufferInteger = InitBuffer(bufferInteger);
bufferBinary = InitBuffer(bufferBinary);
while(counter.countRandomNumber < (NUMBER_OF_TESTS * NUMBER_OF_DIGIT))
{
bufferInteger = FillBuffer(bufferInteger);
while(counter.nbZeroAfterDiv < bufferInteger.size) // Exemple : number 134 (1000 0110)=> size 3 bufferInt = [1,3,4]
{
bufferBinary.p[counter.countNumberDisplay] = FunctionDivByTwo(bufferInteger, counter.nbZeroAfterDiv);
bufferBinary = MemoryAdd(bufferBinary);
counter = TestEqualZero(bufferInteger, counter);
}
counter= PrintBinary(bufferBinary, counter, fp);
memset(bufferBinary.p, 0, 7);
}
//FreeBuffer(bufferBinary);
//FreeBuffer(bufferInteger);
}
|
C
|
#include "config.h"
#include "memory.h"
#include "basic_dict.h"
#include "utils.h"
#include <stdio.h>
#include <string.h>
#include <assert.h>
struct config *
config_init(struct memory *mem)
{
assert(mem);
struct config *context = memory_alloc(mem, sizeof(struct config));
context->_mem = mem;
context->_var = NULL;
context->_varCount = 0;
context->_varMap = DICTIONARY(mem, NULL);
context->_arenaOffset = 0;
context->_arenaSize = 0;
return context;
}
b32
config_load_config(struct config *context, const char *fileName)
{
const u32 nameLength = strlen(fileName);
char *filePath = memory_alloc(context->_mem, (sizeof("resources/configs/") - 1) + nameLength + sizeof(".conf"));
strcpy(filePath, "resources/configs/");
strcat(filePath, fileName);
strcat(filePath, ".conf");
FILE *confFile = fopen(filePath, "r");
if (!confFile)
{
fprintf(stderr, "config_load_config error: Could not load config file \"%s\".\n", fileName);
return B32_FALSE;
}
memory_free(context->_mem, filePath);
const char *delims = ":=\r\n";
char lineBuffer[256];
while(fgets(lineBuffer, sizeof(lineBuffer), confFile))
{
char *token = strtok(lineBuffer, delims);
char *name = NULL;
i32 nameLength;
char *type = NULL;
i32 typeLength;
char *value = NULL;
i32 valueLength;
while (token)
{
char *start = token;
i32 length = 0;
while (!isgraph(start[0]) && start[0] != '\0')
{
++start;
}
if (!name)
{
if (isalpha(start[0]))
{
while (isalnum(start[length]) || start[length] == '_')
{
++length;
}
name = start;
nameLength = length;
name[nameLength] = '\0';
}
else
{
fprintf(stderr, "config_load_config error: Invalid var name \"%s\" in \"%s\" config. Must start with an alphabetical.\n",
start, fileName);
break;
}
}
else if (!type)
{
while (isalpha(start[length]))
{
++length;
}
if (length > 0)
{
type = start;
typeLength = length;
type[typeLength] = '\0';
}
else
{
fprintf(stderr, "config_load_config error: Invalid type \"%s\" in \"%s\" config. Must contain only alphabeticals.\n",
start, fileName);
break;
}
}
else if (!value)
{
b32 isString = start[0] == '\"';
if (isString)
{
while(isgraph(start[length]) || isspace(start[length]))
{
++length;
if (start[length] == '\"' && isString)
{
++length;
break;
}
}
}
else
{
while(isgraph(start[length]))
{
++length;
}
}
if (length > 0)
{
value = start;
valueLength = length;
value[valueLength] = '\0';
}
else
{
fprintf(stderr, "config_load_config error: Invalid value for \"%s\" in \"%s\" config. Must be of appropriate type.\n",
name, fileName);
break;
}
}
else
{
break;
}
token = strtok(NULL, delims);
}
if (name && type && value)
{
if (!strcmp(type, "number"))
{
real32 num;
if (sscanf(value, "%f", &num) > 0)
{
config_set_var_number(context, name, num);
}
else
{
fprintf(stderr, "config_load_config error: Invalid number value \"%s\" for var \"%s\" in \"%s\".\n",
value, name, fileName);
}
}
else if (!strcmp(type, "string"))
{
if (!strcmp(value, "NULL"))
{
config_set_var_string(context, name, NULL);
}
else if (value[0] == '\"' && value[valueLength - 1] == '\"')
{
value[valueLength - 1] = '\0';
config_set_var_string(context, name, value + 1);
}
else
{
fprintf(stderr, "config_load_config error: Invalid string value \"%s\" for var \"%s\" in \"%s\". Must be \"NULL\" or in double quotations.\n",
value, name, fileName);
}
}
else if (!strcmp(type, "boolean"))
{
if (!strcmp(value, "false"))
{
config_set_var_boolean(context, name, B32_FALSE);
}
else if (!strcmp(value, "true"))
{
config_set_var_boolean(context, name, B32_TRUE);
}
else
{
fprintf(stderr, "config_load_config error: Invalid boolean value \"%s\" for var \"%s\" in \"%s\". Must be \"true\" or \"false\".\n", value, name, fileName);
}
}
else
{
fprintf(stderr, "config_load_config error: Invalid type \"%s\" for var \"%s\" in \"%s\".\n", type, name, fileName);
}
}
}
fclose(confFile);
return B32_TRUE;
}
void
config_save_var_config(struct config *context, const char *fileName);
b32
config_set_var_number(struct config *context, const char *name, real32 value)
{
for (const char *c = name; ; ++c)
{
if (c == name && !isalpha(*c))
{
if (*c != '\0')
{
fprintf(stderr, "config_set_var_number error: Invalid var name \"%s\". Must start with alphabetical.\n", name);
}
else
{
fprintf(stderr, "config_set_var_number error: Invalid var name. Empty string.\n");
}
return B32_FALSE;
}
else if (*c == '\0')
{
break;
}
else if (!isalnum(*c) && *c != '_')
{
fprintf(stderr, "config_set_var_number error: Invalid var name \"%s\". Must contain only alphanumerics, or '_'.\n", name);
return B32_FALSE;
}
}
struct config_var_header *varPtr = basic_dict_get(context->_varMap, context->_var, name);
if (!varPtr)
{
u32 diff = context->_arenaSize - context->_arenaOffset;
u32 size = sizeof(struct config_var_header) + sizeof(value);
if (diff < size)
{
if (context->_arenaSize > 0)
{
context->_var = memory_realloc(context->_mem, context->_var, context->_arenaSize += size);
}
else
{
context->_var = memory_alloc(context->_mem, context->_arenaSize += size);
}
}
varPtr = (struct config_var_header *)((u8 *)context->_var + context->_arenaOffset);
u32 nameLength = strlen(name) + 1;
varPtr->name = memory_alloc(context->_mem, nameLength);
memcpy(UTILS_MUTABLE_CAST(char *, varPtr->name), name, nameLength);
varPtr->size = CONFIG_VAR_NUMBER_SIZE;
varPtr->type = CONFIG_VAR_NUMBER;
varPtr->valueCount = 1;
basic_dict_set(context->_varMap, context->_mem, context->_var, name, nameLength, varPtr);
context->_arenaOffset += size;
++context->_varCount;
}
else if (varPtr->type != CONFIG_VAR_NUMBER)
{
fprintf(stderr, "config_set_var_number error: Cannot set value \"%s\". Stored type is not a number.\n", name);
return B32_FALSE;
}
*(real32 *)(varPtr + 1) = value;
return B32_TRUE;
}
b32
config_set_var_string(struct config *context, const char *name, const char *value)
{
for (const char *c = name; ; ++c)
{
if (c == name && !isalpha(*c))
{
if (*c != '\0')
{
fprintf(stderr, "config_set_var_string error: Invalid var name \"%s\". Must start with alphabetical.\n", name);
}
else
{
fprintf(stderr, "config_set_var_string error: Invalid var name. Empty string.\n");
}
return B32_FALSE;
}
else if (*c == '\0')
{
break;
}
else if (!isalnum(*c) && *c != '_')
{
fprintf(stderr, "config_set_var_string error: Invalid var name \"%s\". Must contain only alphanumerics, or '_'.\n", name);
return B32_FALSE;
}
}
struct config_var_header *varPtr = basic_dict_get(context->_varMap, context->_var, name);
if (!varPtr)
{
u32 diff = context->_arenaSize - context->_arenaOffset;
u32 size = sizeof(struct config_var_header) + sizeof(value);
if (diff < size)
{
if (context->_arenaSize > 0)
{
context->_var = memory_realloc(context->_mem, context->_var, context->_arenaSize += size);
}
else
{
context->_var = memory_alloc(context->_mem, context->_arenaSize += size);
}
}
varPtr = (struct config_var_header *)((u8 *)context->_var + context->_arenaOffset);
u32 nameLength = strlen(name) + 1;
varPtr->name = memory_alloc(context->_mem, nameLength);
memcpy(UTILS_MUTABLE_CAST(char *, varPtr->name), name, nameLength);
varPtr->type = CONFIG_VAR_STRING;
varPtr->valueCount = 1;
if (value)
{
u32 valueLength = strlen(value) + 1;
varPtr->size = valueLength;
*(char **)(varPtr + 1) = memory_alloc(context->_mem, valueLength);
memcpy(*(char **)(varPtr + 1), value, valueLength);
}
else
{
varPtr->size = 0;
*(char **)(varPtr + 1) = NULL;
}
basic_dict_set(context->_varMap, context->_mem, context->_var, name, nameLength, varPtr);
context->_arenaOffset += size;
++context->_varCount;
}
else if (varPtr->type != CONFIG_VAR_STRING)
{
fprintf(stderr, "config_set_var_string error: Cannot set value \"%s\". Stored type is not a string.\n", name);
return B32_FALSE;
}
else if (value)
{
u32 valueLength = strlen(value) + 1;
if (valueLength > varPtr->size)
{
if (varPtr->size > 0)
{
*(char **)(varPtr + 1) = memory_realloc(context->_mem, *(char **)(varPtr + 1), valueLength);
}
else
{
*(char **)(varPtr + 1) = memory_alloc(context->_mem, valueLength);
}
varPtr->size = valueLength;
}
memcpy(*(char **)(varPtr + 1), value, valueLength);
}
else if (*(char **)(varPtr + 1))
{
memory_free(context->_mem, *(char **)(varPtr + 1));
*(char **)(varPtr + 1) = NULL;
varPtr->size = 0;
}
return B32_TRUE;
}
b32
config_set_var_boolean(struct config *context, const char *name, b32 value)
{
for (const char *c = name; ; ++c)
{
if (c == name && !isalpha(*c))
{
if (*c != '\0')
{
fprintf(stderr, "config_set_var_boolean error: Invalid var name \"%s\". Must start with alphabetical.\n", name);
}
else
{
fprintf(stderr, "config_set_var_boolean error: Invalid var name. Empty string.\n");
}
return B32_FALSE;
}
else if (*c == '\0')
{
break;
}
else if (!isalnum(*c) && *c != '_')
{
fprintf(stderr, "config_set_var_boolean error: Invalid var name \"%s\". Must contain only alphanumerics, or '_'.\n", name);
return B32_FALSE;
}
}
assert(value == B32_FALSE || value == B32_TRUE);
struct config_var_header *varPtr = basic_dict_get(context->_varMap, context->_var, name);
if (!varPtr)
{
u32 diff = context->_arenaSize - context->_arenaOffset;
u32 size = sizeof(struct config_var_header) + sizeof(value);
if (diff < size)
{
if (context->_arenaSize > 0)
{
context->_var = memory_realloc(context->_mem, context->_var, context->_arenaSize += size);
}
else
{
context->_var = memory_alloc(context->_mem, context->_arenaSize += size);
}
}
varPtr = (struct config_var_header *)((u8 *)context->_var + context->_arenaOffset);
u32 nameLength = strlen(name) + 1;
varPtr->name = memory_alloc(context->_mem, nameLength);
memcpy(UTILS_MUTABLE_CAST(char *, varPtr->name), name, nameLength);
varPtr->size = sizeof(b32);
varPtr->type = CONFIG_VAR_BOOLEAN;
varPtr->valueCount = 1;
basic_dict_set(context->_varMap, context->_mem, context->_var, name, nameLength, varPtr);
context->_arenaOffset += size;
++context->_varCount;
}
else if (varPtr->type != CONFIG_VAR_BOOLEAN)
{
fprintf(stderr, "config_set_var_boolean error: Cannot set value \"%s\". Stored type is not a boolean.\n", name);
return B32_FALSE;
}
*(b32 *)(varPtr + 1) = value;
return B32_TRUE;
}
b32
config_get_var_number(struct config *context, const char *name, real32 *out)
{
assert(out);
struct config_var_header *header = basic_dict_get(context->_varMap, context->_var, name);
if (!header)
{
fprintf(stderr, "config_get_var_number error: Cannot get value \"%s\". Does not exist.\n", name);
return B32_FALSE;
}
else if (header->type != CONFIG_VAR_NUMBER)
{
fprintf(stderr, "config_get_var_number error: Cannot get value \"%s\". Stored type is not a number.\n", name);
return B32_FALSE;
}
*out = *(real32 *)(header + 1);
return B32_TRUE;
}
b32
config_get_var_string(struct config *context, const char *name, const char **out)
{
assert(out);
struct config_var_header *header = basic_dict_get(context->_varMap, context->_var, name);
if (!header)
{
fprintf(stderr, "config_get_var_string error: Cannot get value \"%s\". Does not exist.\n", name);
return B32_FALSE;
}
else if (header->type != CONFIG_VAR_STRING)
{
fprintf(stderr, "config_get_var_string error: Cannot get value \"%s\". Stored type is not a string.\n", name);
return B32_FALSE;
}
*out = *(const char **)(header + 1);
return B32_TRUE;
}
b32
config_get_var_boolean(struct config *context, const char *name, b32 *out)
{
assert(out);
struct config_var_header *header = basic_dict_get(context->_varMap, context->_var, name);
if (!header)
{
fprintf(stderr, "config_get_var_boolean error: Cannot get value \"%s\". Does not exist.\n", name);
return B32_FALSE;
}
else if (header->type != CONFIG_VAR_BOOLEAN)
{
fprintf(stderr, "config_get_var_string error: Cannot get value \"%s\". Stored type is not a boolean.\n", name);
return B32_FALSE;
}
*out = *(b32 *)(header + 1);
return B32_TRUE;
}
|
C
|
/*
* [TEST] Macierz odwrotna - Metoda dopelnien algebraicznych
*/
#include "inversion.h"
#define EPS 0.0001
bool FloatEquals(float a, float b)
{
return fabs(a - b) < EPS;
}
void printMatrixInt(int* a, uint size)
{
for(uint i = 0; i < size; ++i)
{
for(uint j = 0; j < size; ++j)
{
printf("%d ", a[i * size + j]);
}
printf("\n");
}
}
void printMatrixFloat(float* a, uint size)
{
for(uint i = 0; i < size; ++i)
{
for(uint j = 0; j < size; ++j)
{
printf("%.3f ", a[i * size + j]);
}
printf("\n");
}
}
void compareInverse(float* ref, float* calc, uint size)
{
uint incorrect = 0;
for(uint i = 0; i < size; ++i)
{
for(uint j = 0; j < size; ++j)
{
uint index = i * size + j;
if(!FloatEquals(ref[index], calc[index]))
{
printf("Miscompare at i = %d j = %d -- ref = %.3f calc = %.3f\n", i, j, ref[index], calc[index]);
incorrect++;
}
}
}
if(incorrect == 0)
printf("Everything's OK\n\n");
}
int main()
{
printf("TEST 1\n");
int A[2 * 2] = {
1, 2,
3, 4
};
float inverse[2 * 2];
float refInverse[2 * 2] = {
-2.0, 1.0,
1.5, -0.5
};
inverseMatrix(A, inverse, 2);
compareInverse(refInverse, inverse, 2);
printf("TEST 2\n");
int B[3 * 3] = {
1, 2, 3,
4, 5, 6,
7, 8, 9
};
float inverseB[3 * 3];
if (inverseMatrix(B, inverseB, 3))
printf("[ERROR]Inverse matrix was calculated but it shouldn't.\n");
else
printf("Everything's OK\n\n");
return 0;
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include "hash_table.h"
#ifndef HASH_TABLE_SIZE
#define HASH_TABLE_SIZE 5
#endif
// According to http://www.cse.yorku.ca/~oz/hash.html
int compute_hash(const char *key, int size){
unsigned long hash = 5381;
int c;
do{
c = *key;
hash = hash*33 + c;
key++;
}while(c);
return hash % size;
}
struct hash_elem *pop(struct hash_elem **bucket){
struct hash_elem *current = *bucket;
if(current == NULL)
return NULL;
*bucket = current->next;
current->next = NULL;
return current;
}
void push(struct hash_elem *elem, struct hash_elem **bucket){
elem->next = *bucket;
*bucket = elem;
}
void hash_create(struct hash_table **t, hash_data_free_fn f){
struct hash_table *hash_table = malloc(sizeof(struct hash_table));
if(hash_table == NULL)
return NULL;
hash_table->data_free = f;
hash_table->num_buckets = HASH_TABLE_SIZE;
hash_table->buckets = malloc(hash_table->num_buckets * sizeof(struct hash_elem*));
if(hash_table->buckets == NULL){
free(hash_table);
return NULL;
}
t = &hash_table;
}
void hash_release(struct hash_table *hash_table){
for(int i=0; i<hash_table->num_buckets; ++i){
struct hash_elem *bucket = hash_table->buckets[i];
while(bucket != NULL){
free(pop(&bucket));
}
}
free(hash_table->buckets);
free(hash_table);
}
void hash_insert(struct hash_table *hash_table, const char* key, void *data){
int index = compute_hash(key, hash_table->num_buckets);
struct hash_elem *bucket = hash_table->buckets[index];
if(bucket->key == NULL){
bucket->key = key;
bucket->data = data;
}else{
struct hash_elem *new_elem = malloc(sizeof(struct hash_elem));
new_elem->key = key;
new_elem->data = data;
push(new_elem, &hash_table->buckets[index]);
}
}
void* hash_find(struct hash_table *hash_table, const char* key){
int index = compute_hash(key, hash_table->num_buckets);
struct hash_elem *bucket = hash_table->buckets[index];
while(bucket != NULL){
if(strcmp(bucket->key, key) == 0){
return bucket->data;
}
bucket = bucket->next;
}
return NULL;
}
void hash_delete(struct hash_table *hash_table, const char* key){
int index = compute_hash(key, hash_table->num_buckets);
struct hash_elem **bucket = &hash_table->buckets[index];
struct hash_elem *prev, *curr;
for(prev=NULL, curr=*bucket; curr!=NULL; prev=curr, curr=curr->next){
if(strcmp(curr->key, key) == 0){
if(prev == NULL){
*bucket = curr->next;
}else{
prev->next = curr->next;
}
free(curr);
break;
}
}
}
|
C
|
#pragma once
unsigned strhash(const char *str) {
unsigned hash = 1;
for(size_t i = 0; str[i]; i++)
hash = 92821 * hash + str[i];
return hash;
}
|
C
|
#include <fcntl.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <assert.h>
static const long k_defaultBlockSize = 4096;
long get_block_size() {
long size = sysconf(_SC_PAGESIZE);
if (size < 0) {
return k_defaultBlockSize;
}
return size;
}
bool is_hole(char* buffer, ssize_t size) {
for (ssize_t i = 0; i < size; ++i) {
if (buffer[i] != 0) {
return false;
}
}
return true;
}
int main(int argc, char* argv[]) {
if (argc < 3) {
printf("Usage: %s <src> <dst>\n", argv[0]);
return -1;
}
const char* src = argv[1];
const char* dst = argv[2];
int src_fd = open(src, O_RDONLY);
if (src_fd == -1) {
printf("Open src file[%s] failed!\n", src);
return -1;
}
int dst_fd = open(dst, O_WRONLY | O_CREAT, 0644);
if (dst_fd == -1) {
printf("Open dst file[%s] failed!\n", dst);
return -1;
}
long block_size = get_block_size();
char* buffer = (char*)malloc(block_size);
ssize_t read_size = 0;
while ((read_size = read(src_fd, buffer, block_size)) > 0) {
if (is_hole(buffer, read_size)) {
lseek(dst_fd, block_size, SEEK_CUR);
continue;
}
if (write(dst_fd, buffer, read_size) < 0) { return -1; }
}
close(src_fd);
close(dst_fd);
return 0;
}
|
C
|
void main()
{
struct point{int x; int y;};
struct point l[2];
l[0] = {13, 14};
l[1] = l[0];
assert(l[0].x == 13, "l[0].x must be 13");
assert(l[0].y == 14, "l[0].y must be 14");
assert(l[1].x == 13, "l[1].x must be 13");
assert(l[1].y == 14, "l[1].y must be 14");
}
|
C
|
#include "holberton.h"
/**
* _isupper - C F T U C C.
* @c: T I C
* Return: 1 I I I U A 0 O.
*/
int _isupper(int c)
{
if (c > 64 && c < 91)
return (1);
return (0);
}
|
C
|
#include <iostream>
#include <string>
#include <stack>
#include <queue>
#include <climits>
#include <cfloat>
using namespace std;
/**********************************************************/
/******** GLOBAL TYPES, CONSTANTS, AND VARIABLES **********/
/**********************************************************/
// define the maximum number of nodes in the graph,
// node id's are assumed to be 0..Vertices-1
const int VERTICES = 4096;
// store the number of nodes currently in the graph
// (initially 0, and cannot exceed VERTICES)
int numnodes = 0;
// store the number of edges currently in the graph
// (initially 0, and cannot exceed (VERTICES-1)^2)
int numedges = 0;
// define the contents of an individual node in the graph
struct node {
int nodeid; // the node's position in Graph[]
string nodename; // text data for the application
float nodedata; // numeric data for the application
bool visited, processed; // flags used for graph traversals
bool inmst; // flag used for spanning tree creation
float distance; // distance from source node
};
// store pointers to the graph nodes in an array,
// Graph[i] contains a pointer to the node whose id is i
node *Graph[VERTICES];
// create the adjacency matrix for the graph,
// Edges[i][j] is a positive weight if there
// is an edge going from node i to node j
// and is 0 otherwise
float Edges[VERTICES][VERTICES];
/**********************************************************/
/************** EDGELIST HEAP CLASS ***********************/
/**********************************************************/
// define the contents of an edge,
// used for building edgelists
// (for use in spanning tree algorithms)
struct edgenode {
int src;
int dest;
float weight;
};
typedef edgenode* edgenodeptr;
// define a heap, used to store edges with
// the minimum weight edge on top
class heap {
public:
heap(int sz = 0);
~heap();
bool insert(edgenode *e);
edgenode *remove();
private:
int maxsize;
int cursize;
edgenode* *edges;
};
edgenode *heap::remove()
{
if ((cursize >= maxsize) || (!edges)) return NULL;
edgenode *victim = edges[0];
edges[0] = edges[--cursize];
edgenode *e = edges[0];
if (!e) return NULL;
edges[cursize] = NULL;
int pos = 0;
do {
// see if e needs to swap with either of its children
int left = 2 * pos + 1;
int right = left + 1;
// quit if there are no children
if ((left >= cursize) || (edges[left] == NULL)) break;
// check against a lone left child
else if (left == (cursize-1)) {
edgenode *tmp = edges[left];
if (tmp->weight < e->weight) {
edges[left] = e;
edges[pos] = tmp;
pos = left;
} else break;
}
// check against the larger of two children
else {
edgenode *l = edges[left];
edgenode *r = edges[right];
if (!l || !r) break;
if ((l->weight > r->weight) && (l->weight > e->weight)) {
edges[left] = e;
edges[pos] = l;
pos = left;
}
else if (r->weight > e->weight) {
edges[right] = e;
edges[pos] = r;
pos = right;
}
else break;
}
} while (pos < cursize);
return victim;
}
bool heap::insert(edgenode *e)
{
// make sure we have an edge to insert
if (!e) return false;
// insert the new edge
edges[cursize++] = e;
// percolate the edge up the heap
int pos = cursize - 1;
while (pos > 0) {
// figure out the position of the parent
int parent = (pos - 1) / 2;
// if the parent is null there's an error
// (there should be no nulls between
// the heap root and the insert point)
if (!edges[parent]) return false;
// if the parent weight is no bigger than e's
// then e is as far up the heap as it needs to go
if (edges[parent]->weight <= e->weight) return true;
// otherwise swap e and its parent
edges[pos] = edges[parent];
edges[parent] = e;
pos = parent;
}
return true;
}
heap::heap(int sz)
{
if (sz < 0) sz = 0;
if (sz == 0) edges = NULL;
else edges = new edgenodeptr[sz];
if (!edges) maxsize = 0;
else maxsize = sz;
cursize = 0;
for (int i = 0; i < maxsize; i++) edges[i] = NULL;
}
heap::~heap()
{
delete edges;
}
/**********************************************************/
/************** GRAPH FUNCTIONS ***************************/
/**********************************************************/
// List of graph functions
void empty_graph();
bool remove_node(int id);
int insert_node(string name, float data);
bool lookup_node(int id, string &name, float &data);
bool add_edge(int src_id, int dest_id, float wt);
float remove_edge(int src_id, int dest_id);
float check_edge(int src_id, int dest_id);
bool print_node(int id);
void print_graph();
int get_graphsize();
int get_maxsize();
void depth_first();
void breadth_first();
bool mst();
int get_numedges();
// return the number of edges currently in the graph
int get_numedges()
{
return numedges;
}
// call print_node on each node in the graph,
// using a depth-first ordering
void depth_first()
{
// set all nodes' visited and processed flags to false
for (int i = 0; i < VERTICES; i++) {
if (Graph[i] != NULL) {
Graph[i]->visited = false;
Graph[i]->processed = false;
}
}
// maintain a stack of nodes to be processed
stack<node*> s;
// id will track the starting node for seperate
// graph components, in case the graph isn't
// fully connected
int id = 0;
int component = 1;
do { // find and process the next graph component, if any
// find the next vertex that hasn't been processed
while ((id < VERTICES) && (Graph[id] == NULL)) id++;
if (id >= VERTICES) return;
if (Graph[id]->processed == true) { id++; continue; }
// otherwise push our new starting point for exploration
// (after setting its visited field to true)
cout << endl << "Processing graph component " << (component++) << endl;
Graph[id]->visited = true;
s.push(Graph[id]);
// while the stack isn't empty
// take the next node off the stack
// and print it
// for each adjacent node
// if it hasn't been visited yet
// set its visited flag to true
// and push it on the stack
while (s.size() > 0) {
node *n = s.top();
s.pop();
if (!n) continue;
int nid = n->nodeid;
print_node(nid);
n->processed = true;
for (int j = 0; j < VERTICES; j++) {
if ((Edges[nid][j] != 0) && (Graph[j] != NULL)) {
if (Graph[j]->visited == false) {
Graph[j]->visited = true;
s.push(Graph[j]);
}
}
}
}
} while (id < VERTICES);
}
// call print_node on each node in the graph,
// using a breadth-first ordering
void breadth_first()
{
// set all nodes' visited and processed flags to false
for (int i = 0; i < VERTICES; i++) {
if (Graph[i] != NULL) {
Graph[i]->visited = false;
Graph[i]->processed = false;
}
}
// maintain a queue of nodes to be processed
deque<node*> q;
// id will track the starting node for seperate
// graph components, in case the graph isn't
// fully connected
int id = 0;
int component = 1;
do { // find and process the next graph component, if any
// find the next vertex that hasn't been visited
while ((id < VERTICES) && (Graph[id] == NULL)) id++;
if (id >= VERTICES) return;
if (Graph[id]->processed == true) { id++; continue; }
// otherwise push our new starting point for exploration
// (after setting its visited field to true)
cout << endl << "Processing graph component " << (component++) << endl;
Graph[id]->visited = true;
q.push_back(Graph[id]);
// while the queue isn't empty
// take the next node out of the queue
// and print it
// for each adjacent node
// if it hasn't been visited yet
// set its visited flag to true
// and put it into the queue
while (q.size() > 0) {
node *n = q.front();
q.pop_front();
if (!n) continue;
int nid = n->nodeid;
print_node(nid);
Graph[nid]->processed = true;
for (int j = 0; j < VERTICES; j++) {
if ((Edges[nid][j] != 0) && (Graph[j] != NULL)) {
if (Graph[j]->visited == false) {
Graph[j]->visited = true;
q.push_back(Graph[j]);
}
}
}
}
} while (id < VERTICES);
}
// call print_node on each node in the graph,
// ordered by the node ids
void print_graph()
{
for (int i = 0; i < VERTICES; i++)
if (Graph[i]) print_node(i);
}
// return the number of nodes currently in the graph
int get_graphsize()
{
return numnodes;
}
// return the number of nodes the graph is capable of holding
// (i.e. vertices)
int get_maxsize()
{
return VERTICES;
}
// initialize an empty graph,
// wiping out the old graph (if any)
void empty_graph()
{
for (int i = 0; i < VERTICES; i++) {
delete Graph[i];
Graph[i] = NULL;
for (int j = 0; j < VERTICES; j++)
Edges[i][j] = 0;
}
numnodes = 0;
}
// if a node with the specified id exists,
// it is removed from the graph
// along with all edges to and from it
// returns true iff a node is removed
bool remove_node(int id)
{
if ((id < 0) || (id >= VERTICES) || (Graph[id] == NULL)) return false;
delete Graph[id];
Graph[id] = NULL;
for (int i = 0; i < VERTICES; i++) {
if (Edges[i][id]) numedges--;
else Edges[i][id] = 0;
if (Edges[id][i]) numedges--;
else Edges[id][i] = 0;
}
numnodes--;
return true;
}
// create a node and insert it's pointer in the first
// free graph position, returning it's id value
// returns -1 if unsuccessful
int insert_node(string name, float data)
{
int id = 0;
while (id < VERTICES) {
if (Graph[id] == NULL) {
Graph[id] = new node;
if (!Graph[id]) return -1;
Graph[id]->nodeid = id;
Graph[id]->nodename = name;
Graph[id]->nodedata = data;
numnodes++;
return id;
}
id++;
}
return -1;
}
// copy the name and data from the node in position id
// return true iff successful
bool lookup_node(int id, string &name, float &data)
{
if ((id < 0) || (id >= VERTICES) || (Graph[id] == NULL)) return false;
name = Graph[id]->nodename;
data = Graph[id]->nodedata;
return true;
}
// create an edge from the node in position src_id
// to the node in position dest_id
// return true iff a new edge is successfully added
bool add_edge(int src_id, int dest_id, float wt)
{
if ((src_id < 0) || (src_id >= VERTICES) || (Graph[src_id] == NULL)) return false;
if ((dest_id < 0) || (dest_id >= VERTICES) || (Graph[dest_id] == NULL)) return false;
if (Edges[src_id][dest_id]) return false;
Edges[src_id][dest_id] = wt;
numedges++;
return true;
}
// remove the edge from the node in position src_id
// to the node in position dest_id
// return the edge weight iff an edge is successfully removed
// and 0 otherwise
float remove_edge(int src_id, int dest_id)
{
if ((src_id < 0) || (src_id >= VERTICES) || (Graph[src_id] == NULL)) return false;
if ((dest_id < 0) || (dest_id >= VERTICES) || (Graph[dest_id] == NULL)) return false;
if (!Edges[src_id][dest_id]) return false;
float weight = Edges[src_id][dest_id];
Edges[src_id][dest_id] = 0;
numedges--;
return weight;
}
// return the edge weight if there is an edge from the node in
// position src_id to the node in position dest_id
// or 0 otherwise
float check_edge(int src_id, int dest_id)
{
if ((src_id < 0) || (src_id >= VERTICES) || (Graph[src_id] == NULL)) return 0;
if ((dest_id < 0) || (dest_id >= VERTICES) || (Graph[dest_id] == NULL)) return 0;
return Edges[src_id][dest_id];
}
// display the name, data and data for the node in
// position id, then list the node ids for every
// node which can be reached via one edge from
// this node
bool print_node(int id)
{
if ((id < 0) || (id >= VERTICES) || (Graph[id] == NULL)) {
cout << "Invalid node: " << id << endl;
return false;
}
cout << "Vertex " << id << ": (";
cout << Graph[id]->nodename << ", " << Graph[id]->nodedata << ") with outgoing edges to =>" << endl;
for (int i = 0; i < VERTICES; i++) {
if (Edges[id][i] > 0) cout << " node " << i << ", weight " << Edges[id][i] << endl;
}
return true;
}
// if the graph has a minimal spanning tree,
// display the list of edges in the tree
// and return true
// otherwise return false
bool mst()
{
// initialize every node's spanning tree flag to false
for (int i = 0; i < VERTICES; i++) {
if (Graph[i] != NULL) {
Graph[i]->inmst = false;
}
}
// create a heap of edgelists, large enough to
// store all the edges currently in the graph
heap edgelist(get_numedges());
// find a starting node and mark it as in the mst
int pos = 0;
int cursize = get_graphsize();
while ((Graph[pos] == NULL) && (pos < cursize)) pos++;
// if there were no nodes then the graph is empty
if (pos >= cursize) return true;
// use a queue of edgenodes to keep track of our mst
deque<edgenode*> mst;
// keep track of the number of nodes in our mst
int mstsize = 1;
// keep a pointer to the current node
node *curr = Graph[pos];
do {
// mark the current node as part of the mst
if (!curr) break;
else curr->inmst = true;
// put the current node's edges in the heap
for (int i = 0; i < VERTICES; i++) {
if (Edges[pos][i] > 0) {
edgenode *new_e = new edgenode;
if (new_e) {
new_e->src = pos;
new_e->dest = i;
new_e->weight = Edges[pos][i];
edgelist.insert(new_e);
}
}
}
// find the top heaped edge that connects an mst node
// to a non-mst node (quit if there is none)
edgenode *nexte;
node *n1, *n2;
while ((nexte = edgelist.remove()) != NULL) {
n1 = Graph[nexte->src];
n2 = Graph[nexte->dest];
if ((!n1) || (!n2)) {
delete nexte;
continue;
}
if (n1->inmst != n2->inmst) break;
}
if (!nexte) break;
// add the selected edge to the mst
mst.push_front(nexte);
mstsize++;
// make the new current node the one the new edge
// adds to the tree
if (n1->inmst) {
n2->inmst = true;
pos = n2->nodeid;
curr = n2;
} else {
n1->inmst = true;
pos = n1->nodeid;
curr = n1;
}
} while(mstsize < get_graphsize());
// if we couldn't build the entire spanning tree
// then the final result is false
// otherwise the mst is now complete, so display it
// and set the final result to true
bool result = false;
if (mstsize >= (get_graphsize() - 1)) {
result = true;
cout << "The complete spanning tree is" << endl;
} else cout << "The partial spanning tree is" << endl;
while (!mst.empty()) {
edgenode *e = mst.front();
mst.pop_front();
if (e) {
cout << e->src << "->" << e->dest << " (" << e->weight << ")" << endl;
delete e;
}
}
return result;
}
// compute and display the distance of each node
// from a designated source node
// return true if successful, false otherwise
bool distances(int src)
{
// make sure the node exists
if (!Graph[src]) return false;
// initialize every node's distance to infinity
for (int i = 0; i < VERTICES; i++) {
if (Graph[i] != NULL) {
Graph[i]->distance = FLT_MAX;
}
}
// initialize the distance to the start node
Graph[src]->distance = 0;
// create a heap big enough to hold all the edges
heap edgelist(get_numedges());
// add all the source node's edges to the heap
for (int d = 0; d < VERTICES; d++) {
if (Edges[src][d] > 0) {
edgenode *e = new edgenode;
if (e) {
e->src = src;
e->dest = d;
e->weight = Edges[src][d];
edgelist.insert(e);
}
}
}
// while the heap isn't empty
// remove the next (smallest) edge from the heap
// if the edge gives us a new shorter path
// to the destination vertex then:
// update the distance to that vertex
// and insert all it's vertices into the graph
// (if the graph is bidirectional we could do similarly
// in the other direction)
edgenode *e;
node *s, *d;
while ((e = edgelist.remove()) != NULL) {
s = Graph[e->src];
d = Graph[e->dest];
float w = e->weight;
if (d->distance > (s->distance + w)) {
for (int j = 0; j < VERTICES; j++) {
if (Edges[e->dest][j] > 0) {
edgenode *new_e = new edgenode;
if (new_e) {
new_e->src = e->src;
new_e->dest = j;
new_e->weight = Edges[e->src][j];
edgelist.insert(new_e);
}
}
}
}
delete e;
}
// go through the graph, displaying the distance to each node
for (int i = 0; i < VERTICES; i++) {
if (Graph[i] && (i != src)) {
cout << src << "->" << i << " distance: ";
if (Graph[i]->distance == FLT_MAX) cout << "infinite" << endl;
else cout << Graph[i]->distance << endl;
}
}
return true;
}
/**********************************************************/
/******** APPLICATION FUNCTIONS ***************************/
/**********************************************************/
// List of application functions
char getcommand();
void printmenu();
bool processcommand(char cmd);
int getint();
float getfloat();
int main()
{
printmenu();
char cmd = getcommand();
while (processcommand(cmd)) {
cout << endl;
cmd = getcommand();
}
return 0;
}
char getcommand()
{
cout << "Enter your command choice (T, B, D, G, V, E, I, A, R, C, H, Q, S, M, N)" << endl;
char cmd;
cin >> cmd;
cmd = toupper(cmd);
switch (cmd) {
case 'G':
case 'V':
case 'E':
case 'B':
case 'D':
case 'I':
case 'A':
case 'R':
case 'C':
case 'S':
case 'T':
case 'M':
case 'N':
case 'H':
case 'Q': return cmd;
default: cout << "You have entered an invalid command" << endl;
return getcommand();
}
}
void printmenu()
{
cout << "Enter A to add an edge," << endl;
cout << " or B to perform a breadth-first traversal of the graph," << endl;
cout << " or C to eliminate an edge," << endl;
cout << " or D to perform a depth-first traversal of the graph," << endl;
cout << " or E to display a single edge," << endl;
cout << " or G to print the entire graph," << endl;
cout << " or H for help," << endl;
cout << " or I to insert a new vertex," << endl;
cout << " or M to lookup the number of elements the graph can hold," << endl;
cout << " or N to start a new (empty) graph," << endl;
cout << " or Q to quit." << endl;
cout << " or R to remove a vertex," << endl;
cout << " or S to lookup the number of elements currently in the graph," << endl;
cout << " or T to compute the minimal spanning tree." << endl;
cout << " or V to display a single vertex," << endl;
}
bool processcommand(char cmd)
{
string key;
float data, wt;
int id, src, dest;
bool result1, result2;
switch (cmd) {
case 'T': cout << "Computing minimal spanning tree:" << endl;
if (!mst()) cout << "There is no spanning tree" << endl;
break;
case 'D': cout << "Performing depth-first search" << endl;
depth_first();
break;
case 'B': cout << "Performing breath-first search" << endl;
breadth_first();
break;
case 'H': printmenu();
break;
case 'I': cout << "Inserting new vertex" << endl;
cout << "Enter the text data for the new vertex" << endl;
cin >> key;
data = getfloat();
cout << "(" << key << "," << data << ") ";
id = insert_node(key, data);
if (id >= 0)
cout << "was inserted with id " << id << endl;
else cout << "was not inserted correctly" << endl;
break;
case 'S': cout << "There are " << get_graphsize() << " vertices in the graph" << endl;
break;
case 'M': cout << "The graph can hold " << get_maxsize() << " vertices" << endl;
break;
case 'N': empty_graph();
cout << "The graph has been emptied" << endl;
break;
case 'R': id = getint();
result1 = lookup_node(id, key, data);
result2 = remove_node(id);
if (result1 && result2) {
cout << "Removed vertex " << id << " (";
cout << key << "," << data << ")" << endl;
} else {
cout << "Unable to remove vertex " << id << endl;
}
break;
case 'G': cout << "The graph contents are: " << endl;
print_graph();
break;
case 'V': id = getint();
print_node(id);
break;
case 'E': cout << "For the source, ";
src = getint();
cout << "For the destination, ";
dest = getint();
wt = check_edge(src, dest);
if (wt != 0) {
cout << "There is an edge from " << src << " to " << dest;
cout << " with weight " << wt << endl;
} else {
cout << "There is no edge from " << src << " to " << dest << endl;
}
break;
case 'A': cout << "Adding new edge:" << endl;
cout << "For the source, ";
src = getint();
cout << "For the destination, ";
dest = getint();
cout << "For the edge weight, ";
wt = getfloat();
if (add_edge(src, dest, wt) && add_edge(dest, src, wt)) {
cout << "Added edge from " << src << " to " << dest;
cout << ", weight " << wt << endl;
} else
cout << "Unable to add an edge from " << src << " to " << dest << endl;
break;
case 'C': cout << "For the source, ";
src = getint();
cout << "For the destination, ";
dest = getint();
wt = remove_edge(src, dest);
if (wt != 0) {
cout << "Removed an edge from " << src << " to " << dest;
cout << ", with weight " << wt << endl;
} else {
cout << "Unable to remove an edge from " << src << " to " << dest << endl;
}
break;
case 'Q': return false;
default: return true;
}
return true;
}
int getint()
{
string tmp;
cout << "Enter a vertex id" << endl;
cin >> tmp;
return atoi(tmp.c_str());
}
float getfloat()
{
string tmp;
cout << "Enter a numeric value" << endl;
cin >> tmp;
return atof(tmp.c_str());
}
|
C
|
// Ex 1.3.2: Calculates the area of a right traingle from user inputs (base, height)
#include <stdio.h>
int main()
{
float base, height, area;
printf("RIGHT TRIANGLE AREA\n\n");
// Ask user for the base and height
printf("Please enter length of triangle's base: ");
scanf("%f", &base);
printf("Please enter length of triangle's height: ");
scanf("%f", &height);
// Calculate area
area = 0.5*base*height;
// Print area
printf("\nThe area of the right triangle is: %f\n", area);
return 0;
}
|
C
|
#define _REENTRANT
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/uio.h>
#include <unistd.h>
#include <pthread.h>
#include "server.h"
extern int errno;
/*
************* Globals *************
*/
/* The table consisting of all the backend servers */
typedef struct _server_table {
int free; /* Is the server free? */
int fd[MAX_FILES]; /* FDs open on this server */
char name[MAX_S_NAME]; /* Name of server */
}server_table;
/*
* The table representing list of ALL files
* This also has the entries to the server_table where the
* file can be found.
*/
typedef struct _file_table {
int tot_idx; /* Total number of server indexes */
int request; /* Popularity of this file */
int index[MAX_SERVERS]; /* Indexes into the server_table */
char name[MAX_PATH]; /* Name of the file */
}file_table;
/* regulates access to server_list and total_servers */
pthread_mutex_t s_lock = PTHREAD_MUTEX_INITIALIZER;
/* regulates access to file_list and total_files*/
pthread_mutex_t f_lock = PTHREAD_MUTEX_INITIALIZER;
/* These tables are globally distributed among all servers */
static file_table file_list[MAX_FILES];
static server_table server_list[MAX_SERVERS];
static int server_port = -1;
static char this_host[MAX_S_NAME];
static int total_files = 0; /* Total number of unique files */
static int total_servers = 0; /* Total servers */
/*
* Main program
*/
int main(int argc, char **argv) {
int flag = 1;
if (argc < 2) {
printf("Error! Give the port to bind to\n");
exit(1);
}
sscanf(*(argv + 1), "%d", &server_port);
/* get this host's name */
if (gethostname(this_host, sizeof(this_host)) < 0) {
perror("Gethostname");
exit(1);
}
printf("This host: %s\n\n", this_host);
/* Get list of other servers that are running */
printf("Enter other hostnames, where server is running\nEnter . to end\n");
while(flag && (total_servers < MAX_SERVERS)) {
char server[MAX_S_NAME];
scanf("%s", server);
if (server[0] == '.')
flag = 0;
add_server(server);
}
/* Call the listener/forker */
printf("Binding to port %d\n", server_port);
bind_accept_fork(server_port, do_chld);
/* Never reached */
return(0);
}
/* Returns this host's index in the server table */
int get_this_host_idx()
{
int i;
for (i = 0; i < total_servers; i++) {
if (!strcmp(server_list[i].name, this_host)) {
return(i);
}
}
/* Must never reach */
return(-1);
}
/* Fill the local file table, fetching entries from disk */
int fill_file_list(void)
{
int i, j, flag = 0;
int t_files;
int s_idx = -1;
char dir_buff[MAX_FILES][MAX_PATH];
/* get this host's entry in the server table */
if ((s_idx = get_this_host_idx()) < 0) {
return(-1);
}
/* put all local files into file_list (take union) */
t_files = my_scandir(DFS, dir_buff);
for (i = 0; i < t_files; i++) {
/* Search for this file in the file_list */
for (j = 0; j < total_files; j++) {
if (strcmp(file_list[j].name, dir_buff[i]) == 0) {
/* update the entry */
file_list[j].request = 0;
file_list[j].index[file_list[j].tot_idx++] = s_idx;
flag = 1;
break;
}
}
if (!flag) {
/* create new entry */
strcpy(file_list[total_files].name, dir_buff[i]);
file_list[total_files].request = 0;
file_list[total_files].tot_idx = 1;
file_list[total_files].index[0] = s_idx;
total_files++;
}
flag = 0;
}
return(1);
}
/* Adds given hostname to the list of other servers */
void add_server(const char* server)
{
int s_socket = -1;
static int init = 0;
/* If we got a "." then simply fill the server table and file tables */
/* "." must be the first input from the user */
if (!strcmp(".", server)) {
/* return if init is over */
if (init) return;
/* Add this host to the server table */
pthread_mutex_lock(&s_lock); /* lock */
strcpy(server_list[total_servers].name, this_host);
server_list[total_servers].free = MAX_FREE;
total_servers++;
pthread_mutex_unlock(&s_lock); /* unlock */
/* Fill the local file table */
pthread_mutex_lock(&f_lock);
if (fill_file_list() < 0) {
printf("Error! Unable to fill the file table\n");
exit(1);
}
pthread_mutex_unlock(&f_lock);
return;
}
/* Connect to the server and get a list of files */
if ((s_socket = connect_to_server(server, server_port)) < 0) {
perror("Error!");
printf("Server not added to list\n");
return;
}
if (!init) {
init = 1;
/* update the local server_list */
pthread_mutex_lock(&s_lock); /* lock */
if (update_local_st(s_socket) < 0) {
printf("Update of local server table failed\n");
exit(1);
}
/* Add this host to the server table */
strcpy(server_list[total_servers].name, this_host);
server_list[total_servers].free = MAX_FREE;
total_servers++;
pthread_mutex_unlock(&s_lock); /* unlock */
/* Update the local file_list */
pthread_mutex_lock(&f_lock); /* lock */
if (update_local_ft(s_socket) < 0) {
printf("Failed to update local file table\n");
exit(1);
}
/* Add this server's files to the file_table */
if (fill_file_list() < 0) {
printf("Error! unable to fill the file table.\n");
exit(1);
}
pthread_mutex_unlock(&f_lock); /* unlock */
}
/* Now we have the latest copy of both the tables
Send this table to the remote server*/
/* Update the remote server table */
pthread_mutex_lock(&s_lock); /* lock */
if (update_remote_st(s_socket) < 0) {
printf("Update of remote server table failed\n");
pthread_mutex_unlock(&s_lock);
exit(1);
}
pthread_mutex_unlock(&s_lock); /* unlock */
/* Update the remote file table */
pthread_mutex_lock(&f_lock); /* lock */
if (update_remote_ft(s_socket) < 0) {
printf("Update of remote file table failed\n");
pthread_mutex_unlock(&f_lock);
exit(1);
}
pthread_mutex_unlock(&f_lock); /* unlock */
printf("***ADD_SERVER***: total files: %d, total servers %d\n",
total_files, total_servers);
/* End */
client_end(s_socket);
}
/*
* This is the routine that is executed from a new thread
* The thread represents one client
*/
void *do_chld(void *arg)
{
int client_socket = (int) arg;
/* the socket to the server if we are the controller */
int len = 0;
int flag = 1;
printf("Child thread: Socket number = %d\n", client_socket);
while (flag) {
struct op_hdr get_hdr;
/* Read the header */
printf("\t\t\tfirst read\n");
READ_SOC(len, client_socket, &get_hdr, HDR_SIZE);
printf("***HDR***: op: 0x%x, p1: %d, p2: %d, p3: %d\n",
get_hdr.op, get_hdr.p1, get_hdr.p2, get_hdr.p3);
/* ACT */
switch (get_hdr.op) {
case OP_GET_ST:
get_st(client_socket, get_hdr);
break;
case OP_GET_FT:
get_ft(client_socket, get_hdr);
break;
case OP_SET_ST:
set_st(client_socket, get_hdr);
break;
case OP_SET_FT:
set_ft(client_socket, get_hdr);
break;
case OP_OPEN:
server_open(client_socket, get_hdr);
break;
case OP_READ:
server_read(client_socket, get_hdr);
break;
case OP_WRITE:
server_write(client_socket, get_hdr);
break;
case OP_SEEK:
server_seek(client_socket, get_hdr);
break;
case OP_SCANDIR:
server_scandir(client_socket, get_hdr);
break;
case OP_CLOSE:
server_close(client_socket, get_hdr);
break;
case OP_END:
flag = 0;
printf("***END***\n");
break;
default:
/* ERROR! */
/* Since we are the server, we dont know how to handle
errors on the client */
get_hdr.op = -1;
WRITE_SOC(len, client_socket, &get_hdr, HDR_SIZE);
printf("Bad opcode: 0x%x\n", get_hdr.op);
break;
}
}
printf("Child: Done Processing...\n");
/* close the socket and exit this thread */
close(client_socket);
pthread_exit((void *)NULL);
/* never reached */
return(NULL);
}
/*
* Returns the name of the server that will process the
* request for the client.
* Caller must lock both tables
*/
int select_peer(int f_idx)
{
int s_idx = -1;
int max_pair = 0; /* stores max of free+request for this file */
int max_free = 0; /* The server's index that is most free */
int i, j;
/* Traverse all servers and find the highest free + request pair */
max_free = 0;
for (i = 0; i < total_servers; i++) {
/* Find server that is most free */
if (server_list[i].free > server_list[max_free].free)
max_free = i;
}
/* Traverse all servers having this file */
for (j = 0; j < file_list[f_idx].tot_idx; j++) {
int tmp = 0;
/* Calc max of free+request */
if ((tmp = server_list[j].free +
file_list[f_idx].request) > max_pair) {
max_pair = tmp;
s_idx = j; /* server to connect to */
}
}
/* If the chosen server is the localhost */
if (s_idx == get_this_host_idx()) {
/* See if this file needs to be replicated
* Only local files are replicated */
if ((file_list[f_idx].request >= REPL_THRESH &&
max_free != s_idx)) {
printf("***REPLICATE*****\n");
printf("File: %s, server from: %s, server to: %s\n",
file_list[f_idx].name, server_list[s_idx].name,
server_list[max_free].name);
if (replicate(f_idx, max_free) < 0)
printf("Warning! Replication failed\n");
}
}
printf("***SELECT_PEER***\n");
printf("\tRequested file: %s\n", file_list[f_idx].name);
printf("\tChosen server: %s, server_free: %d\n\tfile_req: %d\n",
server_list[s_idx].name, server_list[s_idx].free,
file_list[f_idx].request);
return(s_idx);
}
/*
* Increments/decrements local tables to reflect a file open
* Must be called whenever a file is opened on localhost
*/
void on_fopen(int s_idx, int f_idx)
{
int i;
/* Decrement the *freeness* of this server */
server_list[s_idx].free = (server_list[s_idx].free < 2)?0:
(server_list[s_idx].free - 2);
/* Increment *freeness* all servers */
for (i = 0; i < total_servers; i++) {
server_list[i].free =
(server_list[i].free < MAX_FREE)?server_list[i].free++:MAX_FREE;
}
/* Update the file's request field */
file_list[f_idx].request++;
}
/* gets the file index in file_list, given a file name */
int get_file_idx(const char *fname)
{
int i;
/* Locate file in the file table */
for (i = 0; i < total_files; i++) {
if (strcmp(file_list[i].name, fname) == 0) {
return(i);
}
}
/* Never reached */
return(-1);
}
/*
* Replicates a given local file onto a remote server
* Takes the index in the server table for "to"
* Caller must lock the global tables (modifies the file_list)
*/
int replicate(int f_idx, int to)
{
char *f_name = file_list[f_idx].name;
char *s_to = server_list[to].name;
int fd_to = -1;
int fd_from = -1;
int sock_to = -1;
int r_len = -1, w_len = -1;
char buff[8192];
char path_buff[MAX_PATH];
/* connect to servers */
if ((sock_to = connect_to_server(s_to, server_port)) < 0 ) {
perror("Replication failed");
return(-1);
}
/* open files */
strcpy(path_buff, DFS);
strcpy(path_buff + strlen(DFS), f_name);
if ((fd_from = open(path_buff, O_RDONLY)) < 0) {
perror("Replication failed");
return(-2);
}
if ((fd_to = client_open(sock_to, f_name,
O_CREAT | O_WRONLY | O_REPLICATE)) < 0 ) {
perror("Replication failed");
client_end(sock_to);
return(-2);
}
/* read file from source and transfer to dest server */
do {
if ((r_len = read(fd_from, buff, sizeof(buff))) < 0) {
perror("Replication failed");
close(fd_from);
client_close(sock_to, fd_to);
client_end(sock_to);
return(-3);
}
if ((w_len = client_write(sock_to, fd_to, buff,
r_len)) < 0 ) {
perror("Replication failed");
close(fd_from);
client_close(sock_to, fd_to);
client_end(sock_to);
return(-4);
}
} while (r_len == sizeof(buff)); /* read until eof */
/* close files */
close(fd_from);
client_close(sock_to, fd_to);
client_end(sock_to);
/* update tables - add destn server to file's record */
file_list[f_idx].index[file_list[f_idx].tot_idx++] = to;
return(0);
}
/*
* Updates a remote server table with the local server's server_list
* caller locks all tables
*/
int update_remote_st(int s_socket)
{
struct op_hdr put_hdr, get_hdr;
int len, i;
put_hdr.op = OP_SET_ST;
put_hdr.p1 = total_servers;
WRITE_SOC(len, s_socket, &put_hdr, HDR_SIZE);
/* read the ack */
READ_ALL(len, s_socket, &get_hdr, HDR_SIZE);
if (get_hdr.op != put_hdr.op) {
return(-1);
}
/* DBG write one array ele at a time */
for (i = 0; i < total_servers; i++) {
WRITE_SOC(len, s_socket, &server_list[i],
sizeof(server_table));
//printf("update_remote_st wrote %d\n", len);
}
return(1);
}
/*
* Update the local server_list from remote server
* caller locks all tables
*/
int update_local_st(int s_socket)
{
struct op_hdr put_hdr, get_hdr;
int len, i;
/* Get the remote host's server table */
put_hdr.op = OP_GET_ST;
WRITE_SOC(len, s_socket, &put_hdr, HDR_SIZE);
/* read the ack */
READ_ALL(len, s_socket, &get_hdr, HDR_SIZE);
if (get_hdr.op != put_hdr.op) {
return(-1);
}
total_servers = get_hdr.p1;
/* Safer to update one array element at a time */
for (i = 0; i < total_servers; i++) {
READ_ALL(len, s_socket, &server_list[i],
sizeof(server_table));
}
return(1);
}
/*
* Update the local file_list from remote server
* caller locks all tables
*/
int update_local_ft(int s_socket)
{
struct op_hdr put_hdr, get_hdr;
int len, i;
/* Get the remote host's file table */
put_hdr.op = OP_GET_FT;
WRITE_SOC(len, s_socket, &put_hdr, HDR_SIZE);
/* Read the ack */
READ_ALL(len, s_socket, &get_hdr, HDR_SIZE);
if(get_hdr.op != put_hdr.op) {
return(-1);
}
total_files = get_hdr.p1;
/* Safer to update one array element at a time */
for (i = 0; i < total_files; i++) {
READ_ALL(len, s_socket, &file_list[i],
sizeof(file_table));
}
return(1);
}
/*
* Updates a remote file table with the local server's file_list
* caller locks all tables
*/
int update_remote_ft(int s_socket)
{
struct op_hdr put_hdr, get_hdr;
int len, i;
put_hdr.op = OP_SET_FT;
put_hdr.p1 = total_files;
WRITE_SOC(len, s_socket, &put_hdr, HDR_SIZE);
/* read the ack */
READ_ALL(len, s_socket, &get_hdr, HDR_SIZE);
if (get_hdr.op != put_hdr.op) {
return(-1);
}
/* DBG write one array ele at a time */
for (i = 0; i < total_files; i++) {
WRITE_SOC(len, s_socket, &file_list[i],
sizeof(file_table));
// printf("update_remote_ft wrote %d\n", len);
}
return(1);
}
/* Sends the local server table */
int get_st(int client_socket, struct op_hdr get_hdr)
{
int len = -1;
int i;
struct op_hdr put_hdr;
/* return the ack */
put_hdr.op = OP_GET_ST;
put_hdr.p1 = total_servers;
WRITE_SOC(len, client_socket, &put_hdr, HDR_SIZE);
/* Send the array upto total_servers */
pthread_mutex_lock(&s_lock); /* lock */
/* Send one array element at a time */
for (i = 0; i < total_servers; i++) {
WRITE_SOC(len, client_socket, &server_list[i],
sizeof(server_table));
// printf("get_st wrote: %d\n", len);
}
pthread_mutex_unlock(&s_lock); /* unlock */
return(1);
}
/* Sends the local File table */
int get_ft(int client_socket, struct op_hdr get_hdr)
{
int len = -1;
int i;
struct op_hdr put_hdr;
/* return the ack */
put_hdr.op = OP_GET_FT;
put_hdr.p1 = total_files;
WRITE_SOC(len, client_socket, &put_hdr, HDR_SIZE);
/* Send the array upto total_files */
pthread_mutex_lock(&f_lock); /* lock */
/* Write one struct element at a time */
for (i = 0; i < total_files; i++) {
WRITE_SOC(len, client_socket, &file_list[i],
sizeof(file_table));
// printf("get_ft wrote %d\n", len);
}
pthread_mutex_unlock(&f_lock); /* unlock */
return(1);
}
/* Set this server's Server table */
int set_st(int client_socket, struct op_hdr get_hdr)
{
int len = -1, i;
struct op_hdr put_hdr;
/* Send the ack */
put_hdr.op = OP_SET_ST;
WRITE_SOC(len, client_socket, &put_hdr, HDR_SIZE);
/* Read upto total_servers entries in the remote host */
pthread_mutex_lock(&s_lock); /* lock */
total_servers = get_hdr.p1;
/* Safer to write one array element at a time */
for (i = 0; i < total_servers; i++) {
READ_ALL(len, client_socket, &server_list[i],
sizeof(server_table));
// printf("set_st wrote %d\n", len);
}
pthread_mutex_unlock(&s_lock); /* unlock */
return(1);
}
/* Set this server's File table */
int set_ft(int client_socket, struct op_hdr get_hdr)
{
int len = -1, i;
struct op_hdr put_hdr;
/* Send the ack */
put_hdr.op = OP_SET_FT;
WRITE_SOC(len, client_socket, &put_hdr, HDR_SIZE);
/* Read upto total_file entries in the remote host */
pthread_mutex_lock(&f_lock); /* lock */
total_files = get_hdr.p1;
/* Safer to write one array element at a time */
for (i = 0; i < total_files; i++) {
READ_ALL(len, client_socket, &file_list[i],
sizeof(file_table));
// printf("set_ft wrote %d, asked %d\n", len, sizeof(file_table));
}
pthread_mutex_unlock(&f_lock); /* unlock */
return(1);
}
/* Scans given directory and returns the number of entries added to array */
int my_scandir(const char *dir_name, char file_list[MAX_FILES][MAX_PATH])
{
DIR *dirp = NULL;
struct dirent *dp = NULL;
int next = 0;
/* open the directory */
dirp = opendir(dir_name);
/* Read contents of local directory and put it into array */
while(dirp && (next < MAX_FILES)) {
if ((dp = readdir(dirp)) != NULL) {
if (strcmp(dp->d_name, ".") != 0
&& strcmp(dp->d_name, "..") != 0) {
strcpy(file_list[next++], dp->d_name);
}
} else {
closedir(dirp);
break;
}
}
return next;
}
/* returns directory contents of the root directory (/DFS) */
void server_scandir(int client_socket, struct op_hdr get_hdr)
{
int len = -1;
struct op_hdr put_hdr;
char file_list[MAX_FILES][MAX_PATH];
int next;
/* init */
put_hdr = get_hdr;
printf("\tScan dir \n");
/* Send the size of array (number of files) */
next = my_scandir(DFS, file_list);
put_hdr.p1 = next;
WRITE_SOC(len, client_socket, &put_hdr, HDR_SIZE);
/* Send the array */
WRITE_SOC(len, client_socket, &file_list[0],
MAX_PATH * next);
printf("Directory scan complete\n");
}
/*
* Called when server got OP_OPEN
* The server opens the file and passes the fd back to client
*/
void server_open(int client_socket, struct op_hdr get_hdr) {
int len = -1;
int fd = -1; /* FD */
int mode = -1;
int name_len = 0;
int s_idx = -1;
int f_idx;
int i;
int update_ok = 0;
struct op_hdr put_hdr;
char path_buff[MAX_PATH];
/* init */
put_hdr = get_hdr;
mode = get_hdr.p1;
name_len = get_hdr.p2; /* Size of file name */
printf("\tname_len: %d, mode: %d\n", name_len, mode);
/* Generate path prefix */
strcpy(path_buff, DFS);
/* Read the actual data (name of the file) */
READ_ALL(len, client_socket, path_buff + strlen(DFS), name_len);
path_buff[name_len + strlen(DFS)] = '\0';
if ((f_idx = get_file_idx(path_buff + strlen(DFS))) < 0) {
errno = EACCES;
perror("File open failed");
put_hdr.op = ERR_OPEN;
put_hdr.p1 = errno;
WRITE_SOC(len, client_socket, &put_hdr, HDR_SIZE);
}
printf("\tfilename: %s\n", path_buff);
pthread_mutex_lock(&s_lock); // lock
pthread_mutex_lock(&f_lock); // lock
/*
* Current server will be used if file is being replicated
* or if the file mode has a OP_REDIRECT.
* Send the relative path
*/
if ((mode & O_REPLICATE) || (mode & OP_REDIRECT)) {
int cp_mode = mode;
s_idx = get_this_host_idx();
/* Remove the mode bit */
if (cp_mode & O_REPLICATE) {
update_ok = 0;
mode = mode & ~O_REPLICATE;
}
if (cp_mode & OP_REDIRECT) {
update_ok = 1;
mode = mode & ~OP_REDIRECT;
}
} else {
update_ok = 1;
/* Find the best server to get the file from */
if ((s_idx = select_peer(f_idx)) < 0) {
printf("Requested file: %s not found in table, new file?\n",
path_buff);
/* Maybe user's mode is O_CREAT | O_WRONLY
assume s_idx to be local server */
s_idx = get_this_host_idx();
}
}
/* See if chosen server is the local host */
if (s_idx == get_this_host_idx()) {
/* Open the requested file */
put_hdr.op = OP_OPEN;
if ((fd = open(path_buff, mode,(mode_t)0644)) < 0) {
perror("File open failed");
put_hdr.op = ERR_OPEN;
put_hdr.p1 = errno;
WRITE_SOC(len, client_socket, &put_hdr, HDR_SIZE);
pthread_mutex_unlock(&f_lock); // unlock
pthread_mutex_unlock(&s_lock); // unlock
return;
}
/* Add the FD to the server table */
server_list[s_idx].fd[f_idx] = fd;
/* Reply with the result */
put_hdr.p1 = fd;
WRITE_SOC(len, client_socket, &put_hdr, HDR_SIZE);
printf("Opened %s, FD: %d\n", path_buff, fd);
/* Is it OK to send updates? */
if (update_ok) {
/* File is being opened on localhost, update tables */
on_fopen(s_idx, f_idx);
/*
* Both server_list and file_list have changed
* Update all other remote server tables.
*/
for (i = 0; i< total_servers; i++) {
int s_sock = -1;
/* Skip if localhost */
if (i == get_this_host_idx())
continue;
/* Connect */
if ((s_sock = connect_to_server(server_list[i].name,
server_port)) < 0) {
perror("[server_open] Connect");
continue;
}
/* Update remote server_list */
if (update_remote_st(s_sock) < 0) {
printf("Update of server_list to %s failed\n",
server_list[i].name);
client_end(s_sock);
continue;
}
/* Update the remote file_list */
if (update_remote_ft(s_sock) < 0) {
printf("Update of file_list to %s failed\n",
server_list[i].name);
client_end(s_sock);
continue;
}
/* End this session */
client_end(s_sock);
}
}
} else {
/* Redirect */
char *s_name = server_list[s_idx].name;
int s_len = strlen(s_name);
/* Redirect the client */
put_hdr.op = OP_REDIRECT;
put_hdr.p1 = s_len; /* Length of next pkt */
WRITE_SOC(len, client_socket, &put_hdr, HDR_SIZE);
/* Send the server to connect to */
WRITE_SOC(len, client_socket, s_name, s_len);
}
pthread_mutex_unlock(&f_lock); // unlock
pthread_mutex_unlock(&s_lock); // unlock
}
/*
* Called on OP_READ request
* The server reads the given fd and then transmits it back
*/
void server_read(int client_socket, struct op_hdr get_hdr)
{
int len = -1, len2 = -1;
int fd = -1; /* FD */
int client_size = -1; /* buffer on client side */
struct op_hdr put_hdr;
/* init */
put_hdr = get_hdr;
fd = get_hdr.p1;
client_size = get_hdr.p2;
printf("\tRead on FD: %d\n", fd);
/* Read the file */
{
char buff[client_size];
if ((len2 = read(fd, buff, client_size)) < 0) {
perror("server failed to read file");
put_hdr.op = ERR_READ;
put_hdr.p1 = errno;
WRITE_SOC(len, client_socket, &put_hdr, HDR_SIZE);
return;
}
/* Reply */
put_hdr.p1 = len2;
WRITE_SOC(len, client_socket, &put_hdr, HDR_SIZE);
/* Send the data */
WRITE_SOC(len, client_socket, buff, put_hdr.p1);
}
printf("\tSent file of size: %d\n", put_hdr.p1);
}
/*
* Called on OP_WRITE request
*/
void server_write(int client_socket, struct op_hdr get_hdr)
{
int len = -1;
int fd = -1; /* FD */
int file_size = -1;
struct op_hdr put_hdr;
/* init */
put_hdr = get_hdr;
fd = get_hdr.p1;
file_size = get_hdr.p2;
printf("\tWrite on FD: %d\n", fd);
/* write the file to disk */
{
char buff[file_size];
READ_ALL(len, client_socket, buff, file_size);
if ((len = write(fd, buff, file_size)) != file_size) {
perror("Server failed to write file");
put_hdr.op = ERR_WRITE;
put_hdr.p1 = errno;
WRITE_SOC(len, client_socket, &put_hdr, HDR_SIZE);
return;
}
}
/* Reply */
put_hdr.p1 = len;
WRITE_SOC(len, client_socket, &put_hdr, HDR_SIZE);
printf("\tWrote file of size: %d\n", file_size);
}
/*
* Called on OP_SEEK request
*/
void server_seek(int client_socket, struct op_hdr get_hdr)
{
int fd = -1; /* FD */
off_t offset = -1;
int whence = -1;
int len = -1;
struct op_hdr put_hdr;
/* init */
put_hdr = get_hdr;
fd = get_hdr.p1;
offset = get_hdr.p2;
whence = get_hdr.p3;
printf("\tSeek on FD: %d, offset: %d, whence: %d\n",
fd, (int)offset, (int)whence);
/* seek the given fd */
if ((put_hdr.p1 = lseek(fd, offset, whence)) < 0) {
perror("Server failed to seek");
put_hdr.op = ERR_SEEK;
put_hdr.p1 = errno;
WRITE_SOC(len, client_socket, &put_hdr, HDR_SIZE);
return;
}
/* Reply to client */
WRITE_SOC(len, client_socket, &put_hdr, HDR_SIZE);
printf("seek on %d returned %d\n", fd, put_hdr.p1);
}
/*
* Called on OP_CLOSE request
*/
void server_close(int client_socket, struct op_hdr get_hdr)
{
struct op_hdr put_hdr;
int fd = -1;
int len = -1;
int s_idx;
int f_idx;
int i, j;
int mode;
/* init */
put_hdr = get_hdr;
fd = get_hdr.p1;
/* Get mode of opening */
mode = fcntl(fd, F_GETFL);
/* close the fd */
if ((put_hdr.p1 = close(fd) < 0)) {
perror("File close failed");
put_hdr.op = ERR_CLOSE;
put_hdr.p1 = errno;
WRITE_SOC(len, client_socket, &put_hdr, HDR_SIZE);
return;
}
/* reply to client */
WRITE_SOC(len, client_socket, &put_hdr, HDR_SIZE);
printf("Closed file FD: %d\n", fd);
/* If the file was opened in write mode, replicate it to all servers */
if (mode == -1) {
perror("fcntl failed");
return;
} else if ((mode & O_ACCMODE) == O_WRONLY) {
/* Search for this FD in the server_list */
s_idx = get_this_host_idx();
f_idx = -1;
for (i = 0; i < total_files; i++) {
if (server_list[s_idx].fd[i] == fd) {
f_idx = i;
server_list[s_idx].fd[f_idx] = 0; /* Reset */
break;
}
}
if (f_idx < 0) return;
/* Replicate this file */
/* Traverse all servers having this file */
for (j = 0; j < file_list[f_idx].tot_idx; j++) {
if (j == s_idx) {
/* localhost */
continue;
}
if (replicate(f_idx, j) < 0) {
/* Ignore all errors */
printf("[server_close] Warning! replication failed");
}
}
}
}
|
C
|
/*
*
* This code calculates the house price of a house by learing from
* training data. It uses pseudo inverse of a given matrix to find the
* weight of different features.
*
* Predicted Price : Y = W0 + W1*x1 + W2*X2 + W3*X3 + W4*X4
* Weight Matrix : W = pseudoInv(X)*Y
* pseudoInv(X) = inverse(transpose(X)*X) * transpose(X)
*
* weight(w) = pseudoInv(X) * Y
* where X = Input data matrix
* Y = Target vector
*
*/
#include<stdio.h>
#include<stdlib.h>
// all methods declarations
double** multiplyMatrix(double **matA, double **matB, int r1, int c1, int r2, int c2);
double** transposeMatrix(double** mat, int row, int col);
double** inverseMatrix(double **matA, int dimension);
double** makeArray(int rows, int columns){
double** matrix = (double**) malloc(rows*sizeof(double*));
for(int i =0; i < rows; i++){
matrix[i] = (double*) malloc(columns*sizeof(double*));
}
return matrix;
}
// main method starts here
int main(int argc, char** argv){
// your code goes here
FILE *fp1 = fopen(argv[1],"r");
FILE *fp2 = fopen(argv[2],"r");
if(fp1 == NULL || fp2 == NULL){
printf("Error\n");
if(fp1)
fclose(fp1);
if(fp2)
fclose(fp2);
return 0;
}
int numberOfRows;
int numberOfColumns;
fscanf(fp1,"%d\n", &numberOfColumns);
fscanf(fp1,"%d\n", &numberOfRows);
int numberORowsInTest;
fscanf(fp2,"%d\n", &numberORowsInTest);
numberOfColumns = numberOfColumns +1;
if(numberOfRows == 0 || numberORowsInTest == 0){
if(fp1)
fclose(fp1);
if(fp2)
fclose(fp2);
return 0;
}
double** matrixX = makeArray(numberOfRows,numberOfColumns);
double** matrixY = makeArray(numberOfRows,1);
for(int i=0; i < numberOfRows; i++){
matrixX[i][0] = 1;
}
for(int i=0; i < numberOfRows; i++){
for(int j=1; j <= numberOfColumns;j++){
if(j == numberOfColumns){
fscanf(fp1,"%lf%*[,]",&matrixY[i][0]);
}else{
fscanf(fp1,"%lf%*[,]",&matrixX[i][j]);
}
}
}
double** matrixTest = makeArray(numberORowsInTest,numberOfColumns);
/*for(int i=0; i < numberORowsInTest; i++){
matrixTest[i] = (double*) malloc((numberOfColumns)*sizeof(double*));
}*/
for(int i=0; i < numberORowsInTest; i++){
matrixTest[i][0] = 1;
}
for(int i=0; i < numberORowsInTest; i++){
for(int j=1; j < numberOfColumns;j++){
fscanf(fp2,"%lf%*[,]",&matrixTest[i][j]);
}
}
double** matrixTranspoed = transposeMatrix(matrixX, numberOfRows, numberOfColumns);
/* for(int i=0; i < numberOfColumns; i++){
matrixTranspoed[i] = (double*) malloc(numberOfRows*sizeof(double*));
}*/
// matrixTranspoed = transposeMatrix(matrixX, numberOfRows, numberOfColumns);
double** multipliedMatrix = multiplyMatrix(matrixTranspoed,matrixX, numberOfColumns, numberOfRows, numberOfRows, numberOfColumns);
/*for(int i=0; i < numberOfColumns; i++){
multipliedMatrix[i] = (double*) malloc(numberOfColumns*sizeof(double*));
}*/
// multipliedMatrix = multiplyMatrix(matrixTranspoed,matrixX, numberOfColumns, numberOfRows, numberOfRows, numberOfColumns);
double** inversedMatrix = inverseMatrix(multipliedMatrix,numberOfColumns);
/*for(int i=0; i < numberOfColumns; i++){
inversedMatrix[i] = (double*) malloc(numberOfColumns*sizeof(double*));
}*/
//inversedMatrix = inverseMatrix(multipliedMatrix,numberOfColumns);
double** inverseTransposed = multiplyMatrix(inversedMatrix,matrixTranspoed, numberOfColumns, numberOfColumns, numberOfColumns, numberOfRows);
/*for(int i=0; i < numberOfColumns; i++){
inverseTransposed[i] = (double*) malloc(numberOfRows*sizeof(double*));
}*/
//inverseTransposed = multiplyMatrix(inversedMatrix,matrixTranspoed, numberOfColumns, numberOfColumns, numberOfColumns, numberOfRows);
double** matrixW = multiplyMatrix(inverseTransposed,matrixY, numberOfColumns, numberOfRows, numberOfRows, 1);
/*for(int i=0; i < numberOfColumns; i++){
matrixW[i] = (double*) malloc(sizeof(double*));
}*/
//matrixW = multiplyMatrix(inverseTransposed,matrixY, numberOfColumns, numberOfRows, numberOfRows, 1);
for(int i=0; i < numberORowsInTest; i++){
double sum = 0;
for(int j=0; j < numberOfColumns;j++){
sum = sum + (matrixW[j][0] * matrixTest[i][j]);
}
printf("%0.0lf\n", sum);
}
fclose(fp1);
fclose(fp2);
for(int i=0; i < numberOfColumns; i++){
free(matrixW[i]);
}
free(matrixW);
for(int i=0; i < numberOfRows; i++){
free(matrixX[i]);
}
free(matrixX);
for(int i=0; i < numberOfRows; i++){
free(matrixY[i]);
}
free(matrixY);
for(int i=0; i < numberORowsInTest; i++){
free(matrixTest[i]);
}
free(matrixTest);
for(int i=0; i < numberOfColumns; i++){
free(matrixTranspoed[i]);
}
free(matrixTranspoed);
for(int i=0; i < numberOfColumns; i++){
free(multipliedMatrix[i]);
}
free(multipliedMatrix);
for(int i=numberOfColumns-1; i>=0; i--){
free(inverseTransposed[i]);
}
free(inverseTransposed);
for(int i=0; i < numberOfColumns; i++){
free(inversedMatrix[i]);
}
free(inversedMatrix);
return 0;
}
double** multiplyMatrix(double **matA, double **matB, int r1, int c1, int r2, int c2)
{
if(c1 != r2){
return NULL;
}
double** result=malloc(r1*sizeof(double*));
for(int i=0; i < r1; i++){
result[i] = malloc(c2*sizeof(double*));
}
for(int i=0; i < r1; i++){
for(int j=0; j < c2; j++){
double sum =0;
int x=0;
while( x < r2){
sum = sum + (matA[i][x] * matB[x][j]);
x++;
}
result[i][j] = sum;
}
}
// your code goes here
return result;
}
double** transposeMatrix(double** mat, int row, int col)
{
double** matTran=malloc(col*sizeof(double*));
for(int i =0; i < col; i++){
matTran[i] = malloc(row*sizeof(double*));
}
for(int i =0; i < col; i++){
for(int j =0; j < row; j++){
matTran[i][j] = mat[j][i];
}
}
// your code goes here
return matTran;
}
double** inverseMatrix(double **matA, int dimension)
{
double** matI=malloc(dimension*sizeof(double*));
// your code goes here
for(int i=0; i < dimension; i++){
matI[i] = malloc(dimension*sizeof(double*));
}
int t =0;
for(int i=0; i<dimension; i++){
for(int j=0; j<dimension; j++){
if(t == j){
matI[i][j] = 1;
}else{
matI[i][j] = 0;
}
}
t++;
}
int p =0;
while(p < dimension ){
double point = matA[p][p];
for(int ptr =0; ptr < dimension; ptr++){
matI[p][ptr] = matI[p][ptr] / point;
matA[p][ptr] = matA[p][ptr] / point;
}
for(int i= p+1; i < dimension; i++){
double point2 = matA[i][p];
for(int ptr =0; ptr < dimension; ptr++){
matA[i][ptr] = matA[i][ptr] - (matA[p][ptr]*point2);
matI[i][ptr] = matI[i][ptr] - (matI[p][ptr] * point2);
}
}
p++;
}
for(int k=dimension-1; k > 0; k--){
for(int l=k-1; l > -1; l--){
double point3 = matA[l][k];
for(int ptr =0; ptr < dimension; ptr++){
matA[l][ptr] = matA[l][ptr] - (matA[k][ptr]*point3);
matI[l][ptr] = matI[l][ptr] - (matI[k][ptr]*point3);
}
}
}
return matI;
}
|
C
|
#include<stdio.h>
int main(void){
//Question1
float a,b,c;
printf("Please enter first value");
scanf("%f",&a);
printf("Please enter second value");
scanf("%f",&b);
printf("Please enter third value");
scanf("%f",&c);
printf("%f",(a+b)/2+3*c);
return 0;
//Question2
int number;
printf("Please enter a number");
scanf("%d",&number);
if(number%3==0){
printf("number is divisible by 3",number);
}
else if(number%3!=0){
printf("number is not divisible by 3",number);
}
return 0;
// Question3
float longedge,shortedge,area,circumference;
char ch;
printf("Enter a char:");
scanf("%c",&ch);
if(ch=='a'){
printf("Enter long and short edge:");
scanf("%f %f",&longedge,&shortedge);
printf("%f",shortedge*longedge);
}
else if (ch=='c'){
printf("Enter long and short edge:");
scanf("%f %f",&longedge,&shortedge);
printf("%f",2*longedge+2*shortedge);
}
return 0;
//Question4
int xtop[5],xbottom[5],ytop[5],ybottom[5],area;
printf("input in order:");
scanf("%d %d %d %d",&xtop[0],&xbottom[0],&ytop[1],&ybottom[1]);
area=(xtop[0]-xbottom[0])*(ytop[1]-ybottom[1]);
printf("%d",area);
return 0;
//Question5
int days, years, weeks;
printf("Enter days: ");
scanf("%d", &days);
years = (days / 365); // Ignoring leap year
weeks = (days % 365) / 7;
days = days - ((years * 365) + (weeks * 7));
printf("Years: %d\n", years);
printf("Weeks: %d\n", weeks);
printf("Days: %d", days);
return 0;
//Question6
int sec, h, m, s;
printf("Input seconds: ");
scanf("%d", &sec);
h = (sec/3600);
m = (sec -(3600*h))/60;
s = (sec -(3600*h)-(m*60));
printf("H:M:S - %d:%d:%d\n",h,m,s);
return 0;
//Question7
int numbers[5];
int j, positivectr=0, negativectr=0;
printf("Enter 3 numbers: ");
scanf("%d%d%d", &numbers[0],&numbers[1],&numbers[2]);
for(j = 0; j < 5; j++) {
if(numbers[j] > 0)
{
positivectr++;
}
else if(numbers[j] < 0)
{
negativectr++;
}
}
printf("Number of positive values: %d\n", positivectr);
printf("Number of negative values: %d", negativectr);
return 0;
//Question8
int CostPrice;
int SellingPrice;
int profitamount;
int lossamount;
printf("Enter cost price:");
scanf("%d",&CostPrice);
printf("Enter selling price:");
scanf("%d",&SellingPrice);
profitamount=SellingPrice-CostPrice;
printf("You can booked your profit amount:%d\n",profitamount);
lossamount=CostPrice-SellingPrice;
printf("You got a loss of amount:%d",lossamount);
return 0;
//Question9
int number;
printf("Enter any number:");
scanf("%d",&number);
if(number%2==0){
printf("The number is even");
scanf("%d",&number);
}
else{
printf("The number is odd");
scanf("%d",&number);
}
return 0;
//Question10
int sides[5];
printf("Input three sides:");
scanf("%d %d %d",&sides[0],&sides[1],&sides[2]);
if(sides[0]==sides[1]||sides[0]==sides[2]||sides[1]==sides[2]){
printf("This is an isosceles triangle");
}
else{
printf("This is not an isosceles triangle");
}
return 0;
}
|
C
|
/* ******** Reference design #6 LCD Pong Ping with Mutes Semaphores *********
* Author: Richard Wall
* Date: September 29, 2011
* Revised: December 22, 2012
* Revised: September 25, 2013
*
* Description: An example of FreeRTOS running on an chipKIT Pro MX7
* board with a PIC32MX7 processor. The hardware required for
* this project is the Digilent chipKIT Pro MX7 and the PmodCLP
* peripheral module.
*
* This example passes a counter value between two tasks.
* each task increments the counter before passing it
* back. Each task sends a message to the LCD that is
* protected by a mutex semaphore. Commenting out
* the semaphore take and give demonstrates how the LCD
* text gets messed up without them. (See Line 122 & 161 )
*
* Note: Writing to the LCD is not setup as a task but is a resource
* that requires protected use. This is an example on using an
* device driver.
****************************************************************************/
/* XC32 System Files */
#include <plib.h>
#include <stdio.h>
/* Files to support FreeRTOS */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
/* Files to support Application */
#include "chipKIT_PRO_MX7.h"
#include "FreeRTOS_Common_Tasks.h"
#include "lcddrv.h"
/* The priorities of the various application tasks. */
#define mainCHECK_TASK_PRIORITY ( tskIDLE_PRIORITY + 4 )
xQueueHandle QTask_1_2, QTask_2_1; /* Queue to pass counter back and forth */
xSemaphoreHandle xLCD_semaphore; /* Semaphore for blocking access to LCD */
/* Implements the 'check' task functionality as described at the top of this
* file*/
static void prvCheckTask1( void *pvParameters ) __attribute__((noreturn));
static void prvCheckTask2( void *pvParameters ) __attribute__((noreturn));
/* main Function Description ***************************************
* SYNTAX: int main( void );
* KEYWORDS: Initialize, create, tasks, scheduler
* DESCRIPTION: This is a typical RTOS setup function. Hardware is
* initialized, tasks are created, and the scheduler is
* started.
* PARAMETERS: None
* RETURN VALUE: Exit code - used for error handling
* NOTES: None
* END DESCRIPTION *****************************************************/
int main( void )
{
/* Flag used by to indicate the task create status (pass/fail) */
unsigned long ulStatus1 = pdPASS;
/* Configure any hardware required for this demo. */
vSetupHardware();
initLCD(); /* LCD is not a task but a device driver */
/* prvCheckTask uses sprintf so requires more stack. */
ulStatus1 &= xTaskCreate( prvCheckTask1, (signed char *) "Check1",
configMINIMAL_STACK_SIZE, NULL,
mainCHECK_TASK_PRIORITY, NULL );
ulStatus1 &= xTaskCreate( prvCheckTask2, (signed char *) "Check2",
configMINIMAL_STACK_SIZE, NULL,
mainCHECK_TASK_PRIORITY, NULL );
xLCD_semaphore = xSemaphoreCreateMutex();
if(xLCD_semaphore != NULL)
{
QTask_1_2 = xQueueCreate(5, sizeof(int)); /* Q depth = 5, 4 bytes wide*/
QTask_2_1 = xQueueCreate(5, sizeof(int)); /* Q depth = 5, 4 bytes wide*/
if(ulStatus1 == pdPASS) /* Finally start the scheduler. */
{
vTaskStartScheduler();
}
}
/* Will only reach here if there is insufficient heap available to start
* the scheduler. */
return 1;
} /* End of main */
/* prvCheckTask1 Function Description ***************************************
* SYNTAX: static void prvCheckTask1( void *pvParameters );
* KEYWORDS: Task, mutex, semaphore
* DESCRIPTION: This is the master task that starts passing the counter
* to the slave task. If BTN1 is pressed, a message is
* sent to the LCD. LEDA is toggeled each time it receives a
* message.
* PARAMETERS: the void pointer contains no informatio for this task
* RETURN VALUE: None
* NOTES: None
END DESCRIPTION ************************************************************/
static void prvCheckTask1( void *pvParameters )
{
int pingpong = 0;
char msg[32];
// PORTSetPinsDigitalOut(IOPORT_G, LED1); /* Configure pin as an output. */
while( 1 )
{
LATBINV = LEDA; /* Toggle led */
/* Send message to Task 2 */
xQueueSend(QTask_1_2, &pingpong, portMAX_DELAY);
/* Claim exclusive use of LCD - comment out next line to see what happens*/
xSemaphoreTake(xLCD_semaphore, portMAX_DELAY);
sprintf(msg,"\fTask #1: #%d", pingpong);
putsLCD(msg);
vTaskDelay( 1000 / portTICK_RATE_MS ); /* Delay 1 second */
/* Release exclusive use of LCD */
xSemaphoreGive(xLCD_semaphore);
/* Wait for message from Task 2 */
xQueueReceive(QTask_2_1, &pingpong, portMAX_DELAY);
}
} /* End of prvCheckTask1 */
/* prvCheckTask2 Function Description ***************************************
* SYNTAX: static void prvCheckTask2( void *pvParameters );
* KEYWORDS: Task, mutex, semaphore
* DESCRIPTION: This is the slave task. After receiving the counter
* data, it increments the count and sends it back
* to the master task. LEDB is toggled each time it receives
* a message.
* PARAMETERS: the void pointer contains no information for this task
* RETURN VALUE: None
* NOTES: None
* END DESCRIPTION *****************************************************/
static void prvCheckTask2( void *pvParameters )
{
int pingpong;
char msg[32];
// PORTSetPinsDigitalOut(IOPORT_G, LED2); /* Configure pin as an output. */
for( ;; )
{
LATBINV = LEDB; /* Toggle led */
/* Wait for message from Task 1 */
xQueueReceive(QTask_1_2, &pingpong, portMAX_DELAY);
++pingpong; /* Increment message exchange counter */
/* Claim exclusive use of LCD - comment out next line to see what happens*/
xSemaphoreTake(xLCD_semaphore, portMAX_DELAY);
LCDGotoRow(1);
sprintf(msg,"Task #2: #%d", pingpong);
putsLCD(msg);
vTaskDelay( 2000 / portTICK_RATE_MS ); /* Delay 2 seconds */
/* Release exclusive use of LCD */
xSemaphoreGive(xLCD_semaphore);
/* Send message to Task 1 */
xQueueSend(QTask_2_1, &pingpong, portMAX_DELAY);
}
} /* End of prvCheckTask2 */
/*--------------------------End of main for RD6 - LCD - mutex ---------------*/
|
C
|
#include<stdio.h>
#include<math.h>
int main()
{
int pows,a,b;
scanf("%d%d",&a,&b);
pows=pow(a,b);
printf("%d",pows);
return 0;
}
|
C
|
/***********************************************************/
/* */
/* winsuport2.h */
/* */
/* definicio de constants i prototipus de funcions per */
/* utilitzar la interficie d'acces a "curses" implementada */
/* al modul winsuport2.c */
/* */
/***********************************************************/
/* Definicions generals per utilitzar les funcions de "winsuport2.c" */
#define INVERS 1
#define NO_INV 0
#define TEC_AMUNT 'w'
#define TEC_AVALL 's'
#define TEC_DRETA 'd'
#define TEC_ESQUER 'a'
#define TEC_RETURN 13 /* tecla de Carry Return */
#define EOL 10 /* salt de linia en un fitxer UNIX */
/* Definicions de rutines publiques del fitxer "winsuport2.c" */
int win_ini(int *fil, int *col, char creq, unsigned int inv);
/* Rutina per crear i inicialitzar una finestra de sortida de text, */
/* utilitzant l'entorn de les curses. S'ha de passar per referencia */
/* el numero de files i de columnes que ha de tenir la finestra */
/* (*fil, *col). Si s'especifica un 0 al valor dels dos parametres, */
/* la finestra ocupara tota la pantalla del terminal. L'ultima fila */
/* de la finestra es reserva per mostrar missatges de text. La */
/* resta de files es reserva per a tauler de joc. Es dibuixa un */
/* requadre a tot el tauler de joc, format per caracters creq, que */
/* es mostren invertits si el parametre inv es diferent de zero. */
/* Els errors que retorna aquesta rutina son els seguents: */
/* >0 -> cap problema, retorna el numero de files */
/* -1 -> la finestra ja havia estat creada */
/* -2 -> no es pot inicialitzar l'entorn de curses */
/* -3 -> les mides demanades de camp de joc son massa grans */
/* -4 -> la finestra finalment no s'ha pogut crear */
/* Si el valor dels parametres *fil, *col era zero al cridar la ru- */
/* tina, en sortir de la rutina contindran el numero assignat de */
/* files i de columnes (les dimensions de la finestra de terminal) */
/* Per restaurar el terminal cal cridar a la rutina win_fi abans */
/* de sortir del programa. */
/* */
/* Aquesta rutina es diferencia de la win_ini() original (dins el */
/* fitxer "winsuport.c") en que retorna la mida (en bytes) d'una */
/* zona de memoria compartida que es necessitara per treballar amb */
/* l'entorn de finestres des de diferents processos. Aquesta zona */
/* de memoria s'ha de crear des del proces principal que crida a */
/* la funcio win_ini(). El punter inicial i la seva mida s'han de */
/* passar a la funcio win_set(), des de tots els processos que hi */
/* vulguin accedir. */
void win_set(void *p_mem, int n_fil, int n_col);
/* Rutina per permetre l'acces a una finestra ja creada, on p_mem es un */
/* punter a una zona de memoria compartida que contindra el dibuix del */
/* camp de joc, les dimensions del qual venen indicades per n_fil, n_col. */
/* ATENCIO: aquesta rutina s'ha d'invocar despres de win_ini() i abans */
/* que la resta de rutines d'acces al camp de joc. Se suposa que la zona */
/* de memoria s'ha creat amb la mida retornada per la funcio win_ini(). */
void win_fi();
/* Rutina per eliminar la finestra i restaurar el terminal */
void win_escricar(int f, int c, char car, unsigned int invers);
/* Rutina per escriure un caracter en una posicio de la finestra, */
/* on la primera posicio es la (0,0); si invers es diferent de zero,*/
/* el caracter surt invertit. */
char win_quincar(int f, int c);
/* Rutina per llegir quin caracter hi ha en una posicio de finestra */
/* on la primera posicio es la (0,0). */
int win_quinatri(int f, int c);
/* Rutina per llegir quin atribut hi ha en una posicio de finestra. */
/* De fet, nomes determina si l'atribut es INVERS (retorna != 0), o */
/* si l'atribut no es INVERS (retorna = 0). */
void win_escristr(char *str);
/* Rutina per escriure un string en l'ultima fila de la finestra */
int win_gettec(void);
/* Rutina per llegir una tecla; retorna zero si no hi ha tecla per llegir, */
/* o el codi ASCII d'una tecla normal. */
/* ATENCIO: aquesta rutina nomes es accessible des del proces que hagi */
/* creat l'entorn de la finestra del camp de joc amb funcio win_ini(). */
void win_retard(int ms);
/* Rutina per retardar ms mil.lisegons */
void win_update(void);
/* Rutina per actualizar la zona de dibuix de la finestra, d'acord amb les */
/* ultimes modificacions realitzades sobre la zona de memoria compartida. */
/* ATENCIO: aquesta rutina nomes es accessible des del process que hagi */
/* creat l'entorn de la finestra del camp de joc amb funcio win_ini(). */
int win_carregatauler(char *nom_fitxer, int n_f, int n_c, char creq);
/* rutina per carregar un tauler de joc des d'un fitxer, i dibuixar-lo sobre la
finestra actual de joc; els parametres n_f i n_c indicaran el numero de files
i de columnes que es preten carregar; el fitxer es llegeis caracter a
caracter, suposant que cada fila del tauler ocupa una linia del fitxer.
Els codis ASCII que concideixin amb el parametre creq es visualitzaran en
invers. Els errors que retorna son els seguents:
0 -> cap problema
-1 -> error en nom del fitxer
-2 -> error en el numero de columnes d'alguna fila no coincideix amb
el numero global
-3 -> error en numero de columnes
-4 -> error en numero de files
-5 -> no hi ha finestra activa
*/
|
C
|
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <sys/types.h>
#include "calculations.h"
int output_fd;
char input[20];
// to understand if the p1 process is finished.
int isFinished = 0;
// SIGUSR1 handler
// If SIGUSR1 signal is sent, that means p1 process finished.
void handler(int sig_no)
{
isFinished = 1;
unlink(input);
}
// SIGUSR2 handler
void handler2(int sig_no)
{
/* EMPTY */
}
// SIGTERM handler
void handler3(int sig_no)
{
if (-1 == close(output_fd))
{
perror("Error occured");
exit(1);
}
}
void readLinebyLine(char* temp_name, int _f)
{
output_fd = _f;
struct flock lock;
memset(&lock,0,sizeof(lock));
int wrtOffset = 0, tmp_count = 0, tmp_wr;
int count = 0, totalLine = 0;
int fd, size = -1 ,i, k, j, tour, m = 0;
double mae, mse, rmse;
double a,b;
char ch = ' ';
struct coordinate c[10];
char c_buf[15], lineEquation[20], MAE[20], MSE[20], RMSE[20];
sigset_t set, pendingSet, newMask;
struct sigaction sa;
memset(&sa,0,sizeof(sa));
sa.sa_handler = SIG_IGN;
sigaction(SIGINT,&sa,NULL);
if (sigemptyset(&set) == -1 || sigaddset(&set,SIGINT) == -1)
{
perror("Failed to initialize signal mask");
exit(1);
}
if (sigemptyset(&pendingSet) == -1)
{
perror("Failed to initialize pending mask");
exit(1);
}
// If SIGUSR2 signal arrives, this execution can continue, otherwise it will wait.
// If it waits, that means p1 does not processed any line.
sigfillset(&newMask);
sigdelset(&newMask,SIGUSR2);
sigsuspend(&newMask);
// Open the temporary file in read and write mode
fd = open(temp_name,O_RDWR);
if (fd == -1)
{
perror("Failed to open temporary file");
exit(1);
}
// Calculate the characters of the first row.
while(ch != '\n'){
size = read(fd,&ch,1);
++count;
if (size == -1)
{
perror("Error is occured : \n");
exit(1);
}
// Total line is needed for while calculating mean and standar deviation of error metrics.
// totalLine variable represents how many calculations is made.
if (ch == 'x')
{
totalLine+=1;
}
}
double* errors = (double*) malloc(sizeof(double)*1000000);;
char* num = (char*) malloc(sizeof(char)*10);
char* buf = (char*) malloc(sizeof(char)*count+1);
char* spaceBuf = (char*) malloc(sizeof(char)*count+1);
// For erasing lines.
for (i = 0; i < count; ++i)
{
spaceBuf[i] = ' ';
}
spaceBuf[count] = '\0';
// Set the offset
lseek(fd,0,SEEK_SET);
size = -1;
while(!(size == 0 && isFinished == 1)){
// read the whole row
size = read(fd,buf,count);
if (size == -1)
{
perror("Failed to read temporary file");
exit(1);
}
j = 0;
tour = 0;
for (i = 0; i < count; ++i)
{
if (buf[i] != '(' && buf[i] != ')' && buf[i] != ',' && buf[i] != ' ')
{
k = 0;
// Parse the string
while(buf[i] != ',' && buf[i] != ')')
{
// Save the coordinates in num as string form
num[k] = buf[i];
++k;
++i;
}
// After that save numbers in coordinate array
if (tour % 2 == 0)
{
c[j].x = atoi(num);
}
else{
c[j].y = atoi(num);
++j;
}
free(num);
num = (char*) malloc(sizeof(char)*10);
++tour;
}
// If j equals to ten, it means whole row is processed, now line equation can be processed.
if (j == 10)
{
k = 0;
while(buf[i] != 'x')
{
if (buf[i] != '(' && buf[i] != ')' && buf[i] != ',' && buf[i] != ' ')
{
num[k] = buf[i];
++k;
}
++i;
}
a = atof(num);
free(num);
num = (char*) malloc(sizeof(char)*10);
++i; // to get rid of the x byte
k = 0;
while(buf[i] != '\n'){
if (buf[i] != '+' && buf[i] != ',' && buf[i] != ' ')
{
num[k] = buf[i];
++k;
}
++i;
}
b = atof(num);
i = count;
free(num);
num = (char*) malloc(sizeof(char)*10);
}
}
tmp_count = tmp_count + count;
tmp_wr = count;
count = 0;
ch = ' ';
// Calculate total bytes of the next row
while(ch != '\n'){
size = read(fd,&ch,1);
if (size == -1)
{
perror("Failed to read temporary file");
exit(1);
}
// Calculate how many lines processed
if (ch == 'x')
{
totalLine+=1;
}
// If size equals to zero, it means there are no more bytes to be processed
// and there can be two reasons of that.
// p1 has not finished yet or p1 processed all the contents, p2 reached the EOF
if (size == 0)
{
ch = '\n';
if (isFinished != 1)
{
// Wait for p1, so it can process more lines.
sigsuspend(&newMask);
ch = ' ';
--count;
}
}
++count;
}
if (size != 0)
{
free(buf);
buf = (char*) malloc(sizeof(char)*count+1);
}
/* CRITICAL SECTION */
if (sigprocmask(SIG_BLOCK,&set,NULL) == -1)
{
perror("Error is occured : \n");
}
calculateMAE(&mae,c,a,b);
calculateMSE(&mse,c,a,b);
calculateRMSE(&rmse,mse);
if (sigpending(&pendingSet) == -1)
{
perror("Error is occured : \n");
exit(1);
}
if (sigprocmask(SIG_UNBLOCK,&set,NULL) == -1)
{
perror("Error is occured : \n");
exit(1);
}
/* CRITICAL SECTION IS OVER */
// Lock the file in case other process try to write to it.
lock.l_type = F_WRLCK;
fcntl(fd,F_SETLKW,&lock);
// Set the offset
lseek(fd,wrtOffset,SEEK_SET);
if (-1 == write(fd,spaceBuf,strlen(spaceBuf)))
{
perror("Failed to erase the line");
exit(1);
}
lock.l_type = F_UNLCK;
fcntl(fd,F_SETLKW,&lock);
for (i = 0; i < 10; ++i)
{
sprintf(c_buf,"(%d, %d) , ", c[i].x, c[i].y);
if (-1 == write(_f,c_buf,strlen(c_buf)) )
{
perror("Failed to write to output file");
exit(1);
}
}
// Convert error metrics and line equation to string
sprintf(lineEquation,"%0.3fx + %0.3f, ",a,b);
sprintf(MAE,"%0.3f, ",mae);
sprintf(MSE,"%0.3f, ",mse);
sprintf(RMSE,"%0.3f\n",rmse);
// Save it in the array
errors[m] = mae;
errors[m+1] = mse;
errors[m+2] = rmse;
m = m + 3;
if (-1 == write(_f,lineEquation,strlen(lineEquation)) )
{
perror("Failed to write to output file");
exit(1);
}
if (-1 == write(_f,MAE,strlen(MAE)) )
{
perror("Failed to write to output file");
exit(1);
}
if (-1 == write(_f,MSE,strlen(MSE)) )
{
perror("Failed to write to output file");
exit(1);
}
if (-1 == write(_f,RMSE,strlen(RMSE)) )
{
perror("Failed to write to output file");
exit(1);
}
// Update the offset
wrtOffset =wrtOffset + tmp_wr;
free(spaceBuf);
spaceBuf = (char*) malloc(sizeof(char)*count+1);;
for (i = 0; i < count; ++i)
{
spaceBuf[i] = ' ';
}
spaceBuf[count] = '\0';
// Update the offset for reading operation
lseek(fd,tmp_count,SEEK_SET);
}
double MAEmean = 0;
double MSEmean = 0;
double RMSEmean = 0;
double MAEdeviation = 0;
double MSEdeviation = 0;
double RMSEdeviation = 0;
for (int i = 0; i < m; i+=3)
{
MAEmean += errors[i];
MSEmean += errors[i+1];
RMSEmean += errors[i+2];
}
MAEmean = MAEmean/totalLine;
MSEmean = MSEmean/totalLine;
RMSEmean = RMSEmean/totalLine;
double r1 = 0;
double r2 = 0;
double r3 = 0;
for (int i = 0; i < m; i+=3)
{
r1 = pow((errors[i] - MAEmean),2);
MAEdeviation = MAEdeviation + r1;
r2 = pow((errors[i+1] - MSEmean),2);
MSEdeviation = MSEdeviation + r2;
r3 = pow((errors[i+2] - RMSEmean),2);
RMSEdeviation = RMSEdeviation + r3;
}
MAEdeviation = MAEdeviation / (totalLine -1);
MSEdeviation = MSEdeviation / (totalLine -1);
RMSEdeviation = RMSEdeviation / (totalLine -1);
MAEdeviation = sqrt(MAEdeviation);
MSEdeviation = sqrt(MSEdeviation);
RMSEdeviation = sqrt(RMSEdeviation);
// When p2 is over, Print on the screen mean and the standard deviation of each error metric.
printf("MAE MEAN : %0.3f, MSE MEAN : %0.3f, RMSE MEAN : %0.3f\n",MAEmean,MSEmean,RMSEmean );
printf("MAE SD : %0.3f, MSE SD : %0.3f, RMSE SD : %0.3f\n",MAEdeviation ,MSEdeviation ,RMSEdeviation);
if (close(fd) == -1 || close(_f) == -1)
{
perror("Failed to close open files");
exit(1);
}
free(errors);
free(spaceBuf);
free(num);
free(buf);
}
int main(int argc, char *argv[])
{
strcpy(input,argv[3]);
sigset_t _set;
// Create a set and add it to SIGUSR2 signal.
// This signal is necessary for sigsuspend situation.
if (sigemptyset(&_set) == -1 || sigaddset(&_set,SIGUSR2) == -1)
{
perror("Failed to initialize signal mask");
exit(1);
}
// SIGUSR2 signal should not be sent before the sigsuspend line is executed.
// That's way I blocked it.
if (sigprocmask(SIG_BLOCK,&_set,NULL) == -1)
{
perror("Blocking operation is failed");
exit(1);
}
struct sigaction sa;
memset(&sa,0,sizeof(sa));
sa.sa_handler = &handler;
struct sigaction sa2;
memset(&sa2,0,sizeof(sa2));
sa2.sa_handler = &handler2;
struct sigaction sa3;
memset(&sa3,0,sizeof(sa3));
sa3.sa_handler = &handler3;
sigaction(SIGUSR1,&sa,NULL);
sigaction(SIGUSR2,&sa2,NULL);
sigaction(SIGTERM,&sa3,NULL);
// Send SIGUSR1 signal to parent process. It indicates the child process has started.
if(-1 == kill(getppid(),SIGUSR1))
{
perror("Failed to send a signal to parent process");
exit(1);
}
readLinebyLine(argv[1],atoi(argv[2]));
return 0;
}
|
C
|
/*
Направете глобална константа pi = 3.14, както правихме в
предишния урок. Напишете функция, която изчислява площта на кръг, на
която като параметър подаваме радиуса и връщаме площта на кръга.
Използвайте глобалната константа pi, за да извършите изчисленията.
Извикайте функцията в main() и покажете резултата.
*/
#include <stdio.h>
const float pi = 3.14;
float areaCircle(float r);
int main(){
float circle = areaCircle(5);
printf("%f", circle);
return 0;
}
float areaCircle(float r){
float area = pi*r*r;
return area;
}
|
C
|
#include "getFileByFirstLetter.h"
#include <signal.h> // For sigaction()
#include <wait.h> // For waitpid()
#include <dirent.h> // For opendir(), readdir(), closedir()
#define LINE_LEN 256
const int LO_LEGAL_PORT = 1025;
const int HI_LEGAL_PORT = 65535;
const int ERROR_FD = -1;
const int NUM_CLIENTS_TO_SERVE
= 4;
void sigChildHandler (int sig
)
{
// I. Application validity check:
int status;
pid_t childId;
while ( (childId = waitpid(-1,&status,WNOHANG)) > 0)
{
// printf("Child %d finished.\n",childId);
printf ("\n");
}
// III. Finished:
}
// PURPOSE: To attempt to create and return a file-descriptor for listening
// to the OS telling this server when a client process has connect()-ed
// to 'port'. Returns that file-descriptor, or 'ERROR_FD' on failure.
int getServerFileDescriptor
(int port,
const char* progName
)
{
// I. Application validity check:
if (progName == NULL)
{
fprintf(stderr,"BUG: NULL ptr to getServerFileDescriptor().\n");
exit(EXIT_FAILURE);
}
// II. Attempt to get socket file descriptor and bind it to 'port':
// YOUR CODE HERE
// Create a socket
// Create a socket
int socketDescriptor = socket(AF_INET, // AF_INET domain
SOCK_STREAM, // Reliable TCP
0);
// We'll fill in this datastruct
struct sockaddr_in socketInfo;
// Fill socketInfo with 0's
memset(&socketInfo,'\0',sizeof(socketInfo));
// Use std TCP/IP
socketInfo.sin_family = AF_INET;
// Tell port in network endian with htons()
socketInfo.sin_port = htons(port);
// Allow machine to connect to this service
socketInfo.sin_addr.s_addr = INADDR_ANY;
// Try to bind socket with port and other specifications
int status = bind(socketDescriptor, // from socket()
(struct sockaddr*)&socketInfo,
sizeof(socketInfo)
);
if (status < 0)
{
fprintf(stderr,"Could not bind to port %d\n",port);
exit(EXIT_FAILURE);
}
listen(socketDescriptor,5);
// III. Finished:
return(socketDescriptor /* <-- CHANGE THAT */);
}
// PURPOSE: To install 'sigChildHandler()' as the signal simple handler for
// the 'SIGCHLD' signal. Tells OS to restarts system calls if receives
// 'SIGCHLD'.
void installSigChildHandler ()
{
// I. Application validity check:
// II. Install 'sigChildHandler()' as the 'SIGCHLD' handler:
// YOUR CODE HERE
struct sigaction act;
memset(&act,'\0',sizeof(struct sigaction));
sigemptyset(&act.sa_mask);
act.sa_flags = SA_NOCLDSTOP | SA_RESTART;;
act.sa_handler = sigChildHandler;
// Handle with simpleHandler()
sigaction(SIGCHLD,&act,NULL);
// III. Finished:
}
// PURPOSE: To ask the user which port to attempt to monopolize, and to return
// entered port number.
int getPort ()
{
// I. Application validity check:
// II. Get port number
int port;
do
{
char buffer[BUFFER_LEN];
printf("Please enter port number to monopolize [%d-%d]: ",
LO_LEGAL_PORT,HI_LEGAL_PORT
);
fgets(buffer,BUFFER_LEN,stdin);
port = strtol(buffer,NULL,10);
}
while ( (port < LO_LEGAL_PORT) || (port > HI_LEGAL_PORT) );
// III. Finished:
return(port);
}
// PURPOSE: To do the work of handling the client. Communication with the
// client take place using file-descriptor 'fd'. No return value.
void handleClient (int fd
)
{
// I. Application validity check:
if (fd < 0)
{
fprintf(stderr,"BUG: Illegal file descriptor to handleClient()\n");
exit(EXIT_FAILURE);
}
char letter[1];
read(fd,&letter,1);
const char* dirName = (".");
DIR* dirPtr = opendir(dirName);
struct dirent* entryPtr;
uint32_t fileSize;
if (dirPtr == NULL) {
printf ("Cannot open directory\n");
fileSize = htonl(CANT_READ_DIR_CODE);
write(fd,&fileSize,sizeof(fileSize));
exit(CANT_READ_DIR_CODE);
}
//////////////////////////////////////////////////////////////
struct stat statBuffer;
int filestat = 0;
int fdesc = -1;
while ((entryPtr = readdir(dirPtr)) != NULL) {
if(entryPtr->d_name[0] == letter[0]){
fdesc = open(entryPtr->d_name,O_RDONLY);
stat(entryPtr,&statBuffer);
if(fdesc < 0){
printf("The Server canot open YouCantOpenMe.txt\n");
printf("Cannot read file %s.\n",entryPtr->d_name);
fileSize = htonl(CANT_READ_FILE_CODE);
write(fd,&fileSize,sizeof(fileSize));
exit(CANT_READ_FILE_CODE);
}
filestat = 1;
break;
}
}
while ( (entryPtr = readdir(dirPtr)) != NULL )
{
char filePath[256];
stat(filePath,&statBuffer);
if ( entryPtr->d_name[0] == letter[0] && S_ISDIR(statBuffer.st_mode)) {
printf("\n No Matching File\n");
fileSize = htonl(CANT_READ_FILE_CODE);
write(fd,&fileSize,sizeof(fileSize));
exit(CANT_READ_FILE_CODE);
}
if(filestat == 0){
printf("No file Begins with X\n");
printf("No matching file\n");
fileSize = htonl(NO_MATCH_CODE);
write(fd,&fileSize,sizeof(fileSize));
exit(NO_MATCH_CODE);
}else{
off_t fsize;
fsize = lseek(fdesc, 0, SEEK_END);
fileSize = htonl(fsize); //Default Case
write(fd,&fileSize,sizeof(fileSize));
char buffer[BUFFER_LEN];
unsigned int totalNumBytesRead = 0;
int numBytesRead;
fsize = lseek(fdesc, 0, SEEK_SET);
while ( (totalNumBytesRead < fileSize) &&
( (numBytesRead = read(fdesc,buffer,BUFFER_LEN)) > 0)
)
{
buffer[numBytesRead] = '\0';
totalNumBytesRead += (unsigned int)numBytesRead;
printf("%s",buffer);
write(fd,buffer,numBytesRead);
}
printf("Dir begins with D,but it is not a file.\n",entryPtr->d_name, totalNumBytesRead);
printf("No matching file");
}
closedir (dirPtr);
// III. Finished:
}
// PURPOSE: To serve the clients using file-descriptor 'listenFd' to tell
// when a client has connected. Each client is handled by its own child
// process. Both the parent and the child processes close unnecesary
// file-descriptorors. Serves 'NUM_CLIENTS_TO_SERVE' clients, then quits.
// No return value.
void doServer (int listenFd
)
{
// I. Application validity check:
if (listenFd < 0)
{
fprintf(stderr,"Illegal file-descriptor to doServer()\n");
exit(EXIT_FAILURE);
}
// II. Do the work of the server:
int i;
for (i = 0; i < NUM_CLIENTS_TO_SERVE; i++)
{
// Accept connection to client
int clientDescriptor = accept(listenFd,NULL,NULL);
if (fork() == 0)
{
close(listenFd);
handleClient(clientDescriptor);
exit(EXIT_SUCCESS);
}
close(clientDescriptor);
}
// III. Finished:
}
// PURPOSE: To oversee the main work of the server. Ignores 'argc' but
// uses 'argv[0]' as the name of the program. Returns 'EXIT_SUCCESS' to
// OS on success or 'EXIT_FAILURE' otherwise.
int main (int argc,
char* argv[]
)
{
// I. Application validity check:
// II. Do server:
int port = getPort();
int socketFd = getServerFileDescriptor(port,argv[0]);
installSigChildHandler();
doServer(socketFd);
// III. Finished:
return(EXIT_SUCCESS);
}
|
C
|
int ft_strlen(char *str);
int ft_strlen(char *str){
int i=0;
int count =0;
while(str[i]){
count++;
i++;
}
return count;
}
|
C
|
#ifndef __DECK_H__
#define __DECK_H__
#include <stdint.h>
#include "card.h"
typedef struct deck {
uint8_t capacity; // number of cards in a full deck
uint8_t size; // number of cards in the current deck
card_t* cards; // pointer to array of cards
} deck_t;
void print_deck(deck_t* deck);
int deal_card(deck_t* deck, card_t* card);
void shuffle_deck(deck_t* deck);
void push(card_t* card, deck_t* deck);
void fill_deck(deck_t* deck);
void reset_deck_state(deck_t* deck);
int rand_lim(int limit);
#endif
|
C
|
#ifndef DOG_H
#define DOG_H
/**
*struct dog - a structure that creates variables used in the main function
*which is also accessed in the main function
*@name: A pointer pointing to a string
*@age: A float that takes in an a number
*@owner: A pointer variable that points to a string
*/
struct dog
{
char *name;
float age;
char *owner;
};
typedef struct dog dog_t;
void init_dog(struct dog *d, char *name, float age, char *owner);
void print_dog(struct dog *d);
dog_t *new_dog(char *name, float age, char *owner);
void free_dog(dog_t *d);
#endif
|
C
|
// Program to trapping rainwater problem.
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,ind1,a[20],m,s=0;
clrscr();
printf("Enter size of data of mapping\n");
scanf("%d",&n);
printf("Enter %d data value\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
m=a[i];
if(m==0)
continue;
break;
}
ind1=i;
while(ind1<n-1)
{
for(i=ind1+1;i<n;i++)
{
if(a[i]<m)
{
if(i!=n-1)
{
continue;
}
else
{
ind1++;
m=a[ind1];
break;
}
}
else
{
for(j=i-1;j>ind1;j--)
{
s+=m-a[j];
}
ind1=i;
m=a[i];
break;
}
}
}
printf("\n%d unit water is trapped from above data\n",s);
getch();
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
// compteur nb additions.
int nb_add=0;
/**
* Fibonacci avec affichage de la pile d'appel
*/
int fibo_rec(int n, char* pile)
{
char localPile[1024];
sprintf(localPile,"%s / %d ",pile,n);
printf("Fibo(%d): %s \n",n,localPile);
if (n==0) return 0;
if (n==1) return 1;
nb_add++;
return fibo_rec(n-1, localPile) + fibo_rec(n-2,localPile);
}
/**
* Fibonacci iteratif
*/
int fibo_iter(int n)
{
nb_add =0;
int f1=0;
int f2=1;
int i;
for (i=1;i<n;i++)
{
nb_add++;
int tempo = f1+f2;
f1 = f2;
f2 = tempo;
}
return f2;
}
int main()
{
char *pileVide="Pile:";
int f = fibo_rec(7,pileVide);
printf("Fibo rec= %d\n", f);
printf("NB_ADD = %d\n", nb_add);
f = fibo_iter(7);
printf("Fibo iter = %d\n", f);
printf("NB_ADD = %d\n", nb_add);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "board.h"
void init_board(int player_count, struct board* b, struct player* p) {
b->number_of_players = player_count;
for (int i = 0; i < player_count; ++i) {
b->player_list[i] = &p[i];
p[i].id = i;
init_player(&p[i]);
}
}
void display_board_information(struct board* b) {
for (int i = 0; i < b->number_of_players; ++i) {
printf("player name : player_%d\n", b->player_list[i]->id);
display_player_information(b->player_list[i]);
printf("\n\n");
}
}
int random_player(struct board* b, struct player* p) {
int x = rand() % b->number_of_players;
while ((x == p->id) || (b->player_list[x]->life <= 0))
x = rand() % b->number_of_players;
return x;
}
int number_alive(struct board* b) {
int res = 0;
for (int i = 0; i < b->number_of_players; i++) {
if (is_alive(b->player_list[i]) == 1)
++res;
}
return res;
}
|
C
|
#include"bank.h"
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/msg.h>
#include<sys/ipc.h>
#include<signal.h>
#include<sys/wait.h>
static int msgid1;
static int msgid2;
//创建消息队列
void init(void){
printf("服务器正在初始化,请稍后...\n");
sleep(2);
//创建第一个消息队列
msgid1 = msgget(key1,IPC_CREAT|IPC_EXCL|0666);
if(-1 == msgid1)
{
perror("创建消息队列一失败");
exit(-1);
}
printf("消息队列一创建成功\n");
//创建第二个消息队列
msgid2 = msgget(key2,IPC_CREAT|IPC_EXCL|0666);
if(-1 == msgid2)
{
perror("创建消息队列二失败");
exit(-1);
}
printf("消息队列二创建成功\n");
printf("服务器初始化成功\n");
}
//工作
void start(void)
{
pid_t pid_open = vfork();
if(-1 == pid_open)
{
perror("创建子进程失败");
exit(-1);
}
if(0 == pid_open)
{
//实现开户的功能
execl("./open","open",NULL);
}
//父进程等待子进程结束
waitpid(pid_open,NULL,0);
}
int main(void)
{
//程序退出时,自动执行
atexit(destroy);
printf("关闭服务器请按CTRL+C\n");
signal(SIGINT,sig_exit);
//初始化服务器
init();
//调用start方法
start();
//关闭服务器
//destroy();
return 0;
}
|
C
|
// Included header files
#include "terminal.h"
#include "helpers.h"
#include "events.h"
#include "interface.h"
/*
Source StackOverflow
From http://stackoverflow.com/a/6857444
Author Daniel Leschkowski - http://stackoverflow.com/users/839180/daniel-leschkowski
Editor Tim Cooper - http://stackoverflow.com/users/142162/tim-cooper
*/
// Functions
char input [ 256 ];
static struct termios newterm;
static struct termios originalterm;
// Functions
void startUsingTerminal ( int fd ) {
debug();
enableCharacterBreakMode ( fd );
// Let's read from the "file," or socket, without waiting for it.
fcntl ( fd, F_SETFL, O_NONBLOCK );
// Listen for events!
when (
STDIN_FILENO,
EventReadable | EventFailed,
& onKeyPress
);
}
void enableCharacterBreakMode ( int fd ) {
debug();
if ( tcgetattr ( fd, & originalterm ) == -1 )
error ( NULL );
newterm = originalterm;
newterm.c_lflag = newterm.c_lflag & ~ ( ECHO | ICANON );
newterm.c_cc [ VMIN ] = 1;
newterm.c_cc [ VTIME ] = 0;
if ( tcsetattr ( fd, TCSAFLUSH, & newterm ) == -1 )
error ( NULL );
}
void restoreTerminal ( int fd ) {
debug();
if ( tcsetattr ( fd, TCSANOW, & originalterm ) == -1 )
error ( NULL );
}
int getch () {
debug();
int cinput;
enableCharacterBreakMode ( STDIN_FILENO );
cinput = getchar ();
restoreTerminal ( STDIN_FILENO );
return cinput;
}
void onKeyPress ( int fileNumber, int event ) {
debug();
if ( event & EventReadable ) {
char inputString [ 256 ];
char stringChunk [ 256 ];
memset ( & inputString, 0, sizeof inputString );
memset ( & stringChunk, 0, sizeof stringChunk );
while ( read ( fileNumber, stringChunk, 255 ) > 0 )
appendStringToStringToLimit ( stringChunk, inputString, 255 );
interpretKey ( inputString );
}
if ( event & EventFailed )
error ( "I had a problem while waiting for keys to be pressed!\n" );
}
void stopUsingTerminal ( int fd ) {
debug();
restoreTerminal ( fd );
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
/* ŧir}CΨӦsr */
char str[15]="Hello!zn";
printf(" ==|123456789012345|==\n");
printf("1. |%s|\n",str);
printf("2. |%5s|\n",str);
printf("3. |%15s|\n",str);
printf("4. |%-15s|\n",str);
printf("5. |%10.2s|\n",str);
printf("6. |%-10.2s|\n\n",str);
system("PAUSE");
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include <sys/time.h>
#include <time.h>
/*
struct timespec
{
time_t tv_sec;
long int tv_nsec;
};
*/
int main()
{
struct timespec timeout;
timeout.tv_sec= time(0) + 1; //time(0) ǵǰʱ tv_sec ָ
timeout.tv_nsec=0;
//printf("time(0) = %ld\n",time(0));
//sleep(1);
//gettimeofday(&tv,NULL);
printf("time(0) = %ld\n",time(0));
printf("time %ld:%ld\n",timeout.tv_sec - time(0) ,timeout.tv_nsec);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include"struct.h"
#include<math.h>
int max(int p,int q)
{
if(p>q)
return p;
else return q;
}
int height(btree *root)
{
if(root==NULL)
return 0;
return max(height(root->lchild),height(root->rchild))+1;
}
btree *insertelementlevel(btree **root,int level)
{
if(level==1)
{
if((*root)->lchild==NULL)
return *root;
if((*root)->rchild==NULL)
return *root;
}
else
{
return insertelementlevel((*root)->lchild,level-1);
return insertelementlevel((*root)->rchild,level-1);
}
}
int pow1(int x,int y)
{
while(y!=1)
{
x=x*2;
y--;
}
return x;
}
void insertbtree2(btree **root,int val)
{
static int cou=0;
cou++;
btree *temp;
temp=(btree*)malloc(sizeof(btree));
temp->value=val;
temp->lchild=NULL;
temp->rchild=NULL;
if(*root==NULL)
{
*root=temp;
return;
}
int h;
h=height(*root);
int l=pow1(2,h)-1-cou;
if(l>0)
h=h-1;
btree * ptr,*ptr1;
ptr=*root;
ptr1=insertelementlevel(&ptr,h);
if(ptr1->lchild==NULL)
ptr1->lchild=temp;
else
ptr1->rchild=temp;
printf("element inserted");
}
void print(btree *root)
{
if(root==NULL)
return;
print(root->lchild);
printf("%d ",root->value);
print(root->rchild);
}
int main()
{
btree *root=NULL;
int i,n,val;
printf("Enter number of nodes value :-");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the insert node value:-");
scanf("%d",&val);
insertbtree2(&root,val);
}
print(root);
}
|
C
|
//=============================================================================================================
//If clauses to check if the user s inputs are logical
if (energylab < 0)
{
cout << "Warning: The beam energy cannot be negative or zero. The beam energy is set by default at 0.01 MeV" << endl;
energylab = 0.001 ;
}
if (energylab = 0)
{
cout << "Warning: The beam energy cannot be negative or zero. The beam energy is set by default at 0.01 MeV" << endl;
energylab = 0.001;
}
//-------------------------------------------------------------------------------------------------------------
// 0<initialtheta<90
if(initialthetalab < 0.001)
{
cout << "Warning: Due to Kinematics constraints Mott Scattering is only possible for angles between 0 - 90 degrees with 0 and 90 degrees being mathematical poles. The initial detection angle is set by default at 0.001 degrees " << endl;
initialthetalab = 0.001 ;
}
if(initialthetalab = 0)
{
cout << "Warning: Due to Kinematics constraints Mott Scattering is only possible for angles between 0 - 90 degrees with 0 and 90 degrees being mathematical poles. The initial detection angle is set by default at 0.001 degrees " << endl;
initialthetalab = 0.001;
}
if(initialthetalab > 89.98)
{
cout << "Warning: Due to Kinematics constraints Mott Scattering is only possible for angles between 0 - 90 degrees with 0 and 90 degrees being mathematical poles. The initial detection angle is set by default at 85 degrees " << endl;
initialthetalab = 85;
}
if(initialthetalab = 89.98)
{
cout << "Warning: Due to Kinematics constraints Mott Scattering is only possible for angles between 0 - 90 degrees with 0 and 90 degrees being mathematical poles. The detection angle is set by default at 85 degrees " << endl;
initialthetalab = 85;
}
if(finalthetalab > 89.98)
{
cout << "Warning: Due to Kinematics constraints Mott Scattering is only possible for angles between 0 - 90 degrees with 0 and 90 degrees being mathematical poles. The detection angle is set by default at 89.98 degrees " << endl;
finalthetalab = 89.98;
}
//------------------------------------------------------------------------------------------------------------
//finalthetalab<initialthetalab
if(finalthetalab < initialthetalab)
{
cout << "Warning: The final angle of detection cannot be less than the initial angle. The final detection angle is set by default to be equal with the initial detection angle." << endl;
finalthetalab = initialthetalab ;
}
//------------------------------------------------------------------------------------------------------------
if(steplab < 0.001)
{
steplab = 0.001;
cout << "Warning: The step cannot be less than 0.001 degrees.The step is set by default at 0.001 degrees" << endl;
}
//=============================================================================================================
|
C
|
#include<stdio.h>
int main(){
int vezes =0, x =0, atual =0;
long long int vet[9999], a =0, b=0;
int fbo=0, i =0;
scanf("%d", &vezes);
int vet2[9999];
for(x;x<vezes; x++)
{
a=1,b =0; i =0;
scanf("%d", &fbo);
vet[x]=0;
vet2[x]=fbo;
for(i;i<fbo;i++)
{
vet[x]=vet[x]+a;
a = b;
b=vet[x];
}
}
x=0;
for(x;x<vezes; x++)
{
printf("Fib(%d) = %lld\n", vet2[x],vet[x]);
}
return 0;
}
|
C
|
/* range of armstrong numbers 100 t0 200 */
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i, n=100,sum=0, temp;
temp = n;
for (n=100; n <= 200; n++) {
while (n>0) {
i = n%10;
sum+= i*i*i;
n = n/10;
}
if (sum == n) {
printf(" %d\n",sum);
}
}
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_3__ TYPE_1__ ;
/* Type definitions */
typedef int /*<<< orphan*/ WCHAR ;
struct TYPE_3__ {int /*<<< orphan*/ const* class; int /*<<< orphan*/ alias; } ;
/* Variables and functions */
unsigned int ARRAY_SIZE (TYPE_1__*) ;
TYPE_1__* alias_map ;
int /*<<< orphan*/ strcmpiW (int /*<<< orphan*/ const*,int /*<<< orphan*/ ) ;
__attribute__((used)) static const WCHAR *find_class( const WCHAR *alias )
{
unsigned int i;
for (i = 0; i < ARRAY_SIZE(alias_map); i++)
{
if (!strcmpiW( alias, alias_map[i].alias )) return alias_map[i].class;
}
return NULL;
}
|
C
|
//
// Created by Stephen on 22/01/2018.
//
#include <stdint.h>
#include "main.h"
#ifndef INTERPRETER_COMMANDS_H
#define INTERPRETER_COMMANDS_H
void exec_CMP_char(char op1_val, char op2_val);
void exec_CMP_uchar(unsigned char op1_val, unsigned char op2_val);
void exec_CMP_short(int16_t op1_val, int16_t op2_val);
void exec_CMP_ushort(uint16_t op1_val, uint16_t op2_val);
void exec_CMP_int(int op1_val, int op2_val);
void exec_CMP_uint(unsigned int op1_val, unsigned int op2_val);
void exec_CMP_float(float op1_val, float op2_val);
void exec_JMP(unsigned int addr);
void exec_JE(unsigned int addr);
void exec_JNE(unsigned int addr);
void exec_JLT(unsigned int addr);
void exec_JLE(unsigned int addr);
void exec_JGT(unsigned int addr);
void exec_JGE(unsigned int addr);
void exec_MOV_reg(unsigned char regnum, int length, const unsigned char* str);
void exec_MOV_mem(unsigned long maddr, int length, const unsigned char* str);
void exec_LEA_reg(unsigned char regnum, unsigned int maddr);
void exec_LEA_mem(unsigned int maddr_to, unsigned int maddr_from);
void exec_ADD_char(unsigned char* op1, int op1_type, unsigned char* op2, int op2_type);
void exec_ADD_uchar(unsigned char* op1, int op1_type, unsigned char* op2, int op2_type);
void exec_ADD_short(unsigned char* op1, int op1_type, unsigned char* op2, int op2_type);
void exec_ADD_ushort(unsigned char* op1, int op1_type, unsigned char* op2, int op2_type);
void exec_ADD_int(unsigned char* op1, int op1_type, unsigned char* op2, int op2_type);
void exec_ADD_uint(unsigned char* op1, int op1_type, unsigned char* op2, int op2_type);
void exec_ADD_float(unsigned char* op1, int op1_type, unsigned char* op2, int op2_type);
void exec_arithmetic(char* function, char dtype, unsigned char* op1, unsigned char op1_type,
unsigned char* op2, unsigned char op2_type);
#endif //INTERPRETER_COMMANDS_H
|
C
|
#include "list.h"
void INIT_LIST_HEAD(struct list_head *list)
{
list->next = list;
list->prev = list;
}
void _list_add(struct list_head *new,struct list_head *prev,struct list_head *next)
{
next->prev = new;
new->next = next;
new->prev = prev;
prev->next = new;
}
void list_add(struct list_head *new, struct list_head *head)
{
_list_add(new, head, head->next);
}
void list_add_tail(struct list_head *new, struct list_head *head)
{
_list_add(new, head->prev, head);
}
void _list_del(struct list_head * prev, struct list_head * next)
{
next->prev = prev;
prev->next = next;
}
void list_del(struct list_head *del)
{
_list_del(del->prev,del->next);
}
int list_empty(const struct list_head *head)
{
return head->next == head;
}
|
C
|
// "../Debug/Parsing_Debug.c" version 0.0
// gcc -std=c99 "Parsing_Debug.c" -o "Parsing_Debug.exe"
#include <stdio.h>
// #include "../Core/Parsing.h"
#include "Parsing.h"
int main(
void
){
char Test_String[512];
int Test_Integer;
long int Test_Long;
float Test_Float;
// Initialize_Parser debugging
Struct_Parser *Parser = Initialize_Parser("Parsing_Debug.txt", "//", 512);
printf("Initialize_Parser:\n");
if(Parser == NULL)
goto Error_Test_Failed;
printf(" Input test('!'): %c\n", fgetc(Parser->Input));
printf(" Comment_Prefix('//'): %s\n", Parser->Comment_Prefix);
printf(" Buffer(''): %s\n", Parser->Buffer);
printf(" Buffer_Size(512): %d\n", Parser->Buffer_Size);
printf(" Buffer_Index(0): %d\n", Parser->Buffer_Index);
printf(" Skipped_Lines(0): %d\n", Parser->Skipped_Lines);
printf(" Test SUCCESS!\n");
// Fetch_Clear_Line and Skip_Whitespace debugging
printf("Fetch_Clear_Line/Skip_Whitespace:\n");
if(!Fetch_Clear_Line(Parser))
goto Error_Test_Failed;
printf(" Line taken: %s\n", &Parser->Buffer[Parser->Buffer_Index]);
Fetch_Clear_Line(Parser);
// Next_String debugging
printf("Next_String:\n Parsed strings: (");
for(int i = 0;i < 23;i++){
if(!Next_String(Parser, Test_String)){
printf(" ... !\n");
goto Error_Test_Failed;
}
printf("%s[%d]", Test_String, Parser->Skipped_Lines);
}
printf(")\n");
// Next_Number debugging
printf("Next_Number:\n Parsed floats: (");
for(int i = 0;i < 20;i++){
if(!Next_Number(Parser, Test_Float, FLOAT))
printf("_");
else
printf("%f", Test_Float);
printf("[%d]", Parser->Skipped_Lines);
}
printf(")\n");
printf(" Parsed Integers: (");
for(int i = 0;i < 22;i++){
if(!Next_Number(Parser, Test_Long, LONG_SAFE))
printf("_");
else
printf("%d", Test_Long);
printf("[%d]", Parser->Skipped_Lines);
}
printf(")\n");
// Next_Set debugging
printf("Next_Set:\n Parsed set: ");
if(!Next_Set(Parser, Test_String, "!*====>", "<====*!")){
printf("! \n");
goto Error_Test_Failed;
}
printf("%s\n Test SUCCESS!\n", Test_String);
// Is_Next_Match debugging
printf("Is_Next_Match :\n Case 1: ");
if(!Is_Next_Match(Parser, "This should match...")){
printf("! \n");
goto Error_Test_Failed;
}
printf("SUCCESS!\n Case 2: ");
if(!Is_Next_Match(Parser, "The string here is supposed to match!")){
printf("! \n");
goto Error_Test_Failed;
}
printf("SUCCESS!\n Case 3: ");
if(!Is_Next_Match(Parser, "(){}")){
printf("! \n");
goto Error_Test_Failed;
}
printf("SUCCESS!\n Case 4: ");
if(Is_Next_Match(Parser, " JSKL:DJF *(PQ@J#JIJDK:SJFK")){
printf("! \n");
goto Error_Test_Failed;
}
printf("SUCCESS!\n");
// Finalize
Finalize_Parser(Parser);
return SUCCESS;
Error_Test_Failed:
printf(" Test FAILED.\n");
return FAILURE;
}
// Input (Parsing_Debug.txt)
/*
!//Comment only line (Ignore any following messages denoting success)
//Another comment only line except this one is a little spaced out (Again, ignore any following messages denoting success)
The test of Fetch_Clear_Line and Skip_Whitespace was a SUCCESS! //Actually if it was this comment would be removed...
A B C DDDDDD EE F G //ShouldntSeeMe!
H II J KKK L M N O //ShouldntSeeMe!
189 2 3 ! 3 50 9 Z //ShouldntSeeMe!
1 22 333 4444 8908 1.987 12465.991 -1332 -1.2343 -0 1.
- -. 1..0
321 432 543 6 1 8987 981.0 +123213 -234 -0 1903
123
643
+54
!*====>The test of Next_Set
is
a
SUCCESS
!<====*!
This should match...
The
stringhere
is supposedto match
!
( ) { }
*/
|
C
|
#include "LineSeparator.h"
#define SEPARATOR ","
// Macro for a function for reading a line.
#define READ_LINE(l, f) fgets(l, MAX_LINE_LENGTH, f)
// The 'read' token for the fopen function
#define READ_ONLY "r"
// Enums for the command line arguments that are given to this program.
enum
{
PROG_NAME = 0,
FILE_NAME = 1
} CommandLineArgument;
/**
* Reads a line and extract a vector's initialization from it,
* which includes the data of the vector and perhaps a tag value.
* @param p_v A pointer to a vector to be initialized.
* @param line The string of a line to be parsed.
* @param dim The dimension of the vector.
* @return The pointer of the vector that was initialized.
*/
static Vector * parseLine(Vector* p_v, char* line, int dim)
{
assert (line != NULL && *line != EOL);
char *currNum;
currNum = strtok(line, SEPARATOR);
for (int j = 0; j < dim; j++)
{
sscanf(currNum, "%lf", &(p_v->_data[j]));
currNum = strtok(NULL, SEPARATOR);
}
if (currNum != NULL) // This means a tag value exists
{
sscanf(currNum, "%d", &(p_v->_tag));
}
return p_v;
}
/**
* Gets a classification vector and classifies the vector specified by the given line, i.e
* checks on what side of the hyper-plane determined by p_w this vector is.
* @param p_w A pointer to the classifier vector.
* @param line The string of the line to be parsed.
* @param dim The dimension of the vector.
* @return The Tag value that is given by <w,v> >? 0
* Note that in our case: |<w,v>| < EPSILON <=> <w,v> = 0 => <w,v> < EPSILON ==> Tag = -1
*/
static Tag predict(const Vector* p_w, char* line, int dim)
{
Vector v;
parseLine(&v, line, dim);
return getTag(p_w, &v, dim);
}
/**
* Gets a classification vector and trains it according to a given number of points.
* @param p_w A pointer to the classification vector to be trained.
* @param inFile The file that specifies the training set.
* @param dim The dimension of the vector.
* @param numOfPts The number of training points (m).
* @return A pointer to the same training vector (p_w).
*/
Vector * trainVector(Vector* p_w, FILE* inFile, int dim, int numOfPts)
{
assert (p_w != NULL && inFile != NULL && numOfPts >= 0);
initVector(p_w, dim); // Classifier is initially set to be the 0 vector.
Vector v;
char line[MAX_LINE_LENGTH + 1]; // +1 for '\0'
Tag tempTag; // The predicted Tag value.
for (int i = 0; i < numOfPts; i++)
{
READ_LINE(line, inFile);
parseLine(&v, line, dim);
tempTag = getTag(p_w, &v, dim);
if (tempTag != v._tag) // Checks if an update to the vector is needed.
{
addVector(p_w, &v, dim);
}
}
return p_w;
}
/**
* Gets a classifier and prints its predictions to the the vectors specified in the rest of
* the file.
* @param p_w A pointer to the classifier vector.
* @param inFile The file to read.
* @param dim The dimension of the vector.
*/
void getPredictions(Vector* p_w, FILE* inFile, int dim)
{
assert(inFile != NULL && dim <= MAX_DIMENSION && dim > 1);
char line[MAX_LINE_LENGTH + 1]; // Again, +1 for '\0'
while (!feof(inFile))
{
if (READ_LINE(line, inFile) != NULL)
{// Prints predictions
printf("%d\n", predict(p_w, line, dim));
}
}
return;
}
/**
* Reads the file that was given and train a classifier vector to make predictions.
* @param inFile The given file.
*/
void parseFile(FILE* inFile)
{
assert (inFile != NULL);
char line[MAX_LINE_LENGTH + 1]; // +1 for '\0'
int dim, numOfPts; // Dimension and number of training points
READ_LINE(line, inFile);
sscanf(line, "%d", &dim); // Read the dimension (n) - first line
assert(dim <= MAX_DIMENSION && dim > 1);
READ_LINE(line, inFile);
sscanf(line, "%d", &numOfPts); // Read the number of points (m) - second line
Vector w; // Our classifier (the vector perp. to the linear classifier)
trainVector(&w, inFile, dim, numOfPts);
getPredictions(&w, inFile, dim);
return;
}
/**
* The main function.
* Checks the validity of the command line argument that was given and
* calls the parse function.
*/
int main(int argc, char* argv[])
{
if (argc != 2)
{
printf("Usage: %s <file_name>\n", argv[PROG_NAME]);
return 0;
}
FILE *inFile = fopen(argv[FILE_NAME], READ_ONLY); // Open
if (inFile == NULL)
{
printf("Unable to open input file: %s\n", argv[FILE_NAME]);
return 0;
}
parseFile(inFile);
fclose(inFile); // Close
return 0;
}
|
C
|
// IOS - 2. projekt
// Author: Jakub Svoboda
// Login: xsvobo0z
// Date: 13.4.2016
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
#include <semaphore.h>
#include <fcntl.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/ipc.h>
int arguments(int P,int C,int PT,int RT){
// Validates values of passed arguments. Returns 0 if arguments are legit.
if (P <= 0){ // Check if P is ok.
fprintf(stderr, "P (number of passegers) must be > 0. %d was passed. \n",P);
exit (1);
}
if ((C <= 0) || (P <= C) || ((P % C) !=0)){ // Check if C is ok.
fprintf(stderr, "C (cart capacity) must be: C > 0, P > C, P mod C =0. %d was passed. \n",C);
exit (1);
}
if ((PT < 0) || (PT >= 5001)){ //Check if PT is ok.
fprintf(stderr, "PT (pause time) must be: PT >= 0, PT < 5001. %d was passed. \n",PT);
exit(1);
}
if ((RT < 0) || (RT >= 5001)){ //Check if RT is ok.
fprintf(stderr, "RT (ride time) must be: RT >= 0, RT < 5001. %d was passed. \n",RT);
exit(1);
}
return 0;
}
int clear_semaphores(sem_t *mutex1,sem_t *mutex2,sem_t *board_queue,sem_t *unboard_queue,sem_t *all_aboard,sem_t *all_ashore,sem_t *output_sem,sem_t *kill_all){
//This function first closes and then unlinks all semaphores.
sem_close(mutex1);
sem_unlink("mutex1");
sem_close(mutex2);
sem_unlink("mutex2");
sem_close(board_queue);
sem_unlink("board_queue");
sem_close(unboard_queue);
sem_unlink("unboard_queue");
sem_close(all_ashore);
sem_unlink("all_ashore");
sem_close(all_aboard);
sem_unlink("all_aboard");
sem_close(output_sem);
sem_unlink("output_sem");
sem_close(kill_all);
sem_unlink("kill_all");
return 0;
}
int do_car_stuff(int *A,int C, int RT,sem_t *board_queue,sem_t *unboard_queue,sem_t *all_aboard,sem_t *all_ashore,sem_t *output_sem,FILE *fp){
sem_wait(output_sem); //operation LOAD begins
fprintf (fp,"%d : C 1 : load\n",*A);
fflush(fp);
(*A)++;
sem_post(output_sem);
for(int k =0; k<C; k++){
sem_post(board_queue);
}
sem_wait(all_aboard); // Waits for last passenger to singal all_aboard, LOAD ends.
sem_wait(output_sem); //print run
fprintf (fp,"%d : C 1 : run\n",*A);
fflush(fp);
(*A)++;
sem_post(output_sem);
if (RT>0) usleep((rand() % RT) *1000); //sleep for RT miliseconds
sem_wait(output_sem); //operation UNLOAD begins
fprintf (fp,"%d : C 1 : unload\n",*A);
fflush(fp);
(*A)++;
sem_post(output_sem);
for(int k = C; k>0; k--){
sem_post(unboard_queue); //Sends C signals to passengers to unboard.
}
sem_wait(all_ashore); //Waits for last unboarding passenger to singnal all_ashore
return 0;
}
int do_passenger_stuff(int *A, int *order,int C,int i,int *boarders,int *unboarders, sem_t *mutex1,sem_t *mutex2,sem_t *board_queue,sem_t *unboard_queue,sem_t *all_aboard,sem_t *all_ashore,sem_t *output_sem,sem_t *kill_all,FILE *fp){
*order=*order; //to block -Werror if order is not implemented
sem_wait(output_sem);
fprintf(fp,"%d : P %d : started\n",*A,i); //Prints when passenger get created.
fflush(fp);
(*A)++;
sem_post(output_sem);
sem_wait(board_queue); //Waits for car to send signal to board.
sem_wait(mutex1); // operation LOAD begins
sem_wait(output_sem);
(*boarders)++;
fprintf(fp,"%d : P %d : board \n",*A,i); //Print board message.
fflush(fp);
(*A)++;
if (*boarders == C){
fprintf(fp,"%d : P %d : board last\n",*A,i); //output if last boarder
fflush(fp);
(*A)++;
sem_post(all_aboard);
*boarders=0; //reset boarders count
}else{ //output if not last boarder
fprintf(fp,"%d : P %d : board order %d\n",*A,i, *boarders);
fflush(fp);
(*A)++;
}
sem_post(output_sem);
sem_post(mutex1); // operation LOAD ends
sem_wait(unboard_queue);
sem_wait(mutex2); // operation UNLOAD begins
sem_wait(output_sem);
(*unboarders)++;
fprintf(fp,"%d : P %d : unboard \n",*A,i);
fflush(fp);
(*A)++;
if (*unboarders == C){
fprintf(fp,"%d : P %d : unboard last\n",*A,i); //print if last boarder
fflush(fp);
(*A)++;
sem_post(all_ashore);
*unboarders=0; //reset unboarders counter
}else{ //output for unboarders that are not last
fprintf(fp,"%d : P %d : unboard order %d\n",*A,i,*unboarders);
fflush(fp);
(*A)++;
}
sem_post(output_sem);
sem_post(mutex2); // operation UNLOAD ends
sem_wait(kill_all); //waits for creator to send signal to die
sem_wait(output_sem);
fprintf(fp,"%d : P %d : finished \n",*A,i); //prints final message
fflush(fp);
(*A)++;
sem_post(output_sem);
return 0;
}
int main (int argc, char *argv[]){ //Create shared variables.
int *unboarders= mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
int *boarders = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
int *A = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
int *order = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
*boarders=0; //Number of processes that boarded the cart.
*unboarders=0; //Number of processes that unboarded the cart.
*A=1; //Event number (first number in output).
*order=1; //Not used atm.
FILE *fp; //Open output file for write.
fp=fopen("proj2.out","w+");
int P = 0,C = 0, PT = 0, RT =0;
if (argc != 5){ //Exactly 4 additional arguments must be passed.
fprintf(stderr, "Incorrect number of arguments: %d, should be 5.\n",argc);
exit(1);
}
else{ //Assign aruments to int variables.
P = strtol(argv[1], NULL, 10);
C = strtol(argv[2], NULL, 10);
PT = strtol(argv[3], NULL, 10);
RT = strtol(argv[4], NULL, 10);
arguments(P,C,PT,RT); //Validate values of arguments.
}
//Creates all semaphores.
sem_t *mutex1 = sem_open("mutex1", O_CREAT | O_EXCL, 0644, 1);
sem_t *mutex2 = sem_open("mutex2", O_CREAT | O_EXCL, 0644, 1);
sem_t *board_queue = sem_open("board_queue", O_CREAT | O_EXCL, 0644, 0);
sem_t *unboard_queue = sem_open("unboard_queue", O_CREAT | O_EXCL, 0644, 0);
sem_t *all_aboard = sem_open("all_aboard", O_CREAT | O_EXCL, 0644, 0);
sem_t *all_ashore = sem_open("all_ashore", O_CREAT | O_EXCL, 0644, 0);
sem_t *output_sem = sem_open("output_sem", O_CREAT | O_EXCL, 0644, 1);
sem_t *kill_all = sem_open("kill_all", O_CREAT | O_EXCL, 0644, 0);
pid_t child_pid_or_zero = fork();
if (child_pid_or_zero < 0){ // Error when fork fails.
perror("fork() error");
exit (2);
}
if (child_pid_or_zero != 0){ // Main process.
waitpid(child_pid_or_zero,&child_pid_or_zero,0); //Waits for car to finish.
for(int i=0; i < (P+1) ; i++) sem_post(kill_all); //Allows passengers to end.
wait(NULL); //waits for passengers to end.
munmap(boarders, sizeof(int)); //Free shared memory.
munmap(unboarders, sizeof(int));
munmap(A, sizeof(int));
munmap(order, sizeof(int));
//Free semaphores.
clear_semaphores(mutex1,mutex2,board_queue,unboard_queue,all_aboard,all_ashore,output_sem,kill_all);
fclose(fp); //close output file.
}else{ // Creator process
srand(time(NULL)); // Seed for rand() function.
int car = fork(); // Fork of car process
if (car <0){ // When fork fails, prints error message.
perror("fork error ");
exit(2);
}else if (car == 0 ){ //Car process
sem_wait(output_sem);
fprintf(fp,"%d : C 1 : started\n",*A);
fflush(fp);
(*A)++;
sem_post(output_sem);
for(int j=0; j<(P/C);j++){ //Car rides P/C times
do_car_stuff(A,C,RT,board_queue,unboard_queue,all_aboard,all_ashore,output_sem,fp);
}
sem_wait(output_sem); //Output when finished
fprintf(fp,"%d : C 1 : finished \n",*A);
fflush(fp);
(*A)++;
sem_post(output_sem);
exit (0);
}else{ //Creator process
for(int i=1; i<=P;i++){ //Passagers creation
if (PT> 0) usleep((rand() % PT) * 1000); //Sleep for PT
int passenger = fork();
if (passenger <0){ //error when fork fails
perror("fork error");
exit(2);
}else if (passenger == 0 ){ // Each passager goes for one ride.
do_passenger_stuff(A, order,C, i,boarders, unboarders, mutex1,mutex2,board_queue,unboard_queue,all_aboard,all_ashore,output_sem,kill_all,fp);
exit (0);
}else{
// wait(NULL);
}
}
wait(NULL);
}
// wait(NULL);
// waitpid(car,&car,0);
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* eat_sleep_think.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fcoudert <fcoudert@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/04 10:13:10 by fcoudert #+# #+# */
/* Updated: 2021/03/22 09:15:57 by fcoudert ### ########.fr */
/* */
/* ************************************************************************** */
#include "philo_one.h"
#include <string.h>
void write_stuff(t_info *info, char *message)
{
char *str;
char *time;
pthread_mutex_lock(&info->philo->display);
if (g_died_check == 0)
{
time = ft_itoa(get_micro(info));
str = ft_strjoin(time, " ", info->index_c, message);
write(1, str, ft_strlen(str));
free(str);
free(time);
}
pthread_mutex_unlock(&info->philo->display);
}
void take_fork(t_info *info)
{
if ((info->index % 2) == 0)
{
if (pthread_mutex_lock(&info->next_fork->lock_forks) != 0)
ft_putstr("ERROR\n");
write_stuff(info, " has taken fork\n");
}
if (pthread_mutex_lock(&info->own_fork.lock_forks) != 0)
ft_putstr("ERROR\n");
write_stuff(info, " has taken fork\n");
if ((info->index % 2) == 1)
{
if (pthread_mutex_lock(&info->next_fork->lock_forks) != 0)
ft_putstr("ERROR\n");
write_stuff(info, " has taken fork\n");
}
}
void leave_fork(t_info *info)
{
pthread_mutex_unlock(&info->own_fork.lock_forks);
pthread_mutex_unlock(&info->next_fork->lock_forks);
}
void eat(t_info *info)
{
take_fork(info);
write_stuff(info, " is eating\n");
info->last_meal_milli = get_milli();
sleep_time(info->philo->time_to_eat, info);
leave_fork(info);
}
void eat_sleep_think(t_info *info)
{
eat(info);
info->count_eat += 1;
if (info->philo->monitor_meals &&
info->count_eat > info->philo->nb_must_eat)
info->check_eat = 1;
write_stuff(info, " is sleeping\n");
sleep_time(info->philo->time_to_sleep, info);
write_stuff(info, " is thinking\n");
if ((info->philo->nb_philosopher % 2) == 1)
usleep(500);
}
|
C
|
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <stdlib.h>
typedef struct Matrix{
int matrix1[3][3]; /* A matrix */
int matrix2[3][3]; /* B matrix */
int multiply[3][3]; /* result */
}Matrix;
void* matrix1(void* arg){
Matrix* arg_s = (Matrix*)arg;
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
arg_s->multiply[i][j] = arg_s->matrix1[i][0] * arg_s->matrix2[0][j];} /* matrix execution 1*/
}
}
void* matrix2(void* arg){
Matrix* arg_s = (Matrix*)arg;
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
arg_s->multiply[i][j] = arg_s->matrix1[i][1] * arg_s->matrix2[1][j];} /*matrix execution 2*/
}
}
void* matrix3(void* arg){
Matrix* arg_s = (Matrix*)arg;
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
arg_s->multiply[i][j] = arg_s->matrix1[i][2] * arg_s->matrix2[2][j];} /*matrix execution 3*/
}
}
void print_matrix(Matrix* arg){
Matrix* arg_p = (Matrix*)arg;
for(int i=0; i<3; i++){
for(int j=0;j<3;j++){
printf("[%2d] ", arg_p->multiply[i][j]);}
printf("\n\n");
}
}
int main(void){
clock_t start, end;
float res;
void* funcs[3];
funcs[0] = matrix1;
funcs[1] = matrix2;
funcs[2] = matrix3;
Matrix* mat_1 = (Matrix*)malloc(sizeof(Matrix));
srand(time(NULL));
for(int i=0; i<3;i++){
for(int j=0; j<3; j++){
mat_1->matrix1[i][j] = (rand() % 100);
mat_1->matrix2[i][j] = (rand() % 100);} /*Matrix Value Setting */
}
pthread_t three_matrix[3]; /* Three threads */
start = clock();
for(int i=0; i<3; i++){
if(pthread_create(&three_matrix[i],NULL, funcs[i],(void*)mat_1)){
printf("Pthread Creation Failure.\n");
exit(10);
}
if(pthread_join(three_matrix[i],NULL)){
printf("Pthread Join Failure.\n");
exit(10);
}
}
end = clock();
res = (float)(end - start); /*Execution time*/
print_matrix(mat_1);
printf("Three thread access time : %.6f ms\n", res/1000);
return 0;
}
|
C
|
#include <stdio.h>
#include <cs50.h>
int main(void) {
int height;
int spaces;
int hashes;
do{
printf("Height: ");
height = get_int();
} while(height < 0 || height > 23);
for(int i = 0; i < height; i++) {
for(spaces = height - i; spaces > 1; spaces--) {
printf(" ");
}
for(hashes = 0; hashes <= i + 1; hashes++) {
printf("#");
}
printf("\n");
}
}
|
C
|
#include <stdio.h>
void Swap(int *prt1,int *prt2)
{
int temp = *prt1;
*prt1 = *prt2;
*prt2 = temp;
}
void main()
{
int start = 96 , end = 6;
printf("현재값 = %d, %d ",start , end);
if(start > end)
{
Swap(&start , &end);
}
printf("현재값 = %d, %d ",start , end);
}
// void Test (short *ptr)
// {
// short soft = 0;
// soft = *ptr;
// *ptr = 3;
// printf("soft는 = %d ",soft);
// }
// void main()
// {
// short tips = 5;
// Test(&tips);
// printf("%d ssss",tips);
// }
// short birthday;
// short *prt; //포인터 변수 선언
// prt =&birthday; // birthday 변수의 주소를 ptr변수에 대입 포인터 *이 없다면 주소를 입력하는것
// // * ptr 이라면 가리키는 주소에 갑ㅅ 을 입력하는 것
// printf("birthdayt 변수의 주소는 %p 입니다.\n" , prt);
|
C
|
//
// This is the main program on the BBB
// It launches the DSP code on PRU 0 (slave)
// It also launches the I2S and sample period code on PRU 1 (master)
// At the end we start tclsh as a child process.
//
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdint.h>
#include <math.h>
#include "prussdrv.h"
#include "pruss_intc_mapping.h"
#include "mio.h"
#include "child.h"
#include "bbbLib.h"
#include "mem.h"
#include "PRUlib.h"
#include "robotLib.h"
// TRUE and FALSE
#define TRUE 1
#define FALSE 0
// GUI mode or not
int GUImode = TRUE ;
// We need a global variable that wil point to the shared memory
shared_memory_t *shared_memory ;
// Need a variable for debugging
int debug = TRUE ;
// Need global structure to hold GUI variables
GUIvars_t GUIvars ;
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Routine to execute PRU programs
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
void execPRUprograms() {
// Initialize the PRUs
if (debug) printf("Initializing the PRUs.\n") ;
PRUinit() ;
// Configure PRU 0 based on GUI settings
if (debug) printf("Configuring PRU 0 with GUI data\n") ;
configPRU() ;
// Start the PRUs
if (debug) printf("Start the PRUs ...\n") ;
PRUstart() ;
return ;
}
// **********************************
// Main program
// **********************************
int main (void) {
FILE *read_from, *write_to;
char str[STR_LEN] ;
int exitFlag = FALSE ;
int runFlag = FALSE ;
// Print a welcome statement
if (debug) printf("\nSIUE Beaglebot Project\n") ;
if (debug) printf("24-Jul-2016\n\n") ;
// GPIO initialization
if (debug) printf("Initializing the GPIOs which we will use ...\n") ;
GPIOinit() ;
turnLED(OFF) ;
// Look to see if user wants to use the GUI
if (GUImode) {
// Start the gui
// Two-way pipe
start_child("tclsh", &read_from, &write_to);
fprintf(write_to, "source ./tcl/gui.tcl \n") ;
// Get data from GUI
while (!exitFlag) {
if (fgets(str, STR_LEN, read_from) != NULL) {
getGUIvars(str) ;
exitFlag = GUIvars.exitFlag ;
if (!exitFlag) {
if (!runFlag) {
execPRUprograms() ;
testRobot() ;
runFlag = TRUE ;
} else {;
PRUstop() ;
execPRUprograms() ;
testRobot() ;
} // end if then elseif
} // end if
} //end if
} // end while
} else { // NO GUI!!!!
// Get the GUI string from the robot.config file
// and parse it as usual
loadGuiVarsFromFile(str) ;
getGUIvars(str) ;
// The string we load may have the exit flag set
// We don' want this ...
GUIvars.exitFlag = FALSE ;
// Load, configure, and start the PRUs
execPRUprograms() ;
// Run the the test robot code
testRobot() ;
} // end if-the-else
// User wants to exit so let PRU0 know
exitFlag = TRUE ;
shared_memory->exitFlag = TRUE ;
// Delay for 1 sec before disabling PRUs
if (debug) memoryDump() ;
pauseSec(1) ;
PRUstop() ;
return 0;
} // end main
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.