language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "funciones.h"
#define TAM 50
int main()
{
char seguir='s';
int cantidad;
ePelicula* peliculas;
peliculas = newArrayPeliculas(TAM);
if(peliculas == NULL)
{
printf("No se pudo conseguir memoria en peliculas\n");
exit(1);
}
cantidad = cargarPeliculas(peliculas, TAM, "peliculas.bin");
printf("Se cargaron %d peliculas\n", cantidad);
while(seguir=='s')
{
switch(menu())
{
case 1:
altaPelicula(peliculas,TAM);
break;
case 2:
bajaPelicula(peliculas,TAM);
break;
case 3:
modificaPelicula(peliculas,TAM);
break;
case 4:
generarPagina(peliculas,TAM,"misPeliculas.html");
break;
case 5:
guardarPeliculas(peliculas, TAM, "peliculas.bin");
seguir = 'n';
break;
}
}
return 0;
}
|
C
|
//NAME: Kevin Zhang
//EMAIL: [email protected]
//ID: 104939334
#include "stdio.h"
#include <pthread.h>
#include <time.h>
#include <getopt.h>
#include <stdlib.h>
#include <string.h>
int numThreads = 1;
int numIterations = 1;
char lock = 'n'; //no lock
int opt_yield = 0;
pthread_mutex_t mutex;
int spin_flag = 0;
void add(long long *pointer, long long value) {
long long sum = *pointer + value;
if (opt_yield)
sched_yield();
*pointer = sum;
}
void * performAddition(void * counter){
int i = 0;
long long prev, update;
prev = (*((long long *) counter));
for(; i < numIterations; i++){
switch(lock){
case 'n':
add((long long *)counter, 1);break;
case 'm': //mutex lock
pthread_mutex_lock(&mutex);
add((long long *)counter, 1);
pthread_mutex_unlock(&mutex);
break;
case 's': //spin lock
while(__sync_lock_test_and_set(&spin_flag, 1));
add((long long *) counter, 1);
__sync_lock_release(&spin_flag);
break;
case 'c': //compare and swap lock
do {
prev = *((long long *)counter);
update = prev + 1;
if (opt_yield) { sched_yield(); }
} while (__sync_val_compare_and_swap((long long *)counter, prev, update) != prev);
break;
default:
fprintf(stderr, "Error, lock unrecognized\n");
exit(1);
}
}
i = 0;
for(; i < numIterations; i++){
long long prev, update;
prev = *((long long *)counter);
switch(lock){
case 'n':
add((long long *)counter, -1);break;
case 'm': //mutex lock
pthread_mutex_lock(&mutex);
add((long long *)counter, -1);
pthread_mutex_unlock(&mutex);
break;
case 's': //spin lock
while(__sync_lock_test_and_set(&spin_flag, 1));
add((long long *) counter, -1);
__sync_lock_release(&spin_flag);
break;
case 'c': //compare and swap lock
do {
prev = *((long long *)counter);
update = prev - 1;
if (opt_yield) { sched_yield(); }
} while (__sync_val_compare_and_swap((long long *)counter, prev, update) != prev);
break;
default:
fprintf(stderr, "Error, lock unrecognized\n");
exit(1);
}
}
return NULL;
}
int main(int argc, char ** argv){
pthread_t *threads;
static struct option long_options[] = {
{"threads", required_argument, 0, 't'},
{"iterations", required_argument, 0, 'i'},
{"yield", no_argument, 0, 'y'},
{"sync", required_argument, 0, 's'},
};
long long counter = 0;
int c;
int option_index = 0;
c = getopt_long(argc,argv,"ti", long_options , &option_index);
while(c!=-1){
switch(c){
case 't':
numThreads = atoi(optarg);
break;
case 'i':
numIterations = atoi(optarg);
break;
case 'y':
opt_yield = 1;
break;
case 's':
if(strlen(optarg)==1){
switch(optarg[0]){
case 's':
case 'm':
case 'c':
lock = optarg[0];
break;
default:
fprintf(stderr, "ERROR: Unrecognized sync argument.\n");
exit(1);
}
break;
}
default:
fprintf(stderr, "ERROR: Unrecognized argument.\n Usage: ./lab2a [--threads=n] [--iterations=n] [--yield] [--sync=c]\n");
exit(1);
break;
}
c = getopt_long(argc,argv,"s", long_options , &option_index);
}
if(lock == 'm'){
pthread_mutex_init(&mutex, NULL);
}
struct timespec start;
clock_gettime(CLOCK_MONOTONIC, &start);
threads = malloc(numThreads * sizeof(pthread_t));
int t;
for(t = 0; t < numThreads; t++){
int rc = pthread_create(&threads[t], NULL, performAddition, &counter);
if(rc){
fprintf(stderr, "Creation of thread number, %d, failed. ", t);
exit(1);
}
}
for(t= 0; t<numThreads; t++){
int rc = pthread_join(threads[t], NULL);
if(rc){
fprintf(stderr, "Joining of thread number, %d, failed. ", t);
exit(1);
}
}
struct timespec end;
clock_gettime(CLOCK_MONOTONIC, &end);
long long total = (end.tv_sec - start.tv_sec) * 1000000000 + (end.tv_nsec - start.tv_nsec);
int operations = numThreads * numIterations *2;
long long avg = total/operations;
char str[30] = "add";
char temp[2];
if (opt_yield) strcat(str, "-yield");
switch(lock){
case 'n':
strcat(str, "-none");
break;
case 'm':
case 's':
case 'c':
strcat(str, "-");
temp[0] = lock;
temp[1] = '\0';
strcat(str, temp);
break;
}
printf("%s,%d,%d,%d,%lld,%lld,%lld\n", str, numThreads, numIterations,
operations, total , avg, counter);
free(threads);
pthread_mutex_destroy(&mutex);
}
|
C
|
// Created by Jaymo Aymer on 15/03/2021.
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include "routine.h"
#include "pthreadCreateErrorHandler.h"
#include "pthreadJoinErrorHandler.h"
int main(int argc, char* argv[])
{
// pthread_t vars
pthread_t threadOne, threadTwo;
// threadOne creation check
if (pthread_create(&threadOne, NULL, &routine, NULL) != 0)
{
pthreadCreateErrorHandler();
}
// threadTwo creation check
if (pthread_create(&threadTwo, NULL, &routine, NULL) != 0)
{
pthreadCreateErrorHandler();
}
// threadOne termination check
if (pthread_join(threadOne, NULL) != 0)
{
pthreadJoinErrorHandler();
}
// threadTwo termination check
if (pthread_join(threadTwo, NULL) != 0)
{
pthreadJoinErrorHandler();
}
return 0;
}
|
C
|
/*****************************************************
Author:Dona Siby
Title :Program to determine the youngest of three.
Date :22/05/2021
******************************************************/
#include<stdio.h>
int main(){
int age1,age2,age3;
//First student
printf("\nEnter the age of first student : ");
scanf("%d",&age1);
//Second student
printf("\nEnter the age of second student : ");
scanf("%d",&age2);
//Third student
printf("\nEnter the age of third student : ");
scanf("%d",&age3);
//If else statment to find which student is the youngest.
if (age1<age2 && age1<age3){
printf("The first student is the youngest");
}
else if(age2<age1 && age2<age3){
printf("The second student is the youngest");
}
else{
printf("The third student is the youngest");
}
return 0;
}
|
C
|
#include <stdio.h>
int main() {
/* doesn't compile - ex. 2-2 */
int i = 0;
for (; i < lim - 1; ++i) {
c = getchar();
if (c == '\n')
break;
if (c == EOF)
break;
s[i] = c;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
// ===========================================================================
// =========================== DEFINICJA LIST ================================
// ===========================================================================
struct Mineral
{
char *name;
char *number;
char *composition;
struct Mineral *next;
};
struct sBranch
{
char *branch_name;
struct sBranch *next;
struct Mineral *mineral;
};
// ===========================================================================
// =========================== FUNKCJE POMOCNICZE ============================
// ===========================================================================
//Funkcja sprawdzajaca istnienie katalogu o podanej nazwie
int if_branch_exist(struct sBranch *head, char *text)
{
struct sBranch *branch = head;
while(branch != NULL)
{
if (strcmp(branch->branch_name,text) == 0)
return 1;
branch = branch->next;
}
return 0;
}
//Funkcja sprawdzajaca istnienie mineralu o podanym numerze
int if_record_exist(struct sBranch *head, char *number)
{
struct sBranch *branch = head;
struct Mineral *mineral;
while(branch != NULL)
{
mineral = branch->mineral;
while(mineral != NULL)
{
if (strcmp(mineral->number,number) == 0)
return 1;
mineral = mineral->next;
}
branch = branch->next;
}
return 0;
}
//Usuwamy znak konca linii ze stringa
void change_string(ssize_t *read_length, char** name)
{
int i=0;
*read_length -= 1;
char* help = (char*)malloc(sizeof(*read_length));
for(i=0; i<(*read_length); i++)
help[i] = (*name)[i];
free(*name);
*name = help;
}
//Funkcja czyszczaca bufor
void myFlush(void)
{
int c;
while ((c = fgetc(stdin)) != EOF && c!='\n');
}
//Funkcja zmieniajaca wprowadzony w stringu znaku enter na znak '\0', oznaczajacy koniec stringa
void changeString (char variable[], int max_size)
{
int size = 0;
for (size=0; size<max_size; size++)
if (variable[size] == '\n')
{
variable[size] = '\0';
return ;
}
myFlush();
}
//Funkcja zliczajaca ilosc elementow w stringu
int getStringLength (char variable[], int max_size)
{
int size = 0;
for (size=0; size<max_size; size++)
if (variable[size] == '\0') break;
return size;
}
// ===========================================================================
// ========================== FUNKCJE GŁÓWNE =================================
// ===========================================================================
//Funkcja dodajaca nowy katalog poprzez nazwe
void add_branch(struct sBranch **head, char *new_branch_name)
{
if (*head == NULL)
{
(*head) = (struct sBranch*) malloc (sizeof(struct sBranch));
(*head)->next = NULL;
(*head)->mineral = NULL;
(*head)->branch_name = new_branch_name;
return;
}
if (strcmp((*head)->branch_name, new_branch_name)>0)
{
struct sBranch *new_branch = (struct sBranch*) malloc (sizeof(struct sBranch));
new_branch->next = (*head);
new_branch->branch_name = new_branch_name;
new_branch->mineral = NULL;
*head = new_branch;
return;
}
struct sBranch *help = (*head);
while(help->next != NULL && strcmp(help->next->branch_name, new_branch_name)<0)
help = help->next;
if (help->next != NULL && strcmp(help->next->branch_name, new_branch_name) == 0)
{
printf("Nazwa katalogu istnieje już w bazie!\n");
return;
}
struct sBranch *new_branch = (struct sBranch*) malloc (sizeof(struct sBranch));
new_branch->next = help->next;
new_branch->branch_name = new_branch_name;
new_branch->mineral = NULL;
help->next = new_branch;
}
//Zmiana nazwy katalogu
void change_branch_name(struct sBranch **head, char* old_name, char* new_name)
{
struct sBranch *target = (*head);
while(target != NULL)
{
if (strcmp(target->branch_name,old_name)==0)
{
target->branch_name = new_name;
free(old_name);
break;
}
else target = target->next;
}
}
//Usuniecie katalogu o podanej nazwie
void delete_branch(struct sBranch **head, char* name)
{
struct sBranch *tmp;
struct sBranch *help = (*head);
struct Mineral *temp;
//Katalog do usuniecia to glowa
if(strcmp(help->branch_name,name)==0)
{
while((*head)->mineral != NULL)
{
temp = (*head)->mineral;
(*head)->mineral = (*head)->mineral->next;
free(temp->name);
free(temp->number);
free(temp->composition);
free(temp);
}
(*head) = help->next;
free(help);
//Katalog do usuniecia to nie glowa
} else
{
while(help->next != NULL)
{
//Jezeli znaleziono katalog to usun branch
if(strcmp(help->next->branch_name,name)==0)
{
while(help->next->mineral != NULL)
{
temp = help->next->mineral;
help->next->mineral = help->next->mineral->next;
free(temp->name);
free(temp->number);
free(temp->composition);
free(temp);
}
tmp = help->next;
help->next = help->next->next;
free(tmp);
break;
}
help = help->next;
}
}
}
//Dodanie rekordu
void add_record(struct sBranch *head, char *branch_name, char *mineral_name, char *mineral_number, char *mineral_composition)
{
struct sBranch *help_branch = head;
struct Mineral *help_mineral;
//Nadajemy wartosci nowemu rekordowi
struct Mineral *new_mineral = (struct Mineral*) malloc (sizeof(struct Mineral));
new_mineral->name = mineral_name;
new_mineral->number = mineral_number;
new_mineral->composition = mineral_composition;
new_mineral->next = NULL;
//Znajdz dzial
while (strcmp(help_branch->branch_name,branch_name)!=0)
help_branch = help_branch->next;
help_mineral = help_branch->mineral;
//Jezeli nie ma mineralow
if(help_mineral == NULL)
help_branch->mineral = new_mineral;
//Jezeli nazwa mineralu jest mniejsza niz nazwa glowy
else if (strcmp(help_mineral->name, mineral_name)>0)
{
help_branch->mineral = new_mineral;
new_mineral->next = help_mineral;
}
//Jezeli nazwa mineralu jest wieksza niz nazwa glowy
else
{
//Znajdz ostatni element mniejszy niz mineral
while(help_mineral->next != NULL && strcmp(help_mineral->next->name, mineral_name)<0)
help_mineral = help_mineral->next;
//Podepnij
new_mineral->next = help_mineral->next;
help_mineral->next = new_mineral;
}
}
//Funkcja usuwajaca cala liste
void delete_list(struct sBranch **head)
{
struct sBranch *branch = (*head);
while (branch != NULL)
{
branch = branch->next;
free(*head);
(*head) = branch;
}
}
// ===========================================================================
// ======================== FUNKCJE UŻYTKOWNIKA ==============================
// ===========================================================================
//Dodanie katalogu
void user_add_branch(struct sBranch **head)
{
int i;
char* name;
size_t read_all_name = 0;
ssize_t read_length_name;
//Pobierz nazwe katalogu do dodania
printf("Podaj nazwę katalogu, jaki chcesz dodac: ");
read_length_name = getline(&name, &read_all_name, stdin);
change_string(&read_length_name, &name);
//Sprawdz poprawnosc nazwy katalogu
for(i=0; i<read_length_name; i++)
if (isalpha(name[i])==0 && isspace(name[i])==0)
{
printf("Bledne dane - niepoprawny znak w nazwie katalogu!\n ");
free(name);
return;
}
//Jezeli istnieje
if (!if_branch_exist((*head),name))
add_branch(head,name);
else printf("Podana nazwa katalogu istnieje juz w bazie!\n");
}
//Zmiana nazwy katalogu
void user_change_branch_name(struct sBranch **head)
{
char* old_name;
size_t read_all_old = 0;
ssize_t read_length_old;
char* new_name;
size_t read_all_new = 0;
ssize_t read_length_new;
//Pobierz nazwe katalogu do zmiany
printf("Podaj nazwę katalogu, którą chcesz zmienić: ");
read_length_old = getline(&old_name, &read_all_old, stdin);
change_string(&read_length_old, &old_name);
//Jezeli nie ma takiego katalogu
if (!if_branch_exist((*head),old_name))
{
printf("Podana nazwa katalogu nie istnieje!\n");
free(old_name);
return;
}
//Pobierz nowa nazwe katalogu
printf("Podaj nową nazwę katalogu: ");
read_length_new = getline(&new_name, &read_all_new, stdin);
change_string(&read_length_new, &new_name);
//Jezeli jest taki katalog
if (if_branch_exist((*head),new_name))
{
printf("Podana nazwa katalogu istnieje juz w bazie!");
free(old_name);
free(new_name);
return;
}
//Zmien nazwe
change_branch_name(head, old_name, new_name);
}
//Usuniecie katalogu
void user_delete_branch(struct sBranch **head)
{
char* name;
size_t read_all_name = 0;
ssize_t read_length_name;
//Pobierz nazwe katalogu do dodania
printf("Podaj nazwę katalogu, ktory chcesz usunac: ");
read_length_name = getline(&name, &read_all_name, stdin);
change_string(&read_length_name, &name);
//Jezeli istnieje
if (if_branch_exist((*head),name))
delete_branch(head,name);
else printf("Katalog o podanej nazwie nie istnieje!");
//Zwalnianie zasobow
free(name);
}
//Dodanie rekordu
void user_add_record(struct sBranch *head)
{
int i=0;
char* branch_name, *mineral_name, *number, *composition;
size_t read_all_branch = 0, read_all_mineral = 0, read_all_number = 0, read_all_composition = 0;
ssize_t read_length_branch, read_length_mineral, read_length_number, read_length_composition;
//Pobierz nazwe katalogu
printf("Podaj nazwe katalogu, do ktorego chcesz dodac rekord: ");
read_length_branch = getline(&branch_name, &read_all_branch, stdin);
change_string(&read_length_branch, &branch_name);
//Jezeli nie ma takiego katalogu
if (!if_branch_exist(head,branch_name))
{
printf("Podana nazwa katalogu nie istnieje!\n");
free(branch_name);
return;
}
//Pobierz nazwe mineralu
printf("Podaj nazwe mineralu (malymi literami, nazwa moze zawierac spacje): ");
read_length_mineral = getline(&mineral_name, &read_all_mineral, stdin);
change_string(&read_length_mineral, &mineral_name);
//Sprawdz poprawnosc nazwy mineralu
for(i=0; i<read_length_mineral; i++)
if (islower(mineral_name[i])==0 && isspace(mineral_name[i])==0)
{
printf("Bledne dane - niepoprawny znak w nazwie mineralu! ");
free(branch_name);
free(mineral_name);
return;
}
//Pobierz numer mineralu
printf("Podaj pieciocyfrowy numer mineralu: ");
read_length_number = getline(&number, &read_all_number, stdin);
change_string(&read_length_number, &number);
//Sprawdz, czy jest odpowiedniej dlugosci
if (read_length_number!=5)
{
printf("Podany numer nie jest pieciocyfrowy!\n");
free(branch_name);
free(mineral_name);
free(number);
return;
}
//Sprawdz, czy numer jest poprawny
for(i=0; i<read_length_number; i++)
if (isdigit(number[i])==0)
{
printf("Bledne dane - niepoprawny znak w numerze mineralu!\n");
free(branch_name);
free(mineral_name);
free(number);
return;
}
//Sprawdz, czy numer jest unikalny
if (if_record_exist(head,number))
{
printf("Podany numer jest juz w bazie!\n");
free(branch_name);
free(mineral_name);
free(number);
return;
}
//Sprawdz, czy numer jest unikalny
printf("Podaj sklad chemiczny mineralu: ");
read_length_composition = getline(&composition, &read_all_composition, stdin);
change_string(&read_length_composition, &composition);
//Sprawdz, czy sklad jest poprawny
for(i=0; i<read_length_composition; i++)
if (isalnum(composition[i])==0) //Jesli znak inny niz cyfra lub litera
{
printf("Bledne dane - niepoprawny znak w skladzie mineralu!\n");
free(branch_name);
free(mineral_name);
free(number);
free(composition);
return;
}
//Dodanie mineralu
add_record(head,branch_name,mineral_name,number,composition);
}
//Przenoszenie rekordu
void user_move_record(struct sBranch *head)
{
struct sBranch *source_branch = head;
struct sBranch *destination_branch = head;
struct Mineral *source_mineral, *source_mineral_help;
struct Mineral *destination_mineral;
char *source_name, *destination_name, *option, *number;
size_t read_all_source = 0, read_all_destination = 0, read_all_option = 0, read_all_number = 0;
ssize_t read_length_source, read_length_destination, read_length_option, read_length_number;
//Pobieramy nazwe katalogu zrodlowego
printf("Podaj nazwę katalogu, z ktorego chcesz przeniesc rekordy: ");
read_length_source = getline(&source_name, &read_all_source, stdin);
change_string(&read_length_source, &source_name);
//Jezeli nie istnieje
if (!if_branch_exist(head, source_name))
{
printf("Podana nazwa katalogu nie istnieje!\n");
free(source_name);
return ;
}
//Przechodzimy po liscie do katalogu zrodlowego
while (strcmp(source_branch->branch_name,source_name)!=0)
source_branch = source_branch->next;
//Jezeli katalog nie posiada zadnych rekordow
if (source_branch->mineral==NULL)
{
printf("Nie ma zadnych rekordow do przeniesienia!\n");
free(source_name);
return;
}
//Pobieramy nazwe katalogu docelowego
printf("Podaj nazwe katalogu, do ktorego chcesz przeniesc rekordy: ");
read_length_destination = getline(&destination_name, &read_all_destination, stdin);
change_string(&read_length_destination, &destination_name);
//Jezeli nie istnieje
if (!if_branch_exist(head, destination_name))
{
printf("Podana nazwa katalogu nie istnieje!\n");
free(source_name);
free(destination_name);
return ;
}
//PRzechodzimy po liscie do katalogu docelowego
while (strcmp(destination_branch->branch_name,destination_name)!=0)
destination_branch = destination_branch->next;
//Pytamy o opcje
printf("Chcesz przeniesc wybrany rekord (0), czy wszystkie rekordy(1)?: ");
read_length_option = getline(&option, &read_all_option, stdin);
change_string(&read_length_option, &option);
//Jezli przenosimy jeden rekord
if (strcmp(option,"0")==0)
{
//Pobieramy numer mineralu
printf("Podaj numer mineralu, ktory chcesz przeniesc: ");
read_length_number = getline(&number, &read_all_number, stdin);
change_string(&read_length_number, &number);
//Mineral nie istnieje
if (!if_record_exist(head,number))
{
printf("Rekord o podanym numerze nie istnieje!\n");
free(source_name);
free(destination_name);
free(number);
return ;
}
//Znajdujemy mineral do przeniesienia
source_mineral = source_branch->mineral;
//Jezeli przenosimy mineral z glowy
if (strcmp(source_mineral->number,number)==0)
{
source_branch->mineral = source_mineral->next;
source_mineral->next = NULL;
//Jezeli to nie jest jedyny mineral brancha source
} else if (source_mineral->next != NULL)
{
//Znajdz mineral
while (source_mineral->next!=NULL && strcmp(source_mineral->next->number,number)!=0)
source_mineral=source_mineral->next;
//Nie ma takiego mineralu!
if (source_mineral->next == NULL)
{
printf("Nie ma mineralu o podanym numerze w danym katalogu!\n");
free(source_name);
free(destination_name);
free(option);
free(number);
return;
}
//Odlacz mineral od listy
source_mineral_help = source_mineral;
source_mineral = source_mineral->next;
source_mineral_help->next = source_mineral->next;
source_mineral->next = NULL;
//Jezeli to jedyny mineral
} else
{
printf("Nie ma mineralu o podanym numerze!\n");
free(source_name);
free(destination_name);
free(option);
free(number);
return;
}
//Jezeli w destination nic nie ma
if (destination_branch->mineral == NULL)
destination_branch->mineral = source_mineral;
else
{
//Przejdz do konca listy
destination_mineral = destination_branch->mineral;
while(destination_mineral->next != NULL)
destination_mineral=destination_mineral->next;
//Podepnij
source_mineral->next = destination_mineral->next;
destination_mineral->next = source_mineral;
}
free(source_name);
free(destination_name);
free(option);
free(number);
//Jezeli przenosimy wszystkie rekordy
} else if (strcmp(option,"1")==0)
{
//Jezeli w destination nic nie ma
if (destination_branch->mineral == NULL)
{
destination_branch->mineral = source_branch->mineral;
source_branch->mineral = NULL;
} else
{
//Przejdz do konca listy
destination_mineral = destination_branch->mineral;
while(destination_mineral->next != NULL)
destination_mineral=destination_mineral->next;
//Podepnij
destination_mineral->next = source_branch->mineral;
source_branch->mineral = NULL;
}
free(source_name);
free(destination_name);
free(option);
return;
//Jezeli zla opcja
} else
{
printf("Wybrano nieprawidlowa opcje!\n");
free(source_name);
free(destination_name);
free(option);
}
}
//Zmiana rekordu
void user_change_record(struct sBranch *head)
{
struct sBranch *branch = head;
struct Mineral *mineral;
char* branch_name, *number, *option;
size_t read_all_branch = 0, read_all_number = 0, read_all_option = 0;
ssize_t read_length_branch, read_length_number, read_length_option;
//Pobieramy nazwe katalogu
printf("Podaj nazwę katalogu, w ktorym chcesz zmienic rekord: ");
read_length_branch = getline(&branch_name, &read_all_branch, stdin);
change_string(&read_length_branch, &branch_name);
//Jezeli nie istnieje to koniec
if (!if_branch_exist(head,branch_name))
{
printf("Podana nazwa katalogu nie istnieje!\n");
free(branch_name);
return;
}
//Przechodzimy po liscie do katalogu
while (strcmp(branch->branch_name,branch_name)!=0)
branch = branch->next;
//Jezeli katalog nie posiada zadnych rekordow
if (branch->mineral==NULL)
{
printf("Nie ma zadnych rekordow do zmiany!\n");
free(branch_name);
return;
}
//Pobieramy numer mineralu
printf("Podaj numer mineralu, ktory chcesz zmienic: ");
read_length_number = getline(&number, &read_all_number, stdin);
change_string(&read_length_number, &number);
//Nie ma takiego mineralu
if (!if_record_exist(head, number))
{
printf("Nie ma mineralu o podanym numerze!\n");
free(branch_name);
free(number);
return;
}
//Znajdujemy mineral do zmiany
mineral = branch->mineral;
while (mineral!=NULL && strcmp(mineral->number,number)!=0)
mineral=mineral->next;
//Jest mineral, ale w innym branchu
if (mineral==NULL)
{
printf("Nie ma mineralu o podanym numerze w danym katalogu!\n");
free(branch_name);
free(number);
return;
}
//Pytamy co chce zmienic
printf("Chcesz zmienic nazwe mineralu(1), numer mineralu(2), sklad(3) czy wszystkie pozycje(0)?: ");
read_length_option = getline(&option, &read_all_option, stdin);
change_string(&read_length_option, &option);
//Jezeli zmieniamy nazwe
if (strcmp(option,"1")==0)
{
//Zmienamy nazwe mineralu
printf("Podaj nowa nazwe mineralu: ");
ssize_t read_length_mineral = getline(&mineral->name, &read_all_number, stdin);
change_string(&read_length_mineral, &(mineral->name));
//Jezeli zmieniamy numer
} else if (strcmp(option,"2")==0)
{
//Zmienamy numer mineralu
printf("Podaj nowy numer mineralu: ");
ssize_t read_length_mineral = getline(&mineral->number, &read_all_number, stdin);
change_string(&read_length_mineral, &(mineral->number));
//Jezeli zmieniamy sklad
} else if (strcmp(option,"3")==0)
{
//Zmienamy sklad mineralu
printf("Podaj nowy sklad mineralu: ");
ssize_t read_length_mineral = getline(&mineral->composition, &read_all_number, stdin);
change_string(&read_length_mineral, &(mineral->composition));
//Jezeli zmieniamy wszystko
} else if (strcmp(option,"0")==0)
{
//Zmienamy nazwe mineralu
printf("Podaj nowa nazwe mineralu: ");
ssize_t read_length_mineral = getline(&mineral->name, &read_all_number, stdin);
change_string(&read_length_mineral, &(mineral->name));
//Zmienamy numer mineralu
printf("Podaj nowy numer mineralu: ");
read_length_mineral = getline(&mineral->number, &read_all_number, stdin);
change_string(&read_length_mineral, &(mineral->number));
//Zmienamy sklad mineralu
printf("Podaj nowy sklad mineralu: ");
read_length_mineral = getline(&mineral->composition, &read_all_number, stdin);
change_string(&read_length_mineral, &(mineral->composition));
//Jezeli zla opcja
} else printf("Wybrano nieprawidlowa opcje!\n");
//Sprzatamy
free(branch_name);
free(number);
free(option);
}
// ===========================================================================
// ============================== FUNKCJE FILE ===============================
// ===========================================================================
void load_data_from_file(struct sBranch **head)
{
char* text;
size_t read_all_name = 0;
ssize_t length;
FILE *fo=fopen("a.txt", "r");
char* branch;
//Dopoki plik sie nie skonczyl
do
{
//Pobierz linie
length = getline(&text, &read_all_name, fo);
//Dopoki !EOF
if (length != -1)
{
//Oblicz ilosc wyrazow
int sum = 0, i;
for (i=0; i<length; i++)
if (text[i] == '[' || text[i] == ']') sum++;
//Jezli tylko jeden wyraz (nowy dzial)
if (sum==2)
{
int i=0;
int start, stop;
//Oblicz pozycje wyrazu
for (i=0; i<length; i++)
if (text[i] == '[') start = i;
else if (text[i] == ']') stop = i+1;
//Przydziel pamiec
branch = (char*)malloc((stop-start-1)*sizeof(char));
//Przepisz wyraz
for (i=start; i<stop-1; i++)
branch[i-start-1] = text[i];
//Dodaj branch
add_branch(head,branch);
} else if (sum == 6)
{
int i=0, j=0;
int start, stop;
// Oblicz pozycje name
for (; i<length; i++)
if (text[i] == '[') start = i+1;
else if (text[i] == ']')
{
stop = i-1;
break;
}
//Przydziel pamiec
char* name = (char*)malloc((stop-start-1)*sizeof(char));
//Przepisz wyraz
for (j=start; j<stop+1; j++)
name[j-start] = text[j];
// Oblicz pozycje number
for (i++; i<length; i++)
if (text[i] == '[') start = i+1;
else if (text[i] == ']')
{
stop = i-1;
break;
}
//Przydziel pamiec
char* number = (char*)malloc((stop-start-1)*sizeof(char));
//Przepisz wyraz
for (j=start; j<stop+1; j++)
number[j-start] = text[j];
// Oblicz pozycje composition
for (i++; i<length; i++)
if (text[i] == '[') start = i+1;
else if (text[i] == ']')
{
stop = i-1;
break;
}
//Przydziel pamiec
char* composition = (char*)malloc((stop-start-1)*sizeof(char));
//Przepisz wyraz
for (j=start; j<stop+1; j++)
composition[j-start] = text[j];
//Dodaj rekordy
add_record(*head,branch,name,number,composition);
//printf("%s\t",name);
//printf("%s\t",number);
//printf("%s\n",composition);
} else
{
//blad
printf ("Niepoprawna zawartosc pliku!\n");
}
}
} while(length != -1);
fclose (fo);
}
// ===========================================================================
// ============================ FUNKCJE DRUKUJACE ============================
// ===========================================================================
void print_branch_list(struct sBranch *head) //Funkcja drukujaca liste katalogow
{
struct sBranch *branch = head;
while (branch != NULL)
{
printf("%s\n",branch->branch_name);
branch = branch->next;
}
return;
}
void print_branch_records(struct sBranch *head, char *branch_name) //Funkcja drukujaca liste rekordow danego brancha
{
struct sBranch *help = head;
while(strcmp(help->branch_name,branch_name) != 0)
help = help->next;
if (help->mineral == NULL)
{
printf("Katalog o nazwie %s jest pusty!\n",help->branch_name);
return;
}
else
{
printf("%s\t",help->branch_name);
printf("%s\t",help->mineral->name);
printf("%s\t",help->mineral->number);
printf("%s\n",help->mineral->composition);
}
struct Mineral *tmp = help->mineral;
while (tmp->next != NULL)
{
printf("\t");
printf("%s\t",tmp->next->name);
printf("%s\t",tmp->next->number);
printf("%s\n",tmp->next->composition);
tmp = tmp->next;
}
}
void print_records(struct sBranch *head) //Funkcja drukujaca liste rekordow
{
char* branch_name;
size_t read_all_branch = 0;
ssize_t read_length_branch;
printf("Podaj nazwe katalogu, ktorego zawartosc chcesz wyswietlic: ");
//print_branch_list(head);
read_length_branch = getline(&branch_name, &read_all_branch, stdin);
change_string(&read_length_branch, &branch_name);
if (if_branch_exist(head,branch_name) == 1)
print_branch_records(head,branch_name);
else printf("Podany katalog nie istnieje!\n");
}
// ===========================================================================
// ================================== MAIN ===================================
// ===========================================================================
int main(void)
{
//Stworz wskaznik do poczatku glownej listy
struct sBranch *data_base = NULL;
char option[3];
printf("Program pozwala na stworzenie bazy z danymi o mineralach\n");
while(1)
{
printf("%s%s%s%s%s%s%s%s%s%s",
"1- Dodaj nowy katalog\n",
"2- Zmien nazwe istniejacego katalogu\n",
"3- Usun katalog\n",
"4- Wysweietl liste katalogow\n",
"5- Dodaj rekord do katalogu\n",
"6- Przenies rekordy pomiedzy katalogami\n",
"7- Zmien dane dotyczace rekordu\n",
"8- Wyswietl dane zawarte w katalogu\n",
"9- Wczytaj dane z pliku\n",
"0- Wyjdz z programu\n");
fgets(option, 3, stdin);
changeString (option, 3);
int size = getStringLength(option, 3);
if ( size != 1 )
{
//Powrot do wprowadzania danych
printf("Podales nieodpowiednia liczbe znakow!\n");
continue;
}
if (option[0]=='1')
{
//Dodawanie katalogu
user_add_branch(&data_base);
continue;
}
if (option[0]=='2')
{
//Zmiana nazwy katalogu
user_change_branch_name(&data_base);
continue;
}
if (option[0]=='3')
{
//Usun katalog
user_delete_branch(&data_base);
continue;
}
if (option[0]=='4')
{
//Wyswietl liste katalogow
print_branch_list(data_base);
continue;
}
if (option[0]=='5')
{
//Dodaj rekord
user_add_record(data_base);
continue;
}
if (option[0]=='6')
{
//Przenies rekordy
user_move_record(data_base);
continue;
}
if (option[0]=='7')
{
//Zmien dane
user_change_record(data_base);
continue;
}
if (option[0]=='8')
{
//Wyswietl dane
print_records(data_base);
continue;
}
if (option[0]=='9')
{
//Wczytaj z pliku
load_data_from_file(&data_base);
continue;
}
if (option[0]=='0')
{
//Powtwierdzenie wyjscia z programu
printf("Czy na pewno chcesz opuscic program?\n 1- Nie\n 2- Tak\n");
fgets(option, 3, stdin);
changeString (option, 3);
int size = getStringLength(option, 3);
if ( size != 1 )
{
printf("Podales nieodpowiednia liczbe znakow!\n");
continue;
}
//Wyjscie z programu
if ( option[0] == '2' ) exit(EXIT_SUCCESS);
//Powrot do menu
else if ( option[0] == '1' ) continue;
else
{
printf("Wprowadziles bledny znak!\n");
continue;
}
}
}
//Posprzataj
delete_list(&data_base);
return 0;
}
|
C
|
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
double x1,x2,y1,y2;
double x3,x4,y3,y4;
double m1,n1;
double m2,n2;
cin>>x1>>y1>>x2>>y2;
cin>>x3>>y3>>x4>>y4;
m1 = max(min(x1,x2),min(x3,x4));
n1 = max(min(y1,y2),min(y3,y4));
m2 = min(max(x1,x2),max(x3,x4));
n2 = min(max(y1,y2),max(y3,y4));
if(m1 < m2 && n1 < n2){
printf("%.2lf\n",(m2 - m1) * (n2 - n1));
}
else
printf("0.00\n");
return 0;
}
|
C
|
#include"misc.h"
// rm extract; gcc -O4 extract.c -o extract; ./extract craigslist-apa-data-bc-html-othermeta.csv
// note: should delete the html and otherAttributes folders before (re)running
//
// the program can use append mode for writing files, to catch records with same ID:
// see line: int duplicates = 0; // to ignore duplicates by taking latest record
/*
wc -l craigslist-apa-data-bc.csv
1231197 craigslist-apa-data-bc.csv
*/
int go_to(FILE * f, const char * tag, size_t tag_len, char * buf, size_t * next, size_t * fp){
if(*next == 0){
// if we're at the start of a match, record the present position
*fp = ftell(f);
}
char c = fgetc(f);
if(c != tag[(*next)++]){
// if we failed to match a char
*next = 0;
return 0;
}
else{
// we matched a char
// printf("%c,next=%zu\n", c, *next);
}
if(*next == tag_len){
// if we matched the whole tag
*next = 0;
// read the stuff from the match position to confirm
fseek(f, *fp, SEEK_SET);
size_t br = fread(&buf[0], sizeof(char), tag_len, f);
if(br != tag_len){
printf("Err: br != tag_len\n");
exit(1);
}
buf[tag_len] = '\0';
// printf("buf[%s]\n", buf); // print out match
if(strncmp(buf, tag, tag_len) != 0){
printf("Err: mismatch\n");
exit(1);
}
return 1;
}
return 0;
}
char fgetc2(FILE * f){
fseek(f, -1, SEEK_CUR);
char c = fgetc(f);
fseek(f, -1, SEEK_CUR);
return c;
}
void cr(FILE * f){
// return to start of a line
size_t fp = ftell(f); // where are we?
if(fp == 0) return; // done if at beginning of file
char c;
do{
c = fgetc2(f);
}
while(c != '\n');
while(c == '\n' || c == '\r'){
c = fgetc(f);
}
fseek(f, -1, SEEK_CUR); // back one
}
int main(int argc, char ** argv){
int duplicates = 0;
int a = system("mkdir -p html");
a = system("mkdir -p otherAttributes"); // some random stuff that was stuffed in next to the html, yikes!
int debug = 0; // apply this to print statments in a moment
size_t next, fp;
const char * end_tag = "</html>";
size_t tag_len = (size_t) strlen(end_tag);
char * buf = (char *)(void *)malloc(tag_len + 1);
for(next = 0; next < tag_len + 1; next++){
buf[next] = '\0';
}
next = 0;
time_t t0; time(&t0);
clock_t c0 = clock();
const char * fn = argv[1];
size_t infile_size = file_size(fn); // file size
FILE * f = fopen(fn, "rb");
const char * tf;
if(argc < 3){
tf = strcat(argv[1], "_tag");
}
else{
// allow an option to read from separate file, for parallelism case
tf = argv[2];
}
FILE * g = fopen(tf, "rb");
if(!f) err("failed to open input file"); // the file itself
if(!g) err("failed to open start tag file *_tag: run find_start.c first"); // html start tag file
size_t n;
char ** s = (char **) alloc(sizeof(char *));;
*s = NULL;
size_t i = 0;
do{
n = gs(g, s);
if(n < 1) break;
size_t start_p;
sscanf(*s, "%zu", &start_p);
fseek(f, start_p, SEEK_SET);
n = gs(f, s);
// now find end tag
next = 0;
while(!go_to(f, end_tag, tag_len, buf, &next, &fp));
// this is the span of the html
if(debug) printf("\n%zu %zu\n", start_p, fp + tag_len - 1);
// now just need to apply CR and grab the start tag, and we've split the file
fseek(f, start_p, SEEK_SET);
cr(f);
n = gs(f, s);
if(debug){
prints(*s, n);
printf("\n"); // print start tag
}
const char * id_s = strtok(*s, ",");
size_t id;
sscanf(*s, "%zu,", &id); // don't need strtok to get the number
if(debug) printf("[%zu]\n", id);
const char * pre = "html/";
char * t = alloc(strlen(pre) + strlen(id_s) + 1);
strcpy(t, pre);
strcpy(t + strlen(pre), id_s);
t[strlen(pre) + strlen(id_s)] = '\0';
// output file name
FILE * h = fopen(t, duplicates?"ab":"wb");
// secondary file to save otherAttributes string
const char * pre2 = "otherAttributes/";
char * t2 = alloc(strlen(pre2) + strlen(id_s) + 1);
strcpy(t2, pre2);
strcpy(t2 + strlen(pre2), id_s);
t2[strlen(pre2) + strlen(id_s)] = '\0';
if(debug){
printf("\n%s\n", t2);
}
FILE * j = fopen(t2, duplicates?"ab":"wb");
// write html to file, here:
size_t dat_sz = fp + tag_len - start_p;
char * dat = alloc(dat_sz);
// copy from file to memory
fseek(f, start_p, SEEK_SET);
size_t nr = fread(dat, sizeof(char), dat_sz, f);
size_t nw = fwrite(dat, sizeof(char), dat_sz, h);
if(nr != nw) err("write fail");
fclose(h);
free(dat);
if(debug){
printf("%s\n", t);
}
free(*s);
*s = NULL;
// zoom over any newline, to get to next record
char c = fgetc(f);
while(c == '\n' || c == '\r') c = fgetc(f);
fseek(f, -1, SEEK_CUR); // go back
// sometimes the otherdata field is blank, need a new counter
size_t n2 = gs(f, s);
if(debug){
prints(*s, n2);
printf("\n");
}
size_t nw2 = fwrite(*s, sizeof(char), strlen(*s), j);
fclose(j);
if(++i % 1000 == 0){
float frac = 100. * (float)fp / (float)infile_size;
// time_t t1; time(&t1);
float dt = (float)(clock() - c0) / (float) CLOCKS_PER_SEC; // (float)t1 - (float)t0;
float nps = (float)fp / dt;
float eta = (float)(infile_size - fp) / nps;
printf("%%%.3f +w %s eta: %fs i=%zu\n", frac, t, eta, i );
}
free(t);
}
while(n > 0);
// end program
free(*s);
time_t t1;
time(&t1);
printf("dt %fs\n", (float)(t1 - t0));
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* as_store3.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jszabo <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/07/27 14:31:23 by jszabo #+# #+# */
/* Updated: 2018/07/27 14:35:38 by jszabo ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include "op.h"
#include "asm_struct.h"
#include "asm_prot.h"
#include "colors.h"
#include "as_errors.h"
#include <fcntl.h>
int as_ssize(t_list_byte **size, t_list_byte *code)
{
int s;
int i;
i = 0;
s = as_code_size(code) - PROG_NAME_LENGTH - COMMENT_LENGTH - 16;
while (i < 4)
{
(*size)->type = 6;
(*size)->byte = (s >> (8 * i)) & 0xff;
(*size) = (*size)->next;
i++;
}
return (1);
}
int as_store_non_zero(int length, char *line, int *i, t_list_byte **c)
{
static int l = 0;
as_endcomment(line, 1);
while (line[*i] && line[*i] != '"')
{
if (l < length && !(as_add_byte(c, line[*i], 5)))
return (0);
(*i)++;
l++;
}
if (line[*i] == '"')
{
l = 0;
return (2);
}
else if (l < length)
{
if (!(as_add_byte(c, '\n', 5)))
return (0);
l++;
}
return (1);
}
int as_store_zero(int i, int section, t_list_byte **code)
{
i = (section) ?
(COMMENT_LENGTH - (as_code_size(*code) - PROG_NAME_LENGTH) + 16)
: (PROG_NAME_LENGTH - as_code_size(*code) + 12);
while (i > 0)
{
if (!(as_add_byte(code, 0, 5)))
return (0);
i--;
}
return (1);
}
|
C
|
/* GRR20190374 Tiago Henrique Conte
Projeto de processamento de áudio
Programa de mixagem de arquivos WAV
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "wav.h"
#include "linhaDeComando.h"
int main(int argc, char **argv){
FILE *input = NULL, *output = NULL;
int inputPos[MAX_INPUT+1], i;
// tratamento da linha de comando
trataComandoVariosInputs(argc, argv, inputPos, &output);
// criacao variavel tipo wavFile para armazenar o mix
wavFile_t wavMix;
/* Lê todos os inputs e realiza a mixagem */
int tamInput = inputPos[MAX_INPUT];
for(i = 0; i < tamInput; i++){
input = fopen(argv[inputPos[i]], "r");
// lê o primeiro input antes para adquirir padrão
if(i == 0){
// leitura das informações do arquivo wav
if(!readInfo(&wavMix, input)){
fprintf(stderr, "Erro na leitura das informações do arquivo %s\n", argv[inputPos[i]]);
exit(1);
}
rewind(input);
}
// mixagem de samples
if(!mixSamples(&wavMix, tamInput, input)){
fprintf(stderr, "Erro na leitura das samples do arquivo %s\n", argv[inputPos[i]]);
exit(1);
}
fclose(input);
}
// escreve info no output
if(!writeInfo(&wavMix, output)){
fprintf(stderr, "Erro na escrita de info em arquivo WAV!\n");
exit(1);
}
// escreve os samples no output
if(!writeSamples(&wavMix, output)){
fprintf(stderr, "Erro na escrita das samples em arquivo WAV!\n");
exit(1);
}
free(wavMix.vetorSamples);
fclose(output);
return 0;
}
|
C
|
#include <stdio.h>
int //.1.
count_ones(unsigned v)
{
int ones = 0;
while (v > 0) {
v &= v - 1;
ones++;
}
return ones;
}
//.2.
int main() {
unsigned values[] = { 123, 32, 255 };
for (int i = 0; i < sizeof(values)/sizeof(values[0]);
i++) {
unsigned v = values[i];
printf("# of ones in %u (0x%x) is %d\n", v, v,
count_ones(v));
}
return 0;
}
|
C
|
/*************************************************************************
> File Name: echo_concurIO_client.c
> Author: xjhznick
> Mail: [email protected]
> Created Time: 2015年03月25日 星期三 16时50分55秒
> Description:通过多进程分割客户端的I/O
在功能复杂的程序中,可以简化收发数据的处理逻辑;
可以提高频繁交换数据的程序性能,这在网速较慢的环境中尤其明显
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<sys/socket.h>
void error_handling(char *message);
void read_routine(int sock);
void write_routine(int sock);
#define BUF_SIZE 1024
int main(int argc, char *argv[])
{
int server_sock;
struct sockaddr_in server_addr;
int str_len, recv_len, recv_cnt;
pid_t pid;
if(3 != argc){
printf("Usage : %s <IP> <Port> \n", argv[0]);
exit(1);
}
server_sock = socket(PF_INET, SOCK_STREAM, 0);
if(-1 == server_sock){
error_handling("socket() error!");
exit(1);
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(argv[1]);
server_addr.sin_port = htons(atoi(argv[2]));
if( -1 == connect(server_sock, (struct sockaddr*)&server_addr,
sizeof(server_addr)) ){
error_handling("connect() error!");
}else{
puts("Connected......");
}
//分割I/O
pid = fork();
if(pid < 0){
error_handling("Error fork()");
}else if(pid == 0){
printf("Prompt: Input message at anytime(Q to quit).\n");
read_routine(server_sock);
}else{
write_routine(server_sock);
}
close(server_sock);
return 0;
}
void read_routine(int sock)
{
char buff[BUF_SIZE];
int str_len;
while(1){
str_len = read(sock, buff, BUF_SIZE);
if(str_len < 1){
return;
}
buff[str_len] = 0;
printf("Message from server : %s \n", buff);
}
}
void write_routine(int sock)
{
char buff[BUF_SIZE];
while(1){
//printf("Input message(Q to quit) : ");
fgets(buff, BUF_SIZE, stdin);
if( 0 == strcmp(buff, "q\n") || 0 == strcmp(buff, "Q\n") ){
shutdown(sock, SHUT_WR);
//Due to fork(), two socket file descriptor are existed. Only one close() will not send 'EOF'. So shutdown() is needed.
return;
}
write(sock, buff, strlen(buff));
}
}
void error_handling(char *message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
|
C
|
/*
* Hash_DeleteTable.c --
*
* Source code for the Hash_DeleteTable library procedure.
*
* Copyright 1988 Regents of the University of California
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies. The University of California
* makes no representations about the suitability of this
* software for any purpose. It is provided "as is" without
* express or implied warranty.
*/
#ifndef lint
static char rcsid[] = "$Header: Hash_DeleteTable.c,v 1.2 88/07/25 10:53:37 ouster Exp $ SPRITE (Berkeley)";
#endif not lint
#include "hash.h"
#include <list.h>
#include <stdlib.h>
/*
*---------------------------------------------------------
*
* Hash_DeleteTable --
*
* This routine removes everything from a hash table
* and frees up the memory space it occupied (except for
* the space in the Hash_Table structure).
*
* Results:
* None.
*
* Side Effects:
* Lots of memory is freed up.
*
*---------------------------------------------------------
*/
void
Hash_DeleteTable(tablePtr)
Hash_Table *tablePtr; /* Hash table whose entries are all to
* be freed. */
{
register List_Links *hashTableEnd;
register Hash_Entry *hashEntryPtr;
register List_Links *bucketPtr;
bucketPtr = tablePtr->bucketPtr;
hashTableEnd = &(bucketPtr[tablePtr->size]);
for (; bucketPtr < hashTableEnd; bucketPtr++) {
while (!List_IsEmpty(bucketPtr)) {
hashEntryPtr = (Hash_Entry *) List_First(bucketPtr);
List_Remove((List_Links *) hashEntryPtr);
free((Address) hashEntryPtr);
}
}
free((Address) tablePtr->bucketPtr);
/*
* Set up the hash table to cause memory faults on any future
* access attempts until re-initialization.
*/
tablePtr->bucketPtr = (List_Links *) NIL;
}
|
C
|
#if !defined(ADDINFOMASTER_H_INCLUDE_)
#define ADDINFOMASTER_H_INCLUDE_
#include "memstack.h"
/*
Fichero que maneja el addinfo master de las keywords de CTRL_SA
Dependencias:
MemStack - Almacenamiento en memoria de toda la estrutura
*/
struct ADDINFO_KEYWORD
{
struct ADDINFO_KEYWORD* next;
char *val;
char key[1]; //posicion del 0 o fin de linea
};
struct _ADDINFO_MASTER
{
int binit; // Indica si la estrutura esta inicializada
//DWORD data_size; // tama�o de la estructura en memoria que mantiene las keywords
struct ADDINFO_KEYWORD* first; // Primera keyword de la estructura
union {
struct _MEM_STACK mstack;
BYTE data[4000]; // Estructura en memoria con todas la keywords.
};
};
/*
Inicializar la estrutura
Parametros :
Puntero a la estrutura
Tama�a maximo de la memoria a reservar para el almacenamiento de datos
*/
DWORD Addinfo_Init(struct _ADDINFO_MASTER* addinfo, DWORD size);
DWORD Addinfo_SetData(struct _ADDINFO_MASTER* addinfo, char *data);
DWORD Addinfo_getKeyword(struct _ADDINFO_MASTER* addinfo, char* keyword, char **val);
#endif
|
C
|
/**
* \file vccrypt_stream_start_decryption.c
*
* Generic decryption start method for a stream cipher.
*
* \copyright 2018 Velo Payments, Inc. All rights reserved.
*/
#include <cbmc/model_assert.h>
#include <vccrypt/stream_cipher.h>
#include <vpr/parameters.h>
/**
* \brief Algorithm-specific start for the stream cipher decryption. Reads IV
* from input buffer.
*
* \param context Pointer to stream cipher context.
* \param input The input buffer to read the IV from. Must be at least
* IV_bytes in size.
* \param offset Pointer to the current offset of the buffer. Will be
* set to IV_bytes. The value in this offset is ignored.
*
* \returns a status indicating success or failure.
* - \ref VCCRYPT_STATUS_SUCCESS on success.
* - a non-zero error code on failure.
*/
int vccrypt_stream_start_decryption(
vccrypt_stream_context_t* context, const void* input, size_t* offset)
{
MODEL_ASSERT(NULL != context);
MODEL_ASSERT(NULL != context->options);
MODEL_ASSERT(NULL != input);
MODEL_ASSERT(NULL != offset);
return context->options->vccrypt_stream_alg_start_decryption(
context->options, context, input, offset);
}
|
C
|
#include<stdio.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
int main()
{
int queue[20],n,head;
int i,j,k,dist=0,maximum,diff;
float avgerage;
printf("==============Developed by Jatin==========\n");
printf("Enter the maximum range of disk you want\n");
scanf("%d",&maximum);
printf("After enter range enter the size of queue request \n");
scanf("%d",&n);
printf("Enter the queue of disk positions to be read\n");
for(i=1;i<=n;i++)
scanf("%d",&queue[i]);
printf("Enter the current serving request or initial head position\n");
scanf("%d",&head);
queue[0]=head;
for(j=0;j<=n-1;j++)
{
diff=abs(queue[j+1]-queue[j]);
dist+=diff;
printf("Disk head moves from %d to %d with seek %d\n",queue[j],queue[j+1],diff);
}
printf("\nTotal distance that the disk arm move is %d\n",dist);
avgerage=dist/(float)n;
printf("Average seek time is %f\n",avgerage);
return 0;
}
|
C
|
//#include <stdlib.h>
#include <stdio.h>
#include "pithread.h"
void* func1(void *arg){
int i = 0;
printf("Index initialized with 0\n");
for (; i < 10; i++){
printf("thread 1 with index %d\n\n", i);
if (i % 5 == 0) piyield();
}
return 0;
}
void* func2(void* arg){
int i = 0;
for (; i < 10; i++){
printf("thread 2\n\n");
if (i % 5 == 0) piyield();
}
return 0;
}
int main(int argc, char* argv[]){
printf("Create new thread.\n");
int t1, t2;
t1 = picreate(1, func1, 0);
t2 = picreate(1, func2, 0);
printf("Threads created. Waiting...\n");
piwait(t1);
piwait(t2);
printf("Threads finished. Exiting...\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct filme{
int codigo;
char titulo[100];
int ano;
int quantidade;
char genero[10];
};typedef struct filme Filme;
int nFilmes();
void carregarAcervo(Filme* filmes);
void carregar(Filme* filmes, Filme* f, int n);
Filme buscaPorCod(Filme* filmes, int c, int n);
void buscaPorTitulo(Filme* filmes, char titulo[], int n);
void buscaPorAno(Filme* filmes, int ano, int n);
void buscaPorGenero(Filme* filmes, char genero[], int n);
void locacao(Filme f, Filme* filmes);
void devolucao(Filme f, Filme* filmes, Filme* acervo);
void imprimir(Filme* filmes);
void imprimirFilme(Filme f);
void relatorio(Filme* filmes, int n);
void relatorioPorAno(Filme* filmes, int n, int ano);
void relatorioPorGenero(Filme* filmes, int n, char genero[]);
int main(int argc, char** argv) {
Filme f;
int i, b, n, m = 1;
char string[100];
n = nFilmes();
Filme acervo[n];
Filme filmes[n];
carregarAcervo(acervo);
carregar(acervo, filmes, n);
do{
carregar(filmes, filmes, n);
printf("\n\nLocadora do Alcemar: \n 1-Locacao \n 2-Devolucao\n 3-Buscar filme\n 4-Imprimir filmes do acervo\n 5-Gerar relatorio\n 0-Sair\nOpcao: ");
scanf("%i",&m);
switch(m){
case 1:{
printf("\nInforme o codigo do filme: ");
scanf("%i", &i);
f = buscaPorCod(filmes, i, n);
if(f.codigo == 999){
printf("Filme nao encontrado!");
}else{
locacao(f, filmes);
printf("Bom filme!!!");
}
break;
}
case 2:{
printf("\nInforme o codigo do filme: ");
scanf("%i", &i);
f = buscaPorCod(filmes, i, n);
if(f.codigo == 999){
printf("Filme nao encontrado!");
}else{
devolucao(f, filmes, acervo);
}
break;
}
case 3:{
printf(" Busca por:\n 1-Codigo\n 2-Titulo\n 3-Ano\n 4-Genero\n Opcao: ");
scanf("%i", &b);
switch(b){
case 1:{
printf("\nInforme o codigo do filme: ");
scanf("%i", &i);
f = buscaPorCod(filmes, i, n);
imprimirFilme(f);
break;
}
case 2:{
printf("\nInforme o titulo do filme: ");
fflush(stdin);
fgets(string, 100, stdin);
buscaPorTitulo(filmes, string, n);
break;
}
case 3:{
printf("\nInforme o ano do filme: ");
scanf("%i", &i);
buscaPorAno(filmes, i, n);
break;
}
case 4:{
printf("\nInforme o genero do filme: ");
fflush(stdin);
fgets(string, 100, stdin);
buscaPorGenero(filmes, string, n);
break;
}
default:{
printf("Opcao invalida!!!");
}
}
break;
}
case 4:{
imprimir(filmes);
break;
}
case 5:{
printf(" Gerar Relatorio: \n 1-Por ano\n 2-Por genero\n 3-Todo o acervo\n Opcao:");
scanf("%i",&b);
switch(b){
case 1:{
printf("\nInforme o ano do filme: ");
scanf("%i", &i);
relatorioPorAno(filmes, n, i);
break;
}
case 2:{
printf("\nInforme o genero do filme: ");
fflush(stdin);
fgets(string, 100, stdin);
relatorioPorGenero(filmes, n, string);
break;
}
case 3:{
relatorio(filmes, n);
break;
}
default:{
printf("Opcao invalida!!!");
}
}
break;
}
case 0:{
break;
}
default:{
printf("Opcao invalida!!!");
break;
}
}
}while(m!=0);
return (EXIT_SUCCESS);
}
void carregarAcervo(Filme * filmes){
FILE *acervo;
int n; //numero total de filmes
int c=0;//codigo do filme
char texto[116]; //guarda o texto lido em uma linha do arquivo
char titulo[100];
char ano[4];
char quantidade;
char genero[10];
int a; // usado para correcao de digitos do ano
int y; //contadores
int x=0;
if((acervo=fopen("entrada.txt", "rt"))==NULL){
printf("Erro ao abrir o arquivo!");
}
fseek(acervo,0,SEEK_SET);
fscanf(acervo, "%i \n", &n);
while(fscanf(acervo, "%[^\n]\n", texto)!=EOF){ //le o acervo linha por linha
//printf("\n\n %s", texto);
y=0;
while(texto[y]!=';'){ //le o texto da linha até o ;
titulo[y]=texto[y]; //atribui esse texto ao titulo
y++;
}
titulo[y]='\0'; //delimita os espaços de memoria usados pelo titulo
y++; //corrige a posicao do y (pula o caracter do ;)
x=0;
while(texto[y]!=';'){ //le o texto da linha até o proximo ;
ano[x]=texto[y];
y++;
x++;
}
y++; //corrige a posicao do y (pula o caracter do ;)
while(texto[y]!=';'){ //le o texto da linha até o proximo ;
quantidade=texto[y];
y++;
}
y++; //corrige a posicao do y (pula o caracter do ;)
x=0;
while(texto[y]!='\0'){ //le o texto da linha até o proximo ;
genero[x]=texto[y];
x++;
y++;
}
genero[x]='\0'; //delimita os espaços de memoria usados pelo titulo
a = atoi(ano); //converte o ano para int
//corrige a quantidade de caracteres do ano
if(a>10000000){
a = a /10000;
}
if(a>1000000){
a = a/1000;
}
if(a>100000){
a = a/100;
}
if(a>10000){
a = a/10;
}
strcpy(filmes[c].titulo, titulo);
filmes[c].ano = a;
filmes[c].quantidade = quantidade - '0';
strcpy(filmes[c].genero, genero);
filmes[c].codigo=c;
c++;
}
fclose(acervo);
}
Filme buscaPorCod(Filme* filmes, int c, int n){
int x;
Filme f;
f.codigo = 999;
for(x=0;x<n;x++){
if(filmes[x].codigo == c){
f = filmes[x];
}
}
return f;
}
int nFilmes(){
FILE* acervo;
int n;
if((acervo=fopen("entrada.txt", "rt"))==NULL){
printf("Erro ao abrir o arquivo!");
}
fseek(acervo,0,SEEK_SET);
fscanf(acervo, "%i \n", &n);
fclose(acervo);
return n;
}
void locacao(Filme f, Filme* filmes){
if(filmes[f.codigo].quantidade!=0){
filmes[f.codigo].quantidade--;
}else{
printf("Filme nao disponivel!!!");
}
}
void imprimir(Filme* filmes){
int x, n;
n = nFilmes();
for(x=0;x<n;x++){
printf("\n\nCodigo: %i", filmes[x].codigo);
printf("\nTitulo: %s", filmes[x].titulo);
printf("\nAno: %d", filmes[x].ano);
printf("\nQuantidade: %d", filmes[x].quantidade);
printf("\nGenero: %s\n", filmes[x].genero);
}
}
void imprimirFilme(Filme f){
printf("\n\nCodigo: %i", f.codigo);
printf("\nTitulo: %s", f.titulo);
printf("\nAno: %d", f.ano);
printf("\nQuantidade: %d", f.quantidade);
printf("\nGenero: %s\n", f.genero);
}
void carregar(Filme* filmes, Filme* f, int n){
FILE *acervo;
int x;
if((acervo=fopen("acervo.txt", "w"))==NULL){
printf("Erro ao abrir o arquivo!");
}
fseek(acervo,0,SEEK_SET);
fprintf(acervo, "%i \n", n);
for(x=0;x<n;x++){
fprintf(acervo,"%s;", filmes[x].titulo);
fprintf(acervo,"%i;", filmes[x].ano);
fprintf(acervo,"%i;", filmes[x].quantidade);
fprintf(acervo,"%s \n", filmes[x].genero);
strcpy(f[x].titulo,filmes[x].titulo);
f[x].ano = filmes[x].ano;
f[x].quantidade = filmes[x].quantidade;
strcpy(f[x].genero,filmes[x].genero);
f[x].codigo = x;
}
fclose(acervo);
}
void devolucao(Filme f, Filme* filmes, Filme* acervo){
int q; //quantidade original do filme
q = acervo[f.codigo].quantidade;
if(filmes[f.codigo].quantidade<q){
filmes[f.codigo].quantidade++;
printf("Filme devolvido com sucesso!!!");
}else{
printf("Nao e possivel devolver esse filme!!!");
}
}
void buscaPorTitulo(Filme* filmes, char titulo[], int n){
int x, c=0;
for(x=0;x<n;x++){
if(strcasecmp(filmes[x].titulo, strtok(titulo, "\n"))==0){
imprimirFilme(filmes[x]);
c++;
}
}
if(c==0){
printf("\nFilme nao encontrado! :( \n");
}
}
void buscaPorAno(Filme* filmes, int ano, int n){
int x, c = 0;
for(x=0;x<n;x++){
if(filmes[x].ano == ano){
imprimirFilme(filmes[x]);
c++;
}
}
if(c==0){
printf("\nFilme nao encontrado! :(\n");
}
}
void buscaPorGenero(Filme* filmes, char genero[], int n){
int x, c=0;
for(x=0;x<n;x++){
if(strcasecmp(filmes[x].genero, strtok(genero, "\n"))==0){
imprimirFilme(filmes[x]);
c++;
}
}
if(c==0){
printf("\nFilme nao encontrado! :(\n");
}
}
void relatorio(Filme* filmes, int n){
FILE *acervo;
int x;
if((acervo=fopen("acervo_completo_atual.txt", "w"))==NULL){
printf("Erro ao abrir o arquivo!");
}
fseek(acervo,0,SEEK_SET);
for(x=0;x<n;x++){
fprintf(acervo,"%s;", filmes[x].titulo);
fprintf(acervo,"%i;", filmes[x].ano);
fprintf(acervo,"%i;", filmes[x].quantidade);
fprintf(acervo,"%s \n", filmes[x].genero);
}
fclose(acervo);
}
void relatorioPorAno(Filme* filmes, int n, int ano){
FILE *acervo;
int x;
if((acervo=fopen("relatorioAno.txt", "w"))==NULL){
printf("Erro ao abrir o arquivo!");
}
fseek(acervo,0,SEEK_SET);
printf("%i", ano);
for(x=0;x<n;x++){
if(filmes[x].ano == ano){
fprintf(acervo,"%s;", filmes[x].titulo);
fprintf(acervo,"%i;", filmes[x].ano);
fprintf(acervo,"%i;", filmes[x].quantidade);
fprintf(acervo,"%s \n", filmes[x].genero);
}
}
fclose(acervo);
}
void relatorioPorGenero(Filme* filmes, int n, char genero[]){
FILE *acervo;
int x;
if((acervo=fopen("relatorioGenero.txt", "w"))==NULL){
printf("Erro ao abrir o arquivo!");
}
fseek(acervo,0,SEEK_SET);
fprintf(acervo, "%s \n", genero);
for(x=0;x<n;x++){
if(strcasecmp(filmes[x].genero, strtok(genero, "\n"))==0){
fprintf(acervo,"%s;", filmes[x].titulo);
fprintf(acervo,"%i;", filmes[x].ano);
fprintf(acervo,"%i;", filmes[x].quantidade);
fprintf(acervo,"%s \n", filmes[x].genero);
}
}
fclose(acervo);
}
|
C
|
/*
* Delta programming language
*/
#include "delta/delta.h"
#include <math.h>
#include <string.h>
// from base_convert.c
char* base_convert(char* in, int base1, int base2);
/**
* @category modules/core/math
*
* @brief Hexadecimal to decimal.
* @syntax string hexdoc ( int hex_string )
*
* Returns the decimal equivalent of the hexadecimal number represented by the hex_string argument.
* hexdec() converts a hexadecimal string to a decimal number.
*
* @param hex_string The hexadecimal string to convert.
* @return The decimal representation of hex_string.
* @see bindec
* @see dechex
* @see decbin
* @see base_convert
*/
DELTA_FUNCTION(hexdec)
{
int release_arg0;
struct DeltaVariable *arg0 = delta_cast_string(DELTA_ARG0, &release_arg0);
char* r = base_convert(arg0->value.ptr, 16, 10);
// clean up
DELTA_RELEASE(release_arg0, arg0);
DELTA_RETURN_STRING(r);
}
|
C
|
#include "RGB.h"
//PB9(RGB_DATA),PB8(RGB_CLK)
void RGB_PIN_Init(void)
{
RCC->APB2ENR |=0x01<<3;
GPIOB->CRH &=~(0xFF<<0);
GPIOB->CRH |=(0x11<<0);
RGB_Control(0,0,0);
}
u32 Color_DATA(u8 r,u8 g,u8 b)
{
u32 RGB_COLOR=0;
RGB_COLOR |=0x03<<30;
RGB_COLOR |=((~(b)&0xc0)>>6)<<28;
RGB_COLOR |=((~(g)&0xc0)>>6)<<26;
RGB_COLOR |=((~(r)&0xc0)>>6)<<24;
RGB_COLOR |=b<<16;
RGB_COLOR |=g<<8;
RGB_COLOR |=r<<0;
return RGB_COLOR;
}
void RGB_DATA_Send(u32 RGB_data)
{
u8 i;
for(i=0;i<32;i++)
{
if(RGB_data&0x80000000)
{
RGB_DATA=1;
}
else
{
RGB_DATA=0;
}
RGB_data<<=1;
RGB_CLK=0;
delay_us(200);
RGB_CLK=1;
delay_us(200);
}
}
void RGB_Control(u8 r,u8 g,u8 b)
{
u32 RGB=0;
RGB=Color_DATA(r,g,b);
RGB_DATA_Send(0);
RGB_DATA_Send(RGB);
RGB_DATA_Send(RGB);
}
|
C
|
#include <stdlib.h> // Contains declarations information
#include <stdio.h> // I/O function
#include <sys/types.h> // Defines data types
#include <sys/socket.h> // Define the type socklen_t
#include <netinet/in.h> // Contains definitions for the internet protocol family
#include <string.h> // String function
#include <arpa/inet.h> // Definitions for internet operations.
#define MAXLINE 2000 // Maximum text length
#define PORT 3000 // Server port
int main(int argc, char **argv)
{
int sockfd;
struct sockaddr_in servaddr;
char sending[MAXLINE], receiving[MAXLINE];
if (argc !=2) {
perror("Usage: PLEASE ENTER IP address of the server");
exit(1);
}
//Create a socket for client
if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) <0) {
perror("connection error");
exit(2);
}
//Preparing socket address
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr= inet_addr("192.168.56.105");
servaddr.sin_port = htons(PORT);
//Connection of client's socket
if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr))<0) {
perror("Connection to the server is error!!");
exit(3);
}
printf("~~~~~~~~ HELLO ECHO CLIENT!! WELCOME TO THE ECHO PROTOCOL ~~~~~~~~");
printf("\n.................................................");
printf("\nPlease enter message: ");
//Read the contents of the FILE*stdin
while (fgets(sending, MAXLINE, stdin) != NULL) {
send(sockfd, sending, strlen(sending), 0);
if (recv(sockfd, receiving, MAXLINE,0) == 0){
perror("The server unexpectedly shut down.");
exit(4);
}
printf("~~~~~~~ ATTENTION CLIENT !! ~~~~~~~ \n");
printf("%s", "Received from the server: ");
fputs(receiving, stdout);
}
exit(0);
}
|
C
|
/*
* Copyright (c) 2011, Courtney Cavin
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdlib.h>
#include <string.h>
#include "ringbuffer.h"
#define MIN(x,y) (((x)<(y))?(x):(y))
int ringbuffer_create(ringbuffer_t *buf, unsigned int size)
{
buf->data = malloc(size);
if (buf->data == NULL)
return -1;
buf->size = size;
buf->in = 0;
buf->out = 0;
return 0;
}
void ringbuffer_destroy(ringbuffer_t *buf)
{
free(buf->data);
}
void ringbuffer_flush(ringbuffer_t *buf)
{
buf->in = 0;
buf->out = 0;
}
unsigned int ringbuffer_empty(ringbuffer_t *buf)
{
if (buf->in < buf->out)
return buf->out - buf->in;
else
return buf->size - (buf->in - buf->out);
}
unsigned int ringbuffer_full(ringbuffer_t *buf)
{
if (buf->in >= buf->out)
return buf->in - buf->out;
else
return buf->size - (buf->out - buf->in);
}
int ringbuffer_write(ringbuffer_t *buf, const void *data, unsigned int size)
{
char *b = (char *)buf->data;
unsigned int left = ringbuffer_empty(buf);
unsigned int wlen = MIN(size, left);
char *to = b + buf->in;
if (wlen == 0) {
return 0;
} else if (wlen < (buf->size - buf->in)) {
memcpy(to, data, wlen);
buf->in += wlen;
} else {
const char *d2 = (const char *)data + (buf->size - buf->in);
memcpy(to, data, buf->size - buf->in);
memcpy(b, d2, wlen - (buf->size - buf->in));
buf->in = wlen - (buf->size - buf->in);
}
return wlen;
}
int ringbuffer_read(ringbuffer_t *buf, void *data, unsigned int size)
{
const char *b = (const char *)buf->data;
unsigned int left = ringbuffer_full(buf);
unsigned int rlen = MIN(size, left);
const char *from = b + buf->out;
if (rlen == 0) {
return 0;
} else if (rlen < (buf->size - buf->out)) {
memcpy(data, from, rlen);
buf->out += rlen;
} else {
char *d2 = (char *)data + (buf->size - buf->out);
memcpy(data, from, buf->size - buf->out);
memcpy(d2, b, rlen - (buf->size - buf->out));
buf->out = rlen - (buf->size - buf->out);
}
return rlen;
}
|
C
|
// PTIME - Prime Time
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
unsigned int in;
scanf("%u", &in);
bool *sieve = (bool *)malloc(sizeof(bool) * (in + 1));
memset(sieve, true, sizeof(bool) * (in + 1));
unsigned int *fraction =
(unsigned int *)malloc(sizeof(unsigned int) * (in + 1));
memset(fraction, 0, sizeof(unsigned int) * (in + 1));
for (unsigned int i = 2; (i * i) <= in; i++) {
if (sieve[i])
for (unsigned int j = (i * i); j <= in; j += i)
sieve[j] = false;
}
for (unsigned int i = 2; i <= in; i++) {
for (unsigned int j = 2, k = i; j <= in; j++) {
if ((sieve[j]) && ((k % j) == 0))
while ((k % j) == 0) {
k /= j;
fraction[j]++;
}
}
}
bool first = true;
for (unsigned int i = 0; i <= in; i++) {
if (fraction[i]) {
if (first) {
printf("%u^%u", i, fraction[i]);
first = false;
} else {
printf(" * %u^%u", i, fraction[i]);
}
}
}
putchar('\n');
free(fraction);
free(sieve);
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
void imprimeVetor(int* vetor, int tamanho){
for(int i = 0; i < tamanho; i++)
printf("%d | ", vetor[i] * 2);
}
int main(){
int vetor[] = {1, 2, 3, 4, 5};
int tamanho = (int)(sizeof(vetor)/sizeof(vetor[0]));
imprimeVetor(vetor, tamanho);
return 0;
}
|
C
|
#include <stdio.h>
void cadastra_cliente() {
printf("--->[1] Cadastrar cliente\n\n");
}
void procura_cliente() {
printf("--->[2] Procurar cliente\n\n");
}
void insere_pedido() {
printf("--->[3] Inserir pedido\n\n");
}
int escolhe_opcao() {
int opcao;
printf("[1] Cadastrar cliente\n"
"[2] Procurar cliente\n"
"[3] Inserir pedido\n"
"[0] Sair\n\n""Digite sua escolha: ");
scanf ("%d", &opcao);
switch (opcao) {
case 1:
cadastra_cliente();
break;
case 2:
procura_cliente();
break;
case 3:
insere_pedido();
break;
case 0:
return 0;
default:
printf ("Opção inválida!\n");
}
return opcao;
}
int main(){
int opcao = escolhe_opcao();
while (opcao != 0) {
opcao = escolhe_opcao();
}
return opcao;
}
|
C
|
#include <errno.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include "networking.h"
#define SERVER_ADDRESS "127.0.0.1"
#define PORT_NUMBER 5358
int socket_fd;
int connectToServer() {
// create TCP (NON-BLOCKING) socket
socket_fd = socket(AF_INET, SOCK_STREAM, 0);
if (socket_fd < 0) return -1;
// load host by address and verify if it exists
struct hostent *server = gethostbyname(SERVER_ADDRESS);
if (server == NULL) return -1;
// server address struct initialization
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
memcpy(&server_addr.sin_addr.s_addr, server->h_addr, server->h_length);
server_addr.sin_port = htons(PORT_NUMBER);
// connect to server
int er = connect(socket_fd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0;
if (er) {
fprintf(stderr, "ERROR: %s\n", strerror(errno));
return -1;
}
// set file descriptor to non-blocking mode
fcntl(socket_fd, F_SETFL, O_NONBLOCK);
return 0;
}
int writeToServer(char *message, int size) {
int n = write(socket_fd, message, size);
if (n < 0) return -1;
return n;
}
// DEPRECATED
int readFromServer(char *message, int size) {
int n = read(socket_fd, message, size - 1);
if (n < 0) return -1;
return n;
}
int pullUpdates255(void *message) {
char buffer[256];
memset(buffer, 0, 256);
int n = read(socket_fd, buffer, 256);
if (n > 0) {
strcpy(message, buffer);
}
return 1;
}
|
C
|
#include <sys/select.h>
#include <stdio.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include "node.h"
int main(int argc, char **argv){
//Create the contact information table and 128 node_details *:
int i=0;
routing_table table;
for(i;i<NUMBER_OF_BUCKETS;i++){
table.table[i]=NULL;
}
node_details* result2=NULL;
result2 = k_nearest_nodes(result2, &table, "00000000000", "00000000015");
print_nodes(result2,-1);
printf("***************** first series of test *************\n");
//TEST1:
int bucket_no;
bucket_no = insert_into_contact_table(&table, "ABE34AE3","ABE22222", "127.0.0.1", 9876);
printf("bucket_no: %i\n",bucket_no);
print_nodes(table.table[bucket_no],1);
bucket_no = insert_into_contact_table(&table, "1234683222222222","12346340E22ABC22", "127.0.0.1", 2344);
printf("bucket_no: %i\n",bucket_no);
print_nodes(table.table[bucket_no],1);
bucket_no = insert_into_contact_table(&table, "2323","FFFF", "127.0.0.1", 12);
printf("bucket_no: %i\n",bucket_no);
print_nodes(table.table[bucket_no],1);
bucket_no = insert_into_contact_table(&table, "ABE34AE3","12345665", "127.0.0.1", 9876);
printf("bucket_no: %i\n",bucket_no);
print_nodes(table.table[bucket_no],1);
printf("***************** second series of test *************\n");
/*TEST2:
table.table[1] = move_node_details(table.table[1], "22", "127.0.0.1", 22);
print_nodes(table.table[1],1);
table.table[1] = move_node_details(table.table[1], "22", "127.0.0.1", 22);
print_nodes(table.table[1],1);
table.table[1] = move_node_details(table.table[1], "12", "127.0.0.1", 12);
print_nodes(table.table[1],1);
table.table[1] = move_node_details(table.table[1], "34", "127.0.0.1", 34);
print_nodes(table.table[1],1);
table.table[1] = move_node_details(table.table[1], "12", "127.0.0.1", 12);
print_nodes(table.table[1],1);
table.table[1] = move_node_details(table.table[1], "65", "127.0.0.1", 65);
print_nodes(table.table[1],1);
table.table[1] = move_node_details(table.table[1], "67", "127.0.0.1", 67);
print_nodes(table.table[1],1);
table.table[1] = move_node_details(table.table[1], "46", "127.0.0.1", 46);
print_nodes(table.table[1],1);
table.table[1] = move_node_details(table.table[1], "68" , "127.0.0.1", 68);
print_nodes(table.table[1],1);
*/
printf("***************** third series of test *************\n");
//int u = print_routing_table(table);
printf("***************** fourth series of test *************\n");
// Remplissage k-bucket 1-2
/*bucket_no = insert_into_contact_table(&table, "00000000000","00000000001", "127.0.0.1", 1);
printf("bucket_no: %i\n",bucket_no);
print_nodes(table.table[bucket_no],1);
bucket_no = insert_into_contact_table(&table, "00000000000","00000000002", "127.0.0.1", 2);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","00000000003", "127.0.0.1", 3);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","00000000004", "127.0.0.1", 4);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","00000000005", "127.0.0.1", 5);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","00000000006", "127.0.0.1", 6);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","00000000007", "127.0.0.1", 7);
printf("bucket_no: %i\n",bucket_no);*/
// Remplissage k-bucket 3-5-6
bucket_no = insert_into_contact_table(&table, "00000000000","00000000008", "127.0.0.1", 8);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","00000000009", "127.0.0.1", 9);
printf("bucket_no: %i\n",bucket_no);
/*bucket_no = insert_into_contact_table(&table, "00000000000","0000000000A", "127.0.0.1", 10);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","0000000000D", "127.0.0.1", 13);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","0000000000E", "127.0.0.1", 14);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","0000000000F", "127.0.0.1", 15);
printf("bucket_no: %i\n",bucket_no);*/
bucket_no = insert_into_contact_table(&table, "00000000000","00000000020", "127.0.0.1", 32);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","0000000002A", "127.0.0.1", 42);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","0000000002E", "127.0.0.1", 46);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","00000000034", "127.0.0.1", 52);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","00000000039", "127.0.0.1", 57);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","0000000003F", "127.0.0.1", 63);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","00000000040", "127.0.0.1", 64);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","00000000050", "127.0.0.1", 80);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","00000000060", "127.0.0.1", 96);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","00000000069", "127.0.0.1", 105);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","00000000070", "127.0.0.1", 112);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","0000000007F", "127.0.0.1", 127);
printf("bucket_no: %i\n",bucket_no);
// Semi-remplissage de 4-7 bucket
bucket_no = insert_into_contact_table(&table, "00000000000","00000000010", "127.0.0.1", 16);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","0000000001B", "127.0.0.1", 27);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","00000000014", "127.0.0.1", 20);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","00000000080", "127.0.0.1", 128);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","00000000093", "127.0.0.1", 147);
printf("bucket_no: %i\n",bucket_no);
bucket_no = insert_into_contact_table(&table, "00000000000","000000000D2", "127.0.0.1", 210);
printf("bucket_no: %i\n",bucket_no);
int u = print_routing_table(table);
//look for a node into the bucket_7.
node_details* result=NULL;
result = k_nearest_nodes(result, &table, "00000000000", "00000000015");
print_nodes(result,-1);
return 0;
}
|
C
|
#include "holberton.h"
/**
* _strcmp - compare two strings.
* @s1: string
* @s2: string
* Return: int
*/
int _strcmp(char *s1, char *s2)
{
while (*s1 && (*s1 == *s2))
{
s1++;
s2++;
}
return (*(const unsigned char *)s1 - *(const unsigned char *)s2);
}
|
C
|
#include <stdio.h>
int main() {
// void print_ints(int [], int);
// int numbers[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
// length = sizeof(numbers) / sizeof (int);
char *create_arr();
char *create_arr2();
char *p = create_arr();
create_arr2();
putchar(p[0]);
// print_ints(numbers, length);
}
char *create_arr()
{
char arr[] = {'a', 'b', 'c'};
return arr;
}
char *create_arr2()
{
char arr[] = {'d', 'e', 'f'};
return arr;
}
void print_ints(int nums[], int length)
{
for (int i = 0; i < length; i++) {
printf(i < length - 1 ? "%i, " : "%i", nums[i]);
}
printf("\n");
}
|
C
|
#include<stdio.h>
int main()
{
int n; //no of segments
scanf("%d",&n);
int start[n], end[n]; //2 array to store the start and end points of segments
int i,j; //counting variables
int m; //to store the min number of pts.
//input segments
for(i=0;i<n;i++)
scanf("%d %d",&start[i], &end[i]);
//sorting both arrays in asc order acc to end pts.
/*for()
{
}*/
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(end[i] < start[j])
{
m = m+1;
break;
}
}
}
printf("%d\n",m );
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* otool_process_files.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: afeuerst <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/04/29 14:27:15 by afeuerst #+# #+# */
/* Updated: 2019/05/04 10:54:32 by afeuerst ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_otool.h"
static inline void otool_proc_macho(
struct s_otool *const otool,
struct s_macho_binary *const bin,
struct s_macho *const macho)
{
struct s_section *section;
if (otool->flags & (OTOOL_P | OTOOL_H))
{
if (otool->flags & OTOOL_P)
otool_private_header(otool, macho);
if (otool->flags & OTOOL_H)
otool_headers(otool, macho);
}
else if ((section = get_macho_section(macho, SEG_TEXT, SECT_TEXT)))
{
ft_printf("Contents of (%s,%s) section\n", SEG_TEXT, SECT_TEXT);
if (macho->is32)
otool->content32(otool, bin, macho, section);
else
otool->content64(otool, bin, macho, section);
}
}
static inline void otool_process_statics(
struct s_otool *const otool,
struct s_macho_binary *const bin,
struct s_staticlib_macho *s)
{
ft_printf("Archive: %s\n", bin->file);
while (s)
{
ft_printf("%s(%s):\n", bin->file, s->name);
otool_proc_macho(otool, bin, s->macho);
s = s->next;
}
}
static inline void otool_process_file(
struct s_otool *const otool,
struct s_macho_binary *const bin)
{
int index;
int select;
struct s_macho *ptr;
index = select_arch(bin, &select);
while (index < bin->count)
{
ptr = bin->macho + index++;
if (ptr->statics)
otool_process_statics(otool, bin, ptr->statics);
else
{
if (bin->count > 1 && !select)
ft_printf("%s (architecture %s):\n", bin->file,
get_cputype(ptr->header->cputype, 1));
else
ft_printf("%s:\n", bin->file);
otool_proc_macho(otool, bin, ptr);
}
if (select)
break ;
}
}
void otool_process_files(
struct s_otool *const otool,
char **argv)
{
struct s_macho_binary *bin;
while (*argv)
{
bin = get_macho_binary(*argv++);
if (bin->error)
{
ft_fprintf(STDERR_FILENO, "ft_otool: \'%s\': %s.\n", bin->file, bin->error);
continue ;
}
otool_process_file(otool, bin);
unget_macho_binary(bin);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define MAX 20
void GameTitle(){
printf("\n-----------------------");
printf("\n| |");
printf("\n| HANGMAN |");
printf("\n| |");
printf("\n-----------------------");
}
//Selects one of the given names, that has to be guessed
int SelectWord(){
srand(time(NULL));
int upper = 4;
int lower = 0;
int i = (rand() % (upper - lower + 1)) + lower;
return i;
}
/* counts the length of the word
plus also spaces in between those words*/
int WordLength(char *arr){
int count = 0;
char *pointer = arr;
for(int i = 0; i < pointer[i] != 0; i++){
count++;
}
return count;
}
/* Takes a word and turns every char of the word
into a '-' */
void HiddenWord(char *arr){
printf("\n");
char *ptr = arr;
for(int i = 0; i < WordLength(arr); i++){
if(ptr[i] != ' '){
printf(" - ");
}else{
printf(" ");
}
}
printf("\n");
}
void GuessingGameStart(){
printf("\n\n");
printf("\n-----------------------");
printf("\n| |");
printf("\n| Guess the |");
printf("\n| following |");
printf("\n| word: |");
printf("\n| |");
printf("\n-----------------------");
printf("\n\n");
}
/* counts the same letters in a word
such as London - SameChar = 1*/
int SameChars(char *arr, int length){
int count = 0;
//points to the first letter of the string
/*
int the example *arr = "Boston"
char *ptr = arr;
*ptr points to the B
ptr[0] = 'B'
*/
char *ptr = arr;
char num[20];
for(int i = 0; i < length; i++){
for(int j = 0; j < length; j++){
if(ptr[i] == ptr[j] && i != j && ptr[i] != num[j]){
count++;
//saves the already checked letters
num[i] = ptr[i];
}
}
}
if(ptr[0] == ptr[length-1]){
count++;
}
return count;
}
/* Checks if the chosen letter is in the word or not and
then returns back an array that fills it self up slowly
if the letter was corret*/
char * Guessing(char guess, char *arr, char *reArr){
char *ptr = arr;
//First letter should always be capital
if(ptr[0] == guess || ptr[0] == (guess -32)){
reArr[0] = guess - 32;
}
for(int i = 1; i < WordLength(arr); i++){
if(ptr[i] == guess && ptr[i - 1] != ' '){
reArr[i] = guess;
}else if(ptr[i] == (guess - 32) && ptr[i - 1] == ' '){
reArr[i] = guess - 32;
}
else if(reArr[i] != '-' && ptr[i] != ' '){
reArr[i] = reArr[i];
}else if(ptr[i] == ' ' || reArr[i] == ' '){
reArr[i] = ' ';
}else{
reArr[i] = '-';
}
}
return reArr;
}
/* counts the number of underscores in the array of
the Guessing function */
int CountUnderscore(char *arr){
char *ptr = arr;
int count = 0;
for(int i = 0; i < WordLength(arr); i++){
if(ptr[i] == '-'){
count++;
}
}
return count;
}
void win(){
printf("\n");
printf("\n-----------------------");
printf("\n| |");
printf("\n| You Won! |");
printf("\n| |");
printf("\n-----------------------");
printf("\n");
}
void lost(){
printf("\n");
printf("\n-----------------------");
printf("\n| |");
printf("\n| You Lost! |");
printf("\n| |");
printf("\n-----------------------");
printf("\n");
}
/* basically just a true or false function
if the guess was correct and the letter
does appear in the word then this function
will return a number with the value 1, else
with a value of 0 */
int GoodGuess(char guess, char * arr){
char *ptr = arr;
int reVal = 0;
for(int i = 0; i < WordLength(arr); i++){
if(ptr[i] == guess || ptr[i] == (guess - 32)){
reVal = 1;
return reVal;
}else{
reVal = 0;
}
}
return reVal;
}
/* A function to make every word that will be input
by the user look essentially the same - that means e.g.
always capitalizing the word */
char * EqualDesign(char *arr){
char * ptr = arr;
int i = 1;
if((ptr[0] >= 'a') && (ptr[0] <= 'z')){
ptr[0] = ptr[0] - 32;
}else{
ptr[0] = ptr[0];
}
while(ptr[i] != 0){
if(((ptr[i] >= 'a') && (ptr[i] <= 'z')) && ptr[i - 1] == ' '){
ptr[i] = ptr[i] - 32;
}else if(((ptr[i] >= 'A') && (ptr[i] <= 'Z')) && ptr[i - 1] != ' '){
ptr[i] = ptr[i] + 32;
}
i++;
}
}
void BuildTree(int life, char guess, char * arr){
switch(life){
case 4:
if(GoodGuess(guess, arr) == 0){
printf("\n");
printf("\n-----------------------");
printf("\n| |------| |");
printf("\n| 0 | |");
printf("\n| | |");
printf("\n| | |");
printf("\n| | |");
printf("\n-----------------------");
printf("\n");
}
break;
case 3:
if(GoodGuess(guess, arr) == 0){
printf("\n");
printf("\n-----------------------");
printf("\n| |------| |");
printf("\n| 0 | |");
printf("\n| \\| | |");
printf("\n| | |");
printf("\n| | |");
printf("\n-----------------------");
printf("\n");
}
break;
case 2:
if(GoodGuess(guess, arr) == 0){
printf("\n");
printf("\n-----------------------");
printf("\n| |------| |");
printf("\n| 0 | |");
printf("\n| \\|/ | |");
printf("\n| | |");
printf("\n| | |");
printf("\n-----------------------");
printf("\n");
}
break;
case 1:
if(GoodGuess(guess, arr) == 0){
printf("\n");
printf("\n-----------------------");
printf("\n| |------| |");
printf("\n| 0 | |");
printf("\n| \\|/ | |");
printf("\n| / | |");
printf("\n| | |");
printf("\n-----------------------");
printf("\n");
break;
}
case 0:
if(GoodGuess(guess, arr) == 0){
printf("\n");
printf("\n-----------------------");
printf("\n| |------| |");
printf("\n| 0 | |");
printf("\n| \\|/ | |");
printf("\n| / \\ | |");
printf("\n| | |");
printf("\n-----------------------");
printf("\n");
break;
}
}
/* Game if option: use random word is chosen */
}
void HangmanGame(){
//allocating the memory for each word
char * a = malloc(256);
char * b = malloc(256);
char * c = malloc(256);
char * d = malloc(256);
char * e = malloc(256);
char * f = malloc(256);
char * g = malloc(256);
//copying the String to the variable in the array
strcpy(a, "London");
strcpy(b, "Boston");
strcpy(c, "Munich");
strcpy(d, "Berlin");
strcpy(e, "New York City");
strcpy(f, "New Hampshire");
strcpy(g, "Sri Lanka");
//array of words that can be randomly selected
char *words[7] = {a, b, c, d, e, f, g};
char *Selected[1];
Selected[0] = words[SelectWord()];
GuessingGameStart();
HiddenWord(Selected[0]);
/*Guessing part of the game*/
int lifes = 5;
char Guess;
char *n;
int p = WordLength(Selected[0]);
char tempArr[p];
//fill tempArr with '-':
int length = WordLength(Selected[0]);
for(int m = 0; m < length; m++){
tempArr[m] = '-';
}
int same = SameChars(Selected[0], WordLength(Selected[0]));
//Number of letters the user has to guess:
int quit = length - same;
do{
printf("\n\nEnter a letter: \n");
scanf(" %c", &Guess);
printf("\n");
n = Guessing(Guess, Selected[0], tempArr);
printf("\n");
for(int j = 0; j < length; j++){
printf(" %c ", n[j]);
}
if(GoodGuess(Guess, Selected[0]) == 0){
lifes--;
}
BuildTree(lifes, Guess, Selected[0]);
}while(lifes > 0 && CountUnderscore(n) > 0);
/*print final image of the game*/
if(CountUnderscore(tempArr) == 0){
win();
}else{
lost();
}
//free the allocated memory, after the program is finished
free(a);
free(b);
free(c);
free(d);
free(e);
free(f);
free(g);
}
/* Game if option: own word is chosen */
void HangmanGameOwnWord(char * arr){
GuessingGameStart();
//Make every String have the same overall design
EqualDesign(arr);
HiddenWord(arr);
//Guessing part of the game
int lifes = 5;
char Guess;
char *n;
int length = WordLength(arr);
int p = length;
char tempArr[p];
//fill tempArr with '-':
for(int m = 0; m < length; m++){
tempArr[m] = '-';
}
int same = SameChars(arr,length);
//Number of letters the user has to guess:
int quit = length - same;
do{
printf("\n\nEnter a lowercased letter: \n");
scanf(" %c", &Guess);
printf("\n");
n = Guessing(Guess, arr, tempArr);
printf("\n");
for(int j = 0; j < length; j++){
printf(" %c ", n[j]);
}
if(GoodGuess(Guess, arr) == 0){
lifes--;
}
BuildTree(lifes, Guess, arr);
}while(lifes > 0 && CountUnderscore(n) > 0);
//print final image of the game
if(CountUnderscore(tempArr) == 0){
win();
}else{
lost();
}
}
void main(){
//First print the titel of the game:
GameTitle();
//Ask user if he wants to enter a word or use a random one:
int choice;
printf("\n\nDo you want to use a random word or enter your own word? random = 1, own = 0\n");
scanf("%d", &choice);
/* Common problem with scanf that is followed by a fgets
to solve this problem add a new line after scanf
- best way I found by using getchar()
*/
getchar();
if(choice == 1){
HangmanGame();
}else if(choice == 0){
char str[MAX];
printf("\nEnter a word (Max Length = 20): \n");
/* stdin means standard input stream where data
is sent to and read by a program */
fgets(str, MAX, stdin);
/* REMOVE THE REDUNDANT NEW LINE CHARACTER
OF fgets()
*/
str[strcspn(str, "\n")] = 0;
HangmanGameOwnWord(str);
}else{
printf("\nWrong input - Restart the Game!\n");
}
}
|
C
|
#ifndef _GET_FRAME_H_
#define _GET_FRAME_H_
#include "utils.h"
//read video file
int CapVideo(const char* video_file)
{
VideoCapture cap(video_file); // open the default camera
if (!cap.isOpened()) // check if we succeeded
return -1;
Mat edges;
namedWindow("edges", 1);
int count = 0;
while (true){
Mat frame;
cap >> frame; // get a new frame from camera
if (frame.empty())
break;
count++;
if (count == 4000)
{
imwrite("frame_40.bmp", frame);
break;
}
cvtColor(frame, edges, COLOR_BGR2GRAY);
GaussianBlur(edges, edges, Size(7, 7), 1.5, 1.5);
Canny(edges, edges, 0, 30, 3);
cv::imshow("edges", edges);
if (waitKey(30) >= 0) break;
}
return 0;
}
//Ƶļдͼ֡
int CropVideo2Frames(const char* video_file)
{
VideoCapture cap(video_file); // open the default camera
if (!cap.isOpened()) // check if we succeeded
return -1;
int i = 0;
string suffix;
//\~
Mat hsv_img;
while (true)
{
Mat frame;
cap >> frame;
if (frame.empty())
break;
FormatName(i, suffix);
suffix = string("D:\\Video\\") + suffix + string(".png");
cout << "writing img: " << i << '\t' << "img" << endl;
GaussianBlur(frame, frame, Size(5, 5), 0, 0);
cvtColor(frame, hsv_img, COLOR_BGR2HSV);
imshow("img3color", hsv_img);
imshow("img3src", frame);
if (i == 100)
{
imwrite("img_src.bmp", frame);
imwrite("img_hsv.bmp", hsv_img);
}
cvWaitKey(0);
suffix.clear();
i++;
if (waitKey(2) >= 0)
break;
}
return 0;
}
//write video frame into file
int RecordVideo()
{
VideoCapture vcap(0);
if (!vcap.isOpened()){
cout << "Error opening video stream or file" << endl;
return -1;
}
int frame_width = (int)vcap.get(CV_CAP_PROP_FRAME_WIDTH);
int frame_height = (int)vcap.get(CV_CAP_PROP_FRAME_HEIGHT);
VideoWriter video("D:\\Video\\out.avi", CV_FOURCC('M', 'J', 'P', 'G'), 10, Size(frame_width, frame_height), true);
for (;;){
Mat frame;
vcap >> frame;
video.write(frame);
imshow("Frame", frame);
char c = (char)waitKey(30);
if (c == 27) break;
}
return 0;
}
//֡ͼֱ
void TESTabs()
{
Mat bg_frame = imread("D:\\Video\\out_frames_null\\1024.png",0);
Mat cam_frame = imread("D:\\Video\\out0_frames_v1_3000\\400.png",0);
Mat motion;
//GaussianBlur(cam_frame, cam_frame, Size(7, 7), 1.5, 1.5);
absdiff(bg_frame, cam_frame, motion);
threshold(motion, motion, 0, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);
imshow("bg_frame", bg_frame);
imshow("cam_frame", cam_frame);
//threshold(motion, motion, 0, 255, CV_THRESH_BINARY|CV_THRESH_OTSU);
imshow("motion", motion);
cvWaitKey(0);
}
#endif
|
C
|
#include "3-calc.h"
#include <stdio.h>
/**
*op_add - sum a and b
*@a: n1
*@b: n2
*Return: the sum of a and b
**/
int op_add(int a, int b)
{
return (a + b);
}
/**
*op_sub - subtraction to a and b
*@a: n1
*@b: n2
*Return: the difference of a and b
**/
int op_sub(int a, int b)
{
return (a - b);
}
/**
*op_mul - multiplicates a and b
*@a: n1
*@b: n2
*Return: the product of a and b
**/
int op_mul(int a, int b)
{
return (a * b);
}
/**
*op_div - divides a and b
*@a: n1
*@b: n2
*Return: the result of the division of a by b
**/
int op_div(int a, int b)
{
return (a / b);
}
/**
*op_mod - division of a by b
*@a: n1
*@b: n2
*Return: the remainder of the division of a by b
**/
int op_mod(int a, int b)
{
return (a % b);
}
|
C
|
#include "util.h"
#include <stdio.h>
#include <string.h>
#include<stdbool.h>
#define MaxSize 100
#define INF 32767
#define MaxV 100
typedef struct
{
int x, y;
//int in;
}node;
typedef struct queue {
int front, rear;
node data[10000];
}queue;
void Init(queue *q) {
q->front = q->rear = -1;
}
void push(queue *q, node e) {
q->rear++;
q->data[q->rear] = e;
}
node pop(queue *q) {
q->front++;
return q->data[q->front];
}
int empty(queue *q) {
return q->rear - q->front;
}
typedef struct ANode //ߵĽڵṹ
{
node no;
double weight;//ñߵյλ(i,j)
struct ANode *nextarc; //ָһߵָ
} ArcNode;
typedef struct Vnode //ڽӱͷڵ
{
ArcNode *firstarc; //ָһڵ
} VNode;
typedef struct
{
VNode adjlist[MaxV][MaxV]; //ڽӱͷڵ
} ALGraph; //ͼڽӱ
typedef struct
{
int i; //ǰк
int j; //ǰк
} Box;
ALGraph* CreateAdj(game_state_t state) //ԹӦڽӱG
{
int i, j, i1, j1, di;
ArcNode *p;
ALGraph* G = (ALGraph *)malloc(sizeof(ALGraph));
for (i = 0; i < state.n; i++) //ڽӱͷڵָóֵ
for (j = 0; j < state.m; j++)
G->adjlist[i][j].firstarc = NULL;
for (i = 0; i < state.n; i++) //mgÿԪ
for (j = 0; j < state.m; j++)
if (state.grid[i][j]==0)
{
di = 0;
while (di < 4)
{
switch (di)
{
case 0:i1 = i - 1; j1 = j; break;
case 1:i1 = i; j1 = j + 1; break;
case 2:i1 = i + 1; j1 = j; break;
case 3:i1 = i, j1 = j - 1; break;
}
if (state.grid[i1][j1]==0) //(i1,j1)Ϊ߷
{
p = (ArcNode *)malloc(sizeof(ArcNode)); //һڵ*p
p->no.x = i1; p->no.y = j1;
p->weight = state.cost[i1][j1];
p->nextarc = G->adjlist[i][j].firstarc; //*pڵ
G->adjlist[i][j].firstarc = p;
}
di++;
}
}
return G;
}
void spfa(ALGraph*G, game_state_t state) {
node start = { state.start_x,state.start_y };
node end = { state.goal_x,state.goal_y };
queue *q = (queue*)malloc(sizeof(queue));
Init(q);
int vis[MaxSize][MaxSize] = { 0 };
double dis[MaxSize][MaxSize];
node fa[MaxSize][MaxSize];
node road[MaxSize],road1[MaxSize];
int cnt = 0;
memset(fa, -1, sizeof(fa));
for (int i = 0; i < state.n; i++) {
for (int j = 0; j < state.m; j++) {
if (i == start.x&&j == start.y) {
dis[i][j] = 0;
}
else {
dis[i][j] = INF;
}
}
}
push(q, start);
vis[start.x][start.y] = 1;
while (empty(q) != 0) {
node out = pop(q);
vis[out.x][out.y] = 0;
ArcNode*p;
p = G->adjlist[out.x][out.y].firstarc;
while (p != NULL) {
node to = p->no;
if (dis[to.x][to.y] == INF || (dis[to.x][to.y]) > (dis[out.x][out.y] + p->weight)) {
dis[to.x][to.y] = dis[out.x][out.y] + p->weight;
fa[to.x][to.y].x = out.x;
fa[to.x][to.y].y = out.y;
if (vis[to.x][to.y] == 0) {
vis[to.x][to.y] = 1;
push(q, to);
}
}
p = p->nextarc;
}
}
int length = 0;
while (fa[end.x][end.y].x != -1 && fa[end.x][end.y].y != -1) {
road[length].x = fa[end.x][end.y].x;
road[length].y = fa[end.x][end.y].y;
end = fa[end.x][end.y];
length++;
}
road1[length].x =state.goal_x ;
road1[length].y = state.goal_y;
int Originlen = length;
int j = 0;
while (length--) {
road1[j] = road[length];
//printf("(%d,%d)->", road1[j].x, road1[j].y);
j++;
}
for (int i = 0; i < Originlen - 1; i++) {
if (road1[i + 1].x - road1[i].x == 1) {
printf("S");
}
else if (road1[i + 1].x - road1[i].x == -1)
{
printf("N");
}else if (road1[i + 1].y - road1[i].y == 1) {
printf("E");
}
else if (road1[i + 1].y - road1[i].y == -1) {
printf("W");
}
}
printf("W");
printf("\n");
}
int main() {
game_state_t state;
memset(&state, 0, sizeof(state));
init(&state);
ALGraph *G = CreateAdj(state);
spfa(G, state);
destroy(&state);
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int B[2][3]={{1,2,3},{4,5,6}};
for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{
printf("B[%d][%d]: %p\n",i,j,&B[i][j]);
}
}
printf("B[0]: %p\n", B[0]);
printf("B[1]: %p\n", B[1]);
printf("B[0][4]: %d\n",B[0][3]);
// printf("%d\n",**B);
// printf("%d\n",B[1][2]);
// printf("%d\n",*(*(B+1)+2));
return 0;
}
|
C
|
/* leins, 24.03.2018 */
#include <stdio.h>
#include <stdlib.h>
#include "left_square.h"
#include "square_gauss.h"
#include "source.h"
#define A -20 //
#define B 20
#define EPS 0.000001 //
int main(void)
{
printf("function: (2 - x^2)*cos(x) + 2*x*sin(x)\n");
printf("Left squares method\n");
printf("I of %d to %d : %lf \n", A, B, Runge(A, B, EPS, &LeftSquare));
printf("Gauss method\n");
printf("I of %d to %d : %lf \n", A, B, Runge(A, B, EPS, &SquareGauss));
getchar();
return 0;
} // end of main
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct No {
int valor;
struct No* esquerda;
struct No* direita;
};
int Altura(struct No* h)
{
if(h == NULL){
return 0;
} else {
int altura_esquerda = Altura(h->esquerda);
int altura_direita = Altura(h->direita);
if(altura_esqueda < altura_direita){
return altura_direita + 1;
} else {
return altura_esquerda + 1;
}
}
}
|
C
|
#include "MovementDirectory-12E.c";
void blueLeft(int delayer)
{
wait1Msec(delayer*1000);
move(127); // move forward for 3 secs
wait1Msec(3000);
move(40); // move slower for 2 secs
Outspeed(87); // start the outtake
wait1Msec(2000);
move(0); // stop
wait1Msec(500); // wait half a second
move(-100); // move backwards for .5 seconds
wait1Msec(500);
move(0); // stop moving
wait1Msec(500); // wait half a second
strafeRight(100); // strafe right for .75 seconds
wait1Msec(750);
strafeRight(0); // stop strafing
wait1Msec(1000); // wait 1 second
Inspeed(127); // start the intake
wait1Msec(500); // begin shhoting cycle
Inspeed(0);
wait1Msec(1000);
Inspeed(127);
wait1Msec(500);
Inspeed(0);
wait1Msec(1000);
Inspeed(127);
wait1Msec(500);
Inspeed(0);
wait1Msec(1000);
Inspeed(127);
wait1Msec(500);
Inspeed(0);
Outspeed(0);
}
void blueRight(int delayer)
{
wait1Msec(delayer*1000);
move(127); // move forward for 3 secs
wait1Msec(3000);
move(40); // move slower for 2 secs
Outspeed(87); // start the outtake
wait1Msec(2000);
move(0); // stop
wait1Msec(500); // wait half a second
move(-100); // move backwards for .5 seconds
wait1Msec(500);
move(0); // stop moving
wait1Msec(500); // wait half a second
strafeRight(-100); // strafe right for .75 seconds
wait1Msec(750);
strafeRight(0); // stop strafing
wait1Msec(1000); // wait 1 second
Inspeed(127); // start the intake
wait1Msec(500); // begin shhoting cycle
Inspeed(0);
wait1Msec(1000);
Inspeed(127);
wait1Msec(500);
Inspeed(0);
wait1Msec(1000);
Inspeed(127);
wait1Msec(500);
Inspeed(0);
wait1Msec(1000);
Inspeed(127);
wait1Msec(500);
Inspeed(0);
Outspeed(0);
}
void redLeft(int delayer)
{
wait1Msec(delayer*1000);
move(127); // move forward for 3 secs
wait1Msec(3000);
move(40); // move slower for 2 secs
Outspeed(87); // start the outtake
wait1Msec(2000);
move(0); // stop
wait1Msec(500); // wait half a second
move(-100); // move backwards for .5 seconds
wait1Msec(500);
move(0); // stop moving
wait1Msec(500); // wait half a second
strafeRight(100); // strafe right for .75 seconds
wait1Msec(750);
strafeRight(0); // stop strafing
wait1Msec(1000); // wait 1 second
Inspeed(127); // start the intake
wait1Msec(500); // begin shhoting cycle
Inspeed(0);
wait1Msec(1000);
Inspeed(127);
wait1Msec(500);
Inspeed(0);
wait1Msec(1000);
Inspeed(127);
wait1Msec(500);
Inspeed(0);
wait1Msec(1000);
Inspeed(127);
wait1Msec(500);
Inspeed(0);
Outspeed(0);
}
void redRight(int delayer)
{
wait1Msec(delayer*1000);
move(127); // move forward for 3 secs
wait1Msec(3000);
move(40); // move slower for 2 secs
Outspeed(87); // start the outtake
wait1Msec(2000);
move(0); // stop
wait1Msec(500); // wait half a second
move(-100); // move backwards for .5 seconds
wait1Msec(500);
move(0); // stop moving
wait1Msec(500); // wait half a second
strafeRight(-100); // strafe right for .75 seconds
wait1Msec(750);
strafeRight(0); // stop strafing
wait1Msec(1000); // wait 1 second
Inspeed(127); // start the intake
wait1Msec(500); // begin shhoting cycle
Inspeed(0);
wait1Msec(1000);
Inspeed(127);
wait1Msec(500);
Inspeed(0);
wait1Msec(1000);
Inspeed(127);
wait1Msec(500);
Inspeed(0);
wait1Msec(1000);
Inspeed(127);
wait1Msec(500);
Inspeed(0);
Outspeed(0);
}
|
C
|
#include<stdio.h>
int main(){
unsigned int n=0;
scanf("%u",&n);
while(n>0){
printf("%u\n",n*(n+1)*(2*n+1)/6);
scanf("%u",&n);
}
return 0;
}
|
C
|
#include<stdio.h>
void main()
{
int a=5,b=10,c;
c=a+b;
scanf("%d",&c);
if(c%2==0)
{
printf("it is even number");
}
else
{
printf("it is odd number");
}
}
|
C
|
#include <stdio.h>
/*
A) The following statement should print the character 'c'.
printf(%s\n", 'c');
Correction:
printf("%c\n", 'c');
B) The following statement should print 9.375%.
printf("%.3f%", 9.375);
Correction:
printf("%.3f\%", 9.375);
C) The following statement should print the first character of the string "Monday".
printf("%c\n", "Monday");
Correction:
printf("%1s\n", 'M');
D) puts(""A string in quotes"");
Correction:
puts("\"A string in quotes\"");
E) printf(%d%d, 12, 20);
Correction:
printf("%d%d", 12, 20);
F) printf("%c", "x");
Correction:
printf("%c", 'x');
G) printf("%s\n", 'Richard');
Correction:
printf("%s\n", "Richard");
*/
int main(void) {
}
|
C
|
#include "queue_utils.h"
void queueInit(struct Queue *q, int size)
{
q->size = size;
q->in = q->out = 0;
}
int queuePut(struct Queue *q, int e)
{
if (q->in == ((q->out - 1 + q->size) % q->size))
{
// Kolejka pełna
return -1;
}
q->items[q->in] = e;
q->in = (q->in + 1) % q->size;
return 0;
}
int queueGet(struct Queue *q)
{
int e = q->items[q->out];
q->out = (q->out + 1) % q->size;
return e;
}
int queueEmpty(struct Queue *q)
{
if (q->in == q->out)
return 1;
return 0;
}
|
C
|
#include "timer.h"
#include "motor.h"
#include "main.h"
#include <stdlib.h>
extern motor_ctrl motor1;
extern motor_ctrl motor2;
/************************************************
Purpose: initalize timers to generate PWM or produce update events at specific time periods
Inputs: TIMx:the hardware timer to configure, ARR_value: the value the timer is to count up to,
PWM_out: whether or not the timer is for PWM
Outputs: None
************************************************/
void TIM_Init(TIM_TypeDef * TIMx, int ARR_value,char PWM_out){
if(PWM_out){
RCC->APB1ENR1 |=RCC_APB1ENR1_TIM2EN; //enable timer for timer 2
}
else{
RCC->APB1ENR1 |=RCC_APB1ENR1_TIM5EN; //enable timer 5
}
TIMx-> CR1=0x84; //disable timer and set it to count up
TIMx->CCER &=~0x11;//disable channels 1 and 2
TIMx-> PSC =799; //set prescale clock to 100khz
TIMx-> ARR =ARR_value; // resets after n miliseconds
if (PWM_out){
TIMx-> CCMR1=0x6868; // set ch1 and ch2 as outputs
TIMx-> CCR1=pos_values[0]+offset; // servo 1 set to move to position zero (1 % duty cycle)
TIMx-> CCR2=pos_values[0]+offset; // servo 2 set to move to position zero (2% duty cycle)
TIMx->CCER |=TIM_CCER_CC1E+TIM_CCER_CC2E; //enable timer channel 1 and 2
}
TIMx->EGR |=0x1;//create update event, loading prescaler
TIMx->CR1|=TIM_CR1_CEN; //start timer
}
/************************************************
Purpose: initalize GPIO pins A0, A1 to serve as CH1 and CH2 for TIM2
Inputs: GPIOx: The PIN bank to initalize
Outputs: None
************************************************/
void TIM_GPIO_Init(GPIO_TypeDef *GPIOx){
RCC->AHB2ENR |= RCC_AHB2ENR_GPIOAEN ; //enable clock for GPIO port A
GPIOx->MODER &=~0x0000000f; // clear mode register for PA1 and PA0
GPIOx->MODER|=0x0000000A; //configure PA0 and PA1 as alternative function
GPIOx->AFR[0]&=~0x0000011; //clear alternative function register for PA0 and PA1
GPIOx->AFR[0]|=0x11; //configure PAO and PA1 with alt function (CHx_timx)
}
/************************************************
Purpose: Sets position of motor to given position if position is legal
Inputs: pos the requested position, motor_number: the motor it is requested for,
user_command: whether or not the position request is from a recipe or directly from the user
Outputs: None
************************************************/
void set_motor_position(int pos, int motor_number, int user_command){
char wait_time=0;
char last_pos=motor1.motor_position;
if(motor_number==1&& 0<=pos && pos<=5){
TIM2->CCR1=pos_values[pos]+offset;
motor1.motor_position=pos;
while(wait_time<(2*abs(pos-last_pos)+1)){
if(TIM5->SR & TIM_SR_UIF){
wait_time++;
}
}
}
//if within range.
else if(motor_number==2 && 0<=pos && pos<=5){
TIM2->CCR2=pos_values[pos]+offset;
motor2.motor_position=pos;
//wait at minimum two hundred miliseconds for each position it has to move through
//from its current position to the end position.
while(wait_time<(2*abs(pos-last_pos)+1)){
if(TIM5->SR & TIM_SR_UIF){
wait_time++;
}
}
}
//if out of range position comming from a recipe and not a user command
//set an error state.
else if(motor_number==1 && user_command==0){
motor1.error_state=command_error;
return;
}
//if out of range position comming from a recipe and not a user command
//set an error state.
else if(motor_number==2 && user_command==0){
motor2.error_state=command_error;
return;
}
}
|
C
|
#include <malloc.h>
#include <stdlib.h>
struct A
{
int array[10];
int x;
};
int main(int argc, char *argv[])
{
struct A *a = (char *)malloc(sizeof(struct A));
if (a == NULL)
return (0);
int index = atoi(argv[0]);
//if (index > 10)
//return (0);
a->array[index] = 0;
return 0;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
<<<<<<< HEAD
ǵݹ
int main()
{
int fir = 1;
int sec = 1;
int next = 0;
int n = 0;
printf("input the number:");
scanf("%d", &n);
if (n <= 2)
printf("the number is %d\n", fir);
else
{
for (int i = 2; i < n; i++)
{
next = fir + sec;
fir = sec;
sec = next;
}
printf("the number is %d\n", next);
}
system("pause");
return 0;
}
ݹ
int fibonacci_sequence(int number)
{
if (number <= 2)
return 1;
else
return fibonacci_sequence(number - 2) +fibonacci_sequence(number - 1);
}
int main()
{
int n = 0;
printf("input the number:");
scanf("%d", &n);
printf("the number is %d\n", fibonacci_sequence(n));
system("pause");
return 0;
}
=======
//ǵݹ
//int main()
//{
// int fir = 1;
// int sec = 1;
// int next = 0;
// int n = 0;
// printf("input the number:");
// scanf("%d", &n);
// if (n <= 2)
// printf("the number is %d\n", fir);
// else
// {
// for (int i = 2; i < n; i++)
// {
// next = fir + sec;
// fir = sec;
// sec = next;
// }
// printf("the number is %d\n", next);
// }
// system("pause");
// return 0;
//}
//ݹ
//int fibonacci_sequence(int number)
//{
// if (number <= 2)
// return 1;
// else
// return fibonacci_sequence(number - 2) +fibonacci_sequence(number - 1);
//}
//int main()
//{
// int n = 0;
// printf("input the number:");
// scanf("%d", &n);
// printf("the number is %d\n", fibonacci_sequence(n));
// system("pause");
// return 0;
//}
>>>>>>> f667580587c8ca35c3998cc49cc227872ae50cc1
|
C
|
#include "garbler.h"
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <netdb.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <ctype.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define _GNU_SOURCE
//****************************STRUCTS GLOBAIS****************************
struct Enlaces{
int id_src;
int id_dst;
char mtu[6];
};
struct Nos {
int id;
char ip[16];
char porta[6];
};
struct Dados{
int no_destino;
char ip_dst[16];
char port_dst[6];
char ip_src[16];
char port_src[6];
char data[32];
};
//****************************VARIAVEIS GLOBAIS****************************
struct Nos noh[6]; //maximo de 6 n�s
struct Enlaces enlace[18]; //maximo de 3 enlaces por n� (3x6)
struct Dados dados;
// variaveis globais
int soma;
pthread_t aux;
int resp = 0;
char nome_arq[25]="";
int no_destino=0;
char ip[16]="";
char port[6]="";
char mensagem[20]="";
int id = 0;
int nohh =0;
int ok = 0;
int n_nos = 0;
int n_enlaces = 0;//numero nos e enlaces
char buf[32];
char bufferr[32];
//****************************FUNCOES AUXILIARES****************************
void enviar_mensagem()
{
// variaveis importantes
int s,server_address_size;
unsigned short portt;
// estrutura server do tipo sockaddr_in
struct sockaddr_in server;
// buffer que armazena a string que contem a chamada
int i;
int k;
int l;
char c;
int mtu;
portt = htons(atoi(dados.port_dst));
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("socket()");
exit(1);
}
/* Define o endereço IP e a porta do servidor */
server.sin_family = AF_INET; /* Tipo do endereço */
server.sin_port = portt; /* Porta do servidor */
server.sin_addr.s_addr = inet_addr(dados.ip_dst); /* Endereço IP do servidor */
//printf("\n\nBUFF: %s",buf);
server_address_size = sizeof(server);
for (k = 0; k < (strlen(buf)); k++)
{
l = buf[k];
soma += l;
}
// printf("soma %d\n",soma);
// sizeof(server) envia o tamanho da estrutura server
//if (sendto(s, buf, sizeof(buf)+1, 0, (struct sockaddr *)&server, sizeof(server)) < 0)
if (sendto_garbled(s, buf, sizeof(buf)+1,0,(struct sockaddr *)&server,sizeof(server)) < 0)
// caso ocorra algum problema, o retorno sera -1 e printa a mensagem senao envia a msg
{
perror("sendto()");
exit(2);
}
}
void *receber_mensagem()
{
int sockint,s, namelen, client_address_size;
struct sockaddr_in client, server;
int k = 0;
int somalocal = 0;
int l;
unsigned short portt;
portt = htons(atoi(noh[nohh-1].porta));
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("socket()");
exit(1);
}
server.sin_family = AF_INET; /* Tipo do endereço */
server.sin_port = portt; /* Escolhe uma porta disponível */
server.sin_addr.s_addr = inet_addr(noh[nohh-1].ip);/* Endereço IP do servidor */
if (bind(s, (struct sockaddr *)&server, sizeof(server)) < 0)
{
perror("bind()");
exit(1);
}
/* Consulta qual porta foi utilizada. */
if (getsockname(s, (struct sockaddr *) &server, &namelen) < 0)
{
perror("getsockname()");
exit(1);
}
namelen = sizeof(server);
/* Imprime qual porta foi utilizada. */
client_address_size = sizeof(client);
while(1)
{
if(recvfrom(s, buf, sizeof(buf)+1, 0, (struct sockaddr *) &client,&client_address_size) < 0)
{
perror("recvfrom()");
exit(1);
}
else
{
printf("Recebida a mensagem %s do endereço IP %s da porta %d\n",buf,inet_ntoa(client.sin_addr),ntohs(server.sin_port));
somalocal = 0;
for (k = 0; k < (strlen(buf)); k++)
{
l = buf[k];
somalocal += l;
}
if(somalocal == soma)
{
printf("checksum feito com sucesso\n");
}
else
printf("falha no checksum...\n");
}
}
}
void new_delim(char str[], int tam)//funcao para delimitar ip, e porta;
{
int i;
for(i=0;i<tam;i++)
{
if(str[i]==',' || str[i]==';')
{
str[i]='\0';
break;
}
}
}
int iniciar_programa(char *arquivo, char *no)
{
strcpy(nome_arq,arquivo);
nohh = atoi(no);
int ret;
printf("\n\n--------------------PROJETO REDES 2--------------------");
printf("\n\nArquivo de configuracao: %s\n", nome_arq);
printf("Noh atual: %d\n\n", nohh);
ret = ler_arquivo();
return ret;
}
int validar_id()
{
int i,novo=0;
ok = 0;
for (i = 0 ; i < n_nos; i++)
{
if(noh[i].id == nohh)
{
strcpy(port, noh[i].porta);
strcpy(ip, noh[i].ip);
ok++;
pthread_create (&aux, NULL, (void* ) &receber_mensagem, NULL); // nivel enlace
return 1;
}
}
if(ok == 0)
{
printf("\n\nNoh digitado nao existe no arquivo de conf.\nDigitar noh valido:");
return 0;
}
}
int descobrir_id(char ip2[], char port2[])
{
int i;
for(i=0;i<n_nos;i++)
{
if(!strcmp(noh[i].ip,ip2)) //IPs bateram
if(!strcmp(noh[i].porta,port2)) //Portas bateram
return noh[i].id; //retorna id
}
return 0; //id nao existe
}
int validar_mtu(char ip[], char port[])
{
int i;
for(i=0;i<n_enlaces;i++)//verifica rfligacao 1 -> 2 ou 2 -> 1
{
if(enlace[i].id_src == nohh) //encontrou meu id
{
if(enlace[i].id_dst == descobrir_id(ip, port)) //encontrou destino valido
{
return atoi(enlace[i].mtu);
}
}
if(enlace[i].id_dst == nohh) //encontrou meu id
{
if(enlace[i].id_src == descobrir_id(ip, port)) //encontrou origem valida
{
return atoi(enlace[i].mtu); //retorna o mtu
}
}
}
return 0; //nao existe enlace entre os nohs
}
void limpa(char str[])//limpa string
{
int i;
for(i=0;i<sizeof(str);i++)
str[i]='\0';
}
//****************************FUNCOES PRINCIPAIS****************************
int ler_arquivo()
{
FILE* fp;
char buffer[16];
char limpa[16]=" ";
int i,j;
int resp;
fp = fopen(nome_arq, "r");
fscanf(fp,"%s",buffer);
buffer[strlen(buffer)+1] = '\0';
printf("--------informacao dos nos--------\n\n");
if(!strcmp(buffer, "Nos") || !strcmp(buffer, "Nós"))
{
for(i=0;i<6;i++)
{
strcpy(buffer,limpa);//limpa o buffer
fscanf(fp, "%s", buffer); //le id da maquina ou "enlaces"
if(!strcmp(buffer,"Enlaces"))
break;//condicao de parada dos nos
noh[i].id = atoi(buffer);
for(j=0; j<2; j++)
{
fscanf(fp, "%s", buffer);
}//pula "IP" e "="
strcpy(buffer,limpa);//limpa o buffer
fscanf(fp, "%s", buffer);//le valor IP
strcpy(noh[i].ip, buffer);
new_delim(noh[i].ip,16);
for(j=0; j<2; j++)
{
fscanf(fp, "%s", buffer);
}//pula "Porta" e "="
strcpy(buffer,limpa);//limpa o buffer
fscanf(fp, "%s", buffer);//le valor porta
strcpy(noh[i].porta, buffer);
new_delim(noh[i].porta,6);
printf("ID: %d\nIP: %s\nPORTA: %s\n\n",noh[i].id,noh[i].ip,noh[i].porta);
n_nos++;
}
}
if(n_nos == 6)
fscanf(fp, "%s", buffer);//se houver 6 nos deve se forcar o if-case de "enlaces"
printf("--------relacao de enlaces--------\n\n");
if(!strcmp(buffer, "Enlaces"))
{
for(i=0;i<18;i++)
{
strcpy(buffer,limpa);
fscanf(fp, "%s", buffer); //id src
if(!strcmp(buffer,"Fim"))
break;
enlace[i].id_src = atoi(buffer);
fscanf(fp, "%s", buffer);//pula "->"
strcpy(buffer,limpa);
fscanf(fp, "%s", buffer);//id dst
enlace[i].id_dst = atoi(buffer);
for(j=0; j<2; j++)
{
fscanf(fp, "%s", buffer);
}//pula "MTU" e "="
strcpy(buffer,limpa);
fscanf(fp, "%s", buffer);//le valor MTU
strcpy(enlace[i].mtu, buffer);
new_delim(enlace[i].mtu,6);//mtu precisa ser char para rodar na funcao new_delim
printf("SOURCE: %d\nDESTINATION: %d\nMTU: %s\n\n",enlace[i].id_src,enlace[i].id_dst,enlace[i].mtu);
n_enlaces++;
}
}
fclose(fp);
resp = validar_id();
}
void entrada_usuario(int no_destino, char bufferr[])
{
int i;
int mtu;
strcpy(buf,bufferr);
for(i = 0; i< n_nos; i++)
{
if(noh[i].id == nohh){//obtenho o ip e a porta origem
strcpy(dados.ip_src,noh[i].ip);
strcpy(dados.port_src,noh[i].porta);
printf("IP origem %s e porta origem %s\n", dados.ip_src, dados.port_src);
}
if(noh[i].id == no_destino){//obtenho o ip e a porta destino relacionados ao no digitado
strcpy(dados.ip_dst,noh[i].ip);
strcpy(dados.port_dst,noh[i].porta);
printf("IP destino %s e porta destino %s\n", dados.ip_dst, dados.port_dst);
}
}
mtu = validar_mtu(dados.ip_dst,dados.port_dst);
if(mtu == 0)
{
printf("Nao existe enlace entre os nohs.\nDescartando pacote...\n");
exit(0);
}
else
{
//pthread_create (&aux, NULL, receber_mensagem, NULL);
enviar_mensagem();
}
}
|
C
|
#include <stdlib.h>
#include "lista.h"
struct lista{
int info;
struct lista* prox;
};
Lista* criar_lista(){
return NULL;
}
Lista* inserir_list(Lista* l, int i){
Lista* novo = (Lista*)malloc(sizeof(Lista));
novo->info =i;
novo->prox = l;
return novo;
}
void imprimir_lista(Lista* l){
Lista* p;
for(p = l; p!= NULL; p = p->prox)
printf("%d\n", p->info);
}
Lista* buscar(Lista* l, int v){
Lista* p;
for(p = l; p!= NULL; p = p->prox){
if(p->info == v)
return p;
}
return NULL;
}
int vazia(Lista* l){
if(l == NULL)
return 1;
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* list_utils3.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cclaude <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/07/09 15:26:10 by cclaude #+# #+# */
/* Updated: 2021/09/08 20:01:09 by cclaude ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
int list_index_of(t_node *lst, int val)
{
t_node *nd;
int i;
nd = lst->next;
i = 0;
while (nd != lst && nd->data != val)
{
nd = nd->next;
i++;
}
return (i);
}
int list_value_at(t_node *lst, int index)
{
t_node *nd;
int i;
nd = lst->next;
i = 0;
while (i < index)
{
nd = nd->next;
i++;
}
return (nd->data);
}
int list_value_around(t_node *lst, int mode, int value)
{
t_node *nd;
int under;
int above;
nd = lst->next;
under = INT_MIN;
above = INT_MAX;
while (nd != lst)
{
if (nd->data < value && nd->data > under)
under = nd->data;
if (nd->data > value && nd->data < above)
above = nd->data;
nd = nd->next;
}
if (mode == ABOVE)
return (above);
else
return (under);
}
int list_max(t_node *lst)
{
t_node *nd;
int max;
nd = lst->next;
max = INT_MIN;
while (nd != lst)
{
if (nd->data > max)
max = nd->data;
nd = nd->next;
}
return (max);
}
int list_min(t_node *lst)
{
t_node *nd;
int min;
nd = lst->next;
min = INT_MAX;
while (nd != lst)
{
if (nd->data < min)
min = nd->data;
nd = nd->next;
}
return (min);
}
|
C
|
#include "stdio.h"
int main ()
{
char ch[100],last;
int i;
scanf("%s",ch);
for(i=0;i<=99;i++)
{
if(ch[i]=='\0')
{
printf("%c",ch[i-1]);
break;
}
}
}
|
C
|
/* Continúa agregando funciones al ejercicio anterior que permitan:
a) Calcular y emitir la suma de sus elementos.
b) Calcular y emitir el mínimo del vector.
c) Calcular y emitir el promedio de los valores del vector
d) Emitir los valores de aquellos que superaron ese promedio.
e) Emitir los valores del vector que son múltiplos del último número ingresado en el mismo.
f) Emitir el valor máximo e indicar la cantidad de veces que apareció y el número de orden en
que fue ingresado.
g) Emitir los valores que son pares.
h) Emitir los valores que son impares.
i) Emitir aquellos que estén ubicados en posición par.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define DIM 10
void store(int numbers[]);
int find(int numbers[], int* searchFor);
int countOccurrences(int numbers[], int* match);
void reverse(int numbers[], int right);
int sum(int numbers[]);
int lowest(int numbers[]);
float mean(int numbers[]);
void higherEnd(int numbers[]);
void findMutiples(int numbers[]);
void highest(int numbers[]);
void even(int numbers[]);
void odd(int numbers[]);
void evenPosition(int numbers[]);
int main() {
int numbers[DIM] = {0};
int occurrence = 0;
int searchFor = 0;
int matches = 0;
int match = 0;
int option = 0;
printf(" Welcome.\n");
do {
system("cls");
printf("\n Please, select an option:");
printf("\n 1. Enter numbers into the 'numbers' array");
printf("\n 2. Find the first ocurrence of a number inside the array");
printf("\n 3. Find the number of occurrences of a number inside the array");
printf("\n 4. Reverse all numbers in the array");
// ---------------NEW FUNCTIONS-------------------------------
printf("\n 5. Find the sum of all the elements in the array");
printf("\n 6. Find the lowest number in the array");
printf("\n 7. Find the mean for the elements in the array");
printf("\n 8. Find the numbers higher than the mean");
printf("\n 9. Look for multiples of the last number inside the array");
printf("\n 10. Find the highest number in the array");
printf("\n 11. Print all even numbers inside the array");
printf("\n 12. Print all odd numbers inside the array");
printf("\n 13. Print all numbers in an even position inside the array");
printf("\n 14. Exit\n ");
scanf("%d", &option);
fflush(stdin);
switch (option) {
case 1:
store(&numbers); //-------------------STORE NUMBERS---------------
system("cls");
printf("\n The stored array 'numbers' looks like this:\n");
printf(" [");
for (int i = 0; i < DIM; i++){
printf("%d", numbers[i]);
if(i<DIM-1){
printf(", ");
}
};
printf("]\n\n\n\n");
system("pause");
system("cls");
break;
case 2:
system("cls");
occurrence = find(numbers, &searchFor);//------------------FIND NUMBER----------------
if(occurrence > -1){
printf("\n The first ocurrence of %d appears after %d numbers at numbers[%d]\n\n", searchFor, occurrence, occurrence);
} else {
printf("\n There are no coincidences for %d inside of 'numbers' array.\n\n", searchFor);
};
system("pause");
system("cls");
break;
case 3:
system("cls");
matches = countOccurrences(numbers, &match);//------------------OCCURRENCE OF NUMBER----------------
if(matches > 0){
printf("\n The number %d appears %d times inside of 'numbers' array.\n\n", match, matches);
} else {
printf("\n There are no coincidences for %d inside of 'numbers' array.\n\n", match);
};
system("pause");
system("cls");
break;
case 4:
system("cls");
reverse(&numbers, DIM-1);//---------------REVERSE NUMBERS-------------------
printf("\n The rearranged array 'numbers' looks like this now:\n");
for (int i =0; i < DIM; i++){
printf("%d\n", numbers[i]);
};
printf("\n\n\n\n");
system("pause");
system("cls");
break;
case 5:
printf("The sum of all the elements in the array is %d", sum(numbers));
printf("\n\n\n\n");
system("pause");
system("cls");
break;
case 6:
printf("The lowest number in the array is %d", lowest(numbers));
printf("\n\n\n\n");
system("pause");
system("cls");
break;
case 7:
printf("The mean for the elements in the array is %.2f", mean(numbers));
printf("\n\n\n\n");
system("pause");
system("cls");
break;
case 8:
higherEnd(numbers);
break;
case 9:
findMutiples(numbers);
break;
case 10:
highest(numbers);
break;
case 11:
even(numbers);
break;
case 12:
odd(numbers);
break;
case 13:
evenPosition(numbers);
break;
case 14: //Exit
break;
default:
system("cls");
printf("\n Invalid option.\n\n\n\n");
system("pause");
system("cls");
break;
};
} while (option != 14);
system("pause");
return 0;
};
void store(int numbers[]) {
system("cls");
printf("\n Please, enter the numbers:\n ");
for (int i =0; i < DIM; i++){
scanf("%d", &numbers[i]);
fflush(stdin);
};
};
int find(int numbers[], int *searchFor){
printf("\n Please, enter a number to search for its first ocurrence of.\n ");
scanf("%d", searchFor);
fflush(stdin);
for (int i =0; i < DIM; i++){
if (numbers[i] == (*searchFor)){
return i;
};
};
return -1;
};
int countOccurrences(int numbers[], int* match){
int matches = 0;
printf("\n Please, enter a number to search for all the instances of its ocurrence within numbers array.\n ");
scanf("%d", match);
fflush(stdin);
for (int i =0; i < DIM; i++){
if (numbers[i] == (*match)){
matches++;
};
};
return matches;
};
void reverse(int numbers[], int right) {
int left = 0;
while (left < right){
int temp = numbers[left];
numbers[left] = numbers[right];
left++;
numbers[right] = temp;
right--;
};
};
int sum(int numbers[]) {
int sum = 0;
for (int i =0; i < DIM; i++){
sum += numbers[i];
};
return sum;
};
int lowest(int numbers[]){
int lowest = numbers[0];
for (int i =0; i < DIM; i++){
if(lowest > numbers[i]){
lowest = numbers[i];
};
};
return lowest;
};
float mean(int numbers[]){
int sumAux = sum(numbers);
float mean = (float)sumAux/(float)DIM;
return mean;
};
void higherEnd(int numbers[]) {
float meanAux = mean(numbers);
int none = 1;
printf("\n The numbers higher than the mean of the array are:\n");
for (int i =0; i < DIM; i++){
if(((float)numbers[i]) > meanAux){
none--;
printf("%d ", numbers[i]);
};
};
if (none == 1){
printf("None. Therefore, all numbers inside the array must be the same.");
};
printf("\n\n\n\n");
system("pause");
system("cls");
};
void findMutiples(int numbers[]){
int none = 1;
printf("\n The numbers multiple of %d inside the array are:\n", numbers[DIM-1]);
if(numbers[DIM-1] != 0) {
for (int i =0; i < DIM; i++){
if(numbers[i]%numbers[DIM-1] == 0){
none--;
printf("%d ", numbers[i]);
};
};
};
if (none == 1){
printf("None.");
};
printf("\n\n\n\n");
system("pause");
system("cls");
};
void highest(int numbers[]){
int occurrence = 0;
int highest = numbers[0];
int highestIndex = 0;
for (int i =0; i < DIM; i++){
if(highest < numbers[i]){
highest = numbers[i];
highestIndex = i;
occurrence = 1;
} else if(highest == numbers[i]){
occurrence++;
};
};
printf("The highest number in the array is %d with position %d.\n", highest, highestIndex);
printf("It appears %d times.\n", occurrence);
printf("\n\n\n\n");
system("pause");
system("cls");
};
void even(int numbers[]){
int none = 1;
printf("\n The even numbers inside the array are:\n");
for (int i =0; i < DIM; i++){
if(numbers[i]%2 == 0){
none--;
printf("%d ", numbers[i]);
};
if (none == 1){
printf("None.");
};
};
printf("\n\n\n\n");
system("pause");
system("cls");
};
void odd(int numbers[]){
int none = 1;
printf("\n The odd numbers inside the array are:\n");
for (int i =0; i < DIM; i++){
if(numbers[i]%2 != 0){
none--;
printf("%d ", numbers[i]);
};
};
if (none == 1){
printf("None.");
};
printf("\n\n\n\n");
system("pause");
system("cls");
};
void evenPosition(int numbers[]){
printf("\n The numbers on an even position inside the array are:\n");
for (int i =0; i < DIM; i+=2){
printf("%d ", numbers[i]);
};
printf("\n\n\n\n");
system("pause");
system("cls");
};
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<signal.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<ctype.h>
int status = 1;
int exitf(void){
return 0;
}
char **splitf(char *argv){
int index =0;
const char s[10] = " \t\r\n\a";
char **line = malloc(sizeof(char*)*256);
char *word;
word = strtok(argv,s);
while( word != NULL ){
line[index]= word;
index++;
word = strtok(NULL, s);
}
line[index] = NULL;
return line;
}
char *readf(void){
char *line = NULL;
ssize_t bufsize = 0;
getline(&line, &bufsize, stdin);
return line;
}
int processf(char **argv){
int status;
pid_t pid = fork();
if (pid < -1) {
printf("Error, cannot fork\n");
} else if (pid == 0) {
//printf("[C] I am the child\n");
execvp(argv[0], argv);
printf("icsh: command not found: %s\n", argv[0]);
} else {
//printf("[P] I'm waiting for my child\n");
wait(&status);
if (WIFEXITED(status)) {
int exit_status = WEXITSTATUS(status);
printf("Exit status of the child was %d\n", exit_status);
}
}
return 9;
}
int executef(char **argv){
if (argv[0] == NULL) {
return 1;
}
if(strcmp(argv[0], "exit") == 0){
return exitf();
}
//if(argv[0] == "echo" && argv[1] == "$?"){
if(strcmp(argv[0],"echo") == 0 && strcmp(argv[1], "$?") == 0){
printf("%d\n",status);
return 1;
}
return processf(argv);
}
void ctrlcf(){
;
}
// void ctrlzFunction(){
// ;
// }
void icshLoop(){
// print loop icsh> here
while(status){
signal(SIGINT, ctrlcf);
// signal(SIGSTOP, ctrlzFunction);
printf("icsh> ");
char *read = readf();
char **split = splitf(read);
status = executef(split);
}
//echo
//background & foreground
// terminate foreground ctrl c seperate pid group and kill the group
}
int main(void){
icshLoop();
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SYMBOLS 256
#define MAX_LEN 256
struct tnode
{
struct tnode* left; /*used when in tree*/
struct tnode*right; /*used when in tree*/
int isleaf;
unsigned char symbol;
};
/*global variables*/
struct tnode* root = NULL; /*tree of symbols*/
unsigned long int streamLength;
unsigned int remainCountBS;
char bufferBS;
/*
@function talloc
@desc allocates new node
*/
struct tnode* talloc()
{
struct tnode* p = (struct tnode*)malloc(sizeof(struct tnode));
if (p != NULL)
{
p->left = p->right = NULL;
p->symbol = 0;
p->isleaf = 0;
}
return p;
}
/*
@function build_tree
@desc builds the symbol tree given the list of symbols and code.h
NOTE: alters the global variable root that has already been allocated in main
*/
void build_tree(FILE* fp)
{
//int symbol;
unsigned char strcode[MAX_LEN];
//int items_read;
int i, j, k, l, len;
struct tnode* curr = NULL;
unsigned short entry_count = 0;
unsigned char character_symbol = 0;
unsigned char bitstream_length = 0;
unsigned char bitstream_index = 0;
unsigned char bitstream_length_byte = 0;
unsigned char bitstream_token = 0;
fread_s(&entry_count, sizeof(unsigned short), sizeof(unsigned short), 1, fp);
for (i = 0; i < entry_count; i++) {
fread_s(&character_symbol, sizeof(unsigned char), sizeof(unsigned char), 1, fp);
fread_s(&bitstream_length, sizeof(unsigned char), sizeof(unsigned char), 1, fp);
fread_s(&bitstream_length_byte, sizeof(unsigned char), sizeof(unsigned char), 1, fp);
bitstream_index = 0;
//debug
//printf("[%c] length %d, length_byte %d\n", character_symbol, bitstream_length, bitstream_length_byte);
//debug
for (j = 0; j < bitstream_length_byte; j++) {
fread_s(&bitstream_token, sizeof(unsigned char), sizeof(unsigned char), 1, fp);
if (bitstream_length >= 8) {
l = 8;
bitstream_length -= 8;
}
else {
l = bitstream_length % 8;
}
for (k = 0; k < l; k++) {
if (bitstream_token & 128)
strcode[bitstream_index] = '1';
else
strcode[bitstream_index] = '0';
bitstream_token <<= 1;
bitstream_index++;
}
//debug
//printf("%s\n", strcode);
//debug
}
strcode[bitstream_index] = 0;
//debug
printf("%d %s\n", character_symbol, strcode);
//debug
//if (items_read != 2) break;
curr = root;
len = strlen(strcode);
for (j = 0; j < len; j++)
{
/*TODO: create the tree as you go*/
if (strcode[j] == '0') {
//ʿ ̹ ڽ ֳ ˻Ѵ
if (curr->left == NULL) {
//ʿ ڽ ٰ ǴܵǸ ο Ƶд
curr->left = talloc();
}
//Ŀ ڽ ű
curr = curr->left;
}
else if (strcode[j] == '1') {
//ʿ ̹ ڽ ֳ ˻Ѵ
if (curr->right == NULL) {
//ʿ ڽ ٰ ǴܵǸ ο Ƶд
curr->right = talloc();
}
//Ŀ ڽ ű
curr = curr->right;
}
}
/*assign code*/
curr->isleaf = 1;
curr->symbol = character_symbol;// symbol;
}
}
/*
function decode
*/
void decode(FILE* fin, FILE* fout)
{
int c;
struct tnode* curr = root;
while ((c = getc(fin)) != EOF)
{
/*TODO:
traverse the tree
print the symbols only if you encounter a leaf node
*/
if (c == '0') {
curr = curr->left;
}
else if (c == '1') {
curr = curr->right;
}
if (curr->isleaf) {
fwrite(&(curr->symbol), sizeof(unsigned char), 1, fout);
curr = root;
}
}
}
void printBit(char c) {
int m, i;
putc('b', stdout);
for (i = 7; i >= 0; i--) {
m = 1 << i;
if ((c & m) == 0) {
putc('0', stdout);
}
else {
putc('1', stdout);
}
}
}
void openBS(FILE* fin) {
fread_s(&streamLength, sizeof(unsigned long int), sizeof(unsigned long int), 1, fin);
remainCountBS = 0;
//debug
printf("streamLength : %lu\n", streamLength);
//debug
}
int readBS(FILE* fin) {
int result;
if (remainCountBS == 0) {
if (feof(fin)) {
//debug
printf("End of File\n");
//debug
return EOF;
}
else {
fread_s(&bufferBS, sizeof(char), sizeof(char), 1, fin);
}
remainCountBS = 8;
}
result = bufferBS & (1 << 7);
bufferBS <<= 1;
remainCountBS--;
if (result)
return '1';
else
return '0';
}
/*
function decode_bin
*/
void decode_bin(FILE* fin, FILE* fout)
{
int c;
struct tnode* curr = root;
openBS(fin);
while ((c = readBS(fin)) != EOF)
{
/*TODO:
traverse the tree
print the symbols only if you encounter a leaf node
*/
if (c == '0') {
curr = curr->left;
}
else if (c == '1') {
curr = curr->right;
}
if (curr->isleaf) {
fwrite(&(curr->symbol), sizeof(unsigned char), 1, fout);
curr = root;
streamLength--;
}
if (!streamLength) {
//debug
printf("End of Processing\n");
//debug
break;
}
}
}
/*
@function freetree
@desc cleans up resources for tree
*/
void freetree(struct tnode* root)
{
if (root == NULL)
return;
freetree(root->right);
freetree(root->left);
free(root);
}
int main(int argc, char** argv)
{
char INPUT_FILE[256];
char CODE_FILE[256];
char OUTPUT_FILE[256];
if (argc < 4) {
printf("USAGE : %s file_to_decompress code_file target_file", argv[0]);
return 0;
}
else {
strcpy_s(INPUT_FILE, _countof(INPUT_FILE), argv[1]);
strcpy_s(CODE_FILE, _countof(CODE_FILE), argv[2]);
strcpy_s(OUTPUT_FILE, _countof(OUTPUT_FILE), argv[3]);
}
FILE* fin;
FILE* fcode;
FILE* fout;
/*allocate root*/
root = talloc();
fopen_s(&fcode, CODE_FILE, "rb");
/*build tree*/
//debug
printf("A\n");
//debug
build_tree(fcode);
//debug
printf("B\n");
//debug
fclose(fcode);
/*decode*/
fopen_s(&fin, INPUT_FILE, "rb");
fopen_s(&fout, OUTPUT_FILE, "wb");
//debug
printf("C\n");
//debug
decode_bin(fin, fout);
//debug
printf("D\n");
//debug
fclose(fin);
fclose(fout);
/*cleanup*/
freetree(root);
return 0;
}
|
C
|
#include "blacksmithing.h"
t_piece *piece_create(char type, char x, char y)
{
t_piece *piece;
char *types;
types = "1234RBKQ";
if (!ft_strchr(types, (int)type))
return (NULL);
piece = (t_piece *)ft_memalloc(sizeof(t_piece));
if (piece)
{
piece->layer = FIRST_LAYER;
piece->type = type;
piece->location = ft_pos_create(x, y);
piece->moves = NULL;
}
return (piece);
}
t_list *get_piece_moves(t_piece *piece, t_board *board)
{
t_list **moves;
t_piece *tmp;
char x;
char y;
if (!piece || !board)
return (NULL);
x = piece->location->x;
y = piece->location->y;
tmp = NULL;
switch (piece->type)
{
case '1':
tmp = get_piece_at_pos(UP);
ft_lstappend(moves, tmp, 1);
tmp = get_piece_at_pos(DOWN);
ft_lstappend(moves, tmp, 1);
tmp = get_piece_at_pos(LEFT);
ft_lstappend(moves, tmp, 1);
tmp = get_piece_at_pos(RIGHT);
ft_lstappend(moves, tmp, 1);
tmp = get_piece_at_pos(UP_LEFT);
ft_lstappend(moves, tmp, 1);
tmp = get_piece_at_pos(UP_RIGHT);
ft_lstappend(moves, tmp, 1);
tmp = get_piece_at_pos(DOWN_LEFT);
ft_lstappend(moves, tmp, 1);
tmp = get_piece_at_pos(DOWN_RIGHT);
ft_lstappend(moves, tmp, 1);
case '2':
case '3':
case '4':
case 'R':
case 'B':
case 'K':
case 'Q':
default:
}
}
|
C
|
#include "main.h"
/**
* clear_bit - at a particular index change bit to 1
* @n: value to be converted
* @m: counts bits
*
* Return: formated n
*/
unsigned int flip_bits(unsigned long int n, unsigned long int m)
{
n ^= (1 << m);
return ((unsigned int)n);
}
|
C
|
#include <stdio.h>
int main() {
int entrada, saida;
while (scanf("%d", &entrada) != EOF){
saida = entrada - 1;
printf("%d\n", saida);
}
return 0;
}
|
C
|
#include "mysocket.h"
#include "serverio.h"
int main(int argc, char *argv[]) {
int socket_fd, new_socket_fd, file_fd;
in_port_t server_port;
struct sockaddr_in server_addr, client_addr;
socklen_t client_addr_len;
size_t block_size;
char pathname[MAX_FILE_NAME_SIZE];
pid_t k;
char control_message, *block_buf;
int ret;
if (argc != 3) {
// if the number of arguments is not 2, terminate
fprintf(stderr, "usage: %s <blocksize> <srv-port>\n", argv[0]);
fflush(stderr);
exit(1);
}
// get the block_size
block_size = atoi(argv[1]);
//if blocksize exceeds MAXBUFSZM, set to MAXBUFSZM
if (block_size > MAXBUFSZM)
block_size = MAXBUFSZM;
if ((server_port = (in_port_t) atoi(argv[2])) == 0) {
// if the format of given port number is error, terminate
fprintf(stderr, "server port number format error; terminating...\n");
fflush(stderr);
exit(1);
}
// create a socket file descriptor
socket_fd = create_socket(AF_INET, SOCK_STREAM, 0);
// initialize the server address data structure
memset((void *) &server_addr, 0, sizeof(server_addr));
// use the Internet protocol v4 addresses
server_addr.sin_family = AF_INET;
// server_ip_addr binds any IPv4 address
server_addr.sin_addr.s_addr = htons(INADDR_ANY);
// assign the server port number
server_addr.sin_port = htons(server_port);
// bind the socket with server address data structure
bind_socket(socket_fd, (const struct sockaddr *) &server_addr, sizeof(server_addr));
fprintf(stderr, "bind completed\n");
fflush(stderr);
// mark the server socket as a passive socket
listen_socket(socket_fd, 5);
while (1) {
// accept a new client request
memset((void *) &client_addr, 0, sizeof(client_addr));
client_addr_len = sizeof(client_addr);
new_socket_fd = accept_socket(socket_fd, (struct sockaddr *) &client_addr, &client_addr_len);
fprintf(stderr, "\n[INFO] request received from client %s:%d\n",
inet_ntoa(client_addr.sin_addr),
ntohs(client_addr.sin_port));
fflush(stderr);
// fork a new child
k = fork();
if (k == 0) {
// child code
// close the server listening socket file descriptor
close(socket_fd);
// read the pathname from full duplex socket
get_pathname(pathname, new_socket_fd);
// try to open this file
file_fd = open((const char *) pathname, O_RDONLY);
if (file_fd == -1) {
// open error; it might be "No such file or directory"
perror("open()");
fprintf(stderr, "the request to open file [%s] is failed\n", pathname);
fflush(stderr);
// set the control message to '0' and send it
control_message = '0';
write_to_socket(new_socket_fd, (const char *) &control_message, 1);
close(new_socket_fd);
return 0;
}
if (get_file_size((const char *) pathname) == 0) {
// if the file is empty
// set the control message to '1' and send it
control_message = '1';
write_to_socket(new_socket_fd, (const char *) &control_message, 1);
close(new_socket_fd);
return 0;
}
// otherwise
// set the control message to '2' and send it
control_message = '2';
write_to_socket(new_socket_fd, (const char *) &control_message, 1);
// allocate a buffer with size block_size
block_buf = (char *) malloc(block_size);
// read from local file and write to socket
while ((ret = read(file_fd, (void *) block_buf, block_size)) > 0) {
write_to_socket(new_socket_fd, (const void *) block_buf, (size_t) ret);
}
if (ret == -1) {
perror("read()");
fprintf(stderr, "read failed\n");
fflush(stderr);
}
close(file_fd);
close(new_socket_fd);
free(block_buf);
return 0;
} else {
// parent code
// close the new accepted file descriptor
close(new_socket_fd);
}
}
close(socket_fd);
return 0;
}
|
C
|
#ifdef _DEBUG
#undef _DEBUG
#include <python3.5/Python.h>
#define _DEBUG
#else
#include <python3.5/Python.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#define IOCTL_MAGIC_NUMBER 'j'
#define IOCTL_BUZZER_ON _IO(IOCTL_MAGIC_NUMBER, 0)
#define IOCTL_BUZZER_OFF _IO(IOCTL_MAGIC_NUMBER, 1)
#define DEV_PATH "/dev/buzzer_dev"
void func(int firecheck, int smokecheck)
{
int buz_fd =0;
char *buffer;
if((buz_fd =open(DEV_PATH, O_RDWR | O_NONBLOCK)) <0){
perror("open()");
exit(1);
}
printf("open success!\n");
int channel = 0;
//float fire_res = 0;
printf("while in\n");
int smoke=0;
int fire=0;
if(firecheck==1)
{
fire=1;
}
else if(smokecheck==1)
{
smoke=1;
}
printf("%d %d \n",firecheck, smokecheck);
if(fire==1){ //when fire sensor is on
printf("Turnning on BUZZER_ver1\n");
for(int k=0;k<30;k++)
{
int i=0;
while(i<200){
ioctl(buz_fd, IOCTL_BUZZER_ON, 0);
usleep(1);
ioctl(buz_fd, IOCTL_BUZZER_OFF, 0);
usleep(1);
i++;
}
}
}
if(smoke==1){
printf("Turnning on BUZZER_ver2\n");
for(int k=0;k<3;k++)
{
int i=0;
while(i<200){
ioctl(buz_fd, IOCTL_BUZZER_ON, 0);
usleep(1);
ioctl(buz_fd, IOCTL_BUZZER_OFF, 0);
usleep(1);
i++;
}
usleep(500000);
}
}
close(buz_fd);
printf("close success!\n");
return;
}
int main(int argc, char** argv){
return 0;
}
|
C
|
/*
*
* Compilation Instruction:
* gcc commandline_parser.c -o commandline_parser
* ./commandline_parser
*
*/
#include <assert.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <wait.h>
#include <inttypes.h>
#include "Queue.h"
#include <pthread.h>
pthread_mutex_t lock_queue; //Mutex to handle access to the queue
pthread_cond_t queue_not_empty; //Mutex used to make scheduler thread wait if queue is empty
pthread_cond_t change_policy;
pthread_t command_thread, dispatch_thread;
/* Error Code */
#define EINVAL 1
#define E2BIG 2
#define MAXMENUARGS 6
#define MAXCMDLINE 64
struct Queue_Node *job_queue;
int cmd_run(int nargs, char **args);
int cmd_list(int nargs, char **args);
int cmd_quit(int nargs, char **args);
void create_modules();
void *schedulerMod();
void *dispatcherMod();
void showmenu(const char *name, const char *x[]);
int cmd_helpmenu(int n, char **a);
int cmd_dispatch(char *cmd);
char sched[15] = "FCFS";
pid_t children_ids [20];
int resched = 0;
int idx = 0;
int schedulerType = 1;
/*
* The run command - submit a job.
*/
int cmd_run(int nargs, char **args) {
job_t *job = malloc(sizeof(job_t));
if (nargs != 4) {
printf("Usage: run <job> <time> <priority>\n");
return EINVAL;
}
int burst = atoi(args[2]);
int priority = atoi(args[3]);
job->run_time = burst;
job->priority = priority;
strcpy(job->name, args[1]);
if (job_queue->count < 1) {
job->sub_time = currentTimeMillis();
job_queue->job = job;
job_queue->count++;
pthread_cond_signal(&queue_not_empty);
} else {
job_queue->add(job_queue, job);
}
sort(job_queue, schedulerType);
if (job_queue->count == 1) {
}
printf("\nuse execv to run the job in csubatch.\n");
return 1;
}
int cmd_sched(int nargs, char **args) {
strcpy(sched, args[0]);
resched = 1;
pthread_cond_signal(&change_policy);
return 1;
}
/*
* Display menu information
*/
void showmenu(const char *name, const char *x[]) {
int ct, half, i;
printf("\n");
printf("%s\n", name);
for (i = ct = 0; x[i]; i++) {
ct++;
}
half = (ct + 1) / 2;
for (i = 0; i < half; i++) {
printf(" %-36s", x[i]);
if (i + half < ct) {
printf("%s", x[i + half]);
}
printf("\n");
}
printf("\n");
}
static const char *helpmenu[] = {
"[run] <job> <time> <priority> ",
"[test] <benchmark> <policy> <num_of_jobs> <priority_levels>\n<min_CPU_time> <max_CPU_time>",
"[quit] Exit csubatch ",
"[help] Print help menu ",
"[list] List all jobs ",
"[SJF] Change Scheduling Policy to Shortest Job First ",
"[FCFS] Change Scheduling Policy to First Come First Served ",
"[Priority] Change Scheduling Policy to be based on Priority ",
NULL
};
int cmd_helpmenu(int n, char **a) {
(void) n;
(void) a;
showmenu("csubatch help menu", helpmenu);
return 0;
}
int cmd_test(int nargs, char **args) {
if (nargs != 6) {
printf("Usage:[test] <benchmark> <policy> <num_of_jobs> <priority_levels>\n<min_CPU_time> <max_CPU_time>\",\n");
return EINVAL;
}
return 1;
}
/*
* Command table.
*/
static struct {
const char *name;
int (*func)(int nargs, char **args);
} cmdtable[] = {
/* commands: single command must end with \n */
{"?\n", cmd_helpmenu},
{"h\n", cmd_helpmenu},
{"help\n", cmd_helpmenu},
{"r", cmd_run},
{"run", cmd_run},
{"q\n", cmd_quit},
{"quit\n", cmd_quit},
{"list\n", cmd_list},
{"FCFS\n", cmd_sched},
{"SJF\n", cmd_sched},
{"Priority\n", cmd_sched},
{"test\n", cmd_test},
/* Please add more operations below. */
{NULL, NULL}
};
/*
* List out the jobs
*/
int cmd_list(int nargs, char **args) {
int i;
printf("The Current Scheduling policy is:%s\n", sched);
printf("The following are the list of jobs:\n");
printf("Sub Time \tJob Name\tBurst Time\tPriority\n");
queue_t *jobs = job_queue;
while(jobs != NULL) {
printf("%" PRId64 "\t%s\t\t%d\t\t%d\n", jobs->job->sub_time, jobs->job->name, jobs->job->run_time,
jobs->job->priority);
jobs = jobs->next;
}
return (0);
}
/*
* after 'quit', display performance
*/
void dis_perfo() {
int result_count = job_queue->count;
queue_t *jobs = job_queue->next;
double turnaround = 0;
double burstTime = 0;
if (result_count == 0) {
printf("Program end\n");
return;
}
for (int i = 0; i < result_count; i++) {
turnaround = currentTimeMillis() - jobs->job->sub_time;
burstTime += jobs->job->run_time;
}
printf("Total number jobs submitted: %d\n", result_count);
printf("Average BurstTime:\t\t %.2f\n", burstTime / result_count);
printf("Average waiting time:\t\t %.2f\n", (turnaround - burstTime) / result_count);
printf("Average Throughput:\t\t %.3f\n", (1 / turnaround) / result_count);
}
/*
* The quit command.
*/
int cmd_quit(int nargs, char **args) {
dis_perfo();
pthread_cancel(command_thread);
pthread_cancel(dispatch_thread);
for (int i = 0; i < 20; ++i) {
kill(children_ids[i], SIGKILL);
}
exit(0);
}
/*
* Process a single command.
*/
int cmd_dispatch(char *cmd) {
char *args[MAXMENUARGS];
int nargs = 0;
char *word;
char *context;
int i, result;
for (word = strtok_r(cmd, " ", &context);
word != NULL;
word = strtok_r(NULL, " ", &context)) {
if (nargs >= MAXMENUARGS) {
printf("Command line has too many words\n");
return E2BIG;
}
args[nargs++] = word;
}
if (nargs == 0) {
return 0;
}
for (i = 0; cmdtable[i].name; i++) {
if (*cmdtable[i].name && !strcmp(args[0], cmdtable[i].name)) {
assert(cmdtable[i].func != NULL);
/* Call function through the cmd_table */
result = cmdtable[i].func(nargs, args);
return result;
}
}
printf("%s: Command not found\n", args[0]);
return EINVAL;
}
void create_modules() {
pthread_create(&command_thread, NULL, schedulerMod, NULL);
pthread_create(&dispatch_thread, NULL, dispatcherMod, NULL);
}
//Scheduler thread that works, but doesn't run concurrently
void *dispatcherMod() {
//While it loops, if the quit commans is used, then it will exit
while (job_queue->count == 0) {
pthread_cond_wait(&queue_not_empty, &lock_queue);
}
FILE *f = fopen("C:\\Users\\jazart\\CLionProjects\\CSUBatch\\hello.txt", "w+");
pid_t child = fork();
char *execv_args[] = {"C:\\Users\\jazart\\CLionProjects\\CSUBatch\\hello.exe", NULL};
if (child == 0) {
dup2(fileno(f), STDOUT_FILENO);
fclose(f);
if (execv("C:\\Users\\jazart\\CLionProjects\\CSUBatch\\hello.exe",
execv_args) < 0) {
printf("\nError\n");
exit(0);
}
job_queue->remove_head(job_queue);
}
children_ids[idx++] = child;
if (child != 0) {
waitpid(-1, NULL, 0);
}
sleep(5);
pthread_mutex_unlock(&lock_queue);
}
void *schedulerMod() {
//if job queue is empty, the thread will wait until
while (1) {
while (resched != 1) {
pthread_cond_wait(&change_policy, &lock_queue);
}
if (strcmp(sched, "FCFS\n") == 0) {
schedulerType = 2;
job_queue = sort(job_queue, 2);
printf("Scheduling policy has been changed to %s. All jobs have been reordered according to it. \n", sched);
}
if (strcmp(sched, "Priority\n") == 0) {
schedulerType = 1;
job_queue = sort(job_queue, 1);
printf("Scheduling policy has been changed to %s. All jobs have been reordered according to it. \n", sched);
}
if (strcmp(sched, "SJF\n") == 0) {
schedulerType = 3;
job_queue = sort(job_queue, 3);
printf("Scheduling policy has been changed to %s. All jobs have been reordered according to it. \n", sched);
}
queue_t *cpy = job_queue;
resched = 0;
pthread_mutex_unlock(&lock_queue);
}
}
int main() {
char *buffer;
size_t bufsize = 64;
job_queue = init_queue(job_queue);
int bool = 1;
buffer = (char *) malloc(bufsize * sizeof(char));
if (buffer == NULL) {
perror("Unable to malloc buffer");
exit(1);
}
create_modules();
while (bool == 1) {
printf("> [? for menu]: ");
getline(&buffer, &bufsize, stdin);
if (strcmp(buffer, "quit") == 0) {
bool = 0;
}
cmd_dispatch(buffer);
}
return 0;
}
|
C
|
/*
* timers.c
*
* Created on: 07-Sep-2020
* Author: Chirayu Thakur
*/
#include "timers.h"
//extern int rollover;
/*
* Function name: void initLETIMER0()
*
* Description: Initialize LETIMER0 peripheral
* .
* Parameters: None
*
* Silab API's Used: CMU_ClockEnable(CMU_Clock_TypeDef clock, bool enable),
* void LETIMER_Init(LETIMER_TypeDef *letimer, const LETIMER_Init_TypeDef *init)
* void LETIMER_CompareSet(LETIMER_TypeDef *letimer,unsigned int comp, uint32_t value)
void LETIMER_IntEnable(LETIMER_TypeDef *letimer, uint32_t flags)
void LETIMER_Enable(LETIMER_TypeDef *letimer, bool enable)
* Returns: None
*
*/
void initLETIMER0()
{
CMU_ClockEnable(cmuClock_LFA,1);//enable LFA parent clock
CMU_ClockEnable(cmuClock_LETIMER0,1);//enable LETIMER0 clock
#if LOWEST_ENERGY_MODE < 3
CMU_ClockDivSet(cmuClock_LETIMER0,cmuClkDiv_4);
#else
CMU_ClockDivSet(cmuClock_LETIMER0,cmuClkDiv_1);
#endif
LETIMER_Init_TypeDef init=
{
.enable = false,/* Do not Start counting when init completed*/
.debugRun = false, /* Counter shall not keep running during debug halt. */
.comp0Top = true, /* Load COMP0 register into CNT when counter underflows. COMP is used as TOP */
.bufTop = false, /* Don't load COMP1 into COMP0 when REP0 reaches 0. */
.out0Pol = 0, /* Idle value for output 0. */
.out1Pol = 0, /* Idle value for output 1. */
.ufoa0 = letimerUFOANone, /* No output on output 0 */
.ufoa1 = letimerUFOANone, /* No output on output 1*/
.repMode = letimerRepeatFree /* Count while REP != 0 */
};
LETIMER_Init(LETIMER0,&init); //Initialize LETIMER0
LETIMER_CompareSet(LETIMER0,0,COMP0); //Set Value of COMP0
LETIMER_CompareSet(LETIMER0,1,1500); //Set Value of COMP1
//LETIMER_IntEnable(LETIMER0,LETIMER_IF_COMP0); //Enable COMP0 Interrupt
//LETIMER_IntEnable(LETIMER0,LETIMER_IF_COMP1); //Enable COMP1 Interrupt
//NVIC_EnableIRQ(LETIMER0_IRQn); // config NVIC to take IRQs from LETIMER0
LETIMER_Enable(LETIMER0,1); //LETIMER enable
}
/*
* Function name: void timerWaitUs(uint32_t us_wait)
*
* Description: Provide Interrupt based timing delay in uS
* .
* Parameters: uint32_t us_wait
*
* Silab API's Used: void LETIMER_CompareSet(LETIMER_TypeDef *letimer,unsigned int comp, uint32_t value)
* void LETIMER_IntEnable(LETIMER_TypeDef *letimer, uint32_t flags)
* Returns: None
*
*/
void timerWaitUs(uint32_t us_wait)
{
if(us_wait>3000000)
{
us_wait=3000000; //Maximum possible delay
}
uint32_t interval,initial,final;
initial=LETIMER_CounterGet(LETIMER0);
interval=(us_wait*ACTUAL_CLK_FREQ_Hz)/1000000;
final=initial-interval;
if(final>COMP0) //If result overflows
{
interval=65535-final;
final=COMP0-interval;
}
LETIMER_CompareSet(LETIMER0,1,final);
LETIMER_IntEnable(LETIMER0,LETIMER_IF_COMP1); //Enable COMP1 Interrupt
}
|
C
|
//========================================================================
// Binary Search Tree
//========================================================================
#include <stdio.h>
#include <stdlib.h>
//------------------------------------------------------------------------
// Types: node_t
//------------------------------------------------------------------------
typedef struct node {
int key;
struct node *left, *right;
} node_t;
//------------------------------------------------------------------------
// Function: new_node
//------------------------------------------------------------------------
node_t *new_node(int item) {
node_t *node = (node_t*) malloc(sizeof(node_t));
node->key = item;
node->left = node->right = NULL;
return node;
}
//------------------------------------------------------------------------
// Function: order_print
//------------------------------------------------------------------------
void order_print(node_t *root) {
if(root != NULL) {
order_print(root->left);
printf("%d ", root->key);
order_print(root->right);
}
}
//------------------------------------------------------------------------
// Function: insert
//------------------------------------------------------------------------
node_t *insert(node_t *node, int key) {
if(node == NULL) return new_node(key);
if(key < node->key)
node->left = insert(node->left, key);
else if(key > node->key)
node->right = insert(node->right, key);
return node;
}
//------------------------------------------------------------------------
// Function: main
//------------------------------------------------------------------------
int main() {
node_t *root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
order_print(root);
return 0;
}
|
C
|
struct b_number* clone( int copy, struct b_number* orig ){
struct b_number* new;
new = (struct b_number*) calloc( 1, sizeof(struct b_number));
new->block_list = (uint32_t*) malloc(sizeof(uint32_t) * orig->size );
new->size = orig->size;
if( copy )
memcpy( new->block_list, orig->block_list, sizeof(uint32_t) * orig->size );
return new;
}
|
C
|
// Alexandra Qin
// aq263
//
// HW3 Sender
#include <stdio.h> /* for printf() and fprintf() */
#include <sys/socket.h> /* for socket(), connect(), sendto(), and recvfrom() */
#include <arpa/inet.h> /* for sockaddr_in and inet_addr() */
#include <stdlib.h> /* for atoi() and exit() */
#include <string.h> /* for memset() */
#include <unistd.h> /* for close() */
#include <sys/types.h>
#include <pthread.h>
#include <fcntl.h>
#define ECHOMAX 1004 /* Longest string to echo */
#define BUF_SIZE 1000
#define FRAGS 10000
typedef struct {
int fragment[10];
char buf[10][BUF_SIZE];
int empty[10];
} Buffer;
int sock; /* Socket descriptor */
struct sockaddr_in echoServAddr; /* Echo server address */
struct sockaddr_in fromAddr; /* Source address of echo */
unsigned short echoServPort; /* Echo server port */
char *servIP; /* IP address of server */
char *echoString; /* String to send to echo server */
int echoStringLen; /* Length of string to echo */
Buffer b;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void DieWithError(char *errorMessage) {
printf("%s", errorMessage);
}; /* External error handling function */
void initsocket() {
servIP = "127.0.0.1"; /* First arg: server IP address (dotted quad) */
echoServPort = 2000;
/* Create a datagram/UDP socket */
if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
DieWithError("socket() failed");
/* Construct the server address structure */
memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */
echoServAddr.sin_family = AF_INET; /* Internet addr family */
echoServAddr.sin_addr.s_addr = inet_addr(servIP); /* Server IP address */
echoServAddr.sin_port = htons(echoServPort); /* Server port */
}
void *th1(void *ptr);
void *th2(void *ptr);
void SendFileInPackets() {
char *x;
pthread_t thread1, thread2;
int iret1, iret2;
iret1 = pthread_create(&thread1, NULL, th1, (void*) x);
iret2 = pthread_create(&thread2, NULL, th2, (void*) x);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
exit(0);
}
int main(int argc, char *argv[]) {
int i;
for (i = 0; i < 10; i++) {
b.fragment[i] = -1;
b.empty[i] = 0;
}
initsocket();
SendFileInPackets();
close(sock);
}
void *th1(void *ptr) {
int fd = open("random.txt", O_RDONLY);
int x = 0;
int success = 1;
int pos = 0;
char s[BUF_SIZE];
int cont1 = 1;
int i;
while (cont1) {
i = 0;
// a
if (success) {
success = 0;
if (lseek(fd, pos, SEEK_SET) >= 0) {
read(fd, s, BUF_SIZE);
pos += BUF_SIZE;
x++;
}
else {
printf("Could not read file");
return;
}
}
// b
pthread_mutex_lock(&mutex);
// c
while ((b.empty[i] != 0) && i < 10)
i++;
// d
if (b.empty[i] == 0) {
success = 1;
b.empty[i] = 1;
b.fragment[i] = x;
strcpy(b.buf[i], s);
}
// e
else {
success = 0;
}
// f
pthread_mutex_unlock(&mutex);
if (x == FRAGS - 1) // if this is the last fragment
cont1 = 0; // stop running thread
usleep(1000); // sleep for 1ms
}
close(fd);
}
void *th2(void *ptr) {
char pkt[BUF_SIZE + 4];
int cont2 = 1;
int i, j, min, x, frag, fragnum, same_frag;
int current_frag = 0;
echoString = (char *) malloc(sizeof(pkt));
while (cont2) {
min = FRAGS;
i = 0;
j = 0;
same_frag = 0;
// a
pthread_mutex_lock(&mutex);
// b
for (i = 0; i < 10; i++) {
if ((b.empty[i] != 0) && (b.fragment[i] < min)) {
min = b.fragment[i];
x = i;
}
}
if (b.fragment[x] == FRAGS - 1) // if this is the last fragment
cont2 = 0; // stop running thread
// c
if (b.fragment[x] != -1){
frag = b.fragment[x];
pkt[3] = (frag >> 24) & 0xFF;
pkt[2] = (frag >> 16) & 0xFF;
pkt[1] = (frag >> 8) & 0xFF;
pkt[0] = frag & 0xFF;
for (j = 0; j < BUF_SIZE; j++) {
pkt[j+4] = b.buf[x][j];
}
b.empty[x] = 0;
b.fragment[x] = -1;
}
// d
pthread_mutex_unlock(&mutex);
// e
if (frag > current_frag)
current_frag = frag;
else if (frag == current_frag)
same_frag = 1;
fragnum = 0;
fragnum += (pkt[0] & 0xFF);
fragnum += (pkt[1] & 0xFF) << 8;
fragnum += (pkt[2] & 0xFF) << 16;
fragnum += (pkt[3] & 0xFF) << 24;
if (same_frag == 0) { // makes sure to only send each packet once
printf("%d\n", fragnum); // print number of frag you are sending
// send frag
if (sendto(sock, pkt, 1004, 0, (struct sockaddr *)
&echoServAddr, sizeof(echoServAddr)) != 1004)
DieWithError("sendto() sent a different number of bytes than expected");
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdbool.h>
#include <math.h>
#include <pthread.h>
#define TOL 0.001
typedef struct cplx{
double real;
double imag;
int root;
int iteration;
}cplx;
static long int numb_degree;
static long int numb_pixel;
static long int numb_threads;
int * block;
static cplx ** pixel;
cplx * roots;
char ** colours;
void * ppm_writer(void * arg){
FILE * fp;
fp = fopen("newton_attractors_xd.ppm","w");
fwrite("P3\n10 10\n10",sizeof(char),numb_pixel,fp);
fclose(fp);
}
cplx cplx_mul(cplx b, cplx c) {
cplx a;
a.real = -(b.imag * c.imag) + b.real * c.real;
a.imag = b.real * c.imag + b.imag * c.real;
return a;
}
cplx cplx_pow(cplx a,long int d){
if (d<1)
return a;
d = d-1;
cplx c = a;
for (size_t ix = 0; ix < d; ix++) {
c = cplx_mul(c,a);
}
return c;
}
double norm(cplx a){
double norm = 1.0;
norm = norm*(a.real*a.real+a.imag*a.imag);
return norm;
}
double dist(cplx a, cplx b){
double dist;
dist = (a.real-b.real)*(a.real-b.real)+(a.imag-b.imag)*(a.imag-b.imag);
dist = sqrt(dist);
return dist;
}
cplx cplx_conj(cplx a) {
a.imag = -a.imag;
return a;
}
cplx newton_iteration(cplx cord,long int numb_degree){
cplx a = cord;
cplx b = cord;
cplx c;
cplx d;
cplx e;
c = cplx_pow(a,numb_degree);
b = c;
c.real = c.real - 1.0;
d = cplx_pow(a,numb_degree-1);
double norm1 = numb_degree*norm(d);
d = cplx_conj(d);
e = cplx_mul(c,d);
e.real = (cord.real) - (e.real/norm1);
e.imag = (cord.imag) - (e.imag/norm1);
return e;
}
cplx newton(cplx cord, cplx * roots,long int numb_degree){
int jx = 0;
while(jx<1000000){
jx++;
if (sqrt(norm(cord)) < TOL){
cord.root = 0;
cord.iteration = jx;
//printf("Zero\n");
return cord;
}
if (abs((int) cord.real)>10000000000 ||
abs((int) cord.imag)>10000000000 ||
sqrt(norm(cord)) >10000000000 ){
cord.root = 0;
cord.iteration = jx;
//printf("Inf\n");
return cord;
}
for (size_t ix = 0; ix < numb_degree; ix++) {
if (dist(cord,roots[ix]) < TOL){
cord.root = ix+1;
cord.iteration = jx;
//printf("Yay\n");
return cord;
}
}
cord = newton_iteration(cord,numb_degree);
}
//printf("Doesn't converge\n");
cord.root = 0;
return cord;
}
void * newton_f(void * arg){
int * block_n = (int*) arg;
for (size_t ix = *block_n; ix < *(block_n+1); ix++) {
for (size_t jx = 0; jx < numb_pixel; jx++) {
pixel[ix][jx] = newton(pixel[ix][jx], roots, numb_degree);
}
}
pthread_exit(0);
}
int main(int argc,char * argv[]){
if (argc < 4) {
printf("Wrong number of arguments\n");
return 0;
}
if (argv[1][0] == '-' && argv[1][1] == 't') {
numb_threads = strtol((argv[1]+2),NULL,10);
}
if (argv[2][0] == '-' && argv[2][1] == 'l'){
numb_pixel = strtol((argv[2]+2),NULL,10);
}
numb_degree = strtol(argv[3],NULL,10);
roots = (cplx*) malloc(sizeof(cplx) *numb_degree);
for (size_t ix = 0; ix < numb_degree; ix++) {
roots[ix].real = cos(ix*2*M_PI/(numb_degree));
roots[ix].imag = sin(ix*2*M_PI/(numb_degree));
}
printf("%f,%f\n",roots[0].real,roots[0].imag);
cplx* mem = (cplx*) malloc(sizeof(cplx)*numb_pixel*numb_pixel);
pixel = (cplx **) malloc(sizeof(cplx*)*numb_pixel);
for (size_t ix = 0, jx=0; ix < numb_pixel; ix++, jx+=numb_pixel) {
pixel[ix] = mem+jx;
}
double pixel_size = 4.0/numb_pixel;
for (size_t ix = 0; ix < numb_pixel; ix++) {
for (size_t jx = 0; jx < numb_pixel; jx++) {
pixel[ix][jx].real = -2.0 + jx*pixel_size;
pixel[ix][jx].imag = 2.0 - ix*pixel_size;
}
}
block = (int*) malloc(sizeof(int)*(numb_threads+1));
for (size_t ix = 0; ix < numb_threads+1; ix++) {
block[ix] = ix*numb_pixel/numb_threads;
}
pthread_t threads[numb_threads];
pthread_attr_t attr;
pthread_attr_init(&attr);
for (size_t ix = 0; ix < numb_threads; ix++) {
pthread_create(&threads[ix], &attr, newton_f, &block[ix]);
}
for (size_t ix = 0; ix < numb_threads; ix++) {
pthread_join(threads[ix],NULL);
}
int h;
for (size_t ix = 0; ix < numb_pixel; ix++) {
for (size_t jx = 0; jx < numb_pixel; jx++) {
if (pixel[ix][jx].iteration == 0){
//printf("%f,%f\n", pixel[ix][jx].real,pixel[ix][jx].imag);
h++;
}
}
}
printf("woops %d\n",h);
colours = (char**) malloc(sizeof(char*)*10);
for (size_t i = 0; i < 10; i++) {
colours[i] = (char *) malloc(sizeof(char)*6);
}
colours[0] = "5 1 1 ";
colours[1] = "1 5 1 ";
colours[2] = "1 1 5 ";
colours[3] = "1 1 5 ";
colours[4] = "1 5 1 ";
colours[5] = "1 5 5 ";
colours[6] = "5 1 5 ";
colours[7] = "5 5 1 ";
colours[8] = "5 5 5 ";
colours[9] = "9 5 1 ";
pthread_t painter;
pthread_create(&painter, &attr, ppm_writer, NULL);
pthread_join(painter,NULL);
//pthread_mutex_init(&mutex_sum, NULL);
//
// for (tx=0, ix=0; tx < n_threads; ++tx, ix+=block_size) {
// double ** arg = malloc(2*sizeof(double*));
// arg[0] = a+ix; arg[1] = b+ix;
// if (ret = pthread_create(threads+tx, NULL, newton, (void*)arg)) {
// printf("Error creating thread: %\n", ret);
// exit(1);
// }
//}
// for (size_t ix = 0; ix < numb_pixel; ix++) {
// for (size_t jx = 0; jx < numb_pixel; jx++) {
// newton(pixel[ix][jx],roots,numb_degree);
// }
// }
return 0;
}
|
C
|
//Initializes LCD for character display, 8-bits 2 lines
//Works for Hitachi HD44780 and Tinharp/ Shenzhen Eone 1602A
//Author :Israel N Gbati
//Date : 5/05/16
//Location : Shimoda Village Yokohama Japan
#include "TM4C123.h" // Device header
#include "LCD_init.h"
void LCD_init(void)
{
SYSCTL->RCGCGPIO |=0x01; //Clock for GPIOA
SYSCTL->RCGCGPIO |=0x02; //Clock for GPIOB
LCD_CTRL->DIR |=0xE0; //PA5-7 as output
LCD_CTRL->DATA |=0xE0;
LCD_DATA->DIR =0xFF; //All PB as output
LCD_DATA->DATA =0xFF;
delayMs(20);
LCD_command(0x30);
delayMs(5);
LCD_command(0x30);
delayUs(100);
LCD_command(0x30);
LCD_command(0x38);
LCD_command(0x06);
LCD_command(0x01);
LCD_command(0x0F);
}
void delayMs(int n)
{
int i, j;
for(i = 0 ; i < n; i++)
for(j = 0; j < 3180; j++)
{} // do nothing for 1 ms
}
// delay n microseconds (16 MHz CPU clock)
void delayUs(int n)
{
int i, j;
for(i = 0 ; i < n; i++)
for(j = 0; j < 3; j++)
{}
}
void LCD_command(unsigned char command)
{
LCD_CTRL->DATA =0;// Reset Rs=0, Rw=0
LCD_CTRL->DATA =command;
LCD_CTRL->DATA = EN;
delayUs(0);
LCD_CTRL->DATA =0;
if(command <4){
delayMs(2);
}
else{
delayUs(37);
}
}
/*
void LCD_data(unsigned char data)
{
LCD_DATA->DATA = RS;
LCD_DATA->DATA =data;
LCD_CTRL->DATA = EN |RS;
delayUs(0);
LCD_CTRL->DATA =0;
delayUs(40);
}
*/
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "eyebot.h"
//Starting at a random position, drive straight until the robot is close to a wall. distFromWall specifies how close the robot should get to the wall
void reachWall(int distFromWall) {
//Have robot drive straight to start off with
VWSetSpeed(200,0);
//Drive forward and continually check distance from wall in front
while(true) {
//Get distance from sensor in front
int dist = PSDGet(2);
//Check distance against threshold
if(dist < distFromWall) {
//Stop moving straight, and start turning robot
VWSetSpeed(0,0);
break;
}
}
}
//With the robot in front of a wall, rotate the robot until it's parellel with the wall
void rotateUntilParallel() {
//Start rotating robot right
VWSetSpeed(250,0);
MOTORDrive(1,100);
MOTORDrive(3,100);
MOTORDrive(2,0);
MOTORDrive(4,0);
//Keep rotating robot until front and left sensors are roughly same distance from the wall
while(abs(PSDGet(1) - PSDGet(2)) > 2) {
}
VWSetSpeed(0,0);
MOTORDrive(1,100);
MOTORDrive(2,100);
MOTORDrive(3,100);
MOTORDrive(4,100);
//Now, turn right another 45-48 degrees (roughly)
VWTurn(-48,22);
while(!VWDone()) {
}
}
void rotate90Right() {
VWTurn(-90,30);
while(!VWDone()) {
}
}
void rotate90Left() {
VWTurn(90,30);
while(!VWDone()) {
}
}
//Starting parallel to a wall (with the wall on the left of the vehicle), keep driving straight and correcting course, until hitting another wall
//distFromWall indicates how close to get to the next wall (i.e. when to stop)
//distToMaintain indicates the distance to try and maintain from the wall on the left (that the vehicle is driving along)
void driveAlongLeftWall(int distFromWall, int distToMaintain) {
//Start driving straight
VWSetSpeed(400,0);
//Keep driving straight and correcting course until we reach the next wall
while(PSDGet(2) > distFromWall) {
//Check distance from wall on left
int dist = PSDGet(1);
//Check against threshold (should be roughly 200 from wall)
if(dist < distToMaintain-5) {
//Too close to wall: turn right
MOTORDrive(1,100); //Right
MOTORDrive(2,65); //Left
MOTORDrive(3,100); //Right
MOTORDrive(4,65); //Left
MOTORSpeed(1,1000);
MOTORSpeed(2,1000);
MOTORSpeed(3,1000);
MOTORSpeed(4,1000);
}
else if(dist > distToMaintain+5) {
//Too far from wall: turn left
MOTORDrive(1,65); //Right
MOTORDrive(2,100); //Left
MOTORDrive(3,65); //Right
MOTORDrive(4,100); //Left
MOTORSpeed(1,1000);
MOTORSpeed(2,1000);
MOTORSpeed(3,1000);
MOTORSpeed(4,1000);
}
}
}
//Starting parallel to a wall (with the wall on the right of the vehicle), keep driving straight and correcting course, until hitting another wall
//distFromWall indicates how close to get to the next wall (i.e. when to stop)
//distToMaintain indicates the distance to try and maintain from the wall on the left (that the vehicle is driving along)
void driveAlongRightWall(int distFromWall, int distToMaintain) {
//Start driving straight
VWSetSpeed(400,0);
//Keep driving straight and correcting course until we reach the next wall
while(PSDGet(2) > distFromWall) {
//Check distance from wall on left
int dist = PSDGet(3);
//Check against threshold (should be roughly 200 from wall)
if(dist < distToMaintain-5) {
//Too close to wall: turn left
MOTORDrive(1,65); //Right
MOTORDrive(2,100); //Left
MOTORDrive(3,65); //Right
MOTORDrive(4,100); //Left
MOTORSpeed(1,1000);
MOTORSpeed(2,1000);
MOTORSpeed(3,1000);
MOTORSpeed(4,1000);
}
else if(dist > distToMaintain+5) {
//Too far from wall: turn right
MOTORDrive(1,100); //Right
MOTORDrive(2,65); //Left
MOTORDrive(3,100); //Right
MOTORDrive(4,65); //Left
MOTORSpeed(1,1000);
MOTORSpeed(2,1000);
MOTORSpeed(3,1000);
MOTORSpeed(4,1000);
}
}
}
//Experiments 1 and 2 combined. Find a wall, and then drive a rectangle continuously
void exp1and2() {
//Start by driving towards a wall (until 250mm away from wall)
reachWall(200);
//Rotate robot to be parallel with wall
rotateUntilParallel();
//Now continue these steps in a loop to drive in a box
while(true) {
driveAlongLeftWall(200,200);
rotate90Right();
}
//Now, stop robot
VWSetSpeed(0,0);
}
//Experiments 1 and 3. Find a wall, drive to a corner, and then drive a lawnmower pattern
void exp1and3() {
//Start by driving towards a wall (until 200mm away from wall)
reachWall(200);
//Rotate robot to be parallel with wall
rotateUntilParallel();
//Reach corner and turn right
reachWall(200);
rotate90Right();
//Now, starting in this corner, drive a lawnmower pattern
//Now continue these steps in a loop to drive in a lawnmower pattern
bool right = true;
int i=0;
while(true) {
if(right)
//Drive along wall, maintaining specified distance (changes over time to produce lawnmower pattern)
driveAlongLeftWall(200,200+(150*(i++)));
else
//Drive along wall, maintaining specified distance (changes over time to produce lawnmower pattern)
driveAlongRightWall(200,200+(150*(i++)));
//Rotate 90 degrees
if(right)
rotate90Right();
else
rotate90Left();
//Drive straight a short distance (150mm)
VWStraight(150,100);
while(!VWDone()){
}
//Rotate 90 degrees again
if(right)
rotate90Right();
else
rotate90Left();
//Rotate opposite direction next time
right = !right;
}
//Now, stop robot
VWSetSpeed(0,0);
}
int main() {
//Experiments 1 and 2
// exp1and2();
//Experiments 1 and 3
exp1and3();
}
|
C
|
/*
* file.h
*
* Created on: Jan 9, 2014
* Author: avi
*/
#ifndef FILE_H_
#define FILE_H_
#include <stdio.h>
#include <stdlib.h>
#define MAX_CHAR_IN_LINE 81
#endif /* FILE_H_ */
/**
* This function get file patch and try to open it, if the file
* is opened it return a pointer to the file, else output
* error message
*
* @input
* char *fileName is the full path of the file
*/
FILE * getFile(char*);
/**
* This function release the file resource and report an
* error if it can't release it.
*
* @input
* File *fp - pointer to file
*/
void releaseFile(FILE *);
FILE * newFile(const char * filename, const char * mode );
|
C
|
#include <stdarg.h>
#include <stdio.h>
/**
* printf("format string", formatter_values...)
*
* %[flags][width][.precision]specifier
*
* Format characters:
* %c --> character
* %s --> string
* %u --> unsigned integer
* %x --> hexadecimal
* %d, %i --> decimal integer
* %f --> float
*
* Special extra formatters:
* %(3)d --> minimum width is 3 columns
* %(-)3d --> right pad formatted value minimum width of 3
* %(0)3d --> left pad zeros to reach minimum width
* %(+)3d --> explicitly indicate the value is positive
* %(2.4)f --> atleast 2 characters wide and display minimum of 4 decimal places
* */
int printf(const char *restrict format, ...)
{
va_list args;
va_start(args, format);
char buffer[1000];
size_t written = vsprintf(buffer, format, args);
puts(buffer);
va_end(args);
return written;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
int count = 0;
char string[500] = {};
printf("Enter the string: ");
fgets(string, 500, stdin);
for (int i = 0; string[i] != 0; i++)
{
if (isupper(string[i]))
{
printf("\n");
count++;
}
printf("%c", string[i]);
}
printf("%d \n", count);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/*2. Chiedere all'utente di inserire 3 frasi, e salvarle in un array di stringhe. Chiedere poi all'utente quale delle 3 frasi stampare,
quindi stampare la frase desiderata.*/
#define DIM1I 3
#define DIM2S 20
int main()
{
char strings[DIM1I][DIM2S+1] = {};
int i, nInput;
for (i=0; i<DIM1I; i++)
{
printf("Immetti %da stringa:\n", i+1);
scanf("%20s", strings[i]);
getchar();
}
do {
printf("Che stringa delle %d vuoi stampare? (0-%d)\n", DIM1I, DIM1I-1);
scanf("%d", &nInput);
} while (nInput < 0 || nInput >= DIM1I);
printf("%s\n", strings[nInput]);
return 0;
}
|
C
|
#include<stdio.h>
void main()
{
int sub1,sub2,sub3,sub4,sub5,total,grand_total,division;
float percentage;
printf("\nenter the marks for PHYSICS out of 100 : ");
scanf("%d", &sub1);
printf("enter the marks for CHEMISTRY out of 100 : ");
scanf("%d", &sub2);
printf("enter the marks for BIOLOGY out of 100 : ");
scanf("%d", &sub3);
printf("enter the marks for MATHAMETICS out of 100 : ");
scanf("%d", &sub4);
printf("enter the marks for COMPUTER out of 100 : ");
scanf("%d", &sub5);
printf("\nenter the grand toal marks for 5 subjects : ");
scanf("%d", &grand_total);
total = sub1 + sub2 + sub3 + sub4 + sub5;
percentage = total * 100 / grand_total;
printf("\nthe total percentage is %.2f AND ", percentage);
if(percentage >= 90.00)
printf("GRADE A");
else if(percentage >= 80.00)
printf("GRADE B");
else if(percentage >= 70.00)
printf("GRADE C");
else if(percentage >= 60.00)
printf("GRADE D");
else if(percentage >= 40.00)
printf("GRADE E");
else
printf("GRADE F");
}
|
C
|
/*
** EPITECH PROJECT, 2020
** my_getnbr.c
** File description:
** my_getnbr
*/
int my_strlen(char const *str);
int get_nbr_check(char const *str)
{
int neg = 0;
for (int i = 0; str[i] == '-' || str[i] == '+'; i++)
if (str[i] == '-')
neg++;
return (neg);
}
int my_getnbr(char const *str)
{
int nb = 0;
int neg = get_nbr_check(str);
int i;
for (i = 0; str[i] == '-' || str[i] == '+'; i++);
for (; str[i] >= '0' && str[i] <= '9'; i++) {
if (nb > 0)
nb = -nb;
if (((str[i] >= '0' && str[i] <= '9') &&
(str[i - 10] >= '0' && str[i - 10] <= '9')) ||
(nb == -214748364 && str[i] == '9'))
return (0);
nb = nb * 10 - str[i] + '0';
}
if ((nb == -2147483648) && !(neg % 2))
return (0);
if (neg % 2)
return (nb);
return (nb *= -1);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* fun_512.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sprotsen <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/08/06 20:10:05 by sprotsen #+# #+# */
/* Updated: 2018/08/06 20:10:07 by sprotsen ### ########.fr */
/* */
/* ************************************************************************** */
#include "head_ssl.h"
#define ULLI unsigned long long int
// Ch(x, y, z) = (x AND y) XOR ( NOT x AND z)
// Maj(x, y, z) = (x AND y) XOR (x AND z) XOR (y AND z)
// Sigma0(x) = ROTR(x, 28) XOR ROTR(x, 34) XOR ROTR(x, 39)
// Sigma1(x) = ROTR(x, 14) XOR ROTR(x, 18) XOR ROTR(x, 41)
// Delta0(x) = ROTR(x, 1) XOR ROTR(x, 8) XOR SHR(x, 7)
// Delta1(x) = ROTR(x, 19) XOR ROTR(x, 61) XOR SHR(x, 6)
// Операции над словами (64-битными).
// ROTR - циклический сдвиг вправо на n бит:
// ROTR(x, n) = (x » n) | (x « (64-n))
// SHR - сдвиг вправо на n бит:
// SHR(x, n) = x » n
ULLI rotr_64(ULLI x, int n)
{
return (x >> n) | (x << (64 - n));
}
ULLI shr_64(ULLI x, int n)
{
return (x >> n);
}
ULLI ch_64(ULLI x, ULLI y, ULLI z)
{
return (x & y) ^ ((~x) & z);
}
ULLI maj_64(ULLI x, ULLI y, ULLI z)
{
return (x & y) ^ (x & z) ^ (y & z);
}
ULLI sigma0_64(ULLI x)
{
return rotr_64(x, 28) ^ rotr_64(x, 34) ^ rotr_64(x, 39);
}
ULLI sigma1_64(ULLI x)
{
return rotr_64(x, 14) ^ rotr_64(x, 18) ^ rotr_64(x, 41);
}
ULLI delta0_64(ULLI x)
{
return rotr_64(x, 1) ^ rotr_64(x, 8) ^ shr_64(x, 7);
}
ULLI delta1_64(ULLI x)
{
return rotr_64(x, 19) ^ rotr_64(x, 61) ^ shr_64(x, 6);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void insertatbegin();
void reverse();
void display();
void insertatlast();
// void delete_ok();
struct node
{
int data;
struct node *next;
};
struct node *start = NULL;
int main()
{
int choice;
while (1)
{
printf("\n\n** Main menu **\n");
printf("\n1.Insert at Last");
printf("\n2.Reverse");
printf("\n3.Display");
printf("\n4.Insert at Begin");
printf("\n5.Exit");
// printf("\n6.Delete");
printf("\n.Exit");
printf("\n----------------------------------\n");
printf("Enter your choice :- ");
scanf("%d", &choice);
switch (choice)
{
case 1:
insertatlast();
break;
case 2:
reverse();
break;
case 3:
display();
break;
case 4:
insertatbegin();
break;
case 5:
exit(0);
break;
default:
printf("You have enter wrong choice");
}
}
// getch();
return 0;
}
void insertatlast()
{
int info;
struct node *newnode, *currptr;
newnode = (struct node *)malloc(sizeof(struct node));
if (newnode == NULL)
{
printf("\nMemory out of bound");
exit(0);
}
printf("\nEnter the data :");
scanf("%d", &info);
newnode->data = info;
newnode->next = NULL;
if (start == NULL)
{
start = newnode;
}
else
{
currptr = start;
while (currptr->next != NULL)
{
currptr = currptr->next;
}
currptr->next = newnode;
}
}
void reverse()
{
struct node *currptr, *previous, *frward;
currptr = start;
previous = NULL;
frward = NULL;
if
(start == NULL)
printf("list is empty\n");
else
{
while (currptr != NULL)
{
frward = currptr -> next;
currptr -> next = previous;
previous = currptr;
currptr = frward;
}
start = previous;
}
}
void display()
{
struct node *currptr;
if (start == NULL)
{
printf("\n Element not present in list");
return;
}
else
{
currptr = start;
while (currptr != NULL)
{
printf("%d", currptr->data);
printf("-->");
currptr = currptr->next;
}
}
}
void insertatbegin()
{
int info;
struct node *newnode;
newnode = (struct node *)malloc(sizeof(struct node));
if (newnode == NULL)
{
printf("\nMemmoey out of bound : ");
return;
}
printf("\n Enter the data : ");
scanf("%d", &info);
newnode->data = info;
if (start == NULL)
{
start = newnode;
newnode->next = NULL;
}
else
{
newnode->next = start;
start = newnode;
}
}
|
C
|
/* Program 7.4 : Compare */
#include <stdio.h>
void CommaWrite(long int n);
void ZeroWrite(int m);
void main(void)
{ long int first, second;
scanf("%li%li", &first, &second);
if (first > second)
{ CommaWrite(first); CommaWrite(second); }
else
{ CommaWrite(second); CommaWrite(first); }
}
void CommaWrite(long int n)
{
int millions, thousands, units;
millions = (n / 1000000);
thousands = (n % 1000000) / 1000;
units = (n % 1000);
if (millions > 0)
{
printf("%i,", millions);
ZeroWrite(thousands); putchar(',');
ZeroWrite(units);
}
else
{
if (thousands > 0)
{
printf("%i,", thousands);
ZeroWrite(units);
}
else printf("%i", units);
}
printf("\n");
}
void ZeroWrite(int m)
{
if (m < 100) printf("0");
if (m < 10) printf("0");
printf("%i", m);
}
|
C
|
#include <stdio.h>
int main()
{
int sum=0, tmp=1;
while( tmp != 0){
scanf("%d", &tmp);
sum += tmp;
}printf("%d", sum);
return 0;
}
|
C
|
#include <assert.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
void *my_malloc(size_t size);
void *my_malloc(size_t size) {
void *p = sbrk(0);
/* srbk syscall returns a pointer to the current top of the heap.
* srbk(0) returns a pointer to the current top of the heap, increments
* the heap size by foo and returns a pointer to the previous top of the
* heap.
*/
void *request = sbrk(size);
if (request == (void*) -1) {
return NULL; // srbk failed
} else {
assert( p == request); // not thread safe.
return p;
}
}
|
C
|
#include <stdio.h>
int main()
{
int d,m,y;
printf("Nhap ngay, thang, nam can in ra: ");
//scanf("%2d/%2d/%2d",&d,&m,&y);
//%2d ke ca nhap so co 4 5 chu so cung chi lay 2 so dau.
scanf("%d/%d/%d",&d,&m,&y);
printf("Hom nay la ngay: %02d/%02d/%02d.\n",d,m,y%100);
//%2d nay so nhap vao co 4 5 chu so cung hien ca 4 5 chu so.
//y%100 la lay phan du, ta duoc 2 so cuoi cua nam.
}
|
C
|
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s[100];
int l,i,count=0;
scanf("%s",s);
l=strlen(s);
for(i=0;i<l;i++)
{
if(s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u'||s[i]=='A'||s[i]=='E'||s[i]=='I'||s[i]=='O'||s[i]=='U')
count++;
else
continue;
}
if(count>0)
printf("yes");
else
printf("no");
getch();
}
|
C
|
#include "holberton.h"
/**
* _puts_recursion - This function prints a string
* @s: The string to print
* Return: Nothing
*/
void _puts_recursion(char *s)
{
int a = 0;
if (s[a] == '\0')
{
_putchar('\n');
}
if (s[a] != '\0')
{
_putchar(s[a]);
a++;
_puts_recursion(&(s[a]));
}
}
|
C
|
#include <stdio.h>
int x,y,z;
void f(int *a,int b){
*a=2;
b=2;
z=b;
}
int main()
{
x=y=1;
f(&x,y);
printf("%d\n%d\n%d",x,y,z);
return 0;
}
|
C
|
//Nathalia Lorena Cardoso - 14/0156909 Lude Yuri Ribeiro - 15/0137770
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
FILE *arq;
int **matrizArquivo,caracter, dadosArq[2], somaValores, linhaCentral,colunaCentral, valorDecimal;
char cha[1];
void buscarDadosArq(char *nomeArquivo,int *dadosArq);// pega os dados do arquivo para montar matriz
int binToDec(char *bin); //função criada para converter binario para decimal
char rotacionarBin(char *bin);
int main(){
//por enquanto setando direto depois fazer melhoria para setar o texto de forma randomica
char nomeArquivo[] = "teste_asfalto1.txt";
buscarDadosArq(nomeArquivo, dadosArq); //alocando a matriz dinamicamente
//alocando matriz dinamicamente
matrizArquivo = malloc (dadosArq[0] * sizeof (int *));
for(int i = 0; i < dadosArq[0]; ++i)
matrizArquivo[i] = malloc (dadosArq[1] * sizeof (int)); //A[i][j]
arq = fopen(nomeArquivo,"r");
//passando valores para matriz
for(int i=0;i<dadosArq[0];++i){
for(int j=0;j<dadosArq[1];++j){
fscanf(arq,"%d%c",&matrizArquivo[i][j],&cha);
}
}
fclose(arq);
//pegando a media das submatrizes dentro da matriz principal
int colunaFinal = dadosArq[1]-1; //coluna final
int linhaFinal = dadosArq[0]-1; //linha final
for(int i=1;i<linhaFinal;++i){//inicia na segunda linha e termina antes da ultima
for(int j=1;j<colunaFinal;++j){//inicia na segunda coluna e termina antes da ultima
int somatorio = 0;//somatorio dos valores da submatriz
int pontoCentral = matrizArquivo[i][j]; //ponto central da submatriz que vai ser o pixel
somatorio += matrizArquivo[i-1][j-1] + matrizArquivo[i-1][j] + matrizArquivo[i-1][j+1];//linha inicial
somatorio += matrizArquivo[i][j-1] + pontoCentral + matrizArquivo[i][j+1];//linha do meio
somatorio += matrizArquivo[i+1][j-1] + matrizArquivo[i+1][j] + matrizArquivo[i+1][j+1];//linha final
int mediaMatriz = somatorio/9; //media da submatriz
//printf("Media: %d\n", mediaMatriz);
//##############colocando flags 1 e 0 para definir o binario ############################
char bin[] = ""; //binario vazio do tipo char
if(matrizArquivo[i-1][j-1] > mediaMatriz){;
strcat(bin,"1");
}else{
strcat(bin,"0");
}
if(matrizArquivo[i-1][j] > mediaMatriz){;
strcat(bin,"1");
}else{
strcat(bin,"0");
}
if(matrizArquivo[i-1][j+1] > mediaMatriz){;
strcat(bin,"1");
}else{
strcat(bin,"0");
}
if(matrizArquivo[i][j-1] > mediaMatriz){;
strcat(bin,"1");
}else{
strcat(bin,"0");
}
if(pontoCentral > mediaMatriz){;
strcat(bin,"1");
}else{
strcat(bin,"0");
}
if(matrizArquivo[i][j+1] > mediaMatriz){;
strcat(bin,"1");
}else{
strcat(bin,"0");
}
if(matrizArquivo[i+1][j-1] > mediaMatriz){;
strcat(bin,"1");
}else{
strcat(bin,"0");
}
if(matrizArquivo[i+1][j] > mediaMatriz){;
strcat(bin,"1");
}else{
strcat(bin,"0");
}
if(matrizArquivo[i+1][j+1] > mediaMatriz){;
strcat(bin,"1");
}else{
strcat(bin,"0");
}
for(int i=0;i<dadosArq[0];++i){
for(int j=0;j<dadosArq[1];++j){
printf("%d ",matrizArquivo[i][j]);
}
printf("\n");
}
printf("Media: %d\n", mediaMatriz);
printf("Binario: %s \n", bin);
//############ TERMINOU DE COLOCAR AS FLAGS ###############
valorDecimal = binToDec(bin);
printf("Decimal: %d \n", valorDecimal);
return 0;
}
}
}
//função criada para buscar dados do arquivo
void buscarDadosArq(char *nomeArquivo,int *dadosArq){
arq = fopen(nomeArquivo,"r");
int comecouPalavra = 0, numPalavras = 0, numLinhas = 1;
while( (caracter=fgetc(arq))!= EOF ){
if ((caracter!=';') && (caracter!='\n') && (!comecouPalavra)) {
comecouPalavra = 1;
}
if (((caracter==';') || (caracter == '\n')) && (comecouPalavra)) {
if(numLinhas<2){
comecouPalavra = 0;
numPalavras++;
}
}
if (caracter=='\n') {
numLinhas++;
}
dadosArq[0]=numLinhas;
dadosArq[1]=numPalavras;
}
fclose(arq);
// printf("\n O número de palavras do arquivo é: %d", dadosArq[0]);
// printf("\n O número de linhas do arquivo é: %d \n", dadosArq[1]);
}
//função criada para converter binario para decimal
int binToDec(char *bin){
int somatorio = 0;
int x = 8;
for(int i = 0; i < 9 ;i++){
if(bin[i] == 49){ // como jogo um binario no formato char comparando com um inteiro tive que compara com 48 => "0"
somatorio += pow(2, x); //49 => "1"
}
x--;
};
return somatorio;
}
|
C
|
#include <stdio.h>
/**
* main - prints the numbers from 1 to 100
* Return: always 0
*/
int main(void)
{
int h;
char fizz[] = "Fizz";
char buzz[] = "Buzz";
char fibu[] = "FizzBuzz";
for (h = 1; h <= 100; h++)
{
if (h % 3 == 0 && h % 5 != 0)
printf(" %s", fizz);
else if (h % 5 == 0 && h % 3 != 0)
printf(" %s", buzz);
else if (h % 3 == 0 && h % 5 == 0)
printf(" %s", fibu);
else if (h == 1)
printf("%d", h);
else
printf(" %d", h);
}
printf("\n");
return (0);
}
|
C
|
#include <stdio.h>
void do_something(int x)
{
printf("%d\n",x);
x--;
if(x>0)
do_something(x);
}
int main()
{
int x=10;
do_something(x);
return 0;
}
|
C
|
#include<stdio.h>
void main()
{
int a[10][10],i,j,r,c,sum=0;
printf("input elements in the matrix :\n ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("element- [%d],[%d] : \n");
scanf("%d",&a[i],[j]);
}
}
printf(" \n the matrix is :\n");
for(r=0;r<3;r++)
{
printf("\n");
for(c=0;c<3;c++)
printf("%d"\t,a[r][c]);
}
printf("\n\n");
{
for(r=0;r<i;r++)
{
sum=sum+a[r][r];
}
printf("sum of the diagonal elements : %d ",sum);
}
}
|
C
|
#include<stdlib.h>
#include<stdio.h>
typedef struct node {
int key;
int value;
struct node * next;
} node;
typedef struct hash_table {
int table_size;
int count;
node ** table;
} hash_table;
hash_table * create(int table_size) {
hash_table * hashTable= malloc(sizeof(hash_table));
hashTable->count=0;
hashTable->table_size=table_size;
hashTable->table= malloc(sizeof(node *) * table_size);
if(!(hashTable || hashTable->table)) printf("err");
int i=0;
for(;i<table_size;i++)
hashTable->table[i]=NULL;
return hashTable;
}
void print(hash_table * hashTable) {
int i=0;
printf("printing...");
for(;i<(hashTable->table_size);i++) {
node * temp;
for(temp=hashTable->table[i];temp!=NULL;temp=temp->next) {
printf("%d %d ",temp->key,temp->value);
}
printf("\n");
}
}
int hash (int key, int table_size) {
return key % table_size;
}
void insert(int key, int value, hash_table *h) {
node * temp;
temp=malloc(sizeof(node));
temp->key=key;
temp->value=value;
int index=hash(key,h->table_size);
temp->next=h->table[index];
h->table[index]=temp;
}
hash_table * rehash(hash_table * h) {
hash_table * t;
t=create(h->table_size * 2);
int i=0;
for(;i<(h->table_size);i++) {
node * temp;
for(temp=h->table[i];temp!=NULL;) {
int index=hash(temp->key,t->table_size);
node * a=t->table[index];
t->table[index]=temp;
temp=temp->next;
t->table[index]->next=a;
}
}
return t;
}
int main(void) {
hash_table * h = create(11);
h->count=0;
// print(h);
int i=1;
for(;i<100;i*=2)
insert(i,i,h);
print(h);
hash_table * t= rehash(h);
print(t);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "filebasics.h"
// Mikael Nenonen k90390
// 2017-08-03
int print_file(const char *filename) {
FILE *f = fopen(filename, "r");
if (!f)
return -1;
int length = 0;
while(1) {
char string[1000] = "";
if(fgets(string, 1000, f) == NULL)
break;
length += strlen(string);
printf("%s", string);
}
fclose(f);
return length;
}
char *difference(const char* file1, const char* file2) {
FILE *f1 = fopen(file1, "r");
FILE *f2 = fopen(file2, "r");
if (!f1 || !f2) {
fprintf(stderr, "Opening file failed\n");
return 0;
}
char *s1, *s2, *s1orig, *s2orig;
int bignumber = 10000;
s1 = s1orig = malloc(bignumber);
s2 = s2orig = malloc(bignumber);
while(1) {
s1 = fgets(s1, bignumber, f1);
s2 = fgets(s2, bignumber, f2);
if(s1 == 0 || s2 == 0)
break;
char *s1copy, *s2copy;
s1copy = s1;
s2copy = s2;
int diff = 0;
while(*s1copy) {
if(!(*s1copy == *s2copy)) {
diff = 1;
break;
}
if(*s2copy == 0) {
diff = 1;
break;
}
s1copy++, s2copy++;
}
if(*s2copy)
diff = 1;
if(diff) {
char* dashes = "----\n";
s1 = strcat(s1, dashes);
s1 = strcat(s1, s2);
strcpy(s2, s1);
strcpy(s1orig, s2);
free(s2orig);
fclose(f1);
fclose(f2);
return s1orig;
}
s1++, s2++;
}
fclose(f1);
fclose(f2);
free(s1orig);
free(s2orig);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
char line[80],ctr;
int i,c,end=0,character =0,words=0,lines=0;
printf("Press enter to return\n");
while(end==0)
{
//read a line
c=0;
while((ctr=getchar())!='\n')
line[c++]=ctr;
line[c]='\0';
//counting the line
if(line[0]=='\0')
break;
else
{
words++;
for(i=0;line[i]!='\0';i++)
if(line[i]==' '||line[i]=='\t')
words++;
}
//counting line and charater
lines=lines+1;
character=character + strlen(line);
}
printf("\n");
printf("lines=%d\n",lines);
printf("words=%d\n",words);
printf("charater=%d\n",character);
getch();
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_print_l.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mlenoir <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/04/20 12:09:59 by mlenoir #+# #+# */
/* Updated: 2016/04/29 12:21:57 by mlenoir ### ########.fr */
/* */
/* ************************************************************************** */
#include "../libft/includes/libft.h"
#include "../ft_ls.h"
int ft_print_toto(t_lstdbl_in in)
{
t_lstdbl *tmp;
int toto;
toto = 0;
tmp = in.first;
if (tmp)
{
while (tmp)
{
toto += tmp->st.st_blocks;
tmp = tmp->next;
}
ft_printf("total ");
ft_putnbr(toto);
ft_putchar('\n');
}
return (1);
}
void ft_switch_print_l(t_lstdbl *elem, t_ls_size *size)
{
char my_buf[75];
int len;
ft_print_permission(elem->st);
ft_putcharn(' ', size->size_nlink - ft_intlen(elem->st.st_nlink, 0));
ft_printf(" %d", elem->st.st_nlink);
ft_print_pass(elem, size);
ft_print_size(elem, size);
ft_print_date(elem->st);
ft_printf(" %s", elem->content);
if (S_ISLNK(elem->st.st_mode))
{
len = readlink(elem->path, my_buf, 73);
my_buf[len] = '\0';
ft_printf(" -> %s", my_buf);
}
ft_putchar('\n');
}
int ft_print_l(t_lstdbl_in in)
{
t_lstdbl *first;
t_ls_size *size;
first = in.first;
if (!(size = ft_init_size(in)))
return (0);
ft_print_toto(in);
while (first)
{
ft_switch_print_l(first, size);
first = first->next;
}
free(size);
return (1);
}
|
C
|
/* x_mem.c - x_mem */
#include <avr-Xinu.h>
#include <mem.h>
#include <avr/io.h>
extern char *_etext;
extern char *__bss_start, *__bss_end;
extern char *__data_start, *__data_end;
extern char *_end;
/*
*------------------------------------------------------------------------
* x_mem - (command mem) print memory use and free list information
*------------------------------------------------------------------------
*/
COMMAND x_mem(int narg, int *varg)
//int stdin, stdout, stderr, nargs;
//char *args[];
{
int i;
struct mblock *mptr;
char str[80];
unsigned free;
unsigned avail;
unsigned stkmem;
/* calculate current size of free memory and stack memory */
for( free=0,mptr=memlist.mnext ; mptr!=(struct mblock *)NULL ;
mptr=mptr->mnext)
free += mptr->mlen;
for (stkmem=0,i=0 ; i<NPROC ; i++) {
if (proctab[i].pstate != PRFREE)
stkmem += (unsigned)proctab[i].pstklen;
}
sprintf(str,
"Flash memory: %ul bytes total, %u text\n",
1L + (unsigned long)FLASHEND, (unsigned) &_etext);
write(varg[1], str, strlen(str));
sprintf(str,
"RAM memory: %u bytes RAM, %u registers %u data, %u bss\n",
1 + (unsigned)RAMEND, (unsigned) &__data_start,
(unsigned) &__data_end - (unsigned) &__data_start,
(unsigned) &__bss_end - (unsigned) &__bss_start);
write(varg[1], str, strlen(str));
avail = (unsigned)RAMEND - (unsigned) &_end + 1;
sprintf(str," initially: %5u avail\n", avail);
write(varg[1], str, strlen(str));
sprintf(str," presently: %5u avail, %5u stack, %5u heap\n",
free, stkmem, avail - stkmem - free);
write(varg[1], str, strlen(str));
sprintf(str," free list:\n");
write(varg[1], str, strlen(str));
for( mptr=memlist.mnext ; mptr!=(struct mblock *)NULL ;
mptr=mptr->mnext) {
sprintf(str," block at 0x%4x, length %5u (0x%x)\n",
mptr, mptr->mlen, mptr->mlen);
write(varg[1], str, strlen(str));
}
return(OK);
}
|
C
|
//Supermercado
//Archivos de cabecera
#include<stdio.h>
//Prototipo de funciones
void compra(float *, char *);
void descuento(float *, float *, char *);
void mostrarResul(float *);
//Funcin principal
void main(){
float com,des;
char bol;
compra(&com, &bol);
descuento(&des, &com, &bol);
mostrarResul(&des);
}
//Cuerpo de las funciones
void compra(float *com, char *bol){
printf("Ingrese el monto de la compra: \n");
scanf("%f",*&com);
printf("\nIngrese unicamente la primera letra en mayuscula de la bola que le toco: \n");
scanf(" %c",*&bol);
}
void descuento(float *des, float *com, char *bol){
switch(*bol){
case'A': *des = *com - (*com *.2);
break;
case'R': *des = *com - (*com *.3);
break;
case'B': *des = *com;
break;
}
}
void mostrarResul(float *des){
printf("\nEl total a pagar es: %.2f",*des);
}
|
C
|
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Arcangel.Andres";
char target[20];
int sourcesize, targetsize;
int i;
sourcesize = strlen(source);
/* Se completa el array target con el caracter a */
for (i = 0; i < 20; i++) {
if (i < sourcesize) {
target[i] = source[i];
} else {
target[i] = 'a';
}
}
/* String original */
printf ("Source: ");
for (i = 0; i < sourcesize; i++) {
printf("[%c]",source[i]);
}
printf ("\nSize: %d\n", sourcesize);
/* String target */
targetsize = strlen(target);
printf ("Target: ");
for (i = 0; i < 25; i++) {
printf("[%c]",target[i]);
}
printf ("\nSize: %d\n", targetsize);
return 0;
}
|
C
|
#include "doors.h"
#include "secure.h"
#include "doors_www.h"
#include "esp32/rom/crc.h"
#include "cJSON.h"
#define DOORS_CONFIG 1
#include "doors_config.h"
static const char * TAG = "DOORS_CONFIG";
#define BUTTON_CONNECTIONS 0x1F
#define RELAY_CONNECTIONS 0xFF
// Check if the gpio is valid and not already in used. The *all* mask is updated to reflect
// that the gpio is in use.
static bool check(uint8_t connection, uint8_t * all, uint8_t connections)
{
uint8_t mask = 1 << connection;
if (((mask & connections) == 0) || ((mask & *all) == 0)) return false;
*all = *all & ~mask;
return true;
}
static int seq_length(seq_t * seq)
{
int i = 0;
while (seq[i] != 0) i++;
return i;
}
#define VERIF0(b, msg) if (!b) { ESP_LOGE(TAG, msg); goto err; }
#define VERIF1(b, msg, p1) if (!b) { ESP_LOGE(TAG, msg, p1); goto err; }
#define VERIF2(b, msg, p1, p2) if (!b) { ESP_LOGE(TAG, msg, p1, p2); goto err; }
// Validate the configuration. Check for the following:
//
// - Config structure is of the proper version
//
// - No gpio usage conflict
// - All doors have valid open/close sequences
// - All doors have proper names
//
// - Network SSID and password are present
// - Config password access is present
bool doors_validate_config()
{
int i, len;
uint8_t all_buttons = BUTTON_CONNECTIONS;
uint8_t all_relays = RELAY_CONNECTIONS;
char * msg = NULL;
bool at_least_one_door = false;
msg = "VERSION CONFIG?";
VERIF1((doors_config.version == DOORS_CONFIG_VERSION),
"Config version not valid: %d",
doors_config.version)
for (i = 0; i < DOOR_COUNT; i++) {
if (doors_config.doors[i].enabled) {
at_least_one_door = true;
msg = "CONFLIT CONN. BOUTONS!";
VERIF2(check(doors_config.doors[i].conn_buttons, &all_buttons, BUTTON_CONNECTIONS),
"Button Connection %d already in use or not valid. Door %d, Open Button.",
doors_config.doors[i].conn_buttons, i + 1)
msg = "CONFLIT CONN. RELAIS!";
VERIF2(check(doors_config.doors[i].conn_relays, &all_relays, RELAY_CONNECTIONS ),
"Relay Connection %d already in use or not valid. Door %d, Open Relay.",
doors_config.doors[i].conn_relays, i + 1)
msg = "SEQ. OUVERTURE VIDE!";
VERIF1((doors_config.doors[i].seq_open[0] != 0), "Door %d: No opening sequence.", i + 1)
msg = "SEQ. OUVERTURE NON VALIDE!";
VERIF2((len = seq_length(doors_config.doors[i].seq_open) & 1), "Door %d: Opening sequence length is even: %d", i + 1, len);
msg = "SEQ. FERMETURE VIDE!";
VERIF1((doors_config.doors[i].seq_close[0] != 0), "Door %d: No closing sequence.", i + 1)
msg = "SEQ. FERMETURE NON VALIDE!";
VERIF2((len = seq_length(doors_config.doors[i].seq_open) & 1), "Door %d: Closing sequence length is even: %d", i + 1, len);
msg = "NOM PORTE!";
VERIF1((doors_config.doors[i].name[0] != 0), "Door %d: Name empty.", i + 1)
}
}
msg = "AUCUNE PORTE ACTIVE!";
VERIF0((at_least_one_door), "No active door.")
msg = "CONFIG WIFI!";
VERIF0((doors_config.network.ssid[0] != 0), "SSID empty.")
VERIF0((doors_config.network.pwd[0] != 0), "WiFi password empty.")
msg = "MOT DE PASSE!";
VERIF0((doors_config.pwd[0] != 0), "Configuration password empty.")
set_main_message("", "", NONE);
return true;
err:
set_main_message("ERREUR:", msg, ERROR);
return false;
}
static void doors_init_config(struct config_struct * cfg)
{
ESP_LOGW(TAG, "Config file initialized from default values.");
memset(cfg, 0, sizeof(struct config_struct));
cfg->version = DOORS_CONFIG_VERSION;
strcpy(cfg->pwd, BACKDOOR_PWD);
// Network
strcpy(cfg->network.ssid, "wifi ssid");
strcpy(cfg->network.pwd, "wifi pwd" );
strcpy(cfg->network.ip, "");
strcpy(cfg->network.mask, "255.255.255.0");
strcpy(cfg->network.gw, "192.168.1.1");
cfg->network.www_port = 80;
// Doors
for (int i = 0; i < DOOR_COUNT; i++) {
cfg->doors[i].enabled = false;
strcpy(cfg->doors[i].name, "Porte ");
cfg->doors[i].name[6] = '1' + i;
cfg->doors[i].name[7] = 0;
cfg->doors[i].conn_buttons = i;
cfg->doors[i].conn_relays = i;
cfg->doors[i].seq_open[0] = 500;
cfg->doors[i].seq_close[0] = 500;
}
cfg->relay_abort_length = 250; // ms
}
// Retrieve configuration from SPIFFS config.json file.
// If crc32 is not OK or file does not exists, initialize the config and return FALSE.
// If crc32 is OK, return TRUE
#define GET_STR(obj, var, ident, size) \
if ((item = cJSON_GetObjectItem(obj, ident)) == NULL) { ESP_LOGE(TAG, "Item [%s] not found.", ident); goto fin; } \
if (!cJSON_IsString(item)) { ESP_LOGE(TAG, "ITEM [%s] not a string.", ident); goto fin; } \
if (strlen(item->valuestring) > size) { ESP_LOGE(TAG, "String too long item [%s].", ident); goto fin; } \
strcpy(var, item->valuestring);
#define GET_VAL(obj, var, ident) \
if ((item = cJSON_GetObjectItem(obj, ident)) == NULL) { ESP_LOGE(TAG, "Item [%s] not found.", ident); goto fin; } \
if (!cJSON_IsNumber(item)) { ESP_LOGE(TAG, "ITEM [%s] not a number.", ident); goto fin; } \
var = item->valueint;
#define GET_DOUBLE(obj, var, ident) \
if ((item = cJSON_GetObjectItem(obj, ident)) == NULL) { ESP_LOGE(TAG, "Item [%s] not found.", ident); goto fin; } \
if (!cJSON_IsNumber(item)) { ESP_LOGE(TAG, "ITEM [%s] not a number.", ident); goto fin; } \
var = item->valuedouble;
#define GET_VAL_ITEM(obj, var, ident, index) \
if ((item = cJSON_GetArrayItem(obj, index)) == NULL) { ESP_LOGE(TAG, "Item %s[%d] not found.", ident, index); goto fin; } \
if (!cJSON_IsNumber(item)) { ESP_LOGE(TAG, "Item %s[%d] not a number.", ident, index); goto fin; } \
var = item->valueint;
#define GET_BOOL(obj, var, ident) \
if ((item = cJSON_GetObjectItem(obj, ident)) == NULL) { ESP_LOGE(TAG, "Item [%s] not found.", ident); goto fin; } \
if (!cJSON_IsBool(item)) { ESP_LOGE(TAG, "ITEM [%s] not a boolean.", ident); goto fin; } \
var = cJSON_IsTrue(item);
#define GET_ARRAY(obj, var, ident, size) \
if ((item = cJSON_GetObjectItem(obj, ident)) == NULL) { ESP_LOGE(TAG, "Item [%s] not found.", ident); goto fin; } \
if (!cJSON_IsArray(item)) { ESP_LOGE(TAG, "ITEM [%s] not an array.", ident); goto fin; } \
if (cJSON_GetArraySize(item) != size) { ESP_LOGE(TAG, "Wrong array size for %s (%d).", ident, cJSON_GetArraySize(item)); goto fin; } \
var = item;
#define GET_OBJECT(obj, var, ident) \
if ((item = cJSON_GetObjectItem(obj, ident)) == NULL) { ESP_LOGE(TAG, "Item [%s] not found.", ident); goto fin; } \
if (!cJSON_IsObject(item)) { ESP_LOGE(TAG, "ITEM [%s] not a group.", ident); goto fin; } \
var = item;
#define GET_OBJECT_ITEM(obj, var, ident, index) \
if ((item = cJSON_GetArrayItem(obj, index)) == NULL) { ESP_LOGE(TAG, "Item %s[%d] not found.", ident, index); goto fin; } \
if (!cJSON_IsObject(item)) { ESP_LOGE(TAG, "Item [%d] not a valid object.", index); goto fin; } \
var = item;
bool config_parse_seq(seq_t * seq, char * str, int max_size)
{
char *save = str;
while (*str == ' ') str++;
while (*str && (max_size > 0)) {
*seq = 0;
while (isdigit(*str)) { *seq = (*seq * 10) + (*str - '0'); str++; }
seq++;
max_size--;
while (*str == ' ') str++;
if (*str != ',') break;
str++;
while (*str == ' ') str++;
}
if (max_size > 0) *seq = 0;
if (*str != 0) ESP_LOGE(TAG, "Sequence not valid: [%s]", save);
return *str == 0;
}
static bool doors_get_config_from_file(char * filename)
{
int i;
char * tmp = malloc(181);
FILE *f = fopen(filename, "r");
if (f == NULL) {
ESP_LOGW(TAG, "Config file %s not found.", filename);
return false;
}
else {
ESP_LOGI(TAG, "Reading JSON config file %s.", filename);
fseek(f, 0L, SEEK_END);
int buff_size = ftell(f);
rewind(f);
char * buff = (char *) malloc(buff_size + 1);
fread(buff, 1, buff_size, f);
buff[buff_size] = 0;
fclose(f);
memset(&doors_config, 0, sizeof(doors_config));
cJSON * root = cJSON_Parse(buff);
cJSON * item;
cJSON * net, * doors, * door;
bool completed = false;
GET_VAL(root, doors_config.version, "version");
if (doors_config.version != DOORS_CONFIG_VERSION) {
ESP_LOGE(TAG, "File %s: Wrong config version: %d.", filename, doors_config.version);
return false;
}
double read_crc;
GET_DOUBLE(root, read_crc, "crc32");
doors_config.crc32 = (uint32_t) read_crc;
GET_STR(root, doors_config.pwd, "pwd", PWD_SIZE);
GET_VAL (root, doors_config.relay_abort_length, "relay_abort_length" );
GET_OBJECT(root, net, "network");
GET_STR(net, doors_config.network.ssid, "ssid", SSID_SIZE);
GET_STR(net, doors_config.network.pwd, "pwd", PWD_SIZE );
GET_STR(net, doors_config.network.ip, "ip", IP_SIZE );
GET_STR(net, doors_config.network.mask, "mask", IP_SIZE );
GET_STR(net, doors_config.network.gw, "gw", IP_SIZE );
GET_VAL(net, doors_config.network.www_port, "port");
GET_ARRAY(root, doors, "doors", DOOR_COUNT);
for (i = 0; i < DOOR_COUNT; i++) {
GET_OBJECT_ITEM(doors, door, "door", i);
GET_BOOL(door, doors_config.doors[i].enabled, "enabled" );
GET_STR(door, doors_config.doors[i].name, "name", NAME_SIZE);
GET_VAL(door, doors_config.doors[i].conn_buttons, "conn_buttons" );
GET_VAL(door, doors_config.doors[i].conn_relays, "conn_relays" );
GET_STR(door, tmp, "seq_open", 181);
if (!config_parse_seq(doors_config.doors[i].seq_open, tmp, SEQ_SIZE)) goto fin;
GET_STR(door, tmp, "seq_close", 181);
if (!config_parse_seq(doors_config.doors[i].seq_close, tmp, SEQ_SIZE)) goto fin;
}
completed = true;
fin:
cJSON_Delete(root);
free(buff);
uint32_t crc32 = crc32_le(0, (uint8_t const *) &doors_config, sizeof(doors_config) - 4);
ESP_LOGI(TAG, "Retrieved config: computed CRC: %u.", crc32);
if (!completed) {
ESP_LOGE(TAG, "Unable to complete reading configuration parameters on file %s.", filename);
return false;
}
else if (doors_config.crc32 != crc32) {
ESP_LOGE(TAG, "Configuration CRC error on file %s (%u vs %u).",
filename, doors_config.crc32, crc32);
return false;
}
}
free(tmp);
return true;
}
void config_seq_to_str(seq_t * seq, char * str, int max_size)
{
int cnt = SEQ_SIZE;
bool first = true;
while ((cnt > 0) && (max_size > 0) && (*seq != 0)) {
if (!first) { *str++ = ','; if (--max_size <= 1) break; }
first = false;
int val = *seq++;
int i = 0;
char tmp[5];
do {
tmp[i++] = '0' + (val % 10);
val = val / 10;
} while (val > 0);
do {
*str++ = tmp[--i];
if (--max_size <= 1) break;
} while (i > 0);
cnt--;
}
*str = 0;
}
static bool doors_save_config_to_file(char * filename)
{
int i;
char * tmp = (char *) malloc(181);
doors_config.crc32 = crc32_le(0, (uint8_t const *) &doors_config, sizeof(doors_config) - 4);
ESP_LOGI(TAG, "Saved config computed CRC: %u.", doors_config.crc32);
cJSON * root = cJSON_CreateObject();
cJSON * net, * doors, * door;
cJSON_AddNumberToObject(root, "version", doors_config.version);
cJSON_AddStringToObject(root, "pwd", doors_config.pwd );
cJSON_AddNumberToObject(root, "relay_abort_length", doors_config.relay_abort_length );
cJSON_AddItemToObject (root, "network", net = cJSON_CreateObject() );
cJSON_AddStringToObject(net, "ssid", doors_config.network.ssid );
cJSON_AddStringToObject(net, "pwd", doors_config.network.pwd );
cJSON_AddStringToObject(net, "ip", doors_config.network.ip );
cJSON_AddStringToObject(net, "mask", doors_config.network.mask );
cJSON_AddStringToObject(net, "gw", doors_config.network.gw );
cJSON_AddNumberToObject(net, "port", doors_config.network.www_port);
cJSON_AddItemToObject(root, "doors", doors = cJSON_CreateArray());
for (i = 0; i < DOOR_COUNT; i++) {
cJSON_AddItemToArray(doors, door = cJSON_CreateObject());
cJSON_AddBoolToObject (door, "enabled", doors_config.doors[i].enabled);
cJSON_AddStringToObject(door, "name", doors_config.doors[i].name );
cJSON_AddNumberToObject(door, "conn_buttons", doors_config.doors[i].conn_buttons );
cJSON_AddNumberToObject(door, "conn_relays", doors_config.doors[i].conn_relays );
config_seq_to_str(doors_config.doors[i].seq_open, tmp, 181);
cJSON_AddStringToObject(door, "seq_open", tmp);
config_seq_to_str(doors_config.doors[i].seq_close, tmp, 181);
cJSON_AddStringToObject(door, "seq_close", tmp);
}
cJSON_AddNumberToObject(root, "crc32", doors_config.crc32);
FILE *f = fopen(filename, "w");
bool completed = false;
if (f == NULL) {
ESP_LOGE(TAG, "Not able to create config file %s.", filename);
}
else {
char * str = cJSON_Print(root);
int size = strlen(str);
completed = fwrite(str, 1, size, f) == size;
free(str);
cJSON_Delete(root);
fclose(f);
if (completed) {
ESP_LOGI(TAG, "Config file %s saved.", filename);
}
else {
ESP_LOGE(TAG, "Unable to write config into file %s.", filename);
}
}
free(tmp);
return completed;
}
bool doors_get_config()
{
if (doors_get_config_from_file("/spiffs/config.json")) {
return true;
}
else {
if (doors_get_config_from_file("/spiffs/config_back_1.json")) {
doors_save_config_to_file("/spiffs/config.json");
return true;
}
else if (doors_get_config_from_file("/spiffs/config_back_2.json")) {
doors_save_config_to_file("/spiffs/config.json");
doors_save_config_to_file("/spiffs/config_back_1.json");
return true;
}
else {
doors_init_config(&doors_config);
return doors_save_config();
}
}
}
bool doors_save_config()
{
doors_validate_config();
if (!doors_save_config_to_file("/spiffs/config.json")) return false;
if (!doors_save_config_to_file("/spiffs/config_back_1.json")) return false;
if (!doors_save_config_to_file("/spiffs/config_back_2.json")) return false;
return true;
}
|
C
|
#ifndef list_h
#define list_h
#define LIST_ADD_ITEM(list, item) \
item->prev = NULL; \
item->next = list; \
if(item->next) item->next->prev = item; \
list = item;
#define LIST_REMOVE_ITEM(list, item) \
if(item == list) list=item->next; \
if(item->prev) item->prev->next = item->next; \
if(item->next) item->next->prev = item->prev;
#define LIST_FOREACH(list, cursor, cursor_next) \
for(cursor=list; cursor_next = (cursor) ? cursor->next : NULL, cursor; cursor=cursor_next)
#endif
|
C
|
//
// countWays.c
// BoilerPlate
//
// Created by Nikhil Jagdale on 5/5/16.
// Copyright © 2016 Nikhil Jagdale. All rights reserved.
//
#include "countWays.h"
static int countWays(uint8_t n){
uint8_t numWays[n+1];
numWays[0] = 0;
numWays[1] = 1;
numWays[2] = 2;
numWays[3] = 4;
for(size_t i=4; i<=n; i++){
numWays[i] = numWays[i-1] + numWays[i-2] + numWays[i-3];
}
return numWays[n];
}
static int countWaysRecursiveHelper(int8_t n, uint8_t numWays[]){
if(numWays[n]>0)
return numWays[n];
numWays[n] = countWaysRecursiveHelper(n-1, numWays) +
countWaysRecursiveHelper(n-2, numWays) +
countWaysRecursiveHelper(n-3, numWays);
return numWays[n];
}
static int countWaysRecursive(int8_t n){
unsigned char numWays[n+1];
// init numWays cause it cannot be statically 0ed
for(int i=0; i<=n; i++)
numWays[i] = 0;
numWays[1] = 1;
numWays[2] = 2;
numWays[3] = 4;
return countWaysRecursiveHelper(n, numWays);
}
void test_climb_stairs(int8_t stairs) {
int8_t n = stairs;
printf("CountWays: Number of ways you can climb %d steps "
"1-2-3 at at time is %d\n", n, countWays(n));
printf("CountWaysRecursive: Number of ways you can climb %d steps "
"1-2-3 at at time is %d\n", n, countWaysRecursive(n));
}
|
C
|
/*
441. Arranging Coins
You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.
Given n, find the total number of full staircase rows that can be formed.
n is a non-negative integer and fits within the range of a 32-bit signed integer.
Example 1:
n = 5
The coins can form the following rows:
Because the 3rd row is incomplete, we return 2.
Example 2:
n = 8
The coins can form the following rows:
Because the 4th row is incomplete, we return 3.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdbool.h>
//#define A441
#ifdef A441
int arrangeCoins(int n) {
return sqrt(2 * (double)n + 0.25) - 0.5;
}
/*
// ע
int arrangeCoins(int n) {
return (sqrt(1 + (long)n * 8) - 1) / 2;
}
*/
int main(){
printf("%d", arrangeCoins(1804289383));
return 0;
}
#endif
|
C
|
/* engler, 140e: sorta cleaned up test code from 14-vm. */
#include "rpi.h"
#include "rpi-constants.h"
#include "rpi-interrupts.h"
#include "mmu.h"
static const unsigned OneMB = 1024 * 1024 ;
// for today, just crash and burn if we get a fault.
void data_abort_vector(unsigned lr) {
unsigned fault_addr;
// b4-44
asm volatile("MRC p15, 0, %0, c6, c0, 0" : "=r" (fault_addr));
staff_mmu_disable();
panic("data_abort fault at %x\n", fault_addr);
}
// shouldn't happen: need to fix libpi so we don't have to do this.
void interrupt_vector(unsigned lr) {
staff_mmu_disable();
panic("impossible\n");
}
/*
* an ugly, trivial test run.
* 1. setup the virtual memory sections.
* 2. enable the mmu.
* 3. do some simple tests.
* 4. turn the mmu off.
*/
void vm_test(void) {
// 1. init
staff_mmu_init();
assert(!mmu_is_enabled());
void *base = (void*)0x100000;
fld_t *pt = mmu_pt_alloc_at(base, 4096*4);
assert(pt == base);
// we use a non-zero domain id to test things out.
unsigned dom_id = 1;
// 2. setup mappings
// map the first MB: shouldn't need more memory than this.
staff_mmu_map_section(pt, 0x0, 0x0, dom_id);
// map the page table: for lab cksums must be at 0x100000.
unimplemented();
// map stack (grows down)
unimplemented();
// map the GPIO: make sure these are not cached and not writeback.
// [how to check this in general?]
unimplemented();
// if we don't setup the interrupt stack = super bad infinite loop
unimplemented();
// 3. install fault handler to catch if we make mistake.
mmu_install_handlers();
// 4. start the context switch:
// set up permissions for the different domains.
staff_write_domain_access_ctrl(0b01 << dom_id*2);
// use the sequence on B2-25
staff_set_procid_ttbr0(0x140e, dom_id, pt);
// note: this routine has to flush I/D cache and TLB, BTB, prefetch buffer.
staff_mmu_enable();
/*********************************************************************
* 5. trivial test: write a couple of values, make sure they succeed.
*
* you should write additional tests!
*/
assert(mmu_is_enabled());
// read and write a few values.
int x = 5, v0, v1;
assert(get32(&x) == 5);
v0 = get32(&x);
printk("doing print with vm ON\n");
x++;
v1 = get32(&x);
/*********************************************************************
* done with trivial test, re-enable.
*/
// 6. disable.
staff_mmu_disable();
assert(!mmu_is_enabled());
printk("OFF\n");
// 7. make sure worked.
assert(v0 == 5);
assert(v1 == 6);
printk("******** success ************\n");
}
void notmain() {
uart_init();
printk("implement one at a time.\n");
check_vm_structs();
vm_test();
clean_reboot();
}
|
C
|
#include <unistd.h>
void ft_putstr(char *c)
{
int i;
i = 0;
while (c[i])
{
write(1, &c[i], 1);
i++;
}
}
int count_repear(char c)
{
int res;
if (('a' <= c) && (c <= 'z'))
{
res = c - 'a' + 1;
}
if ('A' <= c && c <= 'Z')
{
res = c - 'A' + 1;
}
return (res);
}
int main(int argc, char **argv)
{
int i;
int count;
if (argc != 2)
{
write(1, "\n", 1);
return (0);
}
i = 0;
while (argv[1][i])
{
count = count_repear(argv[1][i]);
while (count--)
{
write(1, &argv[1][i], 1);
}
i++;
}
}
|
C
|
/*
File: ContFramePool.C
Author:
Date :
*/
/*--------------------------------------------------------------------------*/
/*
POSSIBLE IMPLEMENTATION
-----------------------
The class SimpleFramePool in file "simple_frame_pool.H/C" describes an
incomplete vanilla implementation of a frame pool that allocates
*single* frames at a time. Because it does allocate one frame at a time,
it does not guarantee that a sequence of frames is allocated contiguously.
This can cause problems.
The class ContFramePool has the ability to allocate either single frames,
or sequences of contiguous frames. This affects how we manage the
free frames. In SimpleFramePool it is sufficient to maintain the free
frames.
In ContFramePool we need to maintain free *sequences* of frames.
This can be done in many ways, ranging from extensions to bitmaps to
free-lists of frames etc.
IMPLEMENTATION:
One simple way to manage sequences of free frames is to add a minor
extension to the bitmap idea of SimpleFramePool: Instead of maintaining
whether a frame is FREE or ALLOCATED, which requires one bit per frame,
we maintain whether the frame is FREE, or ALLOCATED, or HEAD-OF-SEQUENCE.
The meaning of FREE is the same as in SimpleFramePool.
If a frame is marked as HEAD-OF-SEQUENCE, this means that it is allocated
and that it is the first such frame in a sequence of frames. Allocated
frames that are not first in a sequence are marked as ALLOCATED.
NOTE: If we use this scheme to allocate only single frames, then all
frames are marked as either FREE or HEAD-OF-SEQUENCE.
NOTE: In SimpleFramePool we needed only one bit to store the state of
each frame. Now we need two bits. In a first implementation you can choose
to use one char per frame. This will allow you to check for a given status
without having to do bit manipulations. Once you get this to work,
revisit the implementation and change it to using two bits. You will get
an efficiency penalty if you use one char (i.e., 8 bits) per frame when
two bits do the trick.
DETAILED IMPLEMENTATION:
How can we use the HEAD-OF-SEQUENCE state to implement a contiguous
allocator? Let's look a the individual functions:
Constructor: Initialize all frames to FREE, except for any frames that you
need for the management of the frame pool, if any.
get_frames(_n_frames): Traverse the "bitmap" of states and look for a
sequence of at least _n_frames entries that are FREE. If you find one,
mark the first one as HEAD-OF-SEQUENCE and the remaining _n_frames-1 as
ALLOCATED.
release_frames(_first_frame_no): Check whether the first frame is marked as
HEAD-OF-SEQUENCE. If not, something went wrong. If it is, mark it as FREE.
Traverse the subsequent frames until you reach one that is FREE or
HEAD-OF-SEQUENCE. Until then, mark the frames that you traverse as FREE.
mark_inaccessible(_base_frame_no, _n_frames): This is no different than
get_frames, without having to search for the free sequence. You tell the
allocator exactly which frame to mark as HEAD-OF-SEQUENCE and how many
frames after that to mark as ALLOCATED.
needed_info_frames(_n_frames): This depends on how many bits you need
to store the state of each frame. If you use a char to represent the state
of a frame, then you need one info frame for each FRAME_SIZE frames.
A WORD ABOUT RELEASE_FRAMES():
When we releae a frame, we only know its frame number. At the time
of a frame's release, we don't know necessarily which pool it came
from. Therefore, the function "release_frame" is static, i.e.,
not associated with a particular frame pool.
This problem is related to the lack of a so-called "placement delete" in
C++. For a discussion of this see Stroustrup's FAQ:
http://www.stroustrup.com/bs_faq2.html#placement-delete
*/
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
/* DEFINES */
/*--------------------------------------------------------------------------*/
/* -- (none) -- */
/*--------------------------------------------------------------------------*/
/* INCLUDES */
/*--------------------------------------------------------------------------*/
#include "cont_frame_pool.H"
#include "console.H"
#include "utils.H"
#include "assert.H"
/*--------------------------------------------------------------------------*/
/* DATA STRUCTURES */
/*--------------------------------------------------------------------------*/
/* -- (none) -- */
/*--------------------------------------------------------------------------*/
/* CONSTANTS */
/*--------------------------------------------------------------------------*/
/* -- (none) -- */
/*--------------------------------------------------------------------------*/
/* FORWARDS */
/*--------------------------------------------------------------------------*/
/* -- (none) -- */
/*--------------------------------------------------------------------------*/
/* METHODS FOR CLASS C o n t F r a m e P o o l */
/*--------------------------------------------------------------------------*/
ContFramePool* ContFramePool::node_head;
ContFramePool* ContFramePool::list;
ContFramePool::ContFramePool(unsigned long _base_frame_no,
unsigned long _n_frames,
unsigned long _info_frame_no,
unsigned long _n_info_frames)
{
// TODO: IMPLEMENTATION NEEEDED!
// bitmap can fit in one single frame
assert(_n_frames <= FRAME_SIZE *8);
base_frame_no = _base_frame_no; // the id of the first frame, in kernel first frame is 512nd frame
n_frames = _n_frames; // how many frames in this pool, 2^9 frames
nFreeFrames = _n_frames;
info_frame_no = _info_frame_no;
n_info_frames = _n_info_frames;
// bitmap == address
// if info_fram =0 means management information store in this frame
// we use first frame in this poll to store information
// and set the bitmap(address) to the address of first frame
// aka. " Frame Number * Frame Size" frame number== base_fram
// this time bitmap should be at 2MB 200000(hex)
if (info_frame_no == 0){
bitmap = (unsigned char *) ( base_frame_no * FRAME_SIZE);
}else{
bitmap = (unsigned char *) (info_frame_no * FRAME_SIZE);
// if not in the first frame set address to the current frame
// which contain the information
}
assert((n_frames %8) == 0);
// status of fram 00 means free
// 01 means head
// 10 meand in accessible
// 11 means allocated
for (int i =0; i*4< n_frames; i++){
bitmap[i] = 0x00;
}
// set first frame in fram pool to allocated
if(info_frame_no==0){
bitmap[0] = 0x40;
nFreeFrames--;
}
// if list has not beem declared
if ( ContFramePool::node_head == NULL)
{
ContFramePool::node_head = this;
ContFramePool::list = this;
}
else
{
ContFramePool::list->next = this;
ContFramePool::list = this;
}
next = NULL;
Console::puts("Frame Pool initialized\n");
}
unsigned long ContFramePool::get_frames(unsigned int _n_frames)
{
// TODO: IMPLEMENTATION NEEEDED!
assert(nFreeFrames > _n_frames );
// first number of frame pool
unsigned long frame_no = base_frame_no;
unsigned int i =0;
unsigned int frames_needed = _n_frames;
unsigned int count =0;
unsigned int same_frame = 0;
unsigned int find = 0;
unsigned char checker = 0xc0;
// find the first frames which has consecutive number of frames we can use
while (( i < n_frames/4) && (count < frames_needed)){
for ( int j =0 ; j < 4 && (count < frames_needed); j++){
// bit manipulation if i and checker = 0 means it's free
if ( (bitmap[i] & checker) == 0x0){
if ( same_frame == 1){
count ++;
}
else{
same_frame =1;
count++;
frame_no += i*4+j;
}
}else{
// this fram is occupied need to reset search
// if previous found fram availabe need to reset
// if not go to next fram directly
if(same_frame ==1){
// means previous search found fram available
//reset
count = 0;
same_frame = 0;
frame_no = base_frame_no;
}
checker = checker >>2;
//if found enough frames break
if ( count == frames_needed){
find = 1; // set the flag if not find return 0
break;
}
}
// do the early break same as outter loop
if (count == frames_needed){
find =1;
break;
}
checker = 0xc0;
i++;
}
if ( find == 0){
return 0;
}
}
// find enough frames we need set the status first to 11 and rest to 01
// now the fram_no is the first frame
// in order to set the checker to correct number need to know the difference between
// current frame and base frame
unsigned char checker_head = 0x40 >>(((frame_no - base_frame_no)%4)*2);
unsigned char checker_reset = 0xc0 >> (((frame_no - base_frame_no)%4)*2);
unsigned char checker_allocated = 0xc0 >> (((frame_no - base_frame_no)%4)*2);
unsigned int bitmap_index = ((frame_no - base_frame_no)/4);
// set the head to 01
bitmap[bitmap_index] =(( bitmap[bitmap_index] & (~checker_reset)) | checker_head);
checker_reset = checker_reset >> 2;
i = 1;
while ( i< _n_frames)
{
while((i < _n_frames) && (checker_reset != 0x0))
{
bitmap[bitmap_index] = (bitmap[bitmap_index] & (~checker_reset)) | checker_allocated;
checker_reset = checker_reset >> 2;
i++;
}
checker_reset = 0xc0;
bitmap_index++;
}
nFreeFrames -= _n_frames;
return (frame_no);
}
void ContFramePool::mark_inaccessible(unsigned long _base_frame_no,
unsigned long _n_frames)
{
unsigned long start = _base_frame_no;
unsigned long end = _base_frame_no + _n_frames;
unsigned int bitmap_index;
unsigned char checker;
unsigned char checker_reset;
for ( start; start < end; start++)
{
bitmap_index = ( (start - base_frame_no)/4);
checker_reset = 0xc0 << ((start%4)*2);
checker = 0x80 >> ((start%4)*2);
// whater the value is reset it
bitmap[bitmap_index] = bitmap[bitmap_index] & ( ~checker_reset);
// set the first two bit to 10 which means inaccessable
bitmap[bitmap_index] = bitmap[bitmap_index] | checker;
}
}
void ContFramePool::release_frames(unsigned long _first_frame_no)
{
// need to check this frame pool possess the frame we want to release
ContFramePool* current = ContFramePool::node_head;
while (( current->base_frame_no > _first_frame_no) || ( _first_frame_no >= current->base_frame_no + current->n_frames))
{
current = current->next;
}
// check if frame is head of sequence
unsigned int bitmap_index = (_first_frame_no - current->base_frame_no)/4;
unsigned char checker_head = 0x80 >>(((_first_frame_no - current->base_frame_no)%4)*2);
unsigned char checker_reset = 0xc0 >> (((_first_frame_no - current->base_frame_no)%4*2));
unsigned int i;
if(((current->bitmap[bitmap_index] ^ checker_head) & checker_reset) == checker_reset)
{
// reset head to free frame
current->bitmap[bitmap_index] = current->bitmap[bitmap_index]&(~checker_reset);
}
// set the rest consective frame to free frame
for ( i = _first_frame_no; i < current->base_frame_no + current->n_frames; i++)
{
int index = ( i - current->base_frame_no)/4;
checker_reset = checker_reset >> (i - current->base_frame_no)%4;
if ((current->bitmap[index] & checker_reset)==0)
{
break;
}
if(( current->bitmap[index] & checker_reset ) ==0)
{
break;
}
current->bitmap[index] = current->bitmap[index] & (~ checker_reset);
}
}
unsigned long ContFramePool::needed_info_frames(unsigned long _n_frames)
{
// 4K = 4096
return (_n_frames*2/ 8*4096) + ( (_n_frames*2) % (8*4096) > 0 ? 1 : 0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int N,K,i,*X,E=100;
scanf("%d %d",&N,&K);
X = (int*)malloc(N*sizeof(int));
for(i=0;i<N;i++){
scanf("%d",&X[i]);
}
for(i=0;i<N;i+=K){
if(X[i]==1){
E = E-3;
}
else{
E = E-1;
}
}
printf("%d\n",E);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.