language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
/* 253. Time Object */
# include <stdio.h>
# include "time.h"
void initTime(Time *time){
time->hour = 0;
time->minute = 0;
time->second = 0;
}
void setTime(Time *time, int hour, int minute, int second){
time->hour = hour;
time->minute = minute;
time->second = second;
}
void addTime(Time *time, int hour, int minute, int second){
time->second += second;
int carryout = time->second / 60;
time->second %= 60;
time->minute += minute + carryout;
carryout = time->minute / 60;
time->minute %= 60;
time->hour = (time->hour + hour + carryout) % 24;
}
void printTime(Time *time){
# ifdef H24
printf("%02d%cm:%02d:%02d\n", time->hour, time->minute, time->second);
# else
printf("%02d%cm:%02d:%02d\n", (time->hour >= 12) ? (time->hour - 12 + ((time->hour == 12) ? 12 : 0)) : (time->hour + ((!time->hour) ? 12 : 0)), ((time->hour >= 12) ? 'p' : 'a'), time->minute, time->second);
# endif
}
|
C
|
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <err.h>
#include <errno.h>
int main()
{
const char* f1 = "f1";
const char* f2 = "f2";
const char* f3 = "f3";
struct stat st;
if (stat(f1, &st) < 0)
{
err(2, "Cannot stat file '%s'", f1);
}
if (!S_ISREG(st.st_mode))
{
errx(3, "First argument should be a file");
}
if (!(st.st_mode & S_IRUSR))
{
errx(4, "File '%s' cannot be read", f1);
}
off_t f1_size = st.st_size;
struct pair_t
{
uint32_t start;
uint32_t length;
}__attribute__((packed)); //attribute packed is not necessary here
if (f1_size % sizeof(struct pair_t) != 0)
{
errx(5, "Error in format of file '%s'", f1);
}
if (stat(f2, &st) < 0)
{
err(5, "Cannot stat file '%s'", f2);
}
if (!S_ISREG(st.st_mode))
{
errx(6, "Second argument should be a file");
}
if (!(st.st_mode & S_IRUSR))
{
errx(7, "File '%s' cannot be read", f2);
}
off_t f2_size = st.st_size;
if (f2_size % sizeof(uint32_t) != 0)
{
errx(8, "Error in format of file '%s'", f2);
}
if (f2_size > 0xFFFFFFFF) //UINT32_MAX
{
warnx("Size of file '%s' is more than acceptable", f2);
}
int fd_1;
int fd_2;
int fd_3;
fd_1 = open(f1, O_RDONLY);
if (fd_1 < 0)
{
err(9, "Cannot open file '%s'", f1);
}
fd_2 = open(f2, O_RDONLY);
if (fd_2 < 0)
{
const int olderrno = errno;
close(fd_1);
errno = olderrno;
err(10, "Cannot open file '%s'", f2);
}
fd_3 = open(f3, O_CREAT | O_TRUNC | O_WRONLY, 0644);
if (fd_3 < 0)
{
const int olderrno = errno;
close(fd_1);
close(fd_2);
errno = olderrno;
err(11, "Cannot open file '%s'", f3);
}
struct pair_t pair;
ssize_t read_f1 = -1;
while((read_f1=read(fd_1, &pair, sizeof(pair))) > 0)
{
if (read_f1 != sizeof(pair))
{
const int olderrno = errno;
close(fd_1);
close(fd_2);
close(fd_3);
errno = olderrno;
errx(12, "Cannot read correctly file '%s'", f1);
}
uint32_t position = pair.start - 1;
off_t check = lseek(fd_2, position*sizeof(uint32_t), SEEK_SET);
if (check < 0)
{
const int olderrno = errno;
close(fd_1);
close(fd_2);
close(fd_3);
errno = olderrno;
err(14, "Error in positioning in file '%s'", f2);
}
uint32_t len = 0;
uint32_t current;
ssize_t read_f2;
while((read_f2=read(fd_2, ¤t, sizeof(current))) > 0)
{
if (read_f2 != sizeof(current))
{
const int olderrno = errno;
close(fd_1);
close(fd_2);
close(fd_3);
errno = olderrno;
errx(15, "Cannot read correctly file '%s'", f2);
}
ssize_t write_f3;
write_f3 = write(fd_3, ¤t, read_f2);
if (write_f3 == -1)
{
const int olderrno = errno;
close(fd_1);
close(fd_2);
close(fd_3);
errno = olderrno;
err(16, "Error in writing in file '%s'", f3);
}
if (write_f3 != read_f2)
{
const int olderrno = errno;
close(fd_1);
close(fd_2);
close(fd_3);
errno = olderrno;
errx(17, "Cannot write correctly in file '%s'", f3);
}
len++;
if (len == pair.length)
{
break;
}
}
if (read_f2 == -1)
{
const int olderrno = errno;
close(fd_1);
close(fd_2);
close(fd_3);
errno = olderrno;
err(18, "Error in reading file '%s'", f2);
}
}
if (read_f1 == -1)
{
const int olderrno = errno;
close(fd_1);
close(fd_2);
close(fd_3);
errno = olderrno;
err(19, "Error in reading file '%s'", f1);
}
close(fd_1);
close(fd_2);
close(fd_3);
exit(0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUM_CLASS 7
#define ATTRIBS 16
//NUM_CLASS is the number of classes we wish to train for. In zoo.data it is 7
// ATTRIBS is the number of attributes we have in our training examples.
//Specific Boundary consists of an array of NUM_CLASS pointers. Each pointer points to another char array.
//This char array is the specific boundary of the corresponding class.
//General Boundary also consists of an array of NUM_CLASS pointers. Each pointer points to the head of a linked list.
//Each node of the linked list corresponds to a hypothesis in the general boundary. It is a linked list to enable easy remove and add operations.
typedef struct node {
char hypothesis[ATTRIBS];
struct node *next;
}ghypo;
//ghypo is a hypothesis in the general boundary. Consists of a char array(the hypothesis) and pointer to next node in the list.
typedef ghypo* ghypoPtr;
int no_concept[NUM_CLASS] = {0};
//Initialize specific boundary as an array of NUM_CLASS pointers.
char *specific_boundary[NUM_CLASS];
//Initialize general boundary as an array of NUM_CLASS pointers.
ghypoPtr general_boundaries[NUM_CLASS];
int type = 0;
int i=0;
int class_type = 1;
char all_possible_values[ATTRIBS][7] = {
{'0','1','\0'}, {'0','1','\0'}, {'0','1','\0'}, {'0','1','\0'}, {'0','1','\0'}, {'0','1','\0'}, {'0','1','\0'},
{'0','1','\0'}, {'0','1','\0'}, {'0','1','\0'}, {'0','1','\0'}, {'0','1','\0'}, {'0','2','4','5','6','8','\0'},
{'0','1','\0'}, {'0','1','\0'}, {'0','1','\0'}
};
void print_general_boundary(){
//Function to print the general boundaries.
for(int g = 0; g < NUM_CLASS; g++)
{
ghypoPtr head = general_boundaries[g];
printf("g = %d\n",g);
while (head != NULL)
{
//Traverse through the linked list and print out each hypothesis
for(int h=0;h<ATTRIBS;h++) printf("%c ",head->hypothesis[h]);
printf(",\n");
head = head->next;
}
printf(";\n");
}
}
void parse_data(char *train_data,char *data){
//This function parses the string data from the dataset file and tokenizes it
//Each tokenized string is stored as char in train_data
char *token = strtok(data,",");
int t=0;
while(token){
token = strtok(NULL,",");
if(token==NULL) break; //Without this line, code gets paused here.
train_data[t++] = *token;
}
return;
}
int consistent(int type, char *hypothesis, char *train_data){
//Check if the hypothesis and train_data are consistent or not
//Returns 1 if negative example and
int value = (type == train_data[ATTRIBS]-'0');
//value if 1 if positive training example, 0 if negative example.
int c;
for(c=0; c<ATTRIBS; c++){
if(!(hypothesis[c] == '?' || hypothesis[c] == train_data[c]) || (value && hypothesis[c]=='o')) return !value;
//If inconsistent, return.
}
return value;
}
int subsetOf(ghypoPtr h1, ghypoPtr h2){ // h2 is more general than or equal to h1 if returned 1
for(i=0; i<ATTRIBS; i++) if(h2->hypothesis[i] != '?' && h1->hypothesis[i] != h2->hypothesis[i]) return 0;
return 1;
}
void remove_hypothesis(int type, ghypoPtr prev, ghypoPtr current)
{
//Remove a hypothesis(node in linked list) from general boundary.
if(prev == NULL) general_boundaries[type-1] = current->next;
else prev->next = current->next;
}
int ispath(char *h1, char *h2)
{
//Check if there is a path from hypothesis h1 to hypothesis h2.
int i;
for(i=0; i<ATTRIBS; i++) if(!(h2[i]=='o' || h2[i]==h1[i] || h1[i]=='?')) return 0;
return 1;
}
void specify_gb(int type, char *train_data, ghypoPtr prev, ghypoPtr current)
{
//Specifying the genera; boundary.
int i,j,k;
for(i=0; i<ATTRIBS; i++)
{
if(current->hypothesis[i] == '?' && specific_boundary[type-1][i] == 'o')
{
j = 0;
while(all_possible_values[i][j] != '\0')
{
ghypoPtr newHypo = (ghypoPtr)malloc(sizeof(ghypo));
for(k=0;k<ATTRIBS;k++)
{
newHypo->hypothesis[k] = current->hypothesis[k];
}
newHypo->hypothesis[i] = all_possible_values[i][j];
j++;
if(!consistent(type,newHypo->hypothesis,train_data) || !ispath(newHypo->hypothesis, specific_boundary[type-1]))
{
free(newHypo);
continue;
}
if(prev == NULL) general_boundaries[type-1] = newHypo;
else prev->next = newHypo;
newHypo->next = current;
prev = newHypo;
}
}
else if(current->hypothesis[i] == '?' && specific_boundary[type-1][i] != '?')
{
ghypoPtr newHypo = (ghypoPtr)malloc(sizeof(ghypo));
for(j=0; j<ATTRIBS; j++) newHypo->hypothesis[j] = current->hypothesis[j];
//memcpy(newHypo->hypothesis,current->hypothesis,sizeof(newHypo->hypothesis));
newHypo->hypothesis[i] = specific_boundary[type-1][i];
if(!consistent(type, newHypo->hypothesis, train_data) || !ispath(newHypo->hypothesis, specific_boundary[type-1])){
free(newHypo);
continue;
}
if(prev == NULL) general_boundaries[type-1] = newHypo;
else prev->next = newHypo;
newHypo->next = current;
prev = newHypo;
}
}
if(prev == NULL) general_boundaries[type-1] = current->next;
else prev->next = current->next;
//current = current->next;
//free(current);
//current = current->next;
}
void build_general_boundary(int type, char *train_data)
{
//printf("Building general boundary\n");
ghypoPtr current = general_boundaries[type-1], prev = NULL,temp;
//for all hypotheses i.e. iterate through linked list
//check consistency for all hypotheses
//remove inconsistent ones
while(current!=NULL){
if(!consistent(type, current->hypothesis,train_data)){
if(type == train_data[ATTRIBS]-'0'){
//If positive example and inconsistent, remove this hypothesis.
remove_hypothesis(type, prev, current);}
//If negative example, specify the general boundary/
else specify_gb(type, train_data, prev, current);
temp=current;
current = current->next;
free(temp);
}
else{
prev = current;
current = current->next;
}
}
}
void build_specific_boundary(int type, char *train_data)
{
//Building the specific boundary.
//printf("Building specific boundary\n");
if(type == train_data[ATTRIBS]-'0') // +ve
{
int x;
for(x=0; x<ATTRIBS; x++)
{
if(specific_boundary[type-1][x] == 'o') specific_boundary[type-1][x] = train_data[x];
else if(specific_boundary[type-1][x] != train_data[x]) specific_boundary[type-1][x] = '?';
}
}
else
{
//TODO
//if(!consistent(type, specific_boundary[type-1], train_data)) no_concept[type-1] = 1;
}
}
void remove_unnecessary_gb()
{
//Remove unnecessary general boundaries.
int p,r;
for(p=0; p<NUM_CLASS; p++)
{
//general_boundaries[0] is NULL here
ghypoPtr left_node = general_boundaries[p], right_node , prev = NULL,temp;
if(left_node==NULL) continue;
right_node = left_node->next;
while (left_node != NULL && left_node->next != NULL)
{
r = 0;
right_node = left_node->next;
while (right_node != NULL)
{
//getting some error here
if(subsetOf(left_node, right_node))
{
remove_hypothesis(p+1, prev, left_node);
temp = left_node->next;
free(left_node);
left_node = temp;
r = 1;
break;
}
right_node = right_node->next;
}
if(r == 1) continue;
prev = left_node;
left_node = left_node->next;
}
}
}
void build_version_space(char *train_data)
{
//Main function which calls the build_specific_boundary and build_general_boundary.
type = train_data[ATTRIBS] - '0';//This is to make type as int
//train_data is of type int, train_data[ATTRIBS] is char
//TODO
//if(no_concept[type-1] >= 1) return;
//Build version space for each class.
for(class_type=1; class_type<=NUM_CLASS; class_type++) // here i is type
{
printf("Training for class %d\n",class_type);
if(class_type==type) // positive example
{
build_general_boundary(class_type, train_data);
build_specific_boundary(class_type, train_data);
}
else // negative example
{
build_specific_boundary(class_type, train_data);
build_general_boundary(class_type, train_data);
remove_unnecessary_gb();
}
}
}
void print_version_space()
{
int x,i;
printf("Specific Boundary\n");
for(x=0; x<NUM_CLASS; x++)
{
for(i=0;i<ATTRIBS;i++){
printf("%c ", specific_boundary[x][i]);
}
printf("\n");
}
printf("General Boundary\n");
print_general_boundary();
return;
}
|
C
| ERROR: type should be string, got "https://app.codility.com/demo/results/training9E4NP2-H33/\n\n#include <string.h>\n\ntypedef struct {\n int pos;\n int cost;\n} node_t;\n\nint *fib;\nint fibSize;\n\nint solution(int A[], int N) {\n // write your code in C99 (gcc 6.2.0)\n //Initializa Queue\n \n if (N < 3) return 1;\n \n node_t *queue = (node_t *)malloc(sizeof(node_t) * N);\n memset(queue, 0, sizeof(node_t) * N);\n int first = 0;\n int last = 0;\n int qsize = 0;\n\n int *visited = (int *)malloc(sizeof(int) * N);\n memset(visited, 0, sizeof(int) * N);\n \n fib = (int *)malloc(sizeof(int) * N);\n fib[0] = 0;\n fib[1] = 1;\n fibSize = 2;\n for (int i = 2; ; i++) {\n int sum = fib[i - 1] + fib[i - 2];\n if (sum > N) {\n break;\n }\n fib[i] = sum;\n fibSize++;\n \n if (A[fib[i] - 1] == 1) {\n queue[last].pos = fib[i] - 1;\n queue[last].cost = 1;\n qsize++;\n last = (last + 1) % N;\n visited[fib[i] - 1] = 1;\n } else if (fib[i] == N + 1) {\n free(fib);\n free(queue);\n return 1;\n }\n }\n \n while (qsize > 0) {\n int cur_pos = queue[first].pos;\n int cur_cost = queue[first].cost;\n first = (first + 1) % N;\n qsize--;\n \n for (int f = 1; f < fibSize; f++) {\n int pos = cur_pos + fib[f];\n if (pos == N) {\n free(fib);\n free(queue);\n return cur_cost + 1;\n } else if (pos < N && !visited[pos] && A[pos] == 1) {\n queue[last].pos = pos;\n queue[last].cost = cur_cost + 1;\n qsize++;\n last = (last + 1) % N;\n visited[pos] = 1;\n }\n }\n }\n \n free(fib);\n free(queue);\n return -1;\n}\n"
|
C
|
//Função para definição de operações.
TPconsulta operacoes(doenca *vetD, medico *vetM, int chave[2][2], int nDoenca, int nMed){
char op[8];
TPconsulta lista=NULL;
while(1){
scanf("%s", op); //Obtenção da operação desejada.
if (op[0]=='0')
break;
switch(op[1]){
case 'd': lista = insereOrd(chave, lista); break; //Add
case 'm': lista = apaga(chave, lista); break; //Rm
case 'l': altera(chave, lista, vetD, vetM, op[5], nDoenca, nMed); break; //Alt
}
}
return lista; //Retorna o início da lista de consultas.
}
/**
* Função para impressão do relatório
* @param letra Letra de início do relatório.
* @param início Apontador para o início da lista de consultas.
* @param chave Chave para criptografia
*/
void imprimeRelat(TPconsulta inicio, char letra, int chave[2][2]){
TPconsulta atual, anterior;
atual = inicio;
cripto(chave, atual->paciente, 'd');
//Definição do início do relatório.
while (atual->paciente[0]<letra){
cripto(chave, atual->paciente, 'e');
//Caso não haja letra posterior à desejada, é listado do começo.
if (atual->prox == inicio){
atual = inicio;
cripto(chave, atual->paciente, 'd');
break;
}
anterior = atual;
atual = atual->prox;
cripto(chave, atual->paciente, 'd');
}
inicio = atual;
//Impressão do relatório, e liberação da memória.
while(1){
printf("%s %s %s %d\n", atual->paciente, atual->data, atual->codigo, atual->crm);
anterior = atual;
atual = atual->prox;
free(anterior);
if (atual == inicio)
break;
cripto(chave, atual->paciente, 'd');
}
return;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* disp_settings.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: acottier <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/09/19 12:09:26 by acottier #+# #+# */
/* Updated: 2016/09/21 16:07:00 by acottier ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/ft_select.h"
static void null_padding(t_elem *lst, int nb)
{
t_elem *link;
link = NULL;
while (lst->next)
lst = lst->next;
while (nb > 0)
{
lst = add_null_elem(lst);
nb--;
}
}
void list_padding(t_elem *lst, t_info *info)
{
int max_col;
max_col = info->col / (lst->biggest + 1);
while (lst)
{
if (!lst->next)
{
if (lst->col < max_col)
null_padding(lst, max_col - lst->col);
}
lst = lst->next;
}
}
static void assign_coords(t_elem *lst, int max_col)
{
int line_pos;
int col_pos;
line_pos = 1;
col_pos = 1;
while (lst)
{
if (col_pos > max_col)
{
col_pos = 1;
line_pos++;
}
lst->li = line_pos;
lst->col = col_pos;
col_pos++;
lst = lst->next;
}
}
static int check_size(t_elem *lst, t_elem *cursor, t_info *info, int total)
{
int biggest;
biggest = 0;
while (cursor)
{
total++;
if ((int)ft_strlen(cursor->name) > biggest)
biggest = (int)ft_strlen(cursor->name);
cursor = cursor->next;
}
cursor = lst;
while (cursor)
{
cursor->biggest = biggest;
cursor = cursor->next;
}
info->max_col = info->col / (biggest + 1);
info->max_line = (to_end(lst)->index / info->max_col) + info->srchprompt;
if (to_end(lst)->index % info->max_col != 0)
info->max_line++;
(info->max_line == 0) ? (info->max_line = 1) : 0;
if (total > info->max_col * info->li)
return (1);
return (0);
}
void disp_settings(t_elem *lst, t_info *info)
{
info->max_col = 0;
if (check_size(lst, lst, info, 0) == 1)
{
tputs(tgetstr("cl", 0), 1, ft_useless);
error(NULL, 1);
}
else
{
assign_coords(lst, info->max_col);
list_padding(lst, info);
info->lst = to_start(lst);
display_elems(lst, info);
}
}
|
C
|
#ifndef UNIT_TESTING
#define UNIT_TESTING
#endif
#include "fake_estantes.h"
#include "fake_mercadeo.h"
#include "fake_supervisor.h"
#include "../../modulos/cajeras.h"
#include <stdio.h>
#include <stdlib.h>
static void* cliente_aleatorio(void *);
int main() {
srand( time(NULL) );
pthread_t clientes_aleatorios;
printf("Inicializando modulo cajera\n");
// Inicializando modulo
init_cajeras(5, 5, 5);
// encender_mitad_cajas();
pthread_create( &clientes_aleatorios, NULL, cliente_aleatorio, NULL);
// printf("Hola\n");
join_cajeras();
pthread_join(clientes_aleatorios, NULL);
return 0;
}
static void* cliente_aleatorio(void *arg)
{
int oneShot = 1;
while (1)
{
// printf(" -------------- \n");
switch (rand() % 20) {
case 0:
// printf("Agregado cliente normal\n");
inc_cola_normal();
break;
case 1:
// printf("Agregado cliente preferencial\n");
inc_cola_pref();
break;
case 2:
// printf("Agregado cliente regulado\n");
inc_cola_regulados();
break;
default:
break;
}
if ( oneShot ) {
printf("One Shot\n");
apagar_mitad_cajas();
oneShot = 0;
}
}
}
|
C
|
#include <stdio.h>
#include <string.h>
int main() {
char smlst[100], lrgst[100];
int i = 0;
char temp[100];
while(1) {
printf("Enter word: ");
scanf("%s", temp);
if(i == 0) {
strcpy(smlst, temp);
strcpy(lrgst, temp);
}
else {
if(strcmp(temp, smlst) < 0) {
strcpy(smlst, temp);
}
if(strcmp(temp, lrgst) > 0) {
strcpy(lrgst, temp);
}
}
if(strlen(temp) == 4) {
break;
}
i++;
}
printf("\nSmallest word: %s\n", smlst);
printf("Largest word: %s\n", lrgst);
}
|
C
|
/*
CH-230-A
a1 p2.[c or cpp or h]
Jose Biehl
jbiehl@jacobs-university.de
*/
#include <stdio.h>
int main() {
int result;
result = (2 + 7) * 9 / 3;
printf("The result is %i\n", result);
return 0;
}
//the variable "result" is not included in the printf statement of the original code, so the %d tries to interpret a non-integer as an integer, creating a garbled mess
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tlebouvi <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/02/11 13:44:04 by tlebouvi #+# #+# */
/* Updated: 2021/04/22 13:42:17 by tlebouvi ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
void *ft_calloc(size_t count, size_t size)
{
void *dst;
size_t i;
unsigned char *ptr;
dst = malloc(count * size);
if (dst == NULL)
return (NULL);
ptr = (unsigned char *)dst;
i = 0;
if ((count * size) <= 0)
return (dst);
while (i < (count * size))
{
ptr[i] = '\0';
i++;
}
return (dst);
}
int assignline(char **gnl, int check, char **line)
{
size_t i;
char *tempo;
char *mask;
size_t x;
x = ft_strlen(*gnl);
i = 0;
tempo = NULL;
if (check < 0)
return (-1);
mask = ft_strchr(*gnl, '\n');
if (!mask)
{
*line = ft_strdup(*gnl);
return (0);
}
i = x - ft_strlen(mask);
*line = ft_substr(*gnl, 0, i);
tempo = ft_substr(*gnl, i + 1, x);
free(*gnl);
*gnl = ft_strdup(tempo);
free(tempo);
tempo = NULL;
return (1);
}
char *mallocstock(int fd, char *stock)
{
if (!(stock = (char *)ft_calloc(BUFFER_SIZE + 1, sizeof(char))))
return (NULL);
if (read(fd, stock, 0) == -1)
{
free(stock);
stock = NULL;
return (NULL);
}
return (stock);
}
int findline(int fd, char **gnl)
{
int spot;
char *tmp;
char *stock;
stock = NULL;
if (!(stock = mallocstock(fd, stock)))
return (-1);
spot = 1;
while (!(ft_strchr(*gnl, '\n')) && spot)
{
spot = read(fd, stock, BUFFER_SIZE);
if (spot)
{
stock[spot] = '\0';
if (!(tmp = ft_strjoin(*gnl, stock)))
return (-1);
free(*gnl);
*gnl = ft_strdup(tmp);
free(tmp);
tmp = NULL;
}
}
free(stock);
stock = NULL;
return (spot);
}
int get_next_line(int fd, char **line)
{
static char *gnl;
int check;
check = 1;
if (fd < 0 || !line || BUFFER_SIZE <= 0)
return (-1);
if (gnl == NULL)
{
if (!(gnl = (char *)calloc(0, sizeof(char))))
return (-1);
}
check = findline(fd, &gnl);
check = assignline(&gnl, check, line);
if (check == 0)
{
free(gnl);
gnl = NULL;
return (check);
}
return (check);
}
|
C
|
#include <cs50.h>
#include <stdio.h>
void make_pyramids(int height);
void make_half_pyramid(int row, int height, char side);
void print_hashes(int n);
void print_spaces(int n);
static const int gap = 2;
int main(void)
{
int height;
do
{
printf("Height: ");
height = get_int();
}
while (height < 0 || height > 23);
make_pyramids(height);
}
void make_pyramids(int height)
{
for (int row = 1; row <= height; row++)
{
make_half_pyramid(row, height, 'l');
make_half_pyramid(row, height, 'r');
}
}
void make_half_pyramid(int row, int height, char side)
{
int blanks = height - row;
if (side == 'l')
{
print_spaces(blanks);
print_hashes(row);
print_spaces(gap);
}
else
{
print_hashes(row);
printf("\n");
}
}
void print_hashes(int n)
{
for (int i = 0; i < n; i++)
{
printf("#");
}
}
void print_spaces(int n)
{
for (int i = 0; i < n; i++)
{
printf(" ");
}
}
|
C
|
/*
* make KOI8->CP866(ALT) and CP866(ALT)->KOI8 translation table
* from koi-alt.tab.
*
* Tatsuo Ishii
*
* $PostgreSQL$
*/
#include <stdio.h>
main()
{
int i;
char koitab[128],
alttab[128];
char buf[4096];
int koi,
alt;
for (i = 0; i < 128; i++)
koitab[i] = alttab[i] = 0;
while (fgets(buf, sizeof(buf), stdin) != NULL)
{
if (*buf == '#')
continue;
sscanf(buf, "%d %d", &koi, &alt);
if (koi < 128 || koi > 255 || alt < 128 || alt > 255)
{
fprintf(stderr, "invalid value %d\n", koi);
exit(1);
}
koitab[koi - 128] = alt;
alttab[alt - 128] = koi;
}
i = 0;
printf("static char koi2alt[] = {\n");
while (i < 128)
{
int j = 0;
while (j < 8)
{
printf("0x%02x", koitab[i++]);
j++;
if (i >= 128)
break;
printf(", ");
}
printf("\n");
}
printf("};\n");
i = 0;
printf("static char alt2koi[] = {\n");
while (i < 128)
{
int j = 0;
while (j < 8)
{
printf("0x%02x", alttab[i++]);
j++;
if (i >= 128)
break;
printf(", ");
}
printf("\n");
}
printf("};\n");
}
|
C
|
#include <stdio.h>
int main(void)
{
float n;
int a;
scanf("%f",&n);
if(n<0)
{
a=(int)(n-0.5);
}
else
{
a=(int)(n+0.5);
}
printf("%d",a);
return 0;
}
|
C
|
/**
* @file mmi_mae_text_util.h
*
* @version $Id: mmi_mae_text_util.h $
*/
#ifndef __MMI_MAE_TEXT_UTIL_H__
#define __MMI_MAE_TEXT_UTIL_H__
#include "mmi_mae_common_def.h"
/*
@brief - to define a ucs2 code of white space character.
*/
#define TEXT_WHITE_SPACE 0x0020
#define TEXT_LINE_FEED 0x000A
#define TEXT_CARRIAGE_RETURN 0x000D
#define TEXT_CHINESE_UNICODE_SECTION1_START 0x4E00
#define TEXT_CHINESE_UNICODE_SECTION1_END 0x709D
#define TEXT_CHINESE_UNICODE_SECTION2_START 0x70AB
#define TEXT_CHINESE_UNICODE_SECTION2_END 0x9FA0
#define TEXT_THAI_UNICODE_SECTION_START 0x0E00
#define TEXT_THAI_UNICODE_SECTION_END 0x0F7F
#define TEXT_MAX_COMPOSED_SIZE 10
#define MAETEXTUTIL_IsReturnChar(_Char_) ((u16)_Char_ == 0x000A || (u16)_Char_ == 0x000D)
#define MAETEXUTIL_IsChineseChar(_Char_) ( ((_Char_ >= TEXT_CHINESE_UNICODE_SECTION1_START && _Char_ <= TEXT_CHINESE_UNICODE_SECTION1_END) || \
(_Char_ >= TEXT_CHINESE_UNICODE_SECTION2_START && _Char_ <= TEXT_CHINESE_UNICODE_SECTION2_END)) )
#define MAETEXUTIL_IsChineseThaiChar(_Char_) ( ((_Char_ >= TEXT_CHINESE_UNICODE_SECTION1_START && _Char_ <= TEXT_CHINESE_UNICODE_SECTION1_END) || \
(_Char_ >= TEXT_CHINESE_UNICODE_SECTION2_START && _Char_ <= TEXT_CHINESE_UNICODE_SECTION2_END)) || \
(_Char_ >= TEXT_THAI_UNICODE_SECTION_START && _Char_ <= TEXT_THAI_UNICODE_SECTION_END) )
#ifdef __BIDI_TEXT__
/*
@brief - to check a input language is RTL or LTR display direction. ( ARABIC, HEBREW now )
*/
#define MAETEXTUTIL_BidiIsRTL( _Level_ ) ( (_Level_ % 2) == 1 )
#endif //__BIDI_TEXT__
typedef enum
{
MAE_TEXTUTIL_BL_FORWARD,
MAE_TEXTUTIL_BL_BACKWARD
}Mae_TextUtil_BLDirection_e;
typedef struct
{
MAE_WChar nBLChar;
boolean bBackwardBreak;
}Mae_TextUtil_BL_t;
typedef struct
{
Mae_TextUtil_BL_t *pBLTable;
u16 nBLTableSize;
}Mae_TextUtil_BLTable_t;
/****************/
/* Text convert */
/****************/
/*
@brief - Convert text to display string. note that only the first paragraph will be convert to display string.
@param - [in]pu16String: a ucs2 string
@param - [in]nStrLen: the length of ucs2 string
@param - [in]bIsRTL: the display direction of the string. (in Arabic language, the bIsRTL should be TRUE)
@param - [in]ppu16DisplayStr: a double pointer of display string, allocate by this function and need to free it by caller.
@return - [out]u32: the length of display string
*/
u32 MAETEXTUTIL_TextToDisplayString( const MAE_WChar *pString, u32 nStrLen, boolean bDisplayRTL, MAE_WChar **ppwDisplayStr, boolean *pIsRTLStr, boolean bWithoutBidi );
/*
@brief - invert part of sequence characters in ucs2 string.
@param - [in]pu16String: a ucs2 string
@param - [in]nStrLen: the length of ucs2 string
@param - [in]nOffset: the start position that want to invert in this string
@param - [in]pSubLength: the length that want to invert
@param - [in][out]pSourcePos: Get the original string location position after invert.
if doesn't get the information, assign to NULL
@return - none
*/
void MAETEXTUTIL_UCS2Invert( MAE_WChar *pString, u32 nStrLen, u32 nOffset, u32 pSubLength, u16 *pSourcePos );
/*
@brief - remove a chararcter at x index in a ucs2 string.
@param - [in]pu16String: a ucs2 string
@param - [in]nStrLen: the length of ucs2 string after removed a character
@param - [in]nOffset: the position of character that want to remvoed in this string
@return - [out]u32: the remain string length after remove a character
*/
u32 MAETEXTUTIL_UCS2RemoveCharAt( MAE_WChar *pString, u32 nStrLen, u32 nOffset );
boolean MAETEXTUTIL_UCS2IsComposedNextChars( const MAE_WChar *pString, u32 nStrLen, u32 nOffset, MAE_WChar **ppComposedStr, u32 *pComposedLen, u32 *paConsumed, boolean bDispStr );
boolean MAETEXTUTIL_UCS2IsComposedPreChars( const MAE_WChar *pString, u32 nStrLen, u32 nOffset, MAE_WChar **ppComposedStr, u32 *pComposedLen, u32 *paConsumed, boolean bDispStr );
#ifdef __MMI_BIDI_UI__
boolean MAETEXTUTIL_IsRTLDisplayLanguage( void );
boolean MAETEXTUTIL_IsRTLLanguage( u8 nLan );
#endif //__MMI_BIDI_UI__
#ifdef __BIDI_TEXT__
/*
@brief - Check a paragraph text's display direction.
@param - [in]pu16String: a ucs2 string.
@param - [in]nStrLen: the length of ucs2 string.
@param - [in]bIsRTL: the display direction of the string. (in Arabic language, the bIsRTL should be TRUE)
@return - [out]boolean: The paragraph text is display RTL or LTR. TRUE, is RTL.
*/
boolean MAETEXTUTIL_ParagraphIsRTL( const MAE_WChar *pString, u32 nStrLen, boolean bDisplayRTL );
/*
@brief - Check a character is an Arabic character.
@param - [in]u16Char: a ucs2 character
@return - [out]boolean: Is an Arabic character or not. TRUE, an Arabic character.
*/
u32 MAETEXTUTIL_MeasureMixedLine( const MAE_WChar *pString, u32 nStrLen, u32 nOffset, u32 nLineStrLen, boolean bDiffDirChangeLine );
#endif //__BIDI_TEXT__
boolean MAETEXTUTIL_MeasureTextToLineBreak( const MAE_WChar *pText, u32 nStrLen, u32 nWidth,u32 nFontCate, u32 nFontSize, u32 nFontType, boolean bDiffDirChangeLine, u32 *pu32FitLen, Mae_TextUtil_BLTable_t *pBLCodeTable );
#ifdef __BIDI_TEXT__
/**********/
/* Arabic */
/**********/
/*
@brief - conver a ucs2 arabic string to a display string.
@param - [in]pu16String: a ucs2 string
@param - [in]nStrLen: the length of ucs2 string.
@return - [out]u32: the display string length after convert to arabic string.
(the string length maybe changed after converting)
*/
u32 MAETEXTUTIL_ConvertToArabicStr( MAE_WChar *pString, u32 nStrLen, boolean bDispStr );
boolean MAETEXTUTIL_ConvertToArabicFEStr( MAE_WChar *pString, u32 nStrLen, boolean bDispStr );
u16 MAETEXTUTIL_ConvertToArabicFEChar( const MAE_WChar *pString, u32 nStrLen, u32 nOffset, boolean bDispStr, u16 *pNextFEChar );
/*
@brief - conver a ucs2 Europe number to a Arabic number.
@param - [in]pu16String: a ucs2 string
@param - [in]nStrLen: the length of ucs2 string.
@return - [out]u32: the string length after converting.
*/
u32 MAETEXTUTIL_NumConvertToArabicNum( MAE_WChar *pString, u32 nStrLen );
/*
@brief - conver a ucs2 Arabic number to a Europe number.
@param - [in]pu16String: a ucs2 string
@param - [in]nStrLen: the length of ucs2 string.
@return - [out]u32: the string length after converting.
*/
u32 MAETEXTUTIL_ArabicNumConvertToNum( MAE_WChar *pString, u32 nStrLen );
/*
@brief - Check text is include arabic characters in it.
@param - [in]pu16String: a ucs2 string
@param - [in]nStrLen: the length of ucs2 string.
@return - [out]boolean: Is an arabic text or not. TRUE, an Arabic text.
*/
boolean MAETEXTUTIL_IsArabicText( const MAE_WChar *pString, u32 nStrLen );
/*
@brief - Check a character is an Arabic character.
@param - [in]u16Char: a ucs2 character
@return - [out]boolean: Is an Arabic character or not. TRUE, an Arabic character.
*/
boolean MAETEXTUTIL_IsArabicChar( MAE_WChar nChar );
/*
@brief - Check a character is concatenate to pre-character or next-character.
@param - [in][out]pu16Char: a ucs2 character that want to check. the return value the convered character for display
@param - [in]u16PreChar: the character before the checked character. If the checked character
is first and assign this value to 0.
@param - [in]u16NextChar: the character after the checked character. If the checked character
is last and assign this value to 0.
@param - [in][out]pbInWord: notic the check character is in a word (not the first or last character of a word)
if the check character is a first character of a word, assign to FALSE.
You maybe should keep the value for check a sequence string by it.
@param - [in][out]pbPreCharIsFirst: notic the pre-character is the first character in a word.
if the check character is a first character of a word, assign to FALSE.
You maybe should keep the value for check a sequence string by it.
@return - [out]boolean: Is an concatenatin character or not. TRUE, an concatenation character.
*/
boolean MAETEXTUTIL_ConcatenationArabicFEChar( MAE_WChar *pChar, MAE_WChar nNextChar );
/******************/
/* Bidi paragraph */
/******************/
/*
@brief - Check a character is an paragraph character.
@param - [in]u16Char: a ucs2 character
@return - [out]boolean: Is an paragraph character or not. TRUE, an paragraph character.
*/
boolean MAETEXTUTIL_BidiIsParagraphChar( MAE_WChar nChar );
__SLDPM_FREE__ boolean MAETEXTUTIL_BidiIsRTLChar( MAE_WChar nChar );
#endif //__BIDI_TEXT__
/*
@brief - To get the first paragraph length from a input text.
@param - [in]pu16String: a ucs2 string.
@return - [out]u32: a paragraph string length.
*/
u32 MAETEXTUTIL_BidiGetParagraphLength( const MAE_WChar *pString, u32 nStrLen );
/*
@brief - To only order the first paragraph of a input text.
@param - [in][out]pu16String: a ucs2 string.
@param - [in][out]pStrLen: input string length and change to paragraph string length after calling.
@param - [in][out]pbDisplayRight2Left: the string display direction.
@param - [out]ppSeqPos: the paragraph logical order of ordering string.
Allocate memory in this function, and must free by caller.
@return - [out]boolean: success or not. TRUE, success.
*/
boolean MAETEXTUTIL_BidiOrderParagraph( MAE_WChar *pString, u32 *pStrLen, boolean bDisplayRight2Left, u16 **ppSeqPos, u8 **ppCharLevel );
/**********************/
/* Bidi order handler */
/**********************/
/*
@brief - To create a bidi handler.
@return - [out]void*: a pointer of bidi handler.
*/
__SLDPM_FREE__ void* MAETEXTUTIL_BidiCreateHandler( void );
/*
@brief - To free a bidi handler.
@param - [in]pHandler: a pointer of bidi handler.
@return - none.
*/
void MAETEXTUTIL_BidiFreeHandler( void *pHandler );
#ifdef __BIDI_TEXT__
/*
@brief - To order the input text. (support multi-paragraph)
ordering result is record in bidi handler. you can access information by bidi handler.
@param - [in]pHandler: a pointer of bidi handler.
@param - [in]pu16String: a ucs2 string.
@param - [in]nStrLen: input string length.
@param - [in]bDisplayRight2Left: the string display direction.
@return - [out]boolean: success or not. TRUE, success.
*/
__SLDPM_FREE__ boolean MAETEXTUTIL_BidiOrderText( void *pHandler, const MAE_WChar *pString, u32 nStrLen, boolean bDisplayRight2Left );
#endif //__BIDI_TEXT__
boolean MAETEXTUTIL_BidiInsertText( void *pHandler, const MAE_WChar *pString, u32 nStrLen, boolean bDisplayRight2Left );
boolean MAETEXTUTIL_BidiReorderText( void *pHandler, u32 nOffset, const MAE_WChar *pString, u32 nStrLen );
/*
@brief - To re-init the bidi hanlder's line table.
@param - [in]pHandler: a pointer of bidi handler.
@return - none.
*/
void MAETEXTUTIL_BidiInitTable( void *pHandler );
/*
@brief - To add a new line information to bidi handler's line table.
It will make the bidi order input string depend on your line information.
@param - [in]pHandler: a pointer of bidi handler.
@param - [in]nOffset: the line begin offset in a text.
@param - [in]nStrLen: the line string length.
@param - [in]bRTL: the line display direction. (depend on current display language)
@return - [out]boolean: success or not. TRUE, success.
*/
__SLDPM_FREE__ boolean MAETEXTUTIL_BidiAddLine( void *pHandler, u32 nOffset, u32 nStrLen, boolean bRTL );
boolean MAETEXTUTIL_BidiModifyLineInfo( void *pHandler, u32 u32Line, u32 nOffset, u32 nStrLen, boolean bRTL );
/*
@brief - To get the bidi handler's line table size.
@param - [in]pHandler: a pointer of bidi handler.
@return - [out]u32: the table size.
*/
u32 MAETEXTUTIL_BidiGetTableSize( void *pHandler );
boolean MAETEXTUTIL_BidiSetTableSize( void *pHandler, u32 u32Size );
/*
@brief - To get a order line's information (after ordering a string by bidi).
@param - [in]pHandler: a pointer of bidi handler.
@param - [in]u32Index: the index of line in handler's line table.
@param - [out]pOffset: the line string begin offset in a input text.
@param - [out]pLineStrLen: the line string length.
@param - [out]pbRTL: the line string display direction.
@param - [out]ppLineString: the line ordering string.
Allocate memory in this function, and must free by caller.
@param - [out]ppSeqInLine: the line logical order of ordering string.
Allocate memory in this function, and must free by caller.
@return - [out]boolean: success or not. TRUE, success.
*/
boolean MAETEXTUTIL_BidiGetLineInf( void *pHandler, u32 u32Index, u32 *pOffset, u32 *pLineStrLen, boolean *pbRTL, u16 **ppLineString, u16 **ppSeqInLine, u8 **pCharLevel );
u16* MAETEXTUTIL_BidiGetOrderStr( void *pHandler, u32 *pStrLen );
#endif /* __MAE_TEXT_UTIL_H__ */
|
C
|
/* Modify the get_first() function of Listing 8.8 so that
it returns the first non-whitespace character encountered.
Test it in a simple program.
*/
#include <stdio.h>
#include <ctype.h>
char get_first(void);
int main(void)
{
printf("%c\n", get_first());
return 0;
}
char get_first(void)
{
int ch;
for (ch = getchar(); isspace(ch); ch = getchar())
continue;
return ch;
}
|
C
|
bool IsItemEquipment (Item item){
extern u8 EquipmentList[];
if (item.number == 0) {
return false;
}
int cnt = 0;
while(EquipmentList[cnt] != 0){
if (item.number == EquipmentList[cnt]){
return true;
}
++cnt;
}
return false;
}
bool CanUnitEquipItem (Unit* unit, Item item){
if (!IsItemEquipment(item)){
return false;
}
// Can add extra conditionals here
return true;
}
Item GetUnitEquippedItem (Unit* unit){
Item item;
if (unit->state & US_UNEQUIPMENT){
return item;
}
for (int i = 0; i < UNIT_ITEM_COUNT; ++i){
if (CanUnitEquipItem(unit, unit->items[i])){
return unit->items[i];
}
}
return item;
}
int GetUnitEquippedItemSlot (Unit* unit){
if (unit->state & US_UNEQUIPMENT){
return 0xFF;
}
for (int i = 0; i < UNIT_ITEM_COUNT; ++i){
if (CanUnitEquipItem(unit, unit->items[i])){
return i;
}
}
return 0xFF;
}
|
C
|
#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <pthread.h>
void *thread1(void *var);
void *thread2(void *var);
int main(void)
{
//identifier for the shared memory segment
int segment_id;
pthread_t tid1,tid2;
//a pointer to the shared memory segment
char* shared_memory;
//the size (int bytes) of the shared memory
const int size = 4096;
//allocate a shared meomry segment
segment_id = shmget(IPC_PRIVATE,size, S_IRUSR | S_IWUSR);
//attach the shared memory segment
shared_memory = (char* ) shmat(segment_id,NULL, 0);
pthread_create(&tid1,NULL,thread1, &segment_id);
pthread_create(&tid2,NULL,thread2, &segment_id);
pthread_join(&tid2,NULL);
pthread_join(&tid1,NULL);
//write a message to shared memory
//sprintf(shared_memory,"Hi! I am Arijit");
//now print out the string from shared memory
//printf("%s\n",shared_memory);
//now detatch the shared meomry
shmdt(shared_memory);
//now remove the shared memory segment
shmctl(segment_id,IPC_RMID,NULL);
return 0;
}
void *thread1(void *var)
{
//int i;
char* shared_memory;
//i = (int *)var;
shared_memory = (char* ) shmat(var,NULL, 0);
sprintf(shared_memory,"Hi! I am Arijit");
printf("Writting in thread1\n");
return NULL;
}
void *thread2(void *var)
{
int i;
char* shared_memory;
i =(int *)var;
shared_memory = (char* ) shmat(i,NULL, 0);
printf("%s\n", shared_memory);
return NULL;
}
|
C
|
#include "clutil.h"
#include <stdio.h>
void print_error(const char *function, cl_int error){
fprintf(stderr,"Error when calling %s, code: %d\n",function,error);
}
/* determine length of file, allocate memory for the output pointer
* and read in the bytes into pointer */
void read_cl_source(const char *filename, char **source_out){
FILE * const fp = fopen(filename,"rb");
if(!fp){
fprintf(stderr,"Failed to load kernel\n");
}
fseek(fp,0,SEEK_END);
const size_t len = ftell(fp);
rewind(fp);
char *source;
source = malloc(len+1);
source[len] = '\0'; /* null terminate the source */
fread(source,sizeof(char),len,fp);
fclose(fp);
*source_out = source;
}
void free_cl_source(char *source){
free(source);
}
|
C
|
inherit "living";
#include <event.h>
#include <macros.h>
#include <state.h>
#include <properties.h>
private int allowed_move;
private object rider;
/*
* Function name: create_mount
* Description: redefinable constructor
*/
static void
create_mount()
{
}
/*
* Function name: create_living
* Description: standard constructor
*/
static nomask void
create_living()
{
create_mount();
}
/* description functions here to add riding person */
string
long()
{
string desc;
object tp;
if (!rider || !(tp = this_player()))
return ::long();
if (tp == rider)
return ::long() + "Mounted by yourself.\n";
if (desc = tp->query_met(rider->query_met_name()))
return ::long() + "Mounted by " + capitalize(desc) + ")";
return ::long() + "Mounted by the " + rider->query_nonmet_name() + ")";
}
nomask string
short()
{
string desc;
object tp;
if (!rider || !(tp = this_player()))
return ::short();
if (tp == rider)
return ::short() + " (mounted by yourself)";
if (desc = tp->query_met(rider->query_met_name()))
return ::short() + " (mounted by " + capitalize(desc) + ")";
return ::short() + " (mounted by the " +
rider->query_nonmet_name() + ")";
}
nomask string
plural_short()
{
string desc;
object tp;
if (!rider || !(tp = this_player()))
return ::plural_short();
if (tp == rider)
return ::plural_short() + " (mounted by yourself)";
if (desc = tp->query_met(rider->query_met_name()))
return ::plural_short() + " (mounted by " + capitalize(desc) + ")";
return ::plural_short() + " (mounted by the " +
rider->query_nonmet_name() + ")";
}
/*
* Function name: dismount_cmd
* Description: called from cmdsoul to dismount this horse
* Arguments: tp - dismounting living
* Returns: 1 if success, -1 else
*/
nomask int
dismount_cmd(object tp)
{
int *co;
mixed qtname;
if (!tp)
return -1;
if (rider != tp)
{
tp->catch_tell("You did not mount this living.\n");
return -1;
}
remove_event(E_MOVE, "catch_moves", this_object());
remove_event(E_MOVE, "catch_moves", rider);
rider = 0;
tp->delete_state(MOUNT);
tp->add_prop(LIVE_MOUNTED, 0);
co = query_coordinates()[..];
co[2] = E(this_object())->query_coordinates()[2];
tp->set_coordinates(co);
qtname = QTNAME(this_object());
tp->catch_msg(({ "You dismount ", qtname, ".\n" }), 0, 0);
tell_objects(LISTEN(E(tp)) - ({ tp }),
({ QCTNAME(tp), " dismounts ", qtname, ".\n" }),
MSG_SEE, tp);
return 1;
}
/*
* Function name: mount_cmd
* Description: called from cmdsoul to mount this horse
* Arguments: tp - mounting living
* Returns: 1 if success, -1 else
*/
nomask int
mount_cmd(object tp)
{
int *co;
mixed qtname;
if (!tp)
return -1;
if (rider)
{
tp->catch_tell("There is already someone.\n");
return -1;
}
if (tp->query_prop(LIVE_MOUNTED))
{
tp->catch_tell("You already mounted something.\n");
return -1;
}
rider = tp;
add_event(E_MOVE, "catch_moves", this_object());
add_event(E_MOVE, "catch_moves", rider);
tp->add_state(MOUNT);
tp->add_prop(LIVE_MOUNTED, this_object());
co = query_coordinates()[..];
co[2] += query_size() / 3;
tp->set_coordinates(co);
qtname = QTNAME(this_object());
tp->catch_msg(({ "You mount ", qtname, ".\n" }), 0, 0);
tell_objects(LISTEN(E(tp)) - ({ tp }),
({ QCTNAME(tp), " mounts ", qtname, ".\n" }),
MSG_SEE, tp);
return 1;
}
/*
* Function name: query_rider()
* Description: the one that rides on this mount
* Returns: object
*/
nomask object
query_rider()
{
return rider;
}
/*
* Function name: catch_moves
* Description: event: catch moves of the mount and dismounts the rider
* if too far away
* Arguments: ob - the moving object
* old - where it comes from
* dest - where it goes
*/
nomask void
catch_moves(object ob, object old, object dest)
{
int *co, *obco;
if (!rider || allowed_move)
return;
co = query_coordinates();
obco = rider->query_coordinates();
if (co[0] != obco[0] || co[1] != obco[1] ||
co[2] + query_size() / 3 != obco[2])
{
rider->add_prop(LIVE_MOUNTED, 0);
rider->delete_state(MOUNT);
remove_event(E_MOVE, "catch_moves", this_object());
remove_event(E_MOVE, "catch_moves", rider);
rider = 0;
}
}
/*
* Function name: move_mount
* Description: called from command soul, if horse is mounted and
* player moves.
* Arguments: room - arrival room
* co - new coordinates
* dir - direction to move
* how - run or walk
* tp - riding player
* Returns: 1 if success, -1 else
*/
nomask int
move_mount(object room, int *co, string dir, int how, object tp)
{
if (!tp || rider != tp)
return -1;
allowed_move = 1;
if (::move_living(room, co, dir, 2)) /* sneak-move to avoid messages */
{
allowed_move = 0;
return -1;
}
co[2] += query_size() / 3;
rider->move_living(room, co, dir, 4);
allowed_move = 0;
return 1;
}
/*
* Function name: move_living
* Description: called from command soul, if horse walks, the rider
* should follow.
* Arguments: room - arrival room
* co - new coordinates
* dir - direction to move
* how - run or walk
* Returns: 1 if success, -1 else
*/
nomask int
move_living(object room, int *co, string dir, int how)
{
if (!rider)
return -1;
allowed_move = 1;
if (::move_living(room, co, dir, how))
{
allowed_move = 0;
return -1;
}
co = co[..];
co[2] += query_size() / 3;
rider->set_coordinates(co);
rider->move(room);
allowed_move = 0;
return 1;
}
nomask int
do_die(object killer)
{
if (rider)
dismount_cmd(rider);
return ::do_die(killer);
}
nomask varargs void
remove_object(object ob)
{
if ((!ob || ob == this_object()) && rider)
dismount_cmd(rider);
::remove_object(ob);
}
|
C
|
// Akash and too many assignments
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void update(char*array,int i,int alphabet,int**fenwikTree,int n){
int olderAlphabet=array[i]-'a';
array[i]=alphabet+'a';
int j=i+1;
while(j<n+1){
fenwikTree[j][alphabet]++;
j=j+(j&(-j));
}
int k=i+1;
while(k<n+1){
fenwikTree[k][olderAlphabet]--;
k=k+(k&(-k));
}
}
int frequenceTillRange(int i,int alphabet,int**fenwikTree,int n){
int j=i+1;
int s=0;
while(j>0){
s+=fenwikTree[j][alphabet];
j=j-(j&(-j));
}
return s;
}
int**buildTree(char*array,int n){
int**fenwikTree=(int**)calloc(1000001,sizeof(int*));
for(int i=0;i<n+1;i++){
fenwikTree[i]=(int*)calloc(30,sizeof(int));
}
for(int i=0;i<26;i++){
fenwikTree[0][i]=0;
}
for(int i=0;i<n;i++){
int j=i+1;
while(j<n+1){
fenwikTree[j][array[i]-'a']++;
j=j+(j&(-j));
}
}
return fenwikTree;
}
void solveProblem(int l,int r,int k,int**fenwikTree,int n){
int sum=0;int i;
for(i=0;i<26;i++){
sum+=(frequenceTillRange(r,i,fenwikTree,n)-frequenceTillRange(l-1,i,fenwikTree,n));
if(sum>=k){
break;
}
}
if(sum>=k){
printf("%c\n",i+'a');
}
else{
printf("Out of range\n");
}
}
int main(){
int n,q;
int op,l,r,k,ind;
char c[1];
scanf("%d %d",&n,&q);
char*input=(char*)calloc(1000000,sizeof(char));
scanf("%s",input);
int**fenwikTree=buildTree(input,n);
for(int i=0;i<q;i++){
scanf("%d",&op);
if(op==0){
scanf("%d %c",&ind,c);
update(input,ind-1,c[0]-'a',fenwikTree,n);
}
else{
scanf("%d %d %d",&l,&r,&k);
solveProblem(l-1,r-1,k,fenwikTree,n);
}
}
free(input);
return 0;
}
|
C
|
/* 3c905C_cntl.c - _3c905C_cntl */
#include <xinu.h>
/*------------------------------------------------------------------------
* _3c905C_cntl - implement control function for a 3c905C device
*------------------------------------------------------------------------
*/
devcall _3c905C_cntl(
struct ether *ethptr, /* entry in device switch table */
int32 func, /* control function */
int32 arg1, /* argument 1, if needed */
int32 arg2 /* argument 2, if needed */
)
{
switch (func) {
/* Get MAC address */
case ETH_CTRL_GET_MAC:
memcpy((byte *)arg1, ethptr->devAddress,
ETH_ADDR_LEN);
break;
default:
return SYSERR;
}
return OK;
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(){
char str[10] = "abcdefg";
printf("%s", strchr(str, 'c'));
}
|
C
|
//**************************************************************
// *
// 1º Trabalho - Técnicas de Programação 2009.1 *
// Equipe: *
// Murilo Lima de Holanda(líder) Mat:0286740 *
// Leandro Monteiro Guimarães Mat:0286756 *
// Leidiane Nascimento de Freitas Mat:0272980 *
// Victor Pessoa de Azevedo Lia Fook Mat:------- *
// *
//**************************************************************
#include <stdio.h>
#include <stdlib.h>
#include <cstring>//Biblioteca usada na manipulação de strings
#include "figuras.h"//Definição das estruruas e funções de manipulação das estruturas de dados usadas e das figuras
int funcao(Figura* fig);
int main();
int main()
{
Figura* fig;
fig = crialista();
system("clear");
funcao(fig);
}
int funcao(Figura* fig)
{
int o,t;
char nome[10];
char cor[10];
float raio, lado, base, altura, a_total;
printf("---------------------------------------------\n");
printf("O que deseja fazer?\n\n");
printf("1 -Inserir figura\n");
printf("2 -Remover figura\n");
printf("3 -Listar figuras\n");
printf("4 -Ordenar figuras por area\n");
printf("5 -Ordenar figuras por nome\n");
printf("6 -Imprimir area total\n");
printf("0 -Sair\n");
scanf("%d",&o);
system("clear");
switch(o)
{
case 0:
exit(0);
break;
case 1:
t=escolha_tipo();
system("clear");
printf("Qual o nome da figura a ser inserida\n");
scanf("%s",&nome);
printf("\nQual o cor da figura a ser inserida\n");
scanf("%s",&cor);
switch(t)
{
case 1:
printf("\nQual o raio do circulo a ser inserido\n");
scanf("%f",&raio);
inserir_cir(fig,nome,cor,raio);
system("clear");
printf("O circulo %s foi inserido com sucesso!\n\n",fig->circ->primeiro->nome);
break;
case 2:
printf("\nQual o lado do quadrado a ser inserido\n");
scanf("%f",&lado);
inserir_quad(fig,nome,cor,lado);
system("clear");
printf("O quadrado %s foi inserido com sucesso!\n\n",fig->quad->primeiro->nome);
break;
case 3:
printf("\nQual a base do triangulo a ser inserido\n");
scanf("%f",&base);
printf("\nQual a altura do triangulo a ser inserido\n");
scanf("%f",&altura);
inserir_tri(fig,nome,cor,base,altura);
system("clear");
printf("O triangulo %s foi inserido com sucesso!\n\n",fig->tri->primeiro->nome);
break;
}
break;
case 2:
int r;
system("clear");
printf("Qual o nome da figura a ser removida\n");
scanf("%s",&nome);
r = remover(fig,nome);
switch(r)
{
case 0:
printf("\n\nNao existe figura com o nome %s!\n\n",nome);
break;
case 1:
printf("\n\nO circulo de nome %s foi removido com sucesso!\n\n",nome);
break;
case 2:
printf("\n\nO quadrado de nome %s foi removido com sucesso!\n\n",nome);
break;
case 3:
printf("\n\nO triangulo de nome %s foi removido com sucesso!\n\n",nome);
break;
}
break;
case 3:
listar(fig);
break;
case 4:
ordenar(1,fig);//O flag "1" indica a ordenação por área
break;
case 5:
ordenar(2,fig);//O flag "2" indica a ordenação por nome
break;
case 6:
system("clear");
printf("A area total das figuras e: \n%10.2f\n\n",area_total(fig));
break;
default:
system("clear");
funcao(fig);
}
funcao(fig);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "load_sys_file.h"
int load_file(char *vmlist_file_path, char *pmlist_file_path, int *divide_count, LIST *vmlist, LIST *pmlist){
init_uvmp(vmlist_file_path, pmlist_file_path, divide_count);
init_pvm_list_fp = init_pvm_list;
(*init_pvm_list_fp)(vmlist_file_path, vmlist);
(*init_pvm_list_fp)(pmlist_file_path, pmlist);
return 0;
}
int init_uvmp(char *vmlist_file_path, char *pmlist_file_path, int *divide_count){
FILE *vmlist_fp;
char *delim = "=";
vmlist_fp = fopen(VMPCONFIG_FILE_PATH, "r");
while(!feof(vmlist_fp)){
char *uvmp_conf[2];
char str[50];
fscanf(vmlist_fp, "%s", str);
uvmp_conf[0] = strtok(str, delim);
uvmp_conf[1] = strtok(NULL, delim);
if(strcmp(uvmp_conf[0], "divide_count") == 0){
*divide_count = atoi(uvmp_conf[1]);
}else if(strcmp(uvmp_conf[0], "vmlist_file_path") == 0){
strcpy(vmlist_file_path, uvmp_conf[1]);
}else if(strcmp(uvmp_conf[0], "pmlist_file_path") == 0){
strcpy(pmlist_file_path, uvmp_conf[1]);
}
}
fclose(vmlist_fp);
return 0;
}
int init_pvm_list(const char *list_path, LIST *list){
int i;
FILE *list_fp;
list_fp = fopen(list_path, "r");
fscanf(list_fp, "%d", &list->list_len);
list->list = (VM *)malloc(sizeof(VM) * list->list_len);
for(i = 0; i < list->list_len; i++){
fscanf(list_fp, "%d %d %d", &(list->list[i].id), &(list->list[i].cpu), &(list->list[i].memory));
}
fclose(list_fp);
return 0;
}
|
C
|
#include "../include/support.h"
#include "../include/scheduler.h"
#include "../include/cthread.h"
#include "../include/cdata.h"
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define SIZEIDENTIFY 67
#define GROUPNAMESTRING "Guilherme Cattani 243589\nAugusto Timm 113887\nGabriel Warken 179787\n"
/******************************************************************************
Parmetros:
name: ponteiro para uma rea de memria onde deve ser escrito um string que contm os nomes dos componentes do grupo e seus nmeros de carto.
Deve ser uma linha por componente.
size: quantidade mxima de caracteres que podem ser copiados para o string de identificao dos componentes do grupo.
Retorno:
Se correto => 0 (zero)
Se erro => Valor negativo.
******************************************************************************/
int cidentify (char *name, int size) {
if(size < SIZEIDENTIFY) {
return ERROR;
}
int index = 0;
while ((name[index] = GROUPNAMESTRING[index]) != '\0') {
index++;
}
return SUCCESS;
}
/******************************************************************************
Parmetros:
start: ponteiro para a funo que a thread executar.
arg: um parmetro que pode ser passado para a thread na sua criao.
prio: NO utilizado neste semestre, deve ser sempre zero.
Retorno:
Se correto => Valor positivo, que representa o identificador da thread criada
Se erro => Valor negativo.
******************************************************************************/
int ccreate (void* (*start)(void*), void *arg, int prio) {
schedulerInitialize();
TCB_t *newThread = (TCB_t *) malloc(sizeof(TCB_t));
newThread->tid = getNewTid(); //vamos usar a main como 0, a vai facilitar no cjoin
newThread->state = PROCST_APTO;
newThread->prio = 0;
newThread->joinedWaitingToFinish = -1;
newThread->joinedBeingWaitBy = -1;
newThread->wasJustScheduled = false;
getcontext(&(newThread->context));
newThread->context.uc_link = getContextToFinishProcess();
newThread->context.uc_stack.ss_sp = (char*) malloc(SIGSTKSZ);
newThread->context.uc_stack.ss_size = SIGSTKSZ;
newThread->context.uc_stack.ss_flags = 0;
makecontext(&(newThread->context), (void (*)(void)) start, 1, arg);
int status = includeInReadyList(newThread);
if(status < 0) {
return ERROR;
}
else {
return newThread->tid;
}
}
/******************************************************************************
Parmetros:
Sem parmetros
Retorno:
Se correto => 0 (zero)
Se erro => Valor negativo.
******************************************************************************/
int cyield(void) {
TCB_t *executingThread = getExecutingThread();
if(executingThread == NULL) {
return ERROR;
}
executingThread->wasJustScheduled = false;
getcontext(&(executingThread->context));
if(executingThread->wasJustScheduled == false) {
int status = yieldExecutingThread();
if(status < 0) {
return ERROR;
}
dispatch();
}
return SUCCESS;
}
/******************************************************************************
Parmetros:
tid: identificador da thread cujo trmino est sendo aguardado.
Retorno:
Se correto => 0 (zero)
Se erro => Valor negativo.
******************************************************************************/
int cjoin(int tid) {
TCB_t* joinedThread = getTidFromReadyList(tid);
int status = 0;
//pra evitar que mais de uma funo se joine
if(joinedThread != NULL && joinedThread->joinedBeingWaitBy < 0) {
TCB_t *executingThread = getExecutingThread();
executingThread->joinedWaitingToFinish = tid;
joinedThread->joinedBeingWaitBy = executingThread->tid;
getcontext(&(executingThread->context));
//quando a thread que chamar voltar pra c ela no vai ser bloqueada novamente, com esse caso
//podemos usar o wasJustScheduled tambm
if(executingThread->joinedWaitingToFinish >= 0) {
status = blockExecutingThread();
if(status < 0) {
return ERROR;
}
dispatch();
}
return SUCCESS;
}
return ERROR;
}
/******************************************************************************
Parmetros:
tid: identificador da thread a ser suspensa.
Retorno:
Se correto => 0 (zero)
Se erro => Valor negativo.
******************************************************************************/
int csuspend(int tid) {
TCB_t *executingThread = getExecutingThread();
if(executingThread->tid != tid) {
return suspendThread(tid);
}
return ERROR;
}
/******************************************************************************
Parmetros:
tid: identificador da thread que ter sua execuo retomada.
Retorno:
Se correto => 0 (zero)
Se erro => Valor negativo.
******************************************************************************/
int cresume(int tid) {
return resumeThread(tid);
}
/******************************************************************************
Parmetros:
sem: ponteiro para uma varivel do tipo
_t. Aponta para uma estrutura de dados que representa a varivel semforo.
count: valor a ser usado na inicializao do semforo. Representa a quantidade de recursos controlados pelo semforo.
Retorno:
Se correto => 0 (zero)
Se erro => Valor negativo.
******************************************************************************/
int csem_init(csem_t *sem, int count) {
sem->count = count;
sem->fila = (FILA2*) malloc(sizeof(FILA2));
int status = CreateFila2(sem->fila);
if(status < 0) {
return ERROR;
}
else {
return SUCCESS;
}
}
/******************************************************************************
Parmetros:
sem: ponteiro para uma varivel do tipo semforo.
Retorno:
Se correto => 0 (zero)
Se erro => Valor negativo.
******************************************************************************/
int cwait(csem_t *sem) {
int status = 0;
if(sem == NULL) {
return -1;
}
TCB_t *executingThread = getExecutingThread();
getcontext(&(executingThread->context));
if(sem->count <= 0) { //recurso est ocupado
AppendFila2(sem->fila, executingThread);
status = blockExecutingThread();
if(status < 0) {
return ERROR;
}
dispatch();
}
sem->count -=1;
if(status < 0) {
return ERROR;
}
else {
return SUCCESS;
}
}
/******************************************************************************
Parmetros:
sem: ponteiro para uma varivel do tipo semforo.
Retorno:
Se correto => 0 (zero)
Se erro => Valor negativo.
******************************************************************************/
int csignal(csem_t *sem) {
if(sem == NULL) {
return ERROR;
}
sem->count +=1;
FirstFila2(sem->fila);
TCB_t *thread = GetAtIteratorFila2(sem->fila);
if (thread == NULL) {
return SUCCESS;
}
DeleteAtIteratorFila2(sem->fila);
int status = unblockThread(thread->tid);
if(status < 0) {
return ERROR;
}
else {
return SUCCESS;
}
}
|
C
|
#include <avr/io.h>
#include <avr/interrupt.h>
#define period (int)((2000000/1) / (3.744*1000))
int set;
int main(void) {
PORTA_DIR = 0xFE; //input switch
PORTC_DIR = 0xFF; //Output LED
PORTC_OUT = 0xFF; //Initially off
tcc0_init();
while(1){
if(PORTA_IN ==0x00 && set==0){
tcc0_init();
PMIC_CTRL = PMIC_LOLVLEN_bm; //Low level interrupts
sei(); //global interrupt
set=1;
}
else if (PORTA_IN ==0x01){
TCC0.CNT = 0; //Initial value 0
TCC0_CTRLA = 0x00; //Prescaler = 1
TCC0.INTCTRLA = 0x00;
PORTC_OUTSET = 0xFF; //Initially off
set =0;
}
}
}
//Initialize TCC0 timer/counter
void tcc0_init(void){
TCC0.CNT = 0; //Initial value 0
TCC0.INTCTRLA = TC_OVFINTLVL_LO_gc; //Low level interrupt
TCC0_PERL = (uint8_t) period; //Period
TCC0_PERH = (uint8_t) (period>>8);
TCC0_CTRLA = 0x01; //Prescaler = 1
return;
}
ISR(TCC0_OVF_vect){
//Preserve Status Reg
uint8_t temp = CPU_SREG;
//Clear interrupt flags
TCC0.INTFLAGS = 0x01;
//Toggle
PORTC_OUTTGL=0xFF;
//Restore Status Reg
CPU_SREG = temp;
//Return from ISR
return;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <memory.h>
/* LU matrix decomposition from Burden, Faires, p359,
implementation for non-singular matrices only.
Real indexing is from 0->n-1, but code is from 1->n.
Must have a(1,1) != 0.
L has diagonal elements 1.
*/
#define a(i,j) a[i-1][j-1]
#define l(i,j) lum[i-1][j-1]
#define u(i,j) lum[i-1][j-1]
double **lu(double **a, int n, double **lum) {
int i,j,k;
if(a(1,1)==0.0) {
printf("\n\tCan't do LU\n");
exit(1);
}
u(1,1)=a(1,1);
for(j=2;j<=n;j++) {
u(1,j)=a(1,j);
l(j,1)=a(j,1)/u(1,1);
}
for(i=2;i<=n-1;i++) {
u(i,i)=a(i,i);
for(k=1;k<=i-1;k++) u(i,i) -= l(i,k)*u(k,i);
if(u(i,i)==0.0) {
printf("\n\tCan't do LU\n");
exit(1);
}
for(j=i+1;j<=n;j++) {
u(i,j)=a(i,j);l(j,i)=a(j,i);
for(k=1;k<=i-1;k++) {
u(i,j) -= l(i,k)*u(k,j);
l(j,i) -= l(j,k)*u(k,i);
}
l(j,i) /= u(i,i);
}
}
u(n,n) = a(n,n);
for(k=1;k<=n-1;k++) u(n,n) -= l(n,k)*u(k,n);
return lum;
}
#define vx(i) vx[i-1]
#define va(i) va[i-1]
#define vb(i) vb[i-1]
/* Solve LU vx[]=vb [] */
double *lu_solve(double **lum, int n, double *vb, double *vx) {
int i,j,k;
double x;
vx(1)=vb(1);
for(i=2;i<=n;i++) {
vx(i)=vb(i);
for(j=1;j<i;j++) vx(i) -= l(i,j)*vx(j);
}
vx(n) /= u(n,n);
for(i=n-1;i>=1;i--) {
x=vx(i);
for(j=i+1;j<=n;j++) x -= u(i,j)*vx(j);
x /= u(i,i);
vx(i)=x;
}
return vx;
}
#ifdef TESTLU
main() {
int i,j,k;
double **a,**b,*va,*vb;
a=(double**)malloc(5*sizeof(double*));
b=(double**)malloc(5*sizeof(double*));
va=(double*)malloc(5*sizeof(double));
vb=(double*)malloc(5*sizeof(double));
for(i=0;i<5;i++) {
a[i]=(double*)malloc(5*sizeof(double));
b[i]=(double*)malloc(5*sizeof(double));
}
for(i=0;i<5;i++) for(j=0;j<5;j++) {
if(i==j) a[i][j]=5.0;
if(i!=j) a[i][j]=2.0;
}
lu(a,5,b);
for(i=0;i<5;i++) {
printf("\n\t");
for(j=0;j<5;j++) printf("%10.3lf ",b[i][j]);
}
for(i=0;i<5;i++) for(j=0;j<5;j++) {
a[i][j]=0.0;
for(k=0;!(k>i||k>j);k++) {
if(i!=k) a[i][j] += b[i][k]*b[k][j];
else a[i][j] += b[i][j];
}
}
printf("\n\n");
for(i=0;i<5;i++) {
printf("\n\t");
for(j=0;j<5;j++) printf("%10.3lf ",a[i][j]);
}
vb[0]=0.0;vb[1]=1.0;vb[2]=2.0;vb[3]=3.0;vb[4]=4.0;
lu_solve(b,5,vb,va);
printf("\n\n\t");
for(j=0;j<5;j++) printf("%10.3lf ",va[j]);
}
#endif
|
C
|
// 6.3 -- embedded loop
#include <stdio.h>
#define SIZE 6
int main(void)
{
// variant 1
char ch = 'F';
char start;
char end;
for(end = ch; end >= 'A'; end--)
{
for(start = ch; start >= end; start--)
printf("%c", start);
printf("\n");
}
// variant 2
int i, j, k;
for(i = 0; i < SIZE; i++)
{
for(j = 0; j <= i; j++)
{
k = 70 - j;
printf("%c", k);
}
printf("\n");
}
return 0;
}
// F
// FE
// FED
// FEDC
// FEDCB
// FEDCBA
|
C
|
#include <sys/socket.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#define BUFFERSIZE 32
#define MAXPENDING 5
/*
1. Create server socket
2. Assign server address and client address using the sockaddr_in struct
3. Bind the socket to the port
4. Listen for requests
5. Accept connections by opening new sockets (using accept())
6. Open connection with client
7. Receive data from client
8. Send data to client
*/
int main()
{
//1. create a socket
int serverSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if(serverSocket < 0)
{
printf("Could not create server side socket");
exit(1);
}
printf("Server socket created\n");
//2.assign server address and client address using sockaddr_in struct
struct sockaddr_in serverAddr;
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(12345);
printf("Server address is assigned\n");
//bind server socket to the port
int temp = bind(serverSocket, (struct sockaddr *)&serverAddr, sizeof(serverAddr));
if(temp < 0)
{
printf("Error while binding\n");
exit(1);
}
printf("Binding successful...\n");
int temp1 = listen(serverSocket, MAXPENDING);
if(temp1 < 0)
{
printf("Error in listening...\n");
exit(1);
}
printf("Now listening...\n");
char msg[BUFFERSIZE];
struct sockaddr_in clientAddr[3];
int clientLength = sizeof(clientAddr[0]);
int i = 3;
int clientSocket[3];
while(i --)
{
clientSocket[i] = accept(serverSocket, (struct sockAddr *)&clientAddr, &clientLength);
if(clientSocket[i] < 0)
{
printf("Error in client socket");
exit(1);
}
printf("Handling client %s\n", inet_ntoa(clientAddr[i].sin_addr));
}
i = 0;
while(i < 3)
{
int temp2 = recv(clientSocket[i], msg, BUFFERSIZE, 0);
if(temp2 < 0)
{
printf("Error in receiving message");
exit(1);
}
printf("%s\n",msg);
printf("Enter message for the client\n");
gets(msg);
int bytesSent = send(clientSocket[i], msg, strlen(msg),0);
if(bytesSent != strlen(msg)){
printf("Error sending message");
exit(1);
}
i++;
}
close(serverSocket);
close(clientSocket);
return 0;
}
|
C
|
/*
C Programming Practice - Struct Basic
Teerapat Kraisrisirikul
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int day;
int month;
int year;
} Date;
typedef struct {
char name[30];
int age;
Date birthday;
} Person;
int main () {
/* Main function */
Person customer[5] = {{"AAA", 18, {15, 6, 1999}},
{"BBB", 17, {16, 3, 2000}},
{"CCC", 19, {11, 11, 1998}},
{"DDD", 20, {20, 9, 1997}},
{"EEE", 22, {14, 2, 1996}}};
printf("No.\tName\tAge\tBirthday\n");
for (int i = 0; i < 5; i++) {
printf("%02i\t", i);
printf("%s\t", customer[i].name);
printf("%i\t", customer[i].age);
printf("%02i/%02i/%i", customer[i].birthday.day, customer[i].birthday.month, customer[i].birthday.year);
printf("\n");
}
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct hashtable {
int entries;
int buckets;
char ** keys;
void ** values;
};
struct hashtable makeHashtable(int buckets) {
struct hashtable ht;
ht.buckets = buckets;
ht.entries = 0;
ht.keys = malloc(buckets*sizeof(char *));
bzero(ht.keys, buckets*sizeof(char *));
ht.values = malloc(buckets*sizeof(void *));
return ht;
}
int deleteHashtable(struct hashtable ht) {
free(ht.keys);
free(ht.values);
return 0;
}
float loadfactor(struct hashtable ht) {
return ht.entries/(float)ht.buckets;
}
int hash(char * key) {
int i;
int hashval = 0;
for (i = 0; i < strlen(key); i++) {
hashval += key[i];
}
return hashval;
}
int put(struct hashtable * ht, char * key, void * value) {
int hashval = hash(key) % ht->buckets;
/* linear probing */
while (ht->keys[hashval] != NULL) {
hashval = (hashval + 1) % ht->buckets;
}
/* add to table and increment entry count */
ht->keys[hashval] = key;
ht->values[hashval] = value;
ht->entries += 1;
/* increase hashtable size if loadfactor too large */
if (loadfactor(*ht) >= 0.7) {
struct hashtable newHt = makeHashtable(ht->buckets*2);
int i;
for (i = 0; i < ht->buckets; i++) {
if (ht->keys[i] != NULL) {
put(&newHt, ht->keys[i], ht->values[i]);
}
}
deleteHashtable(*ht);
*ht = newHt;
}
return 0;
}
void * get(struct hashtable ht, char * key) {
int hashval = hash(key) % ht.buckets;
int probeval = hashval;
/* linear probing */
while (ht.keys[probeval] != NULL &&
strcmp(ht.keys[probeval], key) != 0) {
probeval = (probeval + 1) % ht.buckets;
if (probeval == hashval) {
return NULL;
}
}
return ht.values[probeval];
}
void print(struct hashtable ht) {
int i;
for (i = 0; i < ht.buckets; i++) {
printf("%d: <%s> <%s>\n", i, ht.keys[i], (char *) ht.values[i]);
}
}
int main() {
struct hashtable ht = makeHashtable(2);
char * buf = NULL;
char * cmd, * key, * value;
size_t size = 0;
do {
free(buf);
getline(&buf, &size, stdin);
if (buf[strlen(buf)-1] == '\n') {
buf[strlen(buf)-1] = '\0';
}
cmd = strsep(&buf, " ");
key = strsep(&buf, " ");
value = strsep(&buf, " ");
if (strcmp(cmd, "put") == 0) {
if (key == NULL || value == NULL) {
printf("usage: put <key> <value>\n");
continue;
}
put(&ht, key, value);
} else if (strcmp(cmd, "get") == 0) {
if (key == NULL) {
printf("usage: get <key>");
continue;
}
printf("%s\n", (char *) get(ht, key));
} else if (strcmp(cmd, "info") == 0) {
printf("loadfactor: %f, entries: %d, buckets: %d\n",
loadfactor(ht), ht.entries, ht.buckets);
} else if (strcmp(cmd, "print") == 0) {
print(ht);
} else if (strcmp(cmd, "q") == 0) {
break;
} else {
printf("usage: [ put | get | info | q ]\n");
continue;
}
} while (1);
return 0;
}
|
C
|
#include <stdlib.h>
#include <unistd.h>
#include "thread_pool.h"
int sem_wait(m_sem_t *s)
{
pthread_mutex_lock(&s->lock);
// if the critical part is occupied, then wait
if (s->occupied) {
pthread_cond_wait(&s->cond, &s->lock);
}
// set the critical part as occupied
s->occupied = true;
pthread_mutex_unlock(&s->lock);
return 0;
}
int sem_post(m_sem_t *s)
{
pthread_mutex_lock(&s->lock);
// releasing the critical part.
s->occupied = false;
pthread_mutex_unlock(&s->lock);
pthread_cond_broadcast(&s->cond);
return 0;
}
void sem_init(m_sem_t *s)
{
s->occupied = false;
pthread_mutex_init(&s->lock, NULL);
pthread_cond_init(&s->cond, NULL);
}
void sem_destroy(m_sem_t *s) {
pthread_mutex_destroy(&s->lock);
pthread_cond_destroy(&s->cond);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "arvore.h"
#include "lista.h"
#include "compactador.h"
#define TAM 256
void inic_vet(int *vet, int tam);
int main(int argc, char** argv) {
int vet[TAM];
inic_vet(vet, TAM);
unsigned char* buffer = le_arq(argv[1]);
soma_freq(vet, buffer);
Lista* lista = inic_lista();
faz_lista(vet, TAM, lista);
ordena_lista(lista);
ordena_lista_caracter(lista);
faz_arv_huffman(lista);
compacta(TAM, buffer, retorna_arv(lista), vet, argv[1]);
libera_lista(lista);
return (EXIT_SUCCESS);
}
void inic_vet(int* vet, int tam) {
int i;
for (i = 0; tam > i; i++)
vet[i] = 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
#include <webots/robot.h>
#include <webots/supervisor.h>
#include <webots/receiver.h>
#define MAX_ROB 4
#define TARGET_FLOCKING_DIST 0.3
#define ROBOT_MAX_SPEED 0.002
enum {POS_X=0,POS_Y,POS_Z};
static WbNodeRef robs[MAX_ROB];
static WbDeviceTag receiver;
const double *loc[MAX_ROB];
const double *rot[MAX_ROB];
static double center_pos_start[3], center_pos_end[3];
static void reset();
static int fitness(double* fitness, double* distance, double* velocity);
static void display_data(double fit, double dist, double vel);
static FILE *fp;
/* MAIN - Distribute and test conctrollers */
int main() {
double fit=0, distance=0, velocity=0;
int iter=0;
fp = fopen("formation_metrics.csv","w");
fprintf(fp, "time; fitness; distance; velocity;\n");
/* Initialisation */
wb_robot_init();
reset();
int time_step = wb_robot_get_basic_time_step();
while(wb_robot_step(time_step) != -1){
if (!fitness(&fit, &distance, &velocity)) continue;
//display_data(fit, distance, velocity);
iter++;
}
fit/=iter; distance/=iter; velocity/=iter;
printf("Average Performance over %d iter: \n distance: %.5f\n velocity: %.5f\n fitness: %.5f\n", iter, distance, velocity, fit);
fclose(fp);
return 0;
}
/* RESET - Get device handles and starting locations */
void reset() {
// Device variables
char rob[] = "epuck0";
char re[] = "receiver";
int i; //counter
center_pos_start[POS_X]=0; center_pos_start[POS_Z]=0;
for (i=0;i<MAX_ROB;i++) {
robs[i] = wb_supervisor_node_get_from_def(rob);
loc[i] = wb_supervisor_field_get_sf_vec3f(wb_supervisor_node_get_field(robs[i],"translation"));
rot[i] = wb_supervisor_field_get_sf_rotation(wb_supervisor_node_get_field(robs[i],"rotation"));
center_pos_start[POS_X]+=loc[i][POS_X]; center_pos_start[POS_Z]+=loc[i][POS_Z];
rob[5]++;
}
center_pos_start[POS_X]/=MAX_ROB; center_pos_start[POS_Z]/=MAX_ROB;
receiver = wb_robot_get_device(re);
wb_receiver_enable(receiver,wb_robot_get_basic_time_step());
}
// Calculate fitness
int fitness(double* fitness, double* distance, double* velocity){
double *inbuffer;
int i;
double dist[MAX_ROB];
double vel=0;
double total_distance = 0;
center_pos_start[POS_X]=center_pos_end[POS_X]; center_pos_start[POS_Z]=center_pos_end[POS_Z];
center_pos_end[POS_X]=0; center_pos_end[POS_Z]=0;
for (i=0; i<MAX_ROB; i++){
loc[i] = wb_supervisor_field_get_sf_vec3f(wb_supervisor_node_get_field(robs[i],"translation"));
rot[i] = wb_supervisor_field_get_sf_rotation(wb_supervisor_node_get_field(robs[i],"rotation"));
center_pos_end[POS_X]+=loc[i][POS_X]; center_pos_end[POS_Z]+=loc[i][POS_Z];
}
center_pos_end[POS_X]/=MAX_ROB; center_pos_end[POS_Z]/=MAX_ROB;
for(i=0; i<MAX_ROB; i++)
dist[i]=-1;
while (wb_receiver_get_queue_length(receiver) > 0) {
inbuffer = (double*) wb_receiver_get_data(receiver);
dist[((int) inbuffer[0])-1]=inbuffer[1];
//printf("%d %g\n", (int) inbuffer[0], inbuffer[1]);
wb_receiver_next_packet(receiver);
}
for(i=0; i<MAX_ROB; i++){
if (dist[i]==-1){
return 0;
}
total_distance+=dist[i];
}
total_distance=1.0/(1.0+total_distance/((float) MAX_ROB));
// VELOCITY
vel = sqrt(pow(center_pos_end[POS_X]-center_pos_start[POS_X],2)+pow(center_pos_end[POS_Z]-center_pos_start[POS_Z],2));
vel = vel/(ROBOT_MAX_SPEED);
if (vel>1) // Patch to prevent bad init
return 0;
*distance = total_distance;
*velocity = vel;
*fitness = total_distance*vel;
return 1;
}
void display_data(double fit, double dist, double vel){
char label[20];
sprintf(label, "Fitness: %.5f", fit);
wb_supervisor_set_label(0,label,0.01,0.01,0.1,0x000000,0,"Arial");
sprintf(label, "Distance: %.5f", dist);
wb_supervisor_set_label(2,label,0.01,0.06,0.1,0x000000,0,"Arial");
sprintf(label, "Velocity: %.5f", vel);
wb_supervisor_set_label(3,label,0.01,0.11,0.1,0x000000,0,"Arial");
fprintf(fp, "%g; %g; %g; %g;\n", wb_robot_get_time(), fit, dist, vel);
}
|
C
|
#ifndef COMMON_H
#define COMMON_H
#include <stdint.h>
#ifndef MAX_PATH
#define MAX_PATH 256
#endif
#define MIN(x,y) ((x) < (y) ? (x) : (y))
#define MAX(x,y) ((x) > (y) ? (x) : (y))
typedef enum LogLevel {
INFO_LEVEL,
DEBUG_LEVEL,
ERROR_LEVEL,
FATAL_LEVEL,
} LogLevel;
void logger(LogLevel level, const char* format, ...);
typedef enum Maybe {
OK,
FAILED,
} Maybe;
void* siegeMalloc(size_t size);
void* siegeCalloc(size_t count, size_t size);
void* siegeRealloc(void* ptr, size_t newSize);
void siegeFree(void* mem);
typedef struct TimeStep {
long frameTime; /* time from last frame */
long gameClock; /* current game clock */
double frameTimeFraction; /* time from last frame in fractions of seconds */
} TimeStep;
/*
==============================================
Vector library
==============================================
*/
#include <math.h>
typedef float Vec2[2];
#define VectorClear(v) ((v)[0]=(v)[1]=0)
#define VectorSet(v, x, y) ((v)[0]=(x),(v)[1]=(y))
#define VectorCopy(a, b) ((b)[0]=(a)[0],(b)[1]=(a)[1])
#define VectorCrossProduct(a, b) (((a)[0] * (b)[1]) - ((a)[1] * (b)[0]))
#define VectorDotProduct(a, b) (((a)[1] * (b)[0]) + ((a)[0] * (b)[1]))
#define VectorAdd(a, b, d) ((d)[0]=(a)[0] + (b)[0], (d)[1]=(a)[1] + (b)[1])
#define VectorAddScalar(a, s, d) ((d)[0]=(a)[0] + (s), (d)[1]=(a)[1] + (s))
#define VectorSub(a, b, d) ((d)[0]=(a)[0] - (b)[0], (d)[1]=(a)[1] - (b)[1])
#define VectorSubScalar(a, s, d) ((d)[0]=(a)[0] - (s), (d)[1]=(a)[1] - (s))
#define VectorRotate(a, r, d) ((d)[0] = ((a)[0] * cos(r)) - ((a)[1] * sin(r)), (d)[1] = ((a)[0] * sin(r)) + ((a)[1] * cos(r)))
#define VectorAngle(a, b) (atan2((b)[1], (b)[0]) - atan2((a)[1], (a)[0]))
#define VectorMA(a, b, s, d) ((d)[0] = (a)[0] + (b)[0] * s, (d)[1] = (a)[1] + (b)[1] * s)
#define VectorMS(a, b, s, d) ((d)[0] = (a)[0] - (b)[0] * s, (d)[1] = (a)[1] - (b)[1] * s)
#define VectorEq(a, b) ((a)[0] == (b)[0] && (a)[1] == (b)[1])
#define floatEq(a, b, e) (abs((a) - (b)) < e)
#define VectorEqe(a, b, e) (floatEq((a)[0], (b)[0], (e)) && floatEq((a)[1], (b)[1], (e)))
#define VectorLength(a) (sqrt(((a)[0] * (a)[0]) + ((a)[1] * (a)[1])))
#define VectorLengthSq(a) (((a)[0] * (a)[0]) + ((a)[1] * (a)[1]))
//#define VectorDistance(a, b)
typedef struct Rect {
float x, y, w, h;
} Rect;
#define rectSetPos(r,pos) ((r).x = pos[0], (r).y = pos[1])
#define rectClear(r) ((r).x = (r).y = (r).w = (r).h = 0)
/*
==============================================
Stretchy Buffer
==============================================
*/
#define stb_sb_free(a) ((a) ? free(stb__sbraw(a)),0 : 0)
#define stb_sb_push(a,v) (stb__sbmaybegrow(a,1), (a)[stb__sbn(a)++] = (v))
#define stb_sb_count(a) ((a) ? stb__sbn(a) : 0)
#define stb_sb_add(a,n) (stb__sbmaybegrow(a,n), stb__sbn(a)+=(n), &(a)[stb__sbn(a)-(n)])
#define stb_sb_last(a) ((a)[stb__sbn(a)-1])
#define stb__sbraw(a) ((int *) (a) - 2)
#define stb__sbm(a) stb__sbraw(a)[0]
#define stb__sbn(a) stb__sbraw(a)[1]
#define stb__sbneedgrow(a,n) ((a)==0 || stb__sbn(a)+(n) >= stb__sbm(a))
#define stb__sbmaybegrow(a,n) (stb__sbneedgrow(a,(n)) ? stb__sbgrow(a,n) : 0)
#define stb__sbgrow(a,n) (*((void **)&(a)) = stb__sbgrowf((a), (n), sizeof(*(a))))
#include <stdlib.h>
static void * stb__sbgrowf(void *arr, int increment, int itemsize)
{
int dbl_cur = arr ? 2*stb__sbm(arr) : 0;
int min_needed = stb_sb_count(arr) + increment;
int m = dbl_cur > min_needed ? dbl_cur : min_needed;
int *p = (int *) realloc(arr ? stb__sbraw(arr) : 0, itemsize * m + sizeof(int)*2);
if (p) {
if (!arr)
p[1] = 0;
p[0] = m;
return p+2;
} else {
#ifdef STRETCHY_BUFFER_OUT_OF_MEMORY
STRETCHY_BUFFER_OUT_OF_MEMORY ;
#endif
return (void *) (2*sizeof(int)); // try to force a NULL pointer exception later
}
}
#endif
|
C
|
/*
** EPITECH PROJECT, 2020
** NWP_myftp_2019
** File description:
** pasv
*/
#include "myftp.h"
static char *dots_by_coms(char *str)
{
if (!str)
return (NULL);
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] == '.')
str[i] = ',';
}
return (str);
}
int cmd_pasv(int client_fd, global_t *glob, char **command)
{
client_t *client = list_get_client(glob->clients, client_fd);
uint16_t port;
(void)command;
if (!check_client(client_fd, client, false))
return (84);
if (client->transfer_socket)
close(client->transfer_socket->fd);
if (!(client->transfer_socket = create_socket(0, IP, true)))
return (84);
if (start_listening_socket(client->transfer_socket) == 84)
return (84);
client->transfer_mode = 1;
port = ntohs(client->transfer_socket->socket.sin_port);
fprintf(stderr, "pasv port: %d\n", port);
dprintf(client_fd, "227 Entering Passive Mode (%s,%d,%d).\r\n",
dots_by_coms(inet_ntoa(client->transfer_socket->socket.sin_addr)),
port / 256, port % 256);
return (0);
}
|
C
|
int cmp(const void *x,const void *y)
{
return *(int*)x-*(int *)y;
}
int main()
{
int n;
scanf("%d",&n);
int i=0,j,k,a=0,b=0;
char sex[10];
float man[40],woman[40],h;
while(i<n)
{
scanf("%s %f",sex,&h);
if(sex[0]=='m')
{
man[a]=h;
a++;
}
else
{
woman[b]=h;
b++;
}
i++;
}
qsort(man,a,sizeof(float),cmp);
qsort(woman,b,sizeof(float),cmp);
printf("%.2f",man[0]);
for(k=1;k<a;k++)
printf(" %.2f",man[k]);
for(k=b-1;k>0;k--)
printf(" %.2f",woman[k]);
printf(" %.2f\n",woman[0]);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* stack_operations.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bseven <bseven@student.21-school.> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/14 18:36:41 by bseven #+# #+# */
/* Updated: 2021/11/14 18:36:43 by bseven ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
void swap_stack(t_list **list, char ab)
{
t_list *tmp;
if (*list)
{
tmp = *list;
if ((*list)->next)
{
*list = (*list)->next;
tmp->next = (*list)->next;
(*list)->next = tmp;
}
}
ft_write("s", ab);
}
void push_stack(t_list **dest, t_list **srcs, char ab)
{
t_list *temp;
if (*srcs)
{
temp = *srcs;
if ((*srcs)->next)
(*srcs) = (*srcs)->next;
else
(*srcs) = NULL;
temp->next = NULL;
ft_lstadd_front(dest, temp);
}
ft_write("p", ab);
}
void rotate_stack(t_list **list, char ab)
{
t_list *temp;
if (*list)
{
temp = (*list);
if ((*list)->next)
{
(*list) = (*list)->next;
temp->next = NULL;
ft_lstadd_back(list, temp);
}
}
ft_write("r", ab);
}
void rev_rotate_stack(t_list **list, char ab)
{
t_list *temp;
t_list *curr;
if (*list && (*list)->next)
{
temp = ft_lstlast(*list);
curr = *list;
while (curr->next && curr->next->next)
curr = curr->next;
curr->next = NULL;
temp->next = *list;
*list = temp;
}
ft_write("rr", ab);
}
|
C
|
#include <stdio.h>
#include<time.h>
int main()
{
int a;
printf("Vvedite 1, esli hotite sami ugadivat chislo ili vvedite 0, esli hotite chtob computer ygadival chislo");
do
{
scanf("%d", &a);
} while ((a != 1) && (a != 0));
if (a == 1)
{
int n, x, k = 0;
srand((unsigned int)time(NULL));
n = rand() % 1000;
printf("vvedite pervuyu popitku");
do
{
k++;
scanf("%d", &x);
if (x == n)
{
printf("vi otgadali");
printf("kolichestvo popitok = %d", k);
return 0;
}
if (x < n)
{
printf("bolshe");
}
if (x > n)
{
printf("menshe");
}
} while ((x >= 0) && (x <= 1000));
}
else
{
int x, y = 0, zmax = 1000, zmin = 0, o = 0;
srand((unsigned int)time(NULL));
printf("Mehshe = 0, Ravno = 1, Bolshe = 2 ");
do
{
o++;
x = zmin + rand() % (zmax - zmin + 1);
printf("\n%d", x);
scanf("%d", &y);
switch (y)
{
case 0:
{
zmax = x;
break;
}
case 1:
{
printf("Zagannoe chislo = %d ", x);
printf("\nKolichestvo popitok = %d", o);
return 0;
}
case 2:
{
zmin = x;
break;
}
}
} while (y != 1);
}
}
|
C
|
#include "window.h"
/**
* info_error - handler error
*
* @message_error: message error
*
*/
void info_error(char *message_error)
{
size_t bytes_readed = 0;
bytes_readed = write(2, message_error, strlen(message_error));
if (bytes_readed == EOF)
exit(EOF);
}
/**
* is_map - valid if it's a valid map the content of the file
*
* @data_raw: data without processing
*
* Return: true if it's a valid map else return false
*/
bool is_map(char *data_raw)
{
if (data_raw == NULL)
return (false);
if (*data_raw == '\0')
return (true);
if (*data_raw == '\n' || *data_raw == ' ' || *data_raw == '-')
return (is_map(data_raw + 1));
if (*data_raw >= '0' && *data_raw <= '9')
return (is_map(data_raw + 1));
return (false);
}
/**
* read_file - read content of file
*
* @file_direction: direction of the file to read
*
* Return: data without processing
*/
char *read_file(char *file_direction)
{
size_t file_pointer = 0;
char line[BUFSIZ];
char *content = NULL;
size_t line_size = 0;
file_pointer = open(file_direction, O_RDONLY | O_CREAT);
if (file_pointer == -1)
return (NULL);
line_size = read(file_pointer, line, BUFSIZ);
if (line_size == EOF)
return (NULL);
line[line_size] = '\0';
close(file_pointer);
if (!is_map(line))
return (NULL);
content = malloc(sizeof(char) * strlen(line));
if (!content)
return (NULL);
strcpy(content, line);
return (content);
}
/**
* get_bounds - read the bounds and storage in the bounds struct
*
* @data_raw: data without processing
*
* Return: structure that contain the limits if gid
*/
bounds_t *get_bounds(char *data_raw)
{
int i;
bounds_t *bounds;
bounds = malloc(sizeof(bounds_t));
if (!bounds)
return (NULL);
bounds->axis_y = 0;
bounds->axis_x = 0;
for (i = 0; data_raw[i] != '\0'; i++)
{
bounds->axis_x += !bounds->axis_y && data_raw[i] == ' ';
bounds->axis_y += data_raw[i] == '\n';
}
bounds->axis_x += 1;
bounds->axis_y += 1;
bounds->angle = 0;
get_windows_bound(&bounds->width, &bounds->height, &bounds->min_bound);
bounds->max_bound = bounds->width == bounds->min_bound ? bounds->height : bounds->width;
return (bounds);
}
/**
* get_directions - read the directions and return the struct storage
*
* @data_raw: data without processing
* @bounds: limits of grid
*
* Return: array of strctures storege the directions
*/
axis_t **get_directions(char *data_raw, bounds_t *bounds)
{
int i, lenght = 0;
axis_t *local_directions[BUFSIZ];
axis_t **directions;
char *current = data_raw;
lenght = (int)(bounds->axis_x * bounds->axis_y);
for (i = 0; current; i++)
{
current = strtok(i ? NULL : data_raw, " \n");
if (current != NULL)
{
local_directions[i] = malloc(sizeof(axis_t));
if (!local_directions[i])
{
i-= 1;
for (i--; 0 < i; i--)
free(local_directions[i]);
return (NULL);
}
local_directions[i]->z_raw = (float)atoi(current);
local_directions[i]->z = 0;
local_directions[i]->x = 0;
local_directions[i]->y = 0;
}
else
{
local_directions[i] = NULL;
}
}
directions = calloc(i, sizeof(axis_t *));
if (!directions)
return (NULL);
for (i = 0; local_directions[i]; i++)
directions[i] = local_directions[i];
directions[i] = NULL;
return (directions);
}
/**
* get_windows_bound - get the windows screem bounds
*
* @width: width size of screen
* @height: height size of screen
* @min_size: min_size size of screen
*
*/
void get_windows_bound(DWORD *width, DWORD *height, DWORD *min_size)
{
DWORD local_width = 0;
DWORD local_height = 0;
local_width = GetSystemMetrics(SM_CXSCREEN);
local_height = GetSystemMetrics(SM_CYSCREEN) - GetSystemMetrics(SM_CYSIZE)
- GetSystemMetrics(SM_CYMENU) - GetSystemMetrics(SM_CYCAPTION);
if (width)
*width = local_width;
if (height)
*height = local_height;
if (min_size)
*min_size = ((local_width < local_height ? local_width : local_height));
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("%s is the best %s ever!\n","Svetlozar","programmer");
printf("I ate %d sandwiches last night!\n", 6);
printf("My body temperature is %f.\n", 36.52);
printf("Yesterday it was %.2f.\n", 36.04);
return 0;
}
|
C
|
#ifndef ABB_H
#define ABB_H
#include <stdbool.h>
#include <stddef.h>
/* Los structs deben llamarse "abb" y "abb_iter".*/
typedef struct abb abb_t;
/*Funcion para comparar una clave pasada por parametro con una clave de posicion
* actual del abb.
* Debe devolver 0 si los elementos comparados son iguales. Un número menor a 0
* si el primer elemento es menor al segundo, o mayor a 0 si es mayor.*/
typedef int (*abb_comparar_clave_t) (const char *, const char *);
/* Tipo de función para destruir dato.*/
typedef void (*abb_destruir_dato_t) (void *);
/* Crea el abb*/
abb_t* abb_crear(abb_comparar_clave_t cmp, abb_destruir_dato_t destruir_dato);
/* Guarda un elemento en el abb, si la clave ya se encuentra en la
* estructura, la reemplaza. De no poder guardarlo devuelve false.
* Pre: La estructura abb fue inicializada
* Post: Se almacenó el par (clave, dato) */
bool abb_guardar(abb_t *arbol, const char *clave, void *dato);
/* Borra un elemento del abb y devuelve el dato asociado. Devuelve
* NULL si el dato no se encuentra.
* Pre: La estructura abb fue inicializada
* Post: El elemento fue borrado de la estructura y se lo devolvió,
* en el caso de que estuviera guardado. */
void *abb_borrar(abb_t *arbol, const char *clave);
/* Obtiene el valor de un elemento del abb, si la clave no se encuentra
* devuelve NULL.
* Pre: La estructura abb fue inicializada
* Post: Devuelve un elemento*/
void *abb_obtener(const abb_t *arbol, const char *clave);
/* Determina si clave pertenece o no al abb, devolviendo True o False.
* Pre: La estructura abb fue inicializada */
bool abb_pertenece(const abb_t *arbol, const char *clave);
/* Devuelve la cantidad de elementos del abb.
* Pre: La estructura abb fue inicializada
* Pos: Devuelve cantidad de elementos del abb*/
size_t abb_cantidad(abb_t *arbol);
/* Destruye la estructura liberando la memoria pedida y llamando a la función
* destruir para cada par (clave, dato).
* Pre: La estructura abb fue inicializada
* Post: La estructura abb fue destruida */
void abb_destruir(abb_t *arbol);
/****************************************************************************
* ITERADOR INTERNO *
****************************************************************************/
/* Iterador interno in orden.*/
/* Crea un iterador in orden.
* Pre: El abb fue creado, fue creada la funcion para pasar por parametro.
* Pos: Modifica el abb segun la funcion que se le pasa por parametro.*/
void abb_in_order(abb_t *arbol, bool visitar(const char *, void *, void *), void *extra);
/*Iterador interno in orden con inicio y fin.
Recibe una clave de inicio y otra de fin y aplica la funcion de visitar a los
elementos del arbol que se encuentran en ese rango.*/
void abb_in_order_mod(abb_t* arbol,const char* ini,const char* fin, bool visitar(const char*,void*,void*),void* extra);
/****************************************************************************
* ITERADOR EXTERNO *
****************************************************************************/
/*Estructura del Iterador externo*/
typedef struct abb_iter abb_iter_t;
/* Iterador del abb */
/* Crea iterador in orden.
* En caso de error, devuelve NULL.
* Pre: El abb fue creado.
* Post: Devuelve un iterador.*/
abb_iter_t *abb_iter_in_crear(const abb_t *arbol);
/* Devuelve True o False si se pudo avanzar el iterador al siguiente elemento.
En caso de que esté al final del iterador, devuelve false.
* Pre: El iterador fue creado.*/
bool abb_iter_in_avanzar(abb_iter_t *iter);
/*Devuelve clave actual, esa clave no se puede modificar ni liberar. Si se está al final del iterador, devuelve NULL.
* Pre: el iterador fue creado.
* Post: Se devolvió la clave de la posición actual del iterador.*/
const char *abb_iter_in_ver_actual(const abb_iter_t *iter);
/* Devuelve verdadero o falso, si el iterador llegó al final.
* Pre: el iterador fue creado.*/
bool abb_iter_in_al_final(const abb_iter_t *iter);
/* Destruye iterador*/
void abb_iter_in_destruir(abb_iter_t* iter);
#endif // ABB_H
|
C
|
#include <stdio.h>
#include "log.h"
// Flash is 1024 * 1024 bits.
// One item is 9 * 8 bits
// 1024 * 1024 / (8 * 9) = 14 563,56
#define LOG_MAX_ITEMS 14563
/** LOG FORMAT
*
* | ... | Address
* +----------+----------+----------+----------+
* | ID_(n+0) | ID_(n+1) | ID_(n+2) | ID_(n+3) | 36 n
* +----------+----------+----------+----------+
* | ITEM_(n+0).v32[0] ITEM_(n+0) | 36 n + 4
* +----------------------------- - - - - - - -+
* | ITEM_(n+0).v32[1] |
* +-------------------------------------------+
* | ITEM_(n+1).v32[0] ITEM_(n+1) | 36 n + 8
* +----------------------------- - - - - - - -+
* | ITEM_(n+1).v32[1] |
* +-------------------------------------------+
* | ITEM_(n+2).v32[0] ITEM_(n+2) | 36 n + 12
* +----------------------------- - - - - - - -+
* | ITEM_(n+2).v32[1] |
* +-------------------------------------------+
* | ITEM_(n+3).v32[0] ITEM_(n+3) | 36 n + 16
* +----------------------------- - - - - - - -+
* | ITEM_(n+3).v32[1] |
* +----------+----------+----------+----------+
* | ... | ... | ... | ... |
*
* IDs contain the information needed to
* decode the values in the ITEMs.
*
* Address for ID of item #k is:
* addr(k) = floor(k, 4) * 36 + rem(k, 4)
* floor(k, 4) is (k & ~0x03), round down modulo 4
* rem(k, 4) is (k & 0x03), or (k % 4)
*
* ITEMs have type message_value_t and can be accessed at byte,
* halword and word offsets via the .v8[], .v16[] or .v32[] union
* members.
* Address for ITEM #k is:
* addr(k) = floor(k, 4) * 36 + rem(k, 4) * 8 + 4
* floor(k, 4) is (k & ~0x03)
* rem(k, 4) is (k & 0x03)
*
* The fill rate and status of the log is
* kept separately in static variables.
*
**/
static uint32_t log_id(uint32_t index);
static uint32_t log_item(uint32_t index);
// Number of items in the log
uint32_t logsize;
// Serial communication ling
static serialcomm_t* sc = 0;
static qc_hal_t* hal = 0;
// Return address of ID of item No. i
// ---
// Parameters: i: index of item in the log.
// Returns: The address
// Author: Boldizsar Palotas
uint32_t log_id(uint32_t i) {
return (i & ~0x03ul) * 36 + (i & 0x03ul);
}
// Return address of value of item No. i
// ---
// Parameters: i: index of item in the log.
// Returns: The address
// Author: Boldizsar Palotas
uint32_t log_item(uint32_t i) {
return (i & ~0x03ul) * 36 + (i & 0x03ul) * 8 + 4;
}
// Initialize the log structure
// ---
// Parameters: h: The hal object to use to access the physical storage
// serialcomm: the comm object to use for log readback
// Returns: true if there was an error
// Author: Boldizsar Palotas
bool log_init(qc_hal_t* h, serialcomm_t* serialcomm) {
logsize = 0;
hal = h;
volatile uint32_t to = 10000;
while (--to) {}
bool result = hal->flash_init_fn();
if (result) {
sc = serialcomm;
}
return result;
}
// Write a few values (one item) to the log
// ---
// Parameters: item: The items to write
// Returns: True if there was an error
// Author: Boldizsar Palotas
bool log_write(message_t* item) {
if (LOG_MAX_ITEMS < logsize) {
printf("> Log full!\n");
return false;
}
bool result1 = hal->flash_write_fn(log_id(logsize), &item->ID, 1);
bool result2 = hal->flash_write_fn(log_item(logsize), item->value.v8, 8);
if (result1 && result2) {
logsize++;
return true;
} else {
printf("> Log wr err!\n");
return false;
}
}
// Read a few values (one item) from the log
// ---
// Parameters: item: The items to write
// (out) item: The message object containing the values if no error
// Returns: True if there was an error
// Author: Boldizsar Palotas
bool log_read(uint32_t index, message_t* item) {
if (LOG_MAX_ITEMS < index)
return false;
bool result1 = hal->flash_read_fn(log_id(index), &item->ID, 1);
bool result2 = hal->flash_read_fn(log_item(index), item->value.v8, 8);
if (result1 && result2) {
return true;
} else {
return false;
}
}
// Read all values (all items) from the log and transmit to PC
// ---
// Parameters: none
// Returns: nothing
// Author: Boldizsar Palotas
void log_readback(void) {
message_t msg;
printf("> Log read (sum %"PRIu32")\n", logsize);
if (!sc)
printf("> Log serial error\n");
serialcomm_quick_send(sc, MESSAGE_LOG_START_ID, 0, 0);
int i;
for (i = 0; i < logsize; i++) {
if (!log_read(i, &msg)) {
break;
}
serialcomm_quick_send(sc, msg.ID, msg.value.v32[0], msg.value.v32[1]);
}
serialcomm_quick_send(sc, MESSAGE_LOG_END_ID, 0, 0);
if (i != logsize)
printf("> Log rd err at %d\n", i);
log_reset();
}
// Reset the log
// ---
// Parameters: none
// Returns: nothing
// Author: Koos Eerden
void log_reset(void) {
printf("> Log reset\n");
logsize = 0;
if (!hal->flash_erase_fn())
printf("> Chip erase failed!\n");;
}
|
C
|
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
int main(int argc, string argv[])
{
// Get the key & validate key
if (argc != 2)
{
printf("Usage: ./substitution key\n");
return 1;
}
// Checking for length
if (strlen(argv[1]) != 26)
{
printf("key must be at least 26 characters. \n");
return 1;
}
// Check for Alphabetic characters
for (int i = 0; i < strlen(argv[1]); i++)
{
if(!isalpha(argv[1][i]))
{
printf("Key must contain only alphabetical characters:\n");
return 1;
}
}
char alphabet[2][26];
for (int i = 0; i < strlen(argv[1]); i++)
{
alphabet[0][i] = 'A' + i;
alphabet[1][i] = argv[1][i];
}
// CHeck for repeated alphabetic characters
for (int i = 0; i < strlen(argv[1]); i++)
{
int j = 0;
for (int k = 0; k < strlen(argv[1]); k++)
{
if (toupper(alphabet[1][k]) == toupper(alphabet[1][i]))
{
j++;
if (j == 2)
{
printf("Character is repeated, please check key\n");
return 1;
}
}
}
}
// Prompt user for input
string plaintext = get_string("Plaintext: ");
printf("ciphertext: ");
//Incipher the inout from the user.
for (int i = 0, j = strlen(plaintext); i < j; i++)
{
if (isalpha(plaintext[i]))
{
if (islower(plaintext[i]))
{
for (int k = 0; k < strlen(argv[1]); k++)
{
if (tolower(alphabet[0][k]) == plaintext[i])
{
printf("%c", tolower(alphabet[1][k]));
}
}
}
if (isupper(plaintext[i]))
{
for (int k = 0; k < strlen(argv[1]); k++)
{
if (toupper(alphabet[0][k]) == plaintext[i])
{
printf("%c", toupper(alphabet[1][k]));
}
}
}
}
else
{
// Print the ciphered text
printf("%c", plaintext[i]);
}
}
printf("\n");
return 0;
}
|
C
|
/*Fig. 7.14: fig07_14.c
Attempting to modify a constant pointer to constant data. */
#include <stdio.h>
int main(int argc, char *argv[])
{
int x = 5;
int y;
/* ptr is a constant pointer to a constant integer. ptr always
pointer to the same location; the integer at that location
cannot be modified */
const int *const ptr = &x;
printf( "%d\n", *ptr );
// *ptr = 7; /* error: *ptr is const; cannot assign new value */
// ptr = &y; /* error: ptr is const; cannot assign new address */
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2017
** count_lines.c
** File description:
** algo bsq
*/
int count_lines(char *str)
{
int count = 0;
while (str[count] != '\n')
count++;
return (count);
}
|
C
|
#include<stdio.h>
#include<string.h>
void add(char a[],char b[])
{
int s[501];
int len1=strlen(a)-1;
int len2=strlen(b)-1;
int d=0;
int c=0;
int i;
int w;
while(len1>=0 || len2>=0)
{
w=0;
if(len1>=0) w+=a[len1]-'0';
if(len2>=0) w+=b[len2]-'0';
w+=c;
s[d]=w%10;
c=w/10;
d++;
len1--;
len2--;
}
while(c)
{
s[d++]=c%10;
c/=10;
}
for(i=d-1;i>=0;i--)
printf("%d",s[i]);
printf("\n");
}
void sub1(char a[],char b[])
{
int z[501]={0};
int len1,len2;
int x[501]={0},y[501]={0};
int i,j=0,k=0;
len1=strlen(a);
len2=strlen(b);
for(i=len1-1,j=0;i>=0;i--) x[j++]=a[i]-'0';
for(i=len2-1,k=0;i>=0;i--) y[k++]=b[i]-'0';
if(len1>len2) {for(i=0;i<len1;i++)
{
if(x[i]>=y[i]) z[i]=x[i]-y[i];
else
{
z[i]=x[i]+10-y[i];
x[i+1]=x[i+1]-1;
}
}
for(i=len1-1;i>0;i--)
{
if(z[i]==0) len1--;
else break;
}
for(i=len1-1;i>=0;i--) printf("%d",z[i]);
printf("\n"); }
else if(len1<len2)
{
printf("-");
for(i=0;i<len2;i++)
{
if(y[i]>=x[i]) z[i]=y[i]-x[i];
else
{
z[i]=y[i]+10-x[i];
y[i+1]=y[i+1]-1;
}
}
for(i=len2-1;i>0;i--)
{
if(z[i]==0) len2--;
else break;
}
for(i=len2-1;i>=0;i--) printf("%d",z[i]);
printf("\n");
}
else
{
for(i=len1-1;i>=0;i--)
{
if(x[i]==y[i]) continue;
if(x[i]>y[i])
{
for(i=0;i<len1;i++)
{
if(x[i]>=y[i]) z[i]=x[i]-y[i];
else
{
z[i]=x[i]+10-y[i];
x[i+1]=x[i+1]-1;
}
}
for(i=len1-1;i>0;i--)
{
if(z[i]==0) len1--;
else break;
}
for(i=len1-1;i>=0;i--) printf("%d",z[i]);
printf("\n");
break;
}
if(x[i]<y[i])
{
printf("-");
for(i=0;i<len1;i++)
{
if(y[i]>=x[i]) z[i]=y[i]-x[i];
else
{
z[i]=y[i]+10-x[i];
y[i+1]=y[i+1]-1;
}
}
for(i=len1-1;i>0;i--)
{
if(z[i]==0) len1--;
else break;
}
for(i=len1-1;i>=0;i--) printf("%d",z[i]);
printf("\n");
break;
}
}
}
}
int main()
{
int n;
int count;
int i,j;
int LEN;
char a[501];
char num1[501];
char num2[501];
scanf("%d%*c",&n);
while(n--)
{
count = 1;
scanf("%s",a);
LEN = strlen(a);
for(i=0;i<LEN;i++)
{
if(a[i]=='+')
{
num1[i] = '\0';
break;
}
if(a[i]=='-')
{
num1[i] = '\0';
count = 0;
break;
}
num1[i] = a[i];
}
for(i=strlen(num1)+1,j=0;i<LEN;i++,j++) num2[j] = a[i];
num2[j] = '\0';
if(count) add(num1,num2);
else sub1(num1,num2);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "util/task_helper.h"
void oneback(char *text)
{
int l=strlen(text);
text[l] = '\n';
text[l + 1] ='\0';
}
void uppercase(char *textuppercase)
{
int lungime=strlen(textuppercase),i=1;
if(textuppercase[0]>='a' && textuppercase[0]<='z')
textuppercase[0]=textuppercase[0]-32;
while( i < lungime )
{
if(textuppercase[i-1]!='\n' && textuppercase[i]>='A' && textuppercase[i]<='Z')
textuppercase[i]=textuppercase[i]+32;
else if(textuppercase[i-1]=='\n' && textuppercase[i]>='a' && textuppercase[i]<='z')
textuppercase[i]=textuppercase[i]-32;
i++;
}
return;
}
void trimming(char *texttrimming)
{
int extra=0;
for(int i=0 ; i< strlen(texttrimming) ; i++)
{
if(texttrimming[i]==' ' && texttrimming[i+1]==' ')
{
memmove(texttrimming+i,texttrimming+(i+1),strlen(texttrimming)-(i+1)+1);
i--;
extra++;
}
else if(strchr(".,;!?:",texttrimming[i]) != 0)
{
memmove(texttrimming+i,texttrimming+(i+1),strlen(texttrimming)-(i+1)+1);
i--;
extra++;
}
}
for (int i = 0; i < extra; ++i)
{
--texttrimming;
}
return;
}
void silly(char *prob , char *textsilly)
{
int lungime = strlen(textsilly) ;
float probabil=atof((char *)prob);
for(int i=0;i<lungime;i++)
{
if( (textsilly[i] >= 'a' && textsilly[i] <= 'z' ) || textsilly[i] >= 'A' && textsilly[i] <= 'Z')
{
float randomnr = rand() %100 / 99.0;
if( randomnr < probabil )
{
if( textsilly[i] >= 'a' && textsilly[i] <= 'z')
textsilly[i]=textsilly[i]-32;
else if( textsilly[i] >= 'A' && textsilly[i] <= 'Z' )
textsilly[i]=textsilly[i]+32;
}
}
}
return;
}
int equal_letter(char a, char b)
{
if('a' <= a && a <= 'z')
a -= 32;
if('a' <= b && b <= 'z')
b -= 32;
if(a == b)
return 1;
else
return 0;
}
void make_rhyme(char *s1, char *s2, char *ret1, char *ret2)
{
int len1, len2;
len1 = strlen(s1);
len2 = strlen(s2);
strcpy(ret1,s1);
strcpy(ret2,s2);
if(equal_letter(s1[len1 - 1], s2[len2 - 1]))
return;
int n;
char **lista_sinonime;
int gasit = 0;
get_synonym(s1, &n, &lista_sinonime);
for(int i = 0; i < n; ++i)
{
int len = strlen(lista_sinonime[i]);
if(equal_letter( lista_sinonime[i][len - 1], s2[len2 - 1]))
{
if(gasit == 0)
strcpy(ret1,lista_sinonime[i]);
else if(strcmp(lista_sinonime[i], ret1) < 0)
strcpy(ret1, lista_sinonime[i]);
gasit = 1;
}
}
if(gasit == 1)
return;
get_synonym(s2, &n, &lista_sinonime);
for(int i = 0; i < n; ++i)
{
int len = strlen(lista_sinonime[i]);
if(equal_letter( lista_sinonime[i][len - 1], s1[len1 - 1]))
{
if(gasit == 0)
strcpy(ret2,lista_sinonime[i]);
else if(strcmp(lista_sinonime[i], ret2) < 0)
strcpy(ret2, lista_sinonime[i]);
gasit = 1;
}
}
}
void rhimy(char *textrhimy , char *tiprima)
{
char separatori[] = "; ,.!?\n\0";
char clona[10001];
strcpy(clona, textrhimy);
char catren[4][10001];
char new_catren[4][10001];
char *last_pos = textrhimy;
char *start;
char aux_txt[10001];
int curr_pos = 0;
char* p = strtok(clona, "\n");
while(p != NULL)
{
if(curr_pos < 4)
{
strcpy(catren[curr_pos], p);
++curr_pos;
p = strtok(NULL, "\n");
}
else
{
curr_pos = 0;
for(int i = 0; i < 4; ++i)//retinem ultimul cuvant din vers
{
start = catren[i] + strlen(catren[i]);
--start;
while(strchr(separatori, *start)){
*start = '\0';
--start;
}
while(!strchr(separatori, *start))
--start;
++start;// acesrt lucru il fac pentru a putea sa ajung exact pe prima litera
strcpy(catren[i], start);
}
if(strcmp(tiprima, "imperecheata") == 0)
{
make_rhyme(catren[0], catren[1], new_catren[0], new_catren[1]);
make_rhyme(catren[2], catren[3], new_catren[2], new_catren[3]);
}
else if(strcmp(tiprima, "incrucisata") == 0)
{
make_rhyme(catren[0], catren[2], new_catren[0], new_catren[2]);
make_rhyme(catren[1], catren[3], new_catren[1], new_catren[3]);
}
else if(strcmp(tiprima, "imbratisata") == 0)
{
make_rhyme(catren[0], catren[3], new_catren[0], new_catren[3]);
make_rhyme(catren[1], catren[2], new_catren[1], new_catren[2]);
}
for(int i = 0; i < 4; ++i)
{
if(strcmp(catren[i], new_catren[i]) == 0)
continue;
start = strstr(last_pos, catren[i]);
strcpy(aux_txt, start + strlen(catren[i]));
strcpy(start, new_catren[i]);
last_pos = textrhimy + strlen(textrhimy);
strcat(textrhimy, aux_txt);
}
}
}
for(int i = 0; i < 4; ++i)
{
start = catren[i] + strlen(catren[i]);
--start;
while(strchr(separatori, *start))
{
*start = '\0';
--start;
}
while(!strchr(separatori, *start))
--start;
++start;
strcpy(catren[i], start);
}
if(strcmp(tiprima, "imperecheata") == 0)
{
make_rhyme(catren[0], catren[1], new_catren[0], new_catren[1]);
make_rhyme(catren[2], catren[3], new_catren[2], new_catren[3]);
}
else if(strcmp(tiprima, "incrucisata") == 0)
{
make_rhyme(catren[0], catren[2], new_catren[0], new_catren[2]);
make_rhyme(catren[1], catren[3], new_catren[1], new_catren[3]);
}
else if(strcmp(tiprima, "imbratisata") == 0)
{
make_rhyme(catren[0], catren[3], new_catren[0], new_catren[3]);
make_rhyme(catren[1], catren[2], new_catren[1], new_catren[2]);
}
for(int i = 0; i < 4; ++i)
{
if(strcmp(catren[i], new_catren[i]) == 0)
continue;
start = strstr(last_pos, catren[i]);
strcpy(aux_txt, start + strlen(catren[i]));
strcpy(start, new_catren[i]);
last_pos = textrhimy + strlen(textrhimy);
strcat(textrhimy, aux_txt);
}
if(textrhimy[strlen(textrhimy)-1] != '\n')
strcat(textrhimy,"\n");
}
void friendly(char *textfriendly)
{
char separatori[] = "; ,.!?\n\0";
char *friendlyword[100001],*pozitie;
char clona[100001],auxfriendlytxt[100001];
const char *decupaj;
strcat(clona,textfriendly);
decupaj = strtok(clona, separatori );
char *last_pos = textfriendly;
while( decupaj != NULL )
{
get_friendly_word(decupaj,friendlyword);
if( *friendlyword != NULL )
{
while(1)
{
pozitie=strstr(last_pos,decupaj);//pozitie pe care mi-a gasit cuvantul care are un diminutiv
if(strchr(separatori,*(pozitie-1)) != 0 && strchr( separatori , *(pozitie+strlen(decupaj)) ) !=0 )
{
strcpy(auxfriendlytxt,pozitie+strlen(decupaj));//copiaza in auxfriendly sirul de dupa cuvantul ce trebuie inlocuit
strcpy(pozitie, *friendlyword);
last_pos = textfriendly + strlen(textfriendly);// se modifica pozitia pentru a nu lua de la capat textul
strcat(textfriendly, auxfriendlytxt);
break;
}
else
{
last_pos= pozitie + strlen(decupaj);
}
}
}
decupaj = strtok(NULL, separatori );
}
return;
}
void print(char *textprintare)
{
printf("%s\n",textprintare);
return;
}
int main(void)
{
int contorback=0;
srand(42);
while(1)
{
char argument1[100],argument2[100];
char stocare[10001];
scanf("%s",argument1);
if(strcmp(argument1,"load") == 0 || strcmp(argument1,"make_it_silly") == 0 || strcmp(argument1,"make_it_rhyme") == 0)
scanf("%s",argument2);
if(strcmp(argument1,"load") == 0)
{
const char *file=argument2;
load_file(file,stocare);
}
else if(strcmp(argument1,"uppercase") == 0)
{
uppercase(stocare);
if( contorback == 0)
{
oneback(stocare);
contorback++;
}
}
else if(strcmp(argument1,"trimming") == 0)
{
trimming(stocare);
if( contorback == 0)
{
oneback(stocare);
contorback++;
}
}
else if(strcmp(argument1,"make_it_silly") == 0)
{
silly(argument2,stocare);
if( contorback == 0)
{
oneback(stocare);
contorback++;
}
}
else if(strcmp(argument1,"make_it_friendlier") == 0)
{
friendly(stocare);
if( contorback == 0)
{
oneback(stocare);
contorback++;
}
}
else if(strcmp(argument1,"make_it_rhyme") == 0)
{
rhimy(stocare,argument2);
contorback++;
}
else if(strcmp(argument1,"print") == 0)
{
if( contorback == 0)
{
oneback(stocare);
contorback++;
}
print(stocare);
}
else if(strcmp(argument1,"quit") == 0)
{
break;
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
#include <assert.h>
float fkgrade(char str[]){
int sentences=0, i;
char last = ' ';
for (i=0; str[i] != '\0'; i++){
if(str[i] == '.' || str[i] == '?' || str[i] == '!'){
sentences++;
last = ' ';
} else {
last = str[i];
}
}
int words=0;
for (i=0;str[i] != '\0';i++){
if(str[i]==' ' && str[i+1] != ' '){
words++;
}else if(str[i] == '-' && str[i+1] == '-'){
words --;
}
}
words = words + 1;
int syllables=0;
for (i=0;str[i] != '\0';i++){
if((str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' || str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U') && (str[i+1] != 'a' || str[i+1] != 'e' || str[i+1] != 'i' || str[i+1] != 'o' || str[i+1] != 'u' || str[i+1] != 'A' || str[i+1] != 'E' || str[i+1] != 'I' || str[i+1] != 'O' || str[i+1] != 'U')){
syllables++;
}else if (str[i] == ' '){
continue;
}
}
float grade = (0.39*(words/sentences))+(11.8*(syllables/words))-15.59;
return grade;
}
int main() {
char plato[] = "He who is the real tyrant, whatever men may think, is the real slave, and is obliged to practise the greatest adulation and servility, and to be the flatterer of the vilest of mankind. He has desires which he is utterly unable to satisfy, and has more wants than any one, and is truly poor, if you know how to inspect the whole soul of him: all his life long he is beset with fear and is full of convulsions and distractions, even as the State which he resembles: and surely the resemblance holds?";
char aurelius[] = "Nothing pertains to human beings except what defines us as human. No other things can be demanded of us. They aren't proper to human nature, nor is it incomplete without them. It follows that they are not our goal, or what helps us reach it -- the good. If any of them were proper to us, it would be improper to disdain or resist it. If the things themselves were good, it could hardly be good to give them up. But in reality, the more we deny ourselves such things (and things like them) -- or are deprived of them involuntarily, even -- the better we become.";
char descartes[] = "I suppose, accordingly, that all the things which I see are false (fictitious); I believe that none of those objects which my fallacious memory represents ever existed; I suppose that I possess no senses; I believe that body, figure, extension, motion, and place are merely fictions of my mind. What is there, then, that can be esteemed true? Perhaps this only, that there is absolutely nothing certain.";
printf("Plato...\nexpected sentences = 2\n expected words = 94\n expected syllables = 135\n");
float out = fkgrade(plato);
printf("> Reading Level = %f\n", out);
printf("Marcus Aurelius...\n expected sentences = 7\n expected words = 104\n expected syllables = 151\n");
out = fkgrade(aurelius);
printf("> Reading Level = %f\n", out);
printf("Rene Descartes...\n expected sentences = 3\n expected words = 67\n expected syllables = 111\n");
out = fkgrade(descartes);
printf("> Reading Level = %f\n", out);
}
|
C
|
// Projeto : JNA Example #19
// Algoritmo: example19.c
// Função : : Get a union from C
// Autor(es) : Hugo Dionizio Santos (adaptações e correções), Ethan Shayne in http://www.eshayne.com/jnaex
// Data : Sáb Mai 16 16:27:45 BRT 2015
// Seção de Variáveis Globais
// Interface do algoritmo
// Função Principal
// Seção de Variáveis Locais
// Seção de Comandos
// Seção de Funções
typedef union Example19Union {
int intnumber;
float floatnumber;
char* stringval;
} Example19Union;
enum Example19UnionType{
EX19_UNKNOWN = 0,
EX19_INTEGER = 1,
EX19_FLOAT = 2,
EX19_STRING = 3
};
typedef struct Example19UnionHolder {
enum Example19UnionType uniontype;
Example19Union unionval;
} Example19UnionHolder;
Example19UnionHolder example19_getUnion()
{
Example19UnionHolder holder;
holder.uniontype = EX19_INTEGER;
holder.unionval.intnumber = 26;
return holder;
}
// Fim do algoritmo
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include "plannodes.h"
#include "testability.h"
/*
* example to pass arguments
* isCN, relname, selectivity, targetname, qual op, qual left, qual right, groupcolname
* e.g.
* 0, "tbl1", 50, "product_id", "=", "cust_id", "literal", "product_id"
*/
int main(int argc, char *argv[])
{
QualExpr qual;
List tlist;
RelInfo relInfo;
RelData *rel;
errno_t err = 0;
if (argc < 9)
{
printf("please enter arguments in the format"
" isCN, relname, selectivity, targetname,"
" qual op, qual left, qual right, groupcolname");
return -1;
}
rel = get_rel_data_byname(argv[2]);
if (rel == NULL)
{
printf("Relation not found\r\n");
return -1;
}
// Form the rel info to be passed to parse. Ideally this come from analyzer but here
// we are taking as application input.
relInfo.relId = rel->relId;
relInfo.totalTup = rel->rowCount;
relInfo.estimTup = atoi(argv[3])/100; // can be replace this with actual selectivity calculation.
relInfo.width = rel->width;
relInfo.npages = rel->npages;
relInfo.qual = &qual;
relInfo.tlist = &tlist;
err = strcpy_s(tlist.name, MAX_NAME_LENGTH, argv[4]);
if (err != 0)
{
printf("Failed at %s: %d\r\n",__FUNCTION__, __LINE__);
return -1;
}
qual.oper = argv[5][0];
err = strcpy_s(qual.larg, MAX_NAME_LENGTH, argv[6]);
if (err != 0)
{
printf("Failed at %s: %d\r\n",__FUNCTION__, __LINE__);
return -1;
}
err = strcpy_s(qual.rarg, MAX_VALUE_LENGTH, argv[7]);
if (err != 0)
{
printf("Failed at %s: %d\r\n",__FUNCTION__, __LINE__);
return -1;
}
err = strcpy_s(relInfo.groupCol, MAX_NAME_LENGTH, argv[8]);
if (err != 0)
{
printf("Failed at %s: %d\r\n",__FUNCTION__, __LINE__);
return -1;
}
mock_planner(&relInfo, atoi(argv[1]));
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
#include <string.h>
int main(int argc,char **argv)
{
int i,j,trial,number;
long x_len,count = 0;
char row[256];
char string[16];
char out_name[32];
FILE *fin,*fout;
//complex_t *in_data[8];
double in_data[256];
int chan_flag = 1;
if( argc < 2)
{
printf("Usage:readfile filename\n");
return -1;
}
fin = fopen(argv[1], "r");
strcpy(out_name,argv[1]);
strcat(out_name,".val");
fout = fopen(out_name,"w");
if (fin == NULL)
{
printf("Cannot find input data file\n");
return -2 ;
}
// fseek(fin,0,SEEK_SET);
/* for(i=0;i<8;i++)
{
in_data[i] = (complex_t *)malloc(x_len * sizeof( complex_t ));
memset (in_data[i],0.00, x_len * sizeof(complex_t));
} */
i = 0;
fgets(row,sizeof(row),fin); //skip the first four
fgets(row,sizeof(row),fin);
fgets(row,sizeof(row),fin);
fgets(row,sizeof(row),fin);
while (fgets(row,sizeof(row),fin)!=NULL)
{
if(chan_flag)
{
chan_flag = 0;
continue;
}
sscanf(row, "%d %s %d %lf",&trial,string,&number,&in_data[i]);
i = i + 1;
if ( i == 256 )
{
//write_to_file(in_data);
for(j = 0;j<255;j++)
{
fprintf(fout,"%lf,",in_data[j]);
}
fprintf(fout,"%lf\n",in_data[255]);
i = 0 ;
chan_flag = 1;
continue;
}
}
/*
for(i = 0;i<x_len; i++)
{
for(j = 0;j<8;j++)
{
printf("%lf\t",in_data[j][i].r);
}
printf("\n");
}
*/
fclose(fin);
fclose(fout);
return 0;
}
|
C
|
#include "window.h"
struct event
{
int counter;
char me[20];
};
ENetAddress address;
ENetHost *client;
ENetPeer *peer;
char message[1024];
char me[20]; //Player id
ENetEvent netevent;
ENetPacket *packet;
int neteventStatus;
SDL_Event event;
bool gameover = false;
bool FAILURE = false;
bool SUCCESS = true;
bool GOAL = false;
bool wall = false;
bool print_gameover = false;
bool play_the_game = true;
bool start_game = false;
///Thread
struct event input;
pthread_t Thread_id;
const int FRAME_PER_SECOND = 30; //30 gick bra
int Intervall;
///Time controll
int NextTick;
///NEW VARIABLES
int points_made = 0;
char wall_play[20];
//End of game
SDL_Rect rcendofgame;
SDL_Surface* endofgame = NULL;
void Send_Players_and_Ball_Info()
{
sprintf(message,"%d %d %d %d %d %d %d %d %d %d %d %d %d %d",
rcPlayer1.w, rcPlayer1.h, rcball.w, rcball.h, rcPlayer3.w, rcPlayer3.h,
rcwall_p1.w, rcwall_p1.h, rcwall_p2.w, rcwall_p2.h, rcwall_p3.w, rcwall_p3.h,
rcwall_p4.w, rcwall_p4.h);
packet = enet_packet_create(message, sizeof(message) +1, ENET_PACKET_FLAG_RELIABLE);
enet_peer_send(peer, 0, packet);
printf(">>>%s\n!!",message);
}
void FPS_Fn()
{
if(NextTick > SDL_GetTicks())
{
SDL_Delay(NextTick - SDL_GetTicks());
}
NextTick = SDL_GetTicks() + Intervall;
}
void FPS_Init()
{
NextTick = 0;
Intervall = 1*1000/FRAME_PER_SECOND;
return;
}
int disconnect_from_server()
{
printf("Disconnecting....\n");
enet_peer_disconnect (peer, 0);
/// Allow up to 3 seconds for the disconnect to succeed
/// and drop any packets received packets.
while (enet_host_service (client, & netevent, 3000) > 0)
{
switch (netevent.type)
{
case ENET_EVENT_TYPE_RECEIVE:
enet_packet_destroy (netevent.packet);
break;
case ENET_EVENT_TYPE_DISCONNECT:
puts ("Disconnection succeeded.....");
enet_deinitialize();
///Free resources and close SDL
//close();
return 0;
}
}
///We've arrived here, so the disconnect attempt didn't
///succeed yet. Force the connection down.
enet_peer_reset (peer);
///Free resources and close SDL
//close();
enet_deinitialize();
return 0;
}
bool connect_to_server()
{
//Initialize enet
if (enet_initialize() != 0) {
fprintf(stderr, "An error occured while initializing ENet.\n");
return EXIT_FAILURE;
}
atexit(enet_deinitialize);
///Create a host using enet_host_create
client = enet_host_create(NULL, 1, 2, 57600/8, 14400/8);
if (client == NULL) {
fprintf(stderr, "An error occured while trying to create an ENet server host\n");
exit(EXIT_FAILURE);
}
///Connect to a server with IP address 130.237.84.99 on port 4950//My ip 80.217.155.111
enet_address_set_host(&address, "130.237.84.99");
address.port = 5950;
///Connect and use service
peer = enet_host_connect(client, &address, 2, 0);
if (peer == NULL) {
fprintf(stderr, "No available peers for initializing an ENet connection");
exit(EXIT_FAILURE);
}
/// Try to connect to server within 5 seconds
if (enet_host_service (client, &netevent, 5000) > 0 &&
netevent.type == ENET_EVENT_TYPE_CONNECT)
{
printf("Connection to server succeeded.\n\n");
}
else
{
///Either the 5 seconds are up or a disconnect netevent was
///received. Reset the peer in the netevent the 5 seconds
///had run out without any significant netevent.
enet_peer_reset (peer);
fprintf (stderr, "Connection to server failed\nServer could be full\n.");
exit (EXIT_FAILURE);
}
if (enet_host_service (client, &netevent, 1000) > 0 &&
netevent.type == ENET_EVENT_TYPE_RECEIVE)
{
if(strcmp((char *)netevent.packet->data, "Server are full!") == 0)
{
printf("%s\n", (char*)netevent.packet->data);
disconnect_from_server();
return FAILURE;
}
else if(strcmp((char *)netevent.packet->data, "player4") == 0)
{
strcpy(me,(char *)netevent.packet->data);
//Skicka data om players and ball
Send_Players_and_Ball_Info();
return SUCCESS;
}
else
{
strcpy(me,(char *)netevent.packet->data);
return SUCCESS;
}
}
}
void *deal_with_input(void* input)
{
/* Cast the cookie pointer to the right type. */
struct event* p = (struct event*) input;
//fprintf(stderr, ">%s", p->me);
int n = 0;
//char ThreadStatus[] = "exit";
//Wall extra live
strcpy(wall_play, "");
FPS_Init();
while(!gameover)
{
///Look for events
while( SDL_PollEvent( &event ) )
{
///An event was found
switch (event.type)
{
///Close button clicked
case SDL_QUIT:
gameover = true;
pthread_exit((void*)42);
break;
///Handle the keybord
case SDL_KEYDOWN:
switch (event.key.keysym.sym)
{
case SDLK_ESCAPE:
case SDLK_q:
gameover = true; //Return to main menu and disconnect from the server
break;
case SDLK_f:
if(Mix_PlayChannel(-1,fuck,0 )== -1)
{
fprintf(stderr, "Unable to play WAV file: %s\n", Mix_GetError());
}
break;
case SDLK_LEFT:
strcpy(message, p->me);
strcat(message, " left");
packet = enet_packet_create(message, sizeof(message) +1, ENET_PACKET_FLAG_RELIABLE);
enet_peer_send(peer, 0, packet);
strcpy(message, "");
break;
case SDLK_RIGHT:
strcpy(message, p->me);
strcat(message, " right");
packet = enet_packet_create(message, sizeof(message) +1, ENET_PACKET_FLAG_RELIABLE);
enet_peer_send(peer, 0, packet);
strcpy(message, "");
break;
case SDLK_UP:
strcpy(message, p->me);
strcat(message, " up");
packet = enet_packet_create(message, sizeof(message) +1, ENET_PACKET_FLAG_RELIABLE);
enet_peer_send(peer, 0, packet);
strcpy(message, "");
break;
case SDLK_DOWN:
strcpy(message, p->me);
strcat(message, " down");
packet = enet_packet_create(message, sizeof(message) +1, ENET_PACKET_FLAG_RELIABLE);
enet_peer_send(peer, 0, packet);
strcpy(message, "");
break;
}
break;
}
}
if (GOAL) //Print Score on the screen
{
n = 20; //35 går bra
GOAL = false;
}
else
{
///Apply the image
Update_The_Surface(p->me);
if(n > 0)
{
SDL_BlitSurface(scoreMade, NULL, ScreenSurface, &rcscoreMade);
n--;
}
///Frames per second
FPS_Fn();
SDL_UpdateWindowSurface( Window );
}
}
pthread_exit ((void*) 0);
}
void decode_packet(char* packet)
{
char tmp[20];
int i;
if(strstr(packet, "player1"))
{ ///Jag vill att player försvinner
strcpy(tmp, &packet[8]);
rcPlayer1.x = atoi(tmp);
printf("Player1: %d\n\n", rcPlayer1.x);
}
else if(strstr(packet, "player2"))
{ ///Jag vill att player försvinner
strcpy(tmp, &packet[8]);
rcPlayer2.x = atoi(tmp);
printf("Player2: %d\n\n", rcPlayer2.x);
}
else if(strstr(packet, "player3"))
{ ///Jag vill att player försvinner
strcpy(tmp, &packet[8]);
rcPlayer3.y = atoi(tmp);
printf("Player3: %d\n\n", rcPlayer3.y);
}
else if(strstr(packet, "player4"))
{ ///Jag vill att player försvinner
strcpy(tmp, &packet[8]);
rcPlayer4.y = atoi(tmp);
printf("Player4: %d\n\n", rcPlayer4.y);
}
else if(strstr(packet, "ball.x"))
{ ///Jag vill att player försvinner
strcpy(tmp, &packet[7]);
rcball.x = atoi(tmp);
printf("Ball.x: %d\n\n", rcball.x);
}
else if(strstr(packet, "ball.y"))
{ ///Jag vill att player försvinner
strcpy(tmp, &packet[7]);
rcball.y = atoi(tmp);
printf("Ball.y: %d\n\n", rcball.y);
}
else if (strstr(packet, "points"))
{
sscanf (packet, "%s %d %d %d %d",
tmp, &points[1], &points[2], &points[3], &points[4]);
text1 = TTF_RenderText_Blended(font3, score[points[1]], colors[points[1]]);
text2 = TTF_RenderText_Blended(font3, score[points[2]], colors[points[2]]);
text3 = TTF_RenderText_Blended_Wrapped(font3, score[points[3]], colors[points[3]],30);
text4 = TTF_RenderText_Blended_Wrapped(font3, score[points[4]], colors[points[4]],30);
}
//When someone score a goal SCORE comes up on he screen
else if (strstr(packet, "score"))
{
//FUCK
/*if(Mix_PlayChannel(-1,fuck,0 )== -1)
{
fprintf(stderr, "Unable to play WAV file: %s\n", Mix_GetError());
}*/
GOAL = true;
}
//This is used to count how many points have been scored along the game
//Every five points scored all the players become invisible
else if (strstr(packet, "pmade"))
{
sscanf (packet, "%s %d", tmp, &points_made);
}
//The first player to reach 1 point get a extra live in form of a wall
else if(strstr(packet, "wall"))
{
if(strstr (packet, "play"))
{
strcpy(wall_play, packet);
wall = true;
}
else if (strstr(packet, "fin"))
{
wall = false;
strcpy(wall_play, "");
}
}
else if(strstr(packet, "gameover"))
{
gameover = true;
}
else if(strstr(packet, "collision"))
{
//Play sound
if(Mix_PlayChannel(-1,collision,0 )== -1)
{
fprintf(stderr, "Unable to play WAV file: %s\n", Mix_GetError());
}
}
else if (strstr(packet, "start_game"))
{
start_game = true;
}
}
int go_to_menu_and_connect_to_the_server()
{
gameover = false;
int controll=0;
//Load menu and connect to the server
controll = loadMenu(Window, ScreenSurface, font, effect);
if(controll < 0)
{
printf("Failed to load menu!\n");
return -1;
}
else if(controll==2)
{
return 2; //Close the window
}
///thread arguments and create thread
strcpy(input.me, me);
if (pthread_create(&Thread_id, NULL, &deal_with_input, &input) != 0)
{
perror("pthread_create() error");
exit(1);
}
else
{
printf("\nThread created successfully\n");
}
if(Mix_PlayChannel(-1,music_start,0 )== -1)
{
fprintf(stderr, "Unable to play WAV file: %s\n", Mix_GetError());
}
//FPS_Init();
while(!gameover)
{
// If we had some netevent that interested us
while(enet_host_service(client, &netevent, 0))
{
switch(netevent.type)
{
case ENET_EVENT_TYPE_RECEIVE:
printf("(Client) Message from server : %s\n", netevent.packet->data);
decode_packet((char *)netevent.packet->data);
enet_packet_destroy(netevent.packet);
break;
case ENET_EVENT_TYPE_DISCONNECT:
printf("(Client) %s Server disconnected.....\n\nGAME OVER!!!", (char* )netevent.peer->data);
gameover = true;
start_game = false;
/// Reset client's information
netevent.peer->data = NULL;
return -1;
break;
case ENET_EVENT_TYPE_NONE:
break;
}
//SDL_Delay(1000/60); //hämta 60 packet varje sekund
//Frames per second
//FPS_Fn();
///Apply the image
//Update_The_Surface();
}
}
return 0;
}
int main(int argc, char **argv)
{
///Start up SDL and create window
int controll = 0;
int JoinThread = 0;
if( !create_window())
{
printf( "Failed to initialize!\n" );
}
else
{
///Load media
if( !loadMedia() )
{
printf( "Failed to load media!\n" );
}
else
{
while(play_the_game)
{
controll = go_to_menu_and_connect_to_the_server();
if ( controll < 0)
{
play_the_game = false;
disconnect_from_server();
///Free resources and close SDL
close();
return EXIT_FAILURE;
}
else if (controll == 2) //User presed QUIT or EXIT and it was not connected to the server
{
play_the_game = false;
///Free resources and close SDL
if(close())
{
return EXIT_SUCCESS;
}
else
{
return EXIT_FAILURE;
}
}
if (pthread_join(Thread_id,(void **) &JoinThread) != 0)
{
perror("pthread_join() error");
exit(3);
}
else
{
printf("pthread_join() successfully\n\n");
}
if(JoinThread != 0) //The user presed QUIT during the game.
{
disconnect_from_server();
///Free resources and close SDL
if (close())
{
return EXIT_SUCCESS;
}
else
{
return EXIT_FAILURE;
}
}
else
{
printf(">>%d\n",JoinThread);
}
//Play sound game over
if(Mix_PlayChannel(-1,GM_over,0 )== -1)
{
fprintf(stderr, "Unable to play WAV file: %s\n", Mix_GetError());
}
game_over_and_restart_the_game();
disconnect_from_server();
}
}
}
///Free resources and close SDL
//close();
return EXIT_SUCCESS;
}
|
C
|
//1457 - Oráculo de Alexandria
#include <stdio.h>
#include <string.h>
int main(void)
{
int T;
scanf("%d", &T);
while (T--)
{
long long int N;
int tam;
char K[20];
int vetor[20];
scanf("%lld %s", &N, K);
tam = strlen(K);
int X = 1, cont = 0;
int num = N;
while (num >= 1)
{
num = N - (X * tam);
if (num >= 1)
{
vetor[cont] = num;
X++;
cont++;
}
}
while (cont--)
{
N *= vetor[cont];
}
printf("%lld\n", N);
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<pthread.h>
#include<semaphore.h>
#define BUFFER_SIZE 100
sem_t s;
typedef struct{
char type;
int amount;
char unit;
} item;
item buffer[BUFFER_SIZE];
int first = 0;
int last = 0;
item *consume() {
sem_wait(&s);
item *i = malloc(sizeof(item));
while(first == last) {
}
memcpy(i, &buffer[last],sizeof(item));
last = (last + 1) % BUFFER_SIZE;
sem_post(&s);
return i;
}
void produce(item *i) {
while((first + 1) % BUFFER_SIZE == last) {
}
sem_wait(&s);
memcpy(&buffer[first], i,sizeof(item));
first = (first + 1) % BUFFER_SIZE;
sem_post(&s);
}
void *threadProduce(){
item i1, i2, i3;
i1.type=1;
i1.amount=50;
i1.unit=0;
i2.type=0;
i2.amount=100;
i2.unit=1;
i3.type=1;
i3.amount=25;
i3.unit=0;
produce(&i1);
printf("Type: %d, Amount: %d, Unit: %d, 1st: %d, Last: %d \n", i1.type, i1.amount, i1.unit, first, last);
produce(&i2);
printf("Type: %d, Amount: %d, Unit: %d, 1st: %d, Last: %d \n", i2.type, i2.amount, i2.unit, first, last);
produce(&i3);
printf("Type: %d, Amount: %d, Unit: %d, 1st: %d, Last: %d \n", i3.type, i3.amount, i3.unit, first, last);
}
void *threadConsume(){
item *serveFood;
serveFood = consume();
printf("Consumed items:\nType: %d, Amount: %d, Unit: %d, First:%d, Last:%d",serveFood->type,serveFood->amount,serveFood->unit,first,last);
serveFood = consume();
printf("\nType: %d, Amount: %d, Unit: %d, First:%d, Last:%d \n",serveFood->type,serveFood->amount,serveFood->unit,first,last);
}
int main(){
sem_init(&s,0,1);
pthread_t tid1, tid2;
pthread_create(&tid1,NULL,threadProduce,NULL);
pthread_join(tid1,NULL);
pthread_create(&tid2,NULL,threadConsume,NULL);
pthread_join(tid2,NULL);
return 0;
}
|
C
|
#include "stdio.h"
#include "stdbool.h"
/********** PROTOTIPO DE FUNCIONES **********/
void ImPar();
void Perfecto();
int PerfectoAnid(int);
void Reverso();
int main(){
/********** DECLARACION DE VARIABLES **********/
int opc;
bool band;
band = false;
/********** ENTRADAS **********/
printf("1) Define si 10 numeros son pares o impares!\n" );
printf("2) Los primeros tres numeros perfectos, los conoces?\n" );
printf("3) El inverso de un numero, por ejemplo: 1234 -> 4321\n" );
printf("Su selecci%cn:\n", 162);
/********** PROCESOS **********/
do {
scanf("%d", &opc);
/********** SALIDAS **********/
switch (opc) {
case 1:
ImPar();
band = true;
break;
case 2:
Perfecto();
band = true;
break;
case 3:
Reverso();
band = true;
break;
default:
printf("ERROR: LA OPCION ES INCORRECTA\n");
break;
}
} while(band == false);
return 0;
}
/********** FUNCIONES **********/
void ImPar() {
int num;
for (int i = 0; i < 10; i++) {
printf("Ingresa un numero:\n");
scanf("%d", &num);
if (num % 2 == 0) {
printf("El numero \"%d\" es par.\n", num);
}else {
printf("El numero \"%d\" es impar.\n", num);
}
}
}
void Perfecto() {
int Num, Perf, i;
Perf = 0;
Num = 1;
i = 0;
printf("Los primeros 3 numeros perfecto son: \n");
do {
Num = Num + 1;
Perf = PerfectoAnid(Num);
if (Perf == Num) {
printf("%d, ", Num);
i++;
}
} while(i < 3);
}
int PerfectoAnid(int Num) {
int Sum, Cont;
Sum = 0;
Cont = 1;
do {
if (Num%Cont == 0) {
Sum = Sum + Cont;
}
Cont = Cont + 1;
} while(Cont < Num);
return Sum;
}
void Reverso() {
int Num, Num2, Alm;
Num = 0;
Num2 = 0;
Alm = 0;
printf("Ingrese un numero:\n");
scanf("%d", &Num);
while (Num != 0) {
Alm = Num % 10;
Num2 = (Num2 + Alm)*10;
Num = Num / 10;
}
Num2 = Num2 / 10;
printf("El reverso del numero es: %d \n", Num2);
}
|
C
|
#ifndef _RGB_COLOR_SENSOR_ARRAY_REGISTERS_H_
#define _RGB_COLOR_SENSOR_ARRAY_REGISTERS_H_
/*
* This 1 byte register is R/W
* Read:
* [0] - 1 if the RGB Color Sensor Array is in free-running
* mode and has exclusive control over the LEDS,
* 0 if free-running mode is disabled and the
* user is free to control the LEDS through the LEDS register
* [7:1] - Reserved
* Write:
* [0] - 1 to enter free-running mode, 0 to disable(default)
* [7:1] - Reserved(Write 0)
*/
#define RGB_COLOR_SENSOR_ARRAY_REGISTER_STATUS 0x10
/*
* This 10 byte register is R
* ^Data is only valid if free-running mode is enabled
* Read:
* Byte [0] - Sensor #0, Red Channel
* Byte [1] - Sensor #0, Green Channel
* Byte [2] - Sensor #0, Blue Channel
* Byte [3] - Sensor #1, Red Channel
* Byte [4] - Sensor #1, Green Channel
* Byte [5] - Sensor #1, Blue Channel
* Byte [6] - Sensor #2, Red Channel
* Byte [7] - Sensor #2, Green Channel
* Byte [8] - Sensor #2, Blue Channel
* Byte [9] - Defects
[0] - 1 if Sensor #0 is looking at a defect, 0 looking at surface
[1] - 1 if Sensor #1 is looking at a defect, 0 looking at surface
[2] - 1 if Sensor #2 is looking at a defect, 0 looking at surface
*/
#define RGB_COLOR_SENSOR_ARRAY_REGISTER_DATA 0x11
/*
* This 1 byte register is R/W
* ^Writes are only valid when free running mode is disabled
* Read:
* [1:0] - 0: led 0 is off, 1: led 0 is on, 2: led 0 500 ms blink, 3 led 0 undefined state
* [3:2] - 0: led 1 is off, 1: led 1 is on, 2: led 1 500 ms blink, 3 led 1 undefined state
* [5:4] - 0: led 2 is off, 1: led 2 is on, 2: led 2 500 ms blink, 3 led 2 undefined state
* [7:6] - Reserved
* Write:
[1:0] - 0: turn led 0 off, 1: turn led 0 on, 2: turn led 0 500 ms blink, 3: don't change
[3:2] - 0: turn led 1 off, 1: turn led 1 on, 2: turn led 1 500 ms blink, 3: don't change
[5:4] - 0: turn led 2 off, 1: turn led 2 on, 2: turn led 2 500 ms blink, 3: don't change
[7:6] - Reserved(Write 0)
*/
#define RGB_COLOR_SENSOR_ARRAY_REGISTER_LEDS 0x12
#endif
|
C
|
#include <stdlib.h>
#include <string.h>
#include "group.h"
#include "mark.h"
Group* group_create()
{
Group* g = malloc(sizeof (Group));
g->marks = list_create();
return g;
}
size_t size_group(Group* g)
{
return size_marks(g->marks) + (sizeof (short)) + strlen(g->name) + 1;
}
void serialize_group(Group* g, void* buffer)
{
size_t list_size = size_marks(g->marks);
serialize_marks(g->marks, buffer);
buffer += list_size;
size_t name_length = strlen(g->name) + 1;
*(short*) buffer = name_length;
buffer += sizeof (short);
strcpy(buffer, g->name);
}
void deserialize_group(Group* g, void* buffer)
{
deserialize_marks(g->marks, buffer);
buffer += size_marks(g->marks);
size_t name_length = *(short*) buffer;
buffer += sizeof (short);
g->name = malloc(name_length);
strncpy(g->name, buffer, name_length);
}
// TODO: list serialization is really duplicative. macro?
size_t size_groups(List* group_list)
{
size_t group_sizes = 0;
int group_count = list_length(group_list);
for (int i = 0; i < group_count; i++) group_sizes += size_group((Group*) list_nth(group_list, i));
return (sizeof (short)) + group_sizes;
}
void serialize_groups(List* group_list, void* buffer)
{
int group_count = list_length(group_list);
*(short*) buffer = group_count;
buffer += sizeof (short);
for (int i = 0; i < group_count; i++)
{
Group* g = (Group*) list_nth(group_list, i);
serialize_group(g, buffer);
buffer += size_group(g);
}
}
void deserialize_groups(List* group_list, void* buffer)
{
int group_count = *(short*) buffer;
buffer += sizeof (short);
for (int i = 0; i < group_count; i++)
{
Group* g = group_create();
deserialize_group(g, buffer);
list_add(group_list, g);
buffer += size_group(g);
}
}
void group_destruct(Group* g)
{
marks_destruct(g->marks);
if (g->name) free(g->name);
free(g);
}
void groups_destruct(List* group_list)
{
int group_count = list_length(group_list);
for (int i = 0; i < group_count; i++) group_destruct(list_nth(group_list, i));
list_destruct(group_list);
}
// not really the best place for this? otoh it does directly manipulate list internals.
void group_push_recent(Group* g, Mark* m)
{
short extant = 0;
if (g->marks->head)
{
int idx = 0;
ListItem* cur = g->marks->head;
while (cur)
{
if (((Mark*) cur->data) == m) extant = 1;
if (((Mark*) cur->data)->id == m->id) break;
cur = cur->next;
idx++;
}
if (cur || (idx > 6))
{
idx = (idx > 6) ? 6 : idx;
if (!extant) mark_destruct(list_nth(g->marks, idx));
list_remove(g->marks, idx); // list item is automatically freed.
}
}
Mark* n;
if (extant)
n = m;
else
{
n = malloc(sizeof (Mark));
n->id = m->id;
n->name = malloc(strlen(m->name) + 1);
strcpy(n->name, m->name);
}
ListItem* new = malloc(sizeof (ListItem));
new->next = g->marks->head;
new->data = n;
g->marks->head = new;
}
|
C
|
/* 05E04.c (p. 107) */
#include <stdio.h>
#include <string.h>
typedef enum { False = 0, True } bool;
bool strend(char s[], char t[]);
main() {
char s1[] = "This is the first test string.";
char t1[] = "test string.";
char s2[] = "Oogly boogly boo!";
char t2[] = "blah blah";
printf("First comparison: ");
if (strend(s1, t1))
printf("True");
else
printf("False");
printf("\nSecond comparison: ");
if (strend(s2, t2))
printf("True");
else
printf("False");
printf("\n\n");
system("pause");
return 0;
}
/**
* strend: Returns True if the string t occurs at the end of the string s, and False
* otherwise.
*/
bool strend(char s[], char t[]) {
int tLen = strlen(t);
int sLen = strlen(s);
int i;
if (tLen > sLen)
return False;
for (i = 0; i < tLen && s[sLen - tLen + i] == t[i]; i++);
if (s[sLen - tLen + i] == 0 && t[i] == 0)
return True;
return False;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
struct Tree;
struct TreeLog;
struct MemoEntry;
typedef unsigned long int symbol_t;
typedef struct ParserContext {
const unsigned char *inputs;
size_t length;
const unsigned char *pos;
struct Tree *left;
// AST
struct TreeLog *logs;
size_t log_size;
size_t unused_log;
// stack
struct Wstack *stacks;
size_t stack_size;
size_t unused_stack;
size_t fail_stack;
// SymbolTable
struct SymbolTableEntry* tables;
size_t tableSize;
size_t tableMax;
size_t stateValue;
size_t stateCount;
unsigned long int count;
// Memo
struct MemoEntry *memoArray;
size_t memoSize;
// APIs
void *thunk;
void* (*fnew)(symbol_t, const unsigned char *, size_t, size_t, void *);
void (*fsub)(void *, size_t, symbol_t, void *, void *);
void (*fgc)(void *, int, void*);
} ParserContext;
#ifdef CNEZ_NOGC
#define GCINC(c, v2)
#define GCDEC(c, v1)
#define GCSET(c, v1, v2)
#else
#define GCINC(c, v2) c->fgc(v2, 1, c->thunk)
#define GCDEC(c, v1) c->fgc(v1, -1, c->thunk)
#define GCSET(c, v1, v2) c->fgc(v2, 1, c->thunk); c->fgc(v1, -1, c->thunk)
#endif
/* TreeLog */
#define STACKSIZE 64
#define OpLink 0
#define OpTag 1
#define OpReplace 2
#define OpNew 3
typedef struct TreeLog {
int op;
void *value;
struct Tree *tree;
} TreeLog;
static const char* ops[5] = {"link", "tag", "value", "new"};
static size_t cnez_used = 0;
static void *_malloc(size_t t)
{
size_t *d = (size_t*)malloc(sizeof(size_t) + t);
cnez_used += t;
d[0] = t;
memset((void*)(d+1), 0, t);
return (void*)(d+1);
}
static void *_calloc(size_t items, size_t size)
{
return _malloc(items * size);
}
static void _free(void *p)
{
size_t *d = (size_t*)p;
cnez_used -= d[-1];
free(d-1);
}
// stack
typedef struct Wstack {
size_t value;
struct Tree *tree;
} Wstack;
static Wstack *unusedStack(ParserContext *c)
{
if (c->stack_size == c->unused_stack) {
Wstack *newstack = (Wstack *)_calloc(c->stack_size * 2, sizeof(struct Wstack));
memcpy(newstack, c->stacks, sizeof(struct Wstack) * c->stack_size);
_free(c->stacks);
c->stacks = newstack;
c->stack_size *= 2;
}
Wstack *s = c->stacks + c->unused_stack;
c->unused_stack++;
return s;
}
static
void push(ParserContext *c, size_t value)
{
Wstack *s = unusedStack(c);
s->value = value;
GCDEC(c, s->tree);
s->tree = NULL;
}
static
void pushW(ParserContext *c, size_t value, struct Tree *t)
{
Wstack *s = unusedStack(c);
s->value = value;
GCSET(c, s->tree, t);
s->tree = t;
}
static
Wstack *popW(ParserContext *c)
{
c->unused_stack--;
return c->stacks + c->unused_stack;
}
/* memoization */
#define NotFound 0
#define SuccFound 1
#define FailFound 2
typedef long long int uniquekey_t;
typedef struct MemoEntry {
uniquekey_t key;
long consumed;
struct Tree *memoTree;
int result;
int stateValue;
} MemoEntry;
/* Tree */
typedef struct Tree {
long refc;
symbol_t tag;
const unsigned char *text;
size_t len;
size_t size;
symbol_t *labels;
struct Tree **childs;
} Tree;
static size_t t_used = 0;
static size_t t_newcount = 0;
static size_t t_gccount = 0;
static void *tree_malloc(size_t t)
{
size_t *d = (size_t*)malloc(sizeof(size_t) + t);
t_used += t;
d[0] = t;
return (void*)(d+1);
}
static void *tree_calloc(size_t items, size_t size)
{
void *d = tree_malloc(items * size);
memset(d, 0, items * size);
return d;
}
static void tree_free(void *p)
{
size_t *d = (size_t*)p;
t_used -= d[-1];
free(d-1);
}
static
void *NEW(symbol_t tag, const unsigned char *text, size_t len, size_t n, void *thunk)
{
Tree *t = (Tree*)tree_malloc(sizeof(struct Tree));
t->refc = 0;
t->tag = tag;
t->text = text;
t->len = len;
t->size = n;
if(n > 0) {
t->labels = (symbol_t*)tree_calloc(n, sizeof(symbol_t));
t->childs = (struct Tree**)tree_calloc(n, sizeof(struct Tree*));
}
else {
t->labels = NULL;
t->childs = NULL;
}
t_newcount++;
return t;
}
static
void GC(void *parent, int c, void *thunk)
{
Tree *t = (Tree*)parent;
if(t == NULL) {
return;
}
#ifdef CNEZ_NOGC
if(t->size > 0) {
size_t i = 0;
for(i = 0; i < t->size; i++) {
GC(t->childs[i], -1, thunk);
}
tree_free(t->labels);
tree_free(t->childs);
}
tree_free(t);
#else
if(c == 1) {
t->refc ++;
return;
}
t->refc --;
if(t->refc == 0) {
if(t->size > 0) {
size_t i = 0;
for(i = 0; i < t->size; i++) {
GC(t->childs[i], -1, thunk);
}
tree_free(t->labels);
tree_free(t->childs);
}
tree_free(t);
t_gccount++;
}
#endif
}
static
void LINK(void *parent, size_t n, symbol_t label, void *child, void *thunk)
{
Tree *t = (Tree*)parent;
t->labels[n] = label;
t->childs[n] = (struct Tree*)child;
#ifndef CNEZ_NOGC
GC(child, 1, thunk);
#endif
}
void cnez_free(void *t)
{
GC(t, -1, NULL);
}
static size_t cnez_count(void *v, size_t c)
{
size_t i;
Tree *t = (Tree*)v;
if(t == NULL) {
return c+0;
}
c++;
for(i = 0; i < t->size; i++) {
c = cnez_count(t->childs[i], c);
}
return c;
}
static void cnez_dump_memory(const char *msg, void *t)
{
size_t alive = cnez_count(t, 0);
size_t used = (t_newcount - t_gccount);
fprintf(stdout, "%s: tree=%ld[bytes], new=%ld, gc=%ld, alive=%ld %s\n", msg, t_used, t_newcount, t_gccount, alive, alive == used ? "OK" : "LEAK");
}
static void ParserContext_initTreeFunc(ParserContext *c,
void *thunk,
void* (*fnew)(symbol_t, const unsigned char *, size_t, size_t, void *),
void (*fset)(void *, size_t, symbol_t, void *, void *),
void (*fgc)(void *, int, void*))
{
if(fnew != NULL && fset != NULL && fgc != NULL) {
c->fnew = fnew;
c->fsub = fset;
c->fgc = fgc;
}
else {
c->thunk = c;
c->fnew = NEW;
c->fsub = LINK;
c->fgc = GC;
}
c->thunk = thunk == NULL ? c : thunk;
}
static
void *nonew(symbol_t tag, const unsigned char *pos, size_t len, size_t n, void *thunk)
{
return NULL;
}
static
void nosub(void *parent, size_t n, symbol_t label, void *child, void *thunk)
{
}
static
void nogc(void *parent, int c, void *thunk)
{
}
static void ParserContext_initNoTreeFunc(ParserContext *c)
{
c->fnew = nonew;
c->fsub = nosub;
c->fgc = nogc;
c->thunk = c;
}
/* ParserContext */
static ParserContext *ParserContext_new(const unsigned char *text, size_t len)
{
ParserContext *c = (ParserContext*) _malloc(sizeof(ParserContext));
c->inputs = text;
c->length = len;
c->pos = text;
c->left = NULL;
// tree
c->log_size = 64;
c->logs = (struct TreeLog*) _calloc(c->log_size, sizeof(struct TreeLog));
c->unused_log = 0;
// stack
c->stack_size = 64;
c->stacks = (struct Wstack*) _calloc(c->stack_size, sizeof(struct Wstack));
c->unused_stack = 0;
c->fail_stack = 0;
// symbol table
c->tables = NULL;
c->tableSize = 0;
c->tableMax = 0;
c->stateValue = 0;
c->stateCount = 0;
c->count = 0;
// memo
c->memoArray = NULL;
c->memoSize = 0;
return c;
}
static int ParserContext_eof(ParserContext *c)
{
return !(c->pos < (c->inputs + c->length));
}
static const unsigned char ParserContext_read(ParserContext *c)
{
return *(c->pos++);
}
static const unsigned char ParserContext_prefetch(ParserContext *c)
{
return *(c->pos);
}
static void ParserContext_move(ParserContext *c, int shift)
{
c->pos += shift;
}
static void ParserContext_back(ParserContext *c, const unsigned char *ppos)
{
c->pos = ppos;
}
static int ParserContext_match(ParserContext *c, const unsigned char *text, size_t len) {
if (c->pos + len > c->inputs + c->length) {
return 0;
}
size_t i;
for (i = 0; i < len; i++) {
if (text[i] != c->pos[i]) {
return 0;
}
}
c->pos += len;
return 1;
}
static int ParserContext_eof2(ParserContext *c, size_t n) {
if (c->pos + n <= c->inputs + c->length) {
return 1;
}
return 0;
}
static int ParserContext_match2(ParserContext *c, const unsigned char c1, const unsigned char c2) {
if (c->pos[0] == c1 && c->pos[1] == c2) {
c->pos+=2;
return 1;
}
return 0;
}
static int ParserContext_match3(ParserContext *c, const unsigned char c1, const unsigned char c2, const unsigned char c3) {
if (c->pos[0] == c1 && c->pos[1] == c2 && c->pos[2] == c3) {
c->pos+=3;
return 1;
}
return 0;
}
static int ParserContext_match4(ParserContext *c, const unsigned char c1, const unsigned char c2, const unsigned char c3, const unsigned char c4) {
if (c->pos[0] == c1 && c->pos[1] == c2 && c->pos[2] == c3 && c->pos[3] == c4) {
c->pos+=4;
return 1;
}
return 0;
}
static int ParserContext_match5(ParserContext *c, const unsigned char c1, const unsigned char c2, const unsigned char c3, const unsigned char c4, const unsigned char c5) {
if (c->pos[0] == c1 && c->pos[1] == c2 && c->pos[2] == c3 && c->pos[3] == c4 && c->pos[4] == c5 ) {
c->pos+=5;
return 1;
}
return 0;
}
static int ParserContext_match6(ParserContext *c, const unsigned char c1, const unsigned char c2, const unsigned char c3, const unsigned char c4, const unsigned char c5, const unsigned char c6) {
if (c->pos[0] == c1 && c->pos[1] == c2 && c->pos[2] == c3 && c->pos[3] == c4 && c->pos[4] == c5 && c->pos[5] == c6 ) {
c->pos+=6;
return 1;
}
return 0;
}
static int ParserContext_match7(ParserContext *c, const unsigned char c1, const unsigned char c2, const unsigned char c3, const unsigned char c4, const unsigned char c5, const unsigned char c6, const unsigned char c7) {
if (c->pos[0] == c1 && c->pos[1] == c2 && c->pos[2] == c3 && c->pos[3] == c4 && c->pos[4] == c5 && c->pos[5] == c6 && c->pos[6] == c7) {
c->pos+=7;
return 1;
}
return 0;
}
static int ParserContext_match8(ParserContext *c, const unsigned char c1, const unsigned char c2, const unsigned char c3, const unsigned char c4, const unsigned char c5, const unsigned char c6, const unsigned char c7, const unsigned char c8) {
if (c->pos[0] == c1 && c->pos[1] == c2 && c->pos[2] == c3 && c->pos[3] == c4 && c->pos[4] == c5 && c->pos[5] == c6 && c->pos[6] == c7 && c->pos[7] == c8) {
c->pos+=8;
return 1;
}
return 0;
}
#ifdef CNEZ_SSE
#ifdef _MSC_VER
#include <intrin.h>
#else
#include <x86intrin.h>
#endif
#endif
static const unsigned char *_findchar(
const unsigned char *p, long size,
const unsigned char *range, long range_size) {
#ifdef CNEZ_SSE
const __m128i r = _mm_loadu_si128((const __m128i*)range);
__m128i v;
while (size > 0) {
v = _mm_loadu_si128((const __m128i*)p);
if (!_mm_cmpestra(r, range_size, v, size, 4)) {
if (_mm_cmpestrc(r, range_size, v, size, 4)) {
return p + _mm_cmpestri(r, range_size, v, size, 4);
}
break;
}
p += 16;
size -= 16;
}
#else
size_t i,j;
for (i = 0; i < size; i++) {
const unsigned char c = p[i];
for (j = 0; j < range_size ; j+=2) {
if (range[j] <= c && c <= range[j+1]) {
return p + i;
}
}
}
#endif
return p + size;
}
static void ParserContext_skipRange(ParserContext *c, const unsigned char *range, size_t range_size)
{
size_t size = c->length - (c->pos - c->inputs);
c->pos = _findchar(c->pos, size, range, range_size);
}
static int ParserContext_checkOneMoreRange(ParserContext *c, const unsigned char *range, size_t range_size)
{
size_t size = c->length - (c->pos - c->inputs);
const unsigned char *p = _findchar(c->pos, size, range, range_size);
if(p > c->pos) {
c->pos = p;
return 1;
}
return 0;
}
// AST
static
void _log(ParserContext *c, int op, void *value, struct Tree *tree)
{
if(!(c->unused_log < c->log_size)) {
TreeLog *newlogs = (TreeLog *)_calloc(c->log_size * 2, sizeof(TreeLog));
memcpy(newlogs, c->logs, c->log_size * sizeof(TreeLog));
_free(c->logs);
c->logs = newlogs;
c->log_size *= 2;
}
TreeLog *l = c->logs + c->unused_log;
l->op = op;
l->value = value;
assert(l->tree == NULL);
if(op == OpLink) {
GCSET(c, l->tree, tree);
}
l->tree = tree;
//printf("LOG[%d] %s %p %p\n", (int)c->unused_log, ops[op], value, tree);
c->unused_log++;
}
void cnez_dump(void *v, FILE *fp);
static
void DEBUG_dumplog(ParserContext *c)
{
long i;
for(i = c->unused_log-1; i >= 0; i--) {
TreeLog *l = c->logs + i;
printf("[%d] %s %p ", (int)i, ops[l->op], l->value);
if(l->tree != NULL) {
cnez_dump(l->tree, stdout);
}
printf("\n");
}
}
static void ParserContext_beginTree(ParserContext *c, int shift)
{
_log(c, OpNew, (void *)(c->pos + shift), NULL);
}
static void ParserContext_linkTree(ParserContext *c, symbol_t label)
{
_log(c, OpLink, (void*)label, c->left);
}
static void ParserContext_tagTree(ParserContext *c, symbol_t tag)
{
_log(c, OpTag, (void*)((long)tag), NULL);
}
static void ParserContext_valueTree(ParserContext *c, const unsigned char *text, size_t len)
{
_log(c, OpReplace, (void*)text, (Tree*)len);
}
static void ParserContext_foldTree(ParserContext *c, int shift, symbol_t label)
{
_log(c, OpNew, (void*)(c->pos + shift), NULL);
_log(c, OpLink, (void*)label, c->left);
}
static size_t ParserContext_saveLog(ParserContext *c)
{
return c->unused_log;
}
static void ParserContext_backLog(ParserContext *c, size_t unused_log)
{
if (unused_log < c->unused_log) {
size_t i;
for(i = unused_log; i < c->unused_log; i++) {
TreeLog *l = c->logs + i;
if(l->op == OpLink) {
GCDEC(c, l->tree);
}
l->op = 0;
l->value = NULL;
l->tree = NULL;
}
c->unused_log = unused_log;
}
}
static void ParserContext_endTree(ParserContext *c, int shift, symbol_t tag, const unsigned char *text, size_t len)
{
int objectSize = 0;
long i;
for(i = c->unused_log - 1; i >= 0; i--) {
TreeLog * l = c->logs + i;
if(l->op == OpLink) {
objectSize++;
continue;
}
if(l->op == OpNew) {
break;
}
if(l->op == OpTag && tag == 0) {
tag = (symbol_t)l->value;
}
if(l->op == OpReplace) {
if(text == NULL) {
text = (const unsigned char*)l->value;
len = (size_t)l->tree;
}
l->tree = NULL;
}
}
TreeLog * start = c->logs + i;
if(text == NULL) {
text = (const unsigned char*)start->value;
len = ((c->pos + shift) - text);
}
Tree *t = c->fnew(tag, text, len, objectSize, c->thunk);
GCSET(c, c->left, t);
c->left = t;
if (objectSize > 0) {
int n = 0;
size_t j;
for(j = i; j < c->unused_log; j++) {
TreeLog * cur = c->logs + j;
if (cur->op == OpLink) {
c->fsub(c->left, n++, (symbol_t)cur->value, cur->tree, c->thunk);
}
}
}
ParserContext_backLog(c, i);
}
static size_t ParserContext_saveTree(ParserContext *c)
{
size_t back = c->unused_stack;
pushW(c, 0, c->left);
return back;
}
static void ParserContext_backTree(ParserContext *c, size_t back)
{
Tree* t = c->stacks[back].tree;
if(c->left != t) {
GCSET(c, c->left, t);
c->left = t;
}
c->unused_stack = back;
}
// Symbol Table ---------------------------------------------------------
static const unsigned char NullSymbol[4] = { 0, 0, 0, 0 };
typedef struct SymbolTableEntry {
int stateValue;
symbol_t table;
const unsigned char* symbol;
size_t length;
} SymbolTableEntry;
static
void _push(ParserContext *c, symbol_t table, const unsigned char * utf8, size_t length)
{
if (!(c->tableSize < c->tableMax)) {
SymbolTableEntry* newtable = (SymbolTableEntry*)_calloc(sizeof(SymbolTableEntry), (c->tableMax + 256));
if(c->tables != NULL) {
memcpy(newtable, c->tables, sizeof(SymbolTableEntry) * (c->tableMax));
_free(c->tables);
}
c->tables = newtable;
c->tableMax += 256;
}
SymbolTableEntry *entry = c->tables + c->tableSize;
c->tableSize++;
if (entry->table == table && entry->length == length && memcmp(utf8, entry->symbol, length) == 0) {
// reuse state value
c->stateValue = entry->stateValue;
} else {
entry->table = table;
entry->symbol = utf8;
entry->length = length;
c->stateValue = c->stateCount++;
entry->stateValue = c->stateValue;
}
}
static int ParserContext_saveSymbolPoint(ParserContext *c)
{
return c->tableSize;
}
static
void ParserContext_backSymbolPoint(ParserContext *c, int savePoint)
{
if (c->tableSize != savePoint) {
c->tableSize = savePoint;
if (c->tableSize == 0) {
c->stateValue = 0;
} else {
c->stateValue = c->tables[savePoint - 1].stateValue;
}
}
}
static
void ParserContext_addSymbol(ParserContext *c, symbol_t table, const unsigned char *ppos) {
size_t length = c->pos - ppos;
_push(c, table, ppos, length);
}
static
void ParserContext_addSymbolMask(ParserContext *c, symbol_t table) {
_push(c, table, NullSymbol, 4);
}
static int ParserContext_exists(ParserContext *c, symbol_t table)
{
long i;
for (i = c->tableSize - 1; i >= 0; i--) {
SymbolTableEntry * entry = c->tables + i;
if (entry->table == table) {
return entry->symbol != NullSymbol;
}
}
return 0;
}
static int ParserContext_existsSymbol(ParserContext *c, symbol_t table, const unsigned char *symbol, size_t length)
{
long i;
for (i = c->tableSize - 1; i >= 0; i--) {
SymbolTableEntry * entry = c->tables + i;
if (entry->table == table) {
if (entry->symbol == NullSymbol) {
return 0; // masked
}
if (entry->length == length && memcmp(entry->symbol, symbol, length) == 0) {
return 1;
}
}
}
return 0;
}
static int ParserContext_matchSymbol(ParserContext *c, symbol_t table)
{
long i;
for (i = c->tableSize - 1; i >= 0; i--) {
SymbolTableEntry * entry = c->tables + i;
if (entry->table == table) {
if (entry->symbol == NullSymbol) {
return 0; // masked
}
return ParserContext_match(c, entry->symbol, entry->length);
}
}
return 0;
}
static int ParserContext_equals(ParserContext *c, symbol_t table, const unsigned char *ppos) {
long i;
size_t length = c->pos - ppos;
for (i = c->tableSize - 1; i >= 0; i--) {
SymbolTableEntry * entry = c->tables + i;
if (entry->table == table) {
if (entry->symbol == NullSymbol) {
return 0; // masked
}
return (entry->length == length && memcmp(entry->symbol, ppos, length) == 0);
}
}
return 0;
}
static int ParserContext_contains(ParserContext *c, symbol_t table, const unsigned char *ppos)
{
long i;
size_t length = c->pos - ppos;
for (i = c->tableSize - 1; i >= 0; i--) {
SymbolTableEntry * entry = c->tables + i;
if (entry->table == table) {
if (entry->symbol == NullSymbol) {
return 0; // masked
}
if (length == entry->length && memcmp(ppos, entry->symbol, length) == 0) {
return 1;
}
}
}
return 0;
}
// Counter -----------------------------------------------------------------
static void ParserContext_scanCount(ParserContext *c, const unsigned char *ppos, long mask, int shift)
{
long i;
size_t length = c->pos - ppos;
if (mask == 0) {
c->count = strtol((const char*)ppos, NULL, 10);
} else {
long n = 0;
const unsigned char *p = ppos;
while(p < c->pos) {
n <<= 8;
n |= (*p & 0xff);
p++;
}
c->count = (n & mask) >> shift;
}
}
static int ParserContext_decCount(ParserContext *c)
{
return (c->count--) > 0;
}
// Memotable ------------------------------------------------------------
static
void ParserContext_initMemo(ParserContext *c, int w, int n)
{
int i;
c->memoSize = w * n + 1;
c->memoArray = (MemoEntry *)_calloc(sizeof(MemoEntry), c->memoSize);
for (i = 0; i < c->memoSize; i++) {
c->memoArray[i].key = -1LL;
}
}
static uniquekey_t longkey( uniquekey_t pos, int memoPoint) {
return ((pos << 12) | memoPoint);
}
static
int ParserContext_memoLookup(ParserContext *c, int memoPoint)
{
uniquekey_t key = longkey((c->pos - c->inputs), memoPoint);
unsigned int hash = (unsigned int) (key % c->memoSize);
MemoEntry* m = c->memoArray + hash;
if (m->key == key) {
c->pos += m->consumed;
return m->result;
}
return NotFound;
}
static
int ParserContext_memoLookupTree(ParserContext *c, int memoPoint)
{
uniquekey_t key = longkey((c->pos - c->inputs), memoPoint);
unsigned int hash = (unsigned int) (key % c->memoSize);
MemoEntry* m = c->memoArray + hash;
if (m->key == key) {
c->pos += m->consumed;
GCSET(c, c->left, m->memoTree);
c->left = m->memoTree;
return m->result;
}
return NotFound;
}
static
void ParserContext_memoSucc(ParserContext *c, int memoPoint, const unsigned char* ppos)
{
uniquekey_t key = longkey((ppos - c->inputs), memoPoint);
unsigned int hash = (unsigned int) (key % c->memoSize);
MemoEntry* m = c->memoArray + hash;
m->key = key;
GCSET(c, m->memoTree, c->left);
m->memoTree = c->left;
m->consumed = c->pos - ppos;
m->result = SuccFound;
m->stateValue = -1;
}
static
void ParserContext_memoTreeSucc(ParserContext *c, int memoPoint, const unsigned char* ppos)
{
uniquekey_t key = longkey((ppos - c->inputs), memoPoint);
unsigned int hash = (unsigned int) (key % c->memoSize);
MemoEntry* m = c->memoArray + hash;
m->key = key;
GCSET(c, m->memoTree, c->left);
m->memoTree = c->left;
m->consumed = c->pos - ppos;
m->result = SuccFound;
m->stateValue = -1;
}
static
void ParserContext_memoFail(ParserContext *c, int memoPoint)
{
uniquekey_t key = longkey((c->pos - c->inputs), memoPoint);
unsigned int hash = (unsigned int) (key % c->memoSize);
MemoEntry* m = c->memoArray + hash;
m->key = key;
GCSET(c, m->memoTree, c->left);
m->memoTree = c->left;
m->consumed = 0;
m->result = FailFound;
m->stateValue = -1;
}
/* State Version */
// public final int lookupStateMemo(int memoPoint) {
// long key = longkey(pos, memoPoint, shift);
// int hash = (int) (key % memoArray.length);
// MemoEntry m = c->memoArray[hash];
// if (m.key == key) {
// c->pos += m.consumed;
// return m.result;
// }
// return NotFound;
// }
//
// public final int lookupStateTreeMemo(int memoPoint) {
// long key = longkey(pos, memoPoint, shift);
// int hash = (int) (key % memoArray.length);
// MemoEntry m = c->memoArray[hash];
// if (m.key == key && m.stateValue == c->stateValue) {
// c->pos += m.consumed;
// c->left = m.memoTree;
// return m.result;
// }
// return NotFound;
// }
//
// public void memoStateSucc(int memoPoint, int ppos) {
// long key = longkey(ppos, memoPoint, shift);
// int hash = (int) (key % memoArray.length);
// MemoEntry m = c->memoArray[hash];
// m.key = key;
// m.memoTree = left;
// m.consumed = pos - ppos;
// m.result = SuccFound;
// m.stateValue = c->stateValue;
// // c->CountStored += 1;
// }
//
// public void memoStateTreeSucc(int memoPoint, int ppos) {
// long key = longkey(ppos, memoPoint, shift);
// int hash = (int) (key % memoArray.length);
// MemoEntry m = c->memoArray[hash];
// m.key = key;
// m.memoTree = left;
// m.consumed = pos - ppos;
// m.result = SuccFound;
// m.stateValue = c->stateValue;
// // c->CountStored += 1;
// }
//
// public void memoStateFail(int memoPoint) {
// long key = longkey(pos, memoPoint, shift);
// int hash = (int) (key % memoArray.length);
// MemoEntry m = c->memoArray[hash];
// m.key = key;
// m.memoTree = left;
// m.consumed = 0;
// m.result = FailFound;
// m.stateValue = c->stateValue;
// }
static void ParserContext_free(ParserContext *c)
{
size_t i;
if(c->memoArray != NULL) {
for(i = 0; i < c->memoSize; i++) {
GCDEC(c, c->memoArray[i].memoTree);
c->memoArray[i].memoTree = NULL;
}
_free(c->memoArray);
c->memoArray = NULL;
}
if(c->tables != NULL) {
_free(c->tables);
c->tables = NULL;
}
ParserContext_backLog(c, 0);
_free(c->logs);
c->logs = NULL;
for(i = 0; i < c->stack_size; i++) {
GCDEC(c, c->stacks[i].tree);
c->stacks[i].tree = NULL;
}
_free(c->stacks);
c->stacks = NULL;
_free(c);
}
//----------------------------------------------------------------------------
static inline int ParserContext_bitis(ParserContext *c, int *bits, size_t n)
{
return (bits[n / 32] & (1 << (n % 32))) != 0;
}
long backtrack_length = 0;
long total_backtrack_length = 0;
long backtrack_count = 0;
static int _T = 0;
static int _L = 0;
static int _S = 0;
static const unsigned char _set0[256] = {0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
static const unsigned char _set1[256] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
static int _Lname = 1;
static int _TName = 1;
static int _Llist = 2;
static int _TParam = 2;
static int _TList = 3;
static int _Lbody = 3;
static int _TFunctionDecl = 4;
static int _Lexpr = 4;
static int _Lleft = 5;
static int _TInteger = 5;
static int _TTrue = 6;
static int _TFalse = 7;
static const unsigned char _set2[256] = {0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
static int _TString = 8;
static int _TNull = 9;
static int _TExpression = 10;
static int _TFunctionExpr = 11;
static int _Lrecv = 6;
static int _TApply = 12;
static int _TNot = 13;
static int _TAssign = 14;
static int _TAssignMul = 15;
static int _TAssignDiv = 16;
static int _TAssignMod = 17;
static int _TAssignAdd = 18;
static int _TAssignSub = 19;
static int _TAssignLeftShift = 20;
static int _TAssignRightShift = 21;
static int _TAssignLogicalRightShift = 22;
static int _TAssignBitwiseAnd = 23;
static int _TAssignBitwiseXOr = 24;
static int _TAssignBitwiseOr = 25;
static int _Lright = 7;
static int _TLessThan = 26;
static int _TLessThanEquals = 27;
static int _TGreaterThan = 28;
static int _TGreaterThanEquals = 29;
static int _TEquals = 30;
static int _TNotEquals = 31;
static int _TAnd = 32;
static int _TOr = 33;
static int _Lcond = 8;
static int _Lthen = 9;
static int _Lelse = 10;
static int _TConditional = 34;
static int _TVarDecl = 35;
static int _TVarList = 36;
static int _TDeclaration = 37;
static int _TBlock = 38;
static int _TIf = 39;
static int _TReturn = 40;
static int _TExpressionStatement = 41;
static int _TSource = 42;
static const char * _tags[43] = {"","Name","Param","List","FunctionDecl","Integer","True","False","String","Null","Expression","FunctionExpr","Apply","Not","Assign","AssignMul","AssignDiv","AssignMod","AssignAdd","AssignSub","AssignLeftShift","AssignRightShift","AssignLogicalRightShift","AssignBitwiseAnd","AssignBitwiseXOr","AssignBitwiseOr","LessThan","LessThanEquals","GreaterThan","GreaterThanEquals","Equals","NotEquals","And","Or","Conditional","VarDecl","VarList","Declaration","Block","If","Return","ExpressionStatement","Source"};
static const char * _labels[11] = {"","name","list","body","expr","left","recv","right","cond","then","else"};
static const char * _tables[1] = {""};
// Prototypes
int e73(ParserContext *c);
int p_046UnaryExpression(ParserContext *c);
int e9(ParserContext *c);
int p_046Expression(ParserContext *c);
int e43(ParserContext *c);
int p_046Block(ParserContext *c);
int p_046AssignmentExpression(ParserContext *c);
int p_046FunctionCall(ParserContext *c);
int p_046RelationalExpression(ParserContext *c);
int e29(ParserContext *c);
static inline int p_046S(ParserContext * c){
if (!_set0[ParserContext_read(c)]){
return 0;
}
return 1;
}
static inline int e3(ParserContext * c){
if (ParserContext_read(c) != 42){
return 0;
}
if (ParserContext_read(c) != 47){
return 0;
}
return 1;
}
static inline int e2(ParserContext * c){
{
const unsigned char * pos = c->pos;
if (e3(c)){
return 0;
}
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
}
if (ParserContext_read(c) == 0){
return 0;
}
return 1;
}
static inline int p_046BLOCKCOMMENT(ParserContext * c){
if (ParserContext_read(c) != 47){
return 0;
}
if (ParserContext_read(c) != 42){
return 0;
}
while (1){
const unsigned char * pos = c->pos;
if (!e2(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
break;
}
}
if (ParserContext_read(c) != 42){
return 0;
}
if (ParserContext_read(c) != 47){
return 0;
}
return 1;
}
static inline int e4(ParserContext * c){
if (ParserContext_prefetch(c) == 10){
return 0;
}
if (ParserContext_read(c) == 0){
return 0;
}
return 1;
}
static inline int p_046LINECOMMENT(ParserContext * c){
if (ParserContext_read(c) != 47){
return 0;
}
if (ParserContext_read(c) != 47){
return 0;
}
while (1){
const unsigned char * pos = c->pos;
if (!e4(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
break;
}
}
return 1;
}
static inline int e1(ParserContext * c){
int temp = 1;
if (temp){
const unsigned char * pos = c->pos;
if (p_046S(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
}
}
if (temp){
const unsigned char * pos2 = c->pos;
if (p_046BLOCKCOMMENT(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos2;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos2;
}
}
if (temp){
const unsigned char * pos3 = c->pos;
if (p_046LINECOMMENT(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos3;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos3;
}
}
if (temp){
return 0;
}
return 1;
}
static inline int p_046_(ParserContext * c){
while (1){
const unsigned char * pos = c->pos;
if (!e1(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
break;
}
}
return 1;
}
static inline int p_04634336134(ParserContext * c){
if (ParserContext_read(c) != 33){
return 0;
}
if (ParserContext_read(c) != 61){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int e75(ParserContext * c){
if (!p_04634336134(c)){
return 0;
}
ParserContext_tagTree(c,_TNotEquals);
return 1;
}
static inline int p_04634616134(ParserContext * c){
if (ParserContext_read(c) != 61){
return 0;
}
if (ParserContext_read(c) != 61){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int e74(ParserContext * c){
if (!p_04634616134(c)){
return 0;
}
ParserContext_tagTree(c,_TEquals);
return 1;
}
static inline int p_046343334(ParserContext * c){
if (ParserContext_read(c) != 33){
return 0;
}
if (ParserContext_prefetch(c) == 61){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int e50(ParserContext * c){
ParserContext_beginTree(c,0);
if (!p_046343334(c)){
return 0;
}
{
size_t left = ParserContext_saveTree(c);
if (!p_046UnaryExpression(c)){
return 0;
}
ParserContext_linkTree(c,_Lexpr);
ParserContext_backTree(c,left);
}
ParserContext_tagTree(c,_TNot);
ParserContext_endTree(c,0,_T,NULL, 0);
return 1;
}
static inline int p_046344434(ParserContext * c){
if (ParserContext_read(c) != 44){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int p_0463412412434(ParserContext * c){
if (ParserContext_read(c) != 124){
return 0;
}
if (ParserContext_read(c) != 124){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int p_04634383834(ParserContext * c){
if (ParserContext_read(c) != 38){
return 0;
}
if (ParserContext_read(c) != 38){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int p_04634626134(ParserContext * c){
if (ParserContext_read(c) != 62){
return 0;
}
if (ParserContext_read(c) != 61){
return 0;
}
if (ParserContext_prefetch(c) == 61){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int e72(ParserContext * c){
if (!p_04634626134(c)){
return 0;
}
ParserContext_tagTree(c,_TGreaterThanEquals);
return 1;
}
static inline int p_046346034(ParserContext * c){
if (ParserContext_read(c) != 60){
return 0;
}
if (ParserContext_prefetch(c) == 61){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int e69(ParserContext * c){
if (!p_046346034(c)){
return 0;
}
ParserContext_tagTree(c,_TLessThan);
return 1;
}
static inline int p_046346234(ParserContext * c){
if (ParserContext_read(c) != 62){
return 0;
}
if (ParserContext_prefetch(c) == 61){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int e71(ParserContext * c){
if (!p_046346234(c)){
return 0;
}
ParserContext_tagTree(c,_TGreaterThan);
return 1;
}
static inline int p_04634606134(ParserContext * c){
if (ParserContext_read(c) != 60){
return 0;
}
if (ParserContext_read(c) != 61){
return 0;
}
if (ParserContext_prefetch(c) == 61){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int e70(ParserContext * c){
if (!p_04634606134(c)){
return 0;
}
ParserContext_tagTree(c,_TLessThanEquals);
return 1;
}
static inline int e68(ParserContext * c){
ParserContext_foldTree(c,0,_Lleft);
{
int temp = 1;
if (temp){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e69(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
}
}
if (temp){
const unsigned char * pos4 = c->pos;
size_t left5 = ParserContext_saveTree(c);
size_t log6 = ParserContext_saveLog(c);
if (e70(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos4;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos4;
ParserContext_backTree(c,left5);
ParserContext_backLog(c,log6);
}
}
if (temp){
const unsigned char * pos7 = c->pos;
size_t left8 = ParserContext_saveTree(c);
size_t log9 = ParserContext_saveLog(c);
if (e71(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos7;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos7;
ParserContext_backTree(c,left8);
ParserContext_backLog(c,log9);
}
}
if (temp){
const unsigned char * pos10 = c->pos;
size_t left11 = ParserContext_saveTree(c);
size_t log12 = ParserContext_saveLog(c);
if (e72(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos10;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos10;
ParserContext_backTree(c,left11);
ParserContext_backLog(c,log12);
}
}
if (temp){
return 0;
}
}
{
size_t left13 = ParserContext_saveTree(c);
if (!p_046UnaryExpression(c)){
return 0;
}
ParserContext_linkTree(c,_Lright);
ParserContext_backTree(c,left13);
}
ParserContext_endTree(c,0,_T,NULL, 0);
return 1;
}
static inline int e66(ParserContext * c){
if (!p_046RelationalExpression(c)){
return 0;
}
while (1){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (!e73(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
break;
}
}
return 1;
}
static inline int p_046EqualityExpression(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,27);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e66(c)){
ParserContext_memoTreeSucc(c,27,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,27);
return 0;
}
}
return memo == 1;
}
static inline int e76(ParserContext * c){
ParserContext_foldTree(c,0,_Lleft);
if (!p_04634383834(c)){
return 0;
}
{
size_t left = ParserContext_saveTree(c);
if (!p_046EqualityExpression(c)){
return 0;
}
ParserContext_linkTree(c,_Lright);
ParserContext_backTree(c,left);
}
ParserContext_tagTree(c,_TAnd);
ParserContext_endTree(c,0,_T,NULL, 0);
return 1;
}
static inline int e65(ParserContext * c){
if (!p_046EqualityExpression(c)){
return 0;
}
while (1){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (!e76(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
break;
}
}
return 1;
}
static inline int p_046LogicalAndExpression(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,26);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e65(c)){
ParserContext_memoTreeSucc(c,26,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,26);
return 0;
}
}
return memo == 1;
}
static inline int e77(ParserContext * c){
ParserContext_foldTree(c,0,_Lleft);
if (!p_0463412412434(c)){
return 0;
}
{
size_t left = ParserContext_saveTree(c);
if (!p_046LogicalAndExpression(c)){
return 0;
}
ParserContext_linkTree(c,_Lright);
ParserContext_backTree(c,left);
}
ParserContext_tagTree(c,_TOr);
ParserContext_endTree(c,0,_T,NULL, 0);
return 1;
}
static inline int e64(ParserContext * c){
if (!p_046LogicalAndExpression(c)){
return 0;
}
while (1){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (!e77(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
break;
}
}
return 1;
}
static inline int p_046LogicalOrExpression(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,25);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e64(c)){
ParserContext_memoTreeSucc(c,25,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,25);
return 0;
}
}
return memo == 1;
}
static inline int p_046345834(ParserContext * c){
if (ParserContext_read(c) != 58){
return 0;
}
if (ParserContext_prefetch(c) == 62){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int p_046346334(ParserContext * c){
if (ParserContext_read(c) != 63){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int e78(ParserContext * c){
ParserContext_foldTree(c,0,_Lcond);
if (!p_046346334(c)){
return 0;
}
{
size_t left = ParserContext_saveTree(c);
if (!p_046Expression(c)){
return 0;
}
ParserContext_linkTree(c,_Lthen);
ParserContext_backTree(c,left);
}
if (!p_046345834(c)){
return 0;
}
{
size_t left1 = ParserContext_saveTree(c);
if (!p_046LogicalOrExpression(c)){
return 0;
}
ParserContext_linkTree(c,_Lelse);
ParserContext_backTree(c,left1);
}
ParserContext_tagTree(c,_TConditional);
ParserContext_endTree(c,0,_T,NULL, 0);
return 1;
}
static inline int e63(ParserContext * c){
if (!p_046LogicalOrExpression(c)){
return 0;
}
while (1){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (!e78(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
break;
}
}
return 1;
}
static inline int p_046ConditionalExpression(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,24);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e63(c)){
ParserContext_memoTreeSucc(c,24,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,24);
return 0;
}
}
return memo == 1;
}
static inline int p_046346134(ParserContext * c){
if (ParserContext_read(c) != 61){
return 0;
}
if (ParserContext_prefetch(c) == 61){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int e51(ParserContext * c){
if (!p_046346134(c)){
return 0;
}
ParserContext_tagTree(c,_TAssign);
return 1;
}
static inline int p_046341246134(ParserContext * c){
if (ParserContext_read(c) != 124){
return 0;
}
if (ParserContext_read(c) != 61){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int e62(ParserContext * c){
if (!p_046341246134(c)){
return 0;
}
ParserContext_tagTree(c,_TAssignBitwiseOr);
return 1;
}
static inline int p_04634946134(ParserContext * c){
if (ParserContext_read(c) != 94){
return 0;
}
if (ParserContext_read(c) != 61){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int e61(ParserContext * c){
if (!p_04634946134(c)){
return 0;
}
ParserContext_tagTree(c,_TAssignBitwiseXOr);
return 1;
}
static inline int p_04634476134(ParserContext * c){
if (ParserContext_read(c) != 47){
return 0;
}
if (ParserContext_read(c) != 61){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int e53(ParserContext * c){
if (!p_04634476134(c)){
return 0;
}
ParserContext_tagTree(c,_TAssignDiv);
return 1;
}
static inline int p_04634426134(ParserContext * c){
if (ParserContext_read(c) != 42){
return 0;
}
if (ParserContext_read(c) != 61){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int e52(ParserContext * c){
if (!p_04634426134(c)){
return 0;
}
ParserContext_tagTree(c,_TAssignMul);
return 1;
}
static inline int p_04634436134(ParserContext * c){
if (ParserContext_read(c) != 43){
return 0;
}
if (ParserContext_read(c) != 61){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int e55(ParserContext * c){
if (!p_04634436134(c)){
return 0;
}
ParserContext_tagTree(c,_TAssignAdd);
return 1;
}
static inline int p_04634376134(ParserContext * c){
if (ParserContext_read(c) != 37){
return 0;
}
if (ParserContext_read(c) != 61){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int e54(ParserContext * c){
if (!p_04634376134(c)){
return 0;
}
ParserContext_tagTree(c,_TAssignMod);
return 1;
}
static inline int p_0463460606134(ParserContext * c){
if (ParserContext_read(c) != 60){
return 0;
}
if (ParserContext_read(c) != 60){
return 0;
}
if (ParserContext_read(c) != 61){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int e57(ParserContext * c){
if (!p_0463460606134(c)){
return 0;
}
ParserContext_tagTree(c,_TAssignLeftShift);
return 1;
}
static inline int p_04634456134(ParserContext * c){
if (ParserContext_read(c) != 45){
return 0;
}
if (ParserContext_read(c) != 61){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int e56(ParserContext * c){
if (!p_04634456134(c)){
return 0;
}
ParserContext_tagTree(c,_TAssignSub);
return 1;
}
static inline int p_046346262626134(ParserContext * c){
if (ParserContext_read(c) != 62){
return 0;
}
if (ParserContext_read(c) != 62){
return 0;
}
if (ParserContext_read(c) != 62){
return 0;
}
if (ParserContext_read(c) != 61){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int e59(ParserContext * c){
if (!p_046346262626134(c)){
return 0;
}
ParserContext_tagTree(c,_TAssignLogicalRightShift);
return 1;
}
static inline int p_0463462626134(ParserContext * c){
if (ParserContext_read(c) != 62){
return 0;
}
if (ParserContext_read(c) != 62){
return 0;
}
if (ParserContext_read(c) != 61){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int e58(ParserContext * c){
if (!p_0463462626134(c)){
return 0;
}
ParserContext_tagTree(c,_TAssignRightShift);
return 1;
}
static inline int p_04634386134(ParserContext * c){
if (ParserContext_read(c) != 38){
return 0;
}
if (ParserContext_read(c) != 61){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int e60(ParserContext * c){
if (!p_04634386134(c)){
return 0;
}
ParserContext_tagTree(c,_TAssignBitwiseAnd);
return 1;
}
static inline int p_046_AssignmentOperator(ParserContext * c){
int temp = 1;
if (temp){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e51(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
}
}
if (temp){
const unsigned char * pos4 = c->pos;
size_t left5 = ParserContext_saveTree(c);
size_t log6 = ParserContext_saveLog(c);
if (e52(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos4;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos4;
ParserContext_backTree(c,left5);
ParserContext_backLog(c,log6);
}
}
if (temp){
const unsigned char * pos7 = c->pos;
size_t left8 = ParserContext_saveTree(c);
size_t log9 = ParserContext_saveLog(c);
if (e53(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos7;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos7;
ParserContext_backTree(c,left8);
ParserContext_backLog(c,log9);
}
}
if (temp){
const unsigned char * pos10 = c->pos;
size_t left11 = ParserContext_saveTree(c);
size_t log12 = ParserContext_saveLog(c);
if (e54(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos10;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos10;
ParserContext_backTree(c,left11);
ParserContext_backLog(c,log12);
}
}
if (temp){
const unsigned char * pos13 = c->pos;
size_t left14 = ParserContext_saveTree(c);
size_t log15 = ParserContext_saveLog(c);
if (e55(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos13;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos13;
ParserContext_backTree(c,left14);
ParserContext_backLog(c,log15);
}
}
if (temp){
const unsigned char * pos16 = c->pos;
size_t left17 = ParserContext_saveTree(c);
size_t log18 = ParserContext_saveLog(c);
if (e56(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos16;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos16;
ParserContext_backTree(c,left17);
ParserContext_backLog(c,log18);
}
}
if (temp){
const unsigned char * pos19 = c->pos;
size_t left20 = ParserContext_saveTree(c);
size_t log21 = ParserContext_saveLog(c);
if (e57(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos19;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos19;
ParserContext_backTree(c,left20);
ParserContext_backLog(c,log21);
}
}
if (temp){
const unsigned char * pos22 = c->pos;
size_t left23 = ParserContext_saveTree(c);
size_t log24 = ParserContext_saveLog(c);
if (e58(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos22;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos22;
ParserContext_backTree(c,left23);
ParserContext_backLog(c,log24);
}
}
if (temp){
const unsigned char * pos25 = c->pos;
size_t left26 = ParserContext_saveTree(c);
size_t log27 = ParserContext_saveLog(c);
if (e59(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos25;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos25;
ParserContext_backTree(c,left26);
ParserContext_backLog(c,log27);
}
}
if (temp){
const unsigned char * pos28 = c->pos;
size_t left29 = ParserContext_saveTree(c);
size_t log30 = ParserContext_saveLog(c);
if (e60(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos28;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos28;
ParserContext_backTree(c,left29);
ParserContext_backLog(c,log30);
}
}
if (temp){
const unsigned char * pos31 = c->pos;
size_t left32 = ParserContext_saveTree(c);
size_t log33 = ParserContext_saveLog(c);
if (e61(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos31;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos31;
ParserContext_backTree(c,left32);
ParserContext_backLog(c,log33);
}
}
if (temp){
const unsigned char * pos34 = c->pos;
size_t left35 = ParserContext_saveTree(c);
size_t log36 = ParserContext_saveLog(c);
if (e62(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos34;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos34;
ParserContext_backTree(c,left35);
ParserContext_backLog(c,log36);
}
}
if (temp){
return 0;
}
return 1;
}
static inline int e49(ParserContext * c){
if (!p_046344434(c)){
return 0;
}
{
size_t left = ParserContext_saveTree(c);
if (!p_046AssignmentExpression(c)){
return 0;
}
ParserContext_linkTree(c,_L);
ParserContext_backTree(c,left);
}
return 1;
}
static inline int p_046_ArgumentExpressionList(ParserContext * c){
{
size_t left = ParserContext_saveTree(c);
if (!p_046AssignmentExpression(c)){
return 0;
}
ParserContext_linkTree(c,_L);
ParserContext_backTree(c,left);
}
while (1){
const unsigned char * pos = c->pos;
size_t left2 = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (!e49(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left2);
ParserContext_backLog(c,log);
break;
}
}
return 1;
}
static inline int p_046344034(ParserContext * c){
if (ParserContext_read(c) != 40){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int p_046344134(ParserContext * c){
if (ParserContext_read(c) != 41){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int p_046_FunctionCall(ParserContext * c){
{
size_t left = ParserContext_saveTree(c);
ParserContext_beginTree(c,0);
if (!p_046344034(c)){
return 0;
}
const unsigned char * pos = c->pos;
size_t left2 = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (!p_046_ArgumentExpressionList(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left2);
ParserContext_backLog(c,log);
}
if (!p_046344134(c)){
return 0;
}
ParserContext_tagTree(c,_TList);
ParserContext_endTree(c,0,_T,NULL, 0);
ParserContext_linkTree(c,_L);
ParserContext_backTree(c,left);
}
ParserContext_tagTree(c,_TApply);
return 1;
}
static inline int e48(ParserContext * c){
ParserContext_foldTree(c,0,_Lrecv);
if (!p_046_FunctionCall(c)){
return 0;
}
ParserContext_endTree(c,0,_T,NULL, 0);
return 1;
}
static inline int p_046STRING_CONTENT(ParserContext * c){
if (_set2[ParserContext_prefetch(c)]){
return 0;
}
if (ParserContext_read(c) == 0){
return 0;
}
return 1;
}
static inline int e41(ParserContext * c){
if (ParserContext_read(c) != 34){
return 0;
}
ParserContext_beginTree(c,0);
while (1){
const unsigned char * pos = c->pos;
if (!p_046STRING_CONTENT(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
break;
}
}
ParserContext_tagTree(c,_TString);
ParserContext_endTree(c,0,_T,NULL, 0);
if (ParserContext_read(c) != 34){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int p_046StringLiteral(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,20);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e41(c)){
ParserContext_memoTreeSucc(c,20,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,20);
return 0;
}
}
return memo == 1;
}
static inline int p_046DIGIT(ParserContext * c){
if (!(48 <= ParserContext_prefetch(c) && ParserContext_read(c) < 58)){
return 0;
}
return 1;
}
static inline int p_046W(ParserContext * c){
if (!_set1[ParserContext_read(c)]){
return 0;
}
return 1;
}
static inline int e15(ParserContext * c){
if (ParserContext_read(c) != 101){
return 0;
}
if (ParserContext_read(c) != 108){
return 0;
}
if (ParserContext_read(c) != 115){
return 0;
}
if (ParserContext_read(c) != 101){
return 0;
}
return 1;
}
static inline int e17(ParserContext * c){
if (ParserContext_read(c) != 114){
return 0;
}
if (ParserContext_read(c) != 101){
return 0;
}
if (ParserContext_read(c) != 116){
return 0;
}
if (ParserContext_read(c) != 117){
return 0;
}
if (ParserContext_read(c) != 114){
return 0;
}
if (ParserContext_read(c) != 110){
return 0;
}
return 1;
}
static inline int e16(ParserContext * c){
if (ParserContext_read(c) != 105){
return 0;
}
if (ParserContext_read(c) != 102){
return 0;
}
return 1;
}
static inline int e19(ParserContext * c){
if (ParserContext_read(c) != 118){
return 0;
}
if (ParserContext_read(c) != 97){
return 0;
}
if (ParserContext_read(c) != 114){
return 0;
}
return 1;
}
static inline int e18(ParserContext * c){
if (ParserContext_read(c) != 102){
return 0;
}
if (ParserContext_read(c) != 117){
return 0;
}
if (ParserContext_read(c) != 110){
return 0;
}
if (ParserContext_read(c) != 99){
return 0;
}
if (ParserContext_read(c) != 116){
return 0;
}
if (ParserContext_read(c) != 105){
return 0;
}
if (ParserContext_read(c) != 111){
return 0;
}
if (ParserContext_read(c) != 110){
return 0;
}
return 1;
}
static inline int p_046KEYWORD(ParserContext * c){
{
int temp = 1;
if (temp){
const unsigned char * pos = c->pos;
if (e15(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
}
}
if (temp){
const unsigned char * pos2 = c->pos;
if (e16(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos2;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos2;
}
}
if (temp){
const unsigned char * pos3 = c->pos;
if (e17(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos3;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos3;
}
}
if (temp){
const unsigned char * pos4 = c->pos;
if (e18(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos4;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos4;
}
}
if (temp){
const unsigned char * pos5 = c->pos;
if (e19(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos5;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos5;
}
}
if (temp){
return 0;
}
}
{
const unsigned char * pos6 = c->pos;
if (p_046W(c)){
return 0;
}
backtrack_count = backtrack_count + 1;
long length = c->pos-pos6;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos6;
}
return 1;
}
static inline int p_046NAME(ParserContext * c){
{
const unsigned char * pos = c->pos;
if (p_046DIGIT(c)){
return 0;
}
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
}
{
const unsigned char * pos1 = c->pos;
if (p_046KEYWORD(c)){
return 0;
}
backtrack_count = backtrack_count + 1;
long length = c->pos-pos1;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos1;
}
if (!p_046W(c)){
return 0;
}
while (1){
const unsigned char * pos2 = c->pos;
if (!p_046W(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos2;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos2;
break;
}
}
return 1;
}
static inline int e14(ParserContext * c){
ParserContext_beginTree(c,0);
if (!p_046NAME(c)){
return 0;
}
ParserContext_tagTree(c,_TName);
ParserContext_endTree(c,0,_T,NULL, 0);
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int p_046Identifier(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,5);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e14(c)){
ParserContext_memoTreeSucc(c,5,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,5);
return 0;
}
}
return memo == 1;
}
static inline int e22(ParserContext * c){
ParserContext_beginTree(c,0);
{
size_t left = ParserContext_saveTree(c);
if (!p_046Identifier(c)){
return 0;
}
ParserContext_linkTree(c,_Lname);
ParserContext_backTree(c,left);
}
ParserContext_tagTree(c,_TParam);
ParserContext_endTree(c,0,_T,NULL, 0);
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int p_046FunctionParam(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,7);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e22(c)){
ParserContext_memoTreeSucc(c,7,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,7);
return 0;
}
}
return memo == 1;
}
static inline int e23(ParserContext * c){
if (!p_046344434(c)){
return 0;
}
{
size_t left = ParserContext_saveTree(c);
if (!p_046FunctionParam(c)){
return 0;
}
ParserContext_linkTree(c,_L);
ParserContext_backTree(c,left);
}
return 1;
}
static inline int e21(ParserContext * c){
{
size_t left = ParserContext_saveTree(c);
if (!p_046FunctionParam(c)){
return 0;
}
ParserContext_linkTree(c,_L);
ParserContext_backTree(c,left);
}
while (1){
const unsigned char * pos = c->pos;
size_t left2 = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (!e23(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left2);
ParserContext_backLog(c,log);
break;
}
}
return 1;
}
static inline int e20(ParserContext * c){
ParserContext_beginTree(c,0);
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (!e21(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
}
ParserContext_tagTree(c,_TList);
ParserContext_endTree(c,0,_T,NULL, 0);
return 1;
}
static inline int p_046FunctionParamList(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,6);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e20(c)){
ParserContext_memoTreeSucc(c,6,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,6);
return 0;
}
}
return memo == 1;
}
static inline int p_04634585834(ParserContext * c){
if (ParserContext_read(c) != 58){
return 0;
}
if (ParserContext_read(c) != 58){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int p_046Initializer(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,11);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (p_046AssignmentExpression(c)){
ParserContext_memoTreeSucc(c,11,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,11);
return 0;
}
}
return memo == 1;
}
static inline int e27(ParserContext * c){
if (!p_046346134(c)){
return 0;
}
{
size_t left = ParserContext_saveTree(c);
if (!p_046Initializer(c)){
return 0;
}
ParserContext_linkTree(c,_Lexpr);
ParserContext_backTree(c,left);
}
return 1;
}
static inline int e26(ParserContext * c){
ParserContext_beginTree(c,0);
{
size_t left = ParserContext_saveTree(c);
if (!p_046Identifier(c)){
return 0;
}
ParserContext_linkTree(c,_Lname);
ParserContext_backTree(c,left);
}
const unsigned char * pos = c->pos;
size_t left2 = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (!e27(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left2);
ParserContext_backLog(c,log);
}
ParserContext_tagTree(c,_TVarDecl);
ParserContext_endTree(c,0,_T,NULL, 0);
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int p_046InitDecl(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,10);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e26(c)){
ParserContext_memoTreeSucc(c,10,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,10);
return 0;
}
}
return memo == 1;
}
static inline int e79(ParserContext * c){
if (!p_046344434(c)){
return 0;
}
{
size_t left = ParserContext_saveTree(c);
if (!p_046InitDecl(c)){
return 0;
}
ParserContext_linkTree(c,_L);
ParserContext_backTree(c,left);
}
return 1;
}
static inline int p_046345934(ParserContext * c){
if (ParserContext_read(c) != 59){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int e25(ParserContext * c){
ParserContext_beginTree(c,0);
{
size_t left = ParserContext_saveTree(c);
if (!p_046InitDecl(c)){
return 0;
}
ParserContext_linkTree(c,_L);
ParserContext_backTree(c,left);
}
while (1){
const unsigned char * pos = c->pos;
size_t left2 = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (!e79(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left2);
ParserContext_backLog(c,log);
break;
}
}
ParserContext_tagTree(c,_TVarList);
ParserContext_endTree(c,0,_T,NULL, 0);
return 1;
}
static inline int p_046VariableList(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,9);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e25(c)){
ParserContext_memoTreeSucc(c,9,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,9);
return 0;
}
}
return memo == 1;
}
static inline int p_04634var34(ParserContext * c){
if (ParserContext_read(c) != 118){
return 0;
}
if (ParserContext_read(c) != 97){
return 0;
}
if (ParserContext_read(c) != 114){
return 0;
}
{
const unsigned char * pos = c->pos;
if (p_046W(c)){
return 0;
}
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
}
return 1;
}
static inline int e24(ParserContext * c){
ParserContext_beginTree(c,0);
if (!p_04634var34(c)){
return 0;
}
if (!p_046_(c)){
return 0;
}
{
size_t left = ParserContext_saveTree(c);
if (!p_046VariableList(c)){
return 0;
}
ParserContext_linkTree(c,_Llist);
ParserContext_backTree(c,left);
}
if (!p_046345934(c)){
return 0;
}
ParserContext_tagTree(c,_TDeclaration);
ParserContext_endTree(c,0,_T,NULL, 0);
return 1;
}
static inline int p_046VariableDeclaration(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,8);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e24(c)){
ParserContext_memoTreeSucc(c,8,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,8);
return 0;
}
}
return memo == 1;
}
static inline int p_04634function34(ParserContext * c){
if (ParserContext_read(c) != 102){
return 0;
}
if (ParserContext_read(c) != 117){
return 0;
}
if (ParserContext_read(c) != 110){
return 0;
}
if (ParserContext_read(c) != 99){
return 0;
}
if (ParserContext_read(c) != 116){
return 0;
}
if (ParserContext_read(c) != 105){
return 0;
}
if (ParserContext_read(c) != 111){
return 0;
}
if (ParserContext_read(c) != 110){
return 0;
}
{
const unsigned char * pos = c->pos;
if (p_046W(c)){
return 0;
}
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
}
return 1;
}
static inline int e13(ParserContext * c){
ParserContext_beginTree(c,0);
if (!p_04634function34(c)){
return 0;
}
if (!p_046_(c)){
return 0;
}
{
size_t left = ParserContext_saveTree(c);
if (!p_046Identifier(c)){
return 0;
}
ParserContext_linkTree(c,_Lname);
ParserContext_backTree(c,left);
}
if (!p_046_(c)){
return 0;
}
if (!p_046344034(c)){
return 0;
}
{
size_t left1 = ParserContext_saveTree(c);
if (!p_046FunctionParamList(c)){
return 0;
}
ParserContext_linkTree(c,_Llist);
ParserContext_backTree(c,left1);
}
if (!p_046344134(c)){
return 0;
}
{
size_t left2 = ParserContext_saveTree(c);
if (!p_046Block(c)){
return 0;
}
ParserContext_linkTree(c,_Lbody);
ParserContext_backTree(c,left2);
}
ParserContext_tagTree(c,_TFunctionDecl);
ParserContext_endTree(c,0,_T,NULL, 0);
return 1;
}
static inline int p_046FunctionDeclaration(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,4);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e13(c)){
ParserContext_memoTreeSucc(c,4,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,4);
return 0;
}
}
return memo == 1;
}
static inline int e12(ParserContext * c){
int temp = 1;
if (temp){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (p_046FunctionDeclaration(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
}
}
if (temp){
const unsigned char * pos4 = c->pos;
size_t left5 = ParserContext_saveTree(c);
size_t log6 = ParserContext_saveLog(c);
if (p_046VariableDeclaration(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos4;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos4;
ParserContext_backTree(c,left5);
ParserContext_backLog(c,log6);
}
}
if (temp){
return 0;
}
return 1;
}
static inline int p_046Declaration(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,3);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e12(c)){
ParserContext_memoTreeSucc(c,3,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,3);
return 0;
}
}
return memo == 1;
}
static inline int e11(ParserContext * c){
{
size_t left = ParserContext_saveTree(c);
if (!p_046Declaration(c)){
return 0;
}
ParserContext_linkTree(c,_L);
ParserContext_backTree(c,left);
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int e84(ParserContext * c){
ParserContext_beginTree(c,0);
{
size_t left = ParserContext_saveTree(c);
if (!p_046Expression(c)){
return 0;
}
ParserContext_linkTree(c,_Lexpr);
ParserContext_backTree(c,left);
}
if (!p_046345934(c)){
return 0;
}
ParserContext_tagTree(c,_TExpressionStatement);
ParserContext_endTree(c,0,_T,NULL, 0);
return 1;
}
static inline int p_0463412534(ParserContext * c){
if (ParserContext_read(c) != 125){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int p_0463412334(ParserContext * c){
if (ParserContext_read(c) != 123){
return 0;
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int p_04634if34(ParserContext * c){
if (ParserContext_read(c) != 105){
return 0;
}
if (ParserContext_read(c) != 102){
return 0;
}
{
const unsigned char * pos = c->pos;
if (p_046W(c)){
return 0;
}
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
}
return 1;
}
static inline int p_04634else34(ParserContext * c){
if (ParserContext_read(c) != 101){
return 0;
}
if (ParserContext_read(c) != 108){
return 0;
}
if (ParserContext_read(c) != 115){
return 0;
}
if (ParserContext_read(c) != 101){
return 0;
}
{
const unsigned char * pos = c->pos;
if (p_046W(c)){
return 0;
}
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
}
return 1;
}
static inline int e81(ParserContext * c){
if (!p_04634else34(c)){
return 0;
}
if (!p_046_(c)){
return 0;
}
{
size_t left = ParserContext_saveTree(c);
if (!p_046Block(c)){
return 0;
}
ParserContext_linkTree(c,_Lelse);
ParserContext_backTree(c,left);
}
return 1;
}
static inline int e80(ParserContext * c){
ParserContext_beginTree(c,0);
if (!p_04634if34(c)){
return 0;
}
if (!p_046_(c)){
return 0;
}
if (!p_046344034(c)){
return 0;
}
{
size_t left = ParserContext_saveTree(c);
if (!p_046Expression(c)){
return 0;
}
ParserContext_linkTree(c,_Lcond);
ParserContext_backTree(c,left);
}
if (!p_046344134(c)){
return 0;
}
{
size_t left1 = ParserContext_saveTree(c);
if (!p_046Block(c)){
return 0;
}
ParserContext_linkTree(c,_Lthen);
ParserContext_backTree(c,left1);
}
const unsigned char * pos = c->pos;
size_t left3 = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (!e81(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left3);
ParserContext_backLog(c,log);
}
ParserContext_tagTree(c,_TIf);
ParserContext_endTree(c,0,_T,NULL, 0);
return 1;
}
static inline int e83(ParserContext * c){
size_t left = ParserContext_saveTree(c);
if (!p_046Expression(c)){
return 0;
}
ParserContext_linkTree(c,_Lexpr);
ParserContext_backTree(c,left);
return 1;
}
static inline int p_04634return34(ParserContext * c){
if (ParserContext_read(c) != 114){
return 0;
}
if (ParserContext_read(c) != 101){
return 0;
}
if (ParserContext_read(c) != 116){
return 0;
}
if (ParserContext_read(c) != 117){
return 0;
}
if (ParserContext_read(c) != 114){
return 0;
}
if (ParserContext_read(c) != 110){
return 0;
}
{
const unsigned char * pos = c->pos;
if (p_046W(c)){
return 0;
}
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
}
return 1;
}
static inline int e82(ParserContext * c){
ParserContext_beginTree(c,0);
if (!p_04634return34(c)){
return 0;
}
if (!p_046_(c)){
return 0;
}
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (!e83(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
}
if (!p_046345934(c)){
return 0;
}
ParserContext_tagTree(c,_TReturn);
ParserContext_endTree(c,0,_T,NULL, 0);
return 1;
}
static inline int e7(ParserContext * c){
int temp = 1;
if (temp){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (p_046Block(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
}
}
if (temp){
const unsigned char * pos4 = c->pos;
size_t left5 = ParserContext_saveTree(c);
size_t log6 = ParserContext_saveLog(c);
if (e80(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos4;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos4;
ParserContext_backTree(c,left5);
ParserContext_backLog(c,log6);
}
}
if (temp){
const unsigned char * pos7 = c->pos;
size_t left8 = ParserContext_saveTree(c);
size_t log9 = ParserContext_saveLog(c);
if (e82(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos7;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos7;
ParserContext_backTree(c,left8);
ParserContext_backLog(c,log9);
}
}
if (temp){
const unsigned char * pos10 = c->pos;
size_t left11 = ParserContext_saveTree(c);
size_t log12 = ParserContext_saveLog(c);
if (e84(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos10;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos10;
ParserContext_backTree(c,left11);
ParserContext_backLog(c,log12);
}
}
if (temp){
return 0;
}
return 1;
}
static inline int p_046Statement(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,1);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e7(c)){
ParserContext_memoTreeSucc(c,1,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,1);
return 0;
}
}
return memo == 1;
}
static inline int e10(ParserContext * c){
{
size_t left = ParserContext_saveTree(c);
if (!p_046Statement(c)){
return 0;
}
ParserContext_linkTree(c,_L);
ParserContext_backTree(c,left);
}
if (!p_046_(c)){
return 0;
}
return 1;
}
int e9(ParserContext * c){
int temp = 1;
if (temp){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e10(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
}
}
if (temp){
const unsigned char * pos4 = c->pos;
size_t left5 = ParserContext_saveTree(c);
size_t log6 = ParserContext_saveLog(c);
if (e11(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos4;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos4;
ParserContext_backTree(c,left5);
ParserContext_backLog(c,log6);
}
}
if (temp){
return 0;
}
return 1;
}
static inline int e8(ParserContext * c){
ParserContext_beginTree(c,0);
if (!p_0463412334(c)){
return 0;
}
while (1){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (!e9(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
break;
}
}
if (!p_0463412534(c)){
return 0;
}
ParserContext_tagTree(c,_TBlock);
ParserContext_endTree(c,0,_T,NULL, 0);
return 1;
}
int p_046Block(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,2);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e8(c)){
ParserContext_memoTreeSucc(c,2,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,2);
return 0;
}
}
return memo == 1;
}
static inline int e47(ParserContext * c){
{
size_t left = ParserContext_saveTree(c);
if (!p_046Identifier(c)){
return 0;
}
ParserContext_linkTree(c,_Lname);
ParserContext_backTree(c,left);
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int e46(ParserContext * c){
ParserContext_beginTree(c,0);
if (!p_04634function34(c)){
return 0;
}
if (!p_046_(c)){
return 0;
}
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (!e47(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
}
if (!p_046344034(c)){
return 0;
}
{
size_t left3 = ParserContext_saveTree(c);
if (!p_046FunctionParamList(c)){
return 0;
}
ParserContext_linkTree(c,_Llist);
ParserContext_backTree(c,left3);
}
if (!p_046344134(c)){
return 0;
}
{
size_t left4 = ParserContext_saveTree(c);
if (!p_046Block(c)){
return 0;
}
ParserContext_linkTree(c,_Lbody);
ParserContext_backTree(c,left4);
}
if (!p_04634585834(c)){
return 0;
}
ParserContext_tagTree(c,_TFunctionExpr);
ParserContext_endTree(c,0,_T,NULL, 0);
return 1;
}
static inline int p_046FunctionExpression(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,23);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e46(c)){
ParserContext_memoTreeSucc(c,23,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,23);
return 0;
}
}
return memo == 1;
}
static inline int e37(ParserContext * c){
if (ParserContext_read(c) != 48){
return 0;
}
return 1;
}
static inline int e36(ParserContext * c){
if (!(49 <= ParserContext_prefetch(c) && ParserContext_read(c) < 58)){
return 0;
}
while (1){
const unsigned char * pos = c->pos;
if (!p_046DIGIT(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
break;
}
}
return 1;
}
static inline int p_046DECIMAL(ParserContext * c){
int temp = 1;
if (temp){
const unsigned char * pos = c->pos;
if (e36(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
}
}
if (temp){
const unsigned char * pos2 = c->pos;
if (e37(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos2;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos2;
}
}
if (temp){
return 0;
}
return 1;
}
static inline int e35(ParserContext * c){
ParserContext_beginTree(c,0);
if (!p_046DECIMAL(c)){
return 0;
}
ParserContext_tagTree(c,_TInteger);
ParserContext_endTree(c,0,_T,NULL, 0);
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int p_046IntegerLiteral(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,18);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e35(c)){
ParserContext_memoTreeSucc(c,18,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,18);
return 0;
}
}
return memo == 1;
}
static inline int p_04634false34(ParserContext * c){
if (ParserContext_read(c) != 102){
return 0;
}
if (ParserContext_read(c) != 97){
return 0;
}
if (ParserContext_read(c) != 108){
return 0;
}
if (ParserContext_read(c) != 115){
return 0;
}
if (ParserContext_read(c) != 101){
return 0;
}
{
const unsigned char * pos = c->pos;
if (p_046W(c)){
return 0;
}
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
}
return 1;
}
static inline int e40(ParserContext * c){
if (!p_04634false34(c)){
return 0;
}
ParserContext_beginTree(c,0);
ParserContext_tagTree(c,_TFalse);
ParserContext_endTree(c,0,_T,NULL, 0);
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int p_04634true34(ParserContext * c){
if (ParserContext_read(c) != 116){
return 0;
}
if (ParserContext_read(c) != 114){
return 0;
}
if (ParserContext_read(c) != 117){
return 0;
}
if (ParserContext_read(c) != 101){
return 0;
}
{
const unsigned char * pos = c->pos;
if (p_046W(c)){
return 0;
}
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
}
return 1;
}
static inline int e39(ParserContext * c){
if (!p_04634true34(c)){
return 0;
}
ParserContext_beginTree(c,0);
ParserContext_tagTree(c,_TTrue);
ParserContext_endTree(c,0,_T,NULL, 0);
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int e38(ParserContext * c){
int temp = 1;
if (temp){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e39(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
}
}
if (temp){
const unsigned char * pos4 = c->pos;
size_t left5 = ParserContext_saveTree(c);
size_t log6 = ParserContext_saveLog(c);
if (e40(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos4;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos4;
ParserContext_backTree(c,left5);
ParserContext_backLog(c,log6);
}
}
if (temp){
return 0;
}
return 1;
}
static inline int p_046BooleanLiteral(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,19);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e38(c)){
ParserContext_memoTreeSucc(c,19,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,19);
return 0;
}
}
return memo == 1;
}
static inline int p_04634null34(ParserContext * c){
if (ParserContext_read(c) != 110){
return 0;
}
if (ParserContext_read(c) != 117){
return 0;
}
if (ParserContext_read(c) != 108){
return 0;
}
if (ParserContext_read(c) != 108){
return 0;
}
{
const unsigned char * pos = c->pos;
if (p_046W(c)){
return 0;
}
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
}
return 1;
}
static inline int e42(ParserContext * c){
if (!p_04634null34(c)){
return 0;
}
ParserContext_beginTree(c,0);
ParserContext_tagTree(c,_TNull);
ParserContext_endTree(c,0,_T,NULL, 0);
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int p_046NullLiteral(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,21);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e42(c)){
ParserContext_memoTreeSucc(c,21,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,21);
return 0;
}
}
return memo == 1;
}
static inline int e34(ParserContext * c){
int temp = 1;
if (temp){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (p_046IntegerLiteral(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
}
}
if (temp){
const unsigned char * pos4 = c->pos;
size_t left5 = ParserContext_saveTree(c);
size_t log6 = ParserContext_saveLog(c);
if (p_046BooleanLiteral(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos4;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos4;
ParserContext_backTree(c,left5);
ParserContext_backLog(c,log6);
}
}
if (temp){
const unsigned char * pos7 = c->pos;
size_t left8 = ParserContext_saveTree(c);
size_t log9 = ParserContext_saveLog(c);
if (p_046StringLiteral(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos7;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos7;
ParserContext_backTree(c,left8);
ParserContext_backLog(c,log9);
}
}
if (temp){
const unsigned char * pos10 = c->pos;
size_t left11 = ParserContext_saveTree(c);
size_t log12 = ParserContext_saveLog(c);
if (p_046NullLiteral(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos10;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos10;
ParserContext_backTree(c,left11);
ParserContext_backLog(c,log12);
}
}
if (temp){
return 0;
}
return 1;
}
static inline int p_046Constant(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,17);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e34(c)){
ParserContext_memoTreeSucc(c,17,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,17);
return 0;
}
}
return memo == 1;
}
static inline int e33(ParserContext * c){
int temp = 1;
if (temp){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (p_046Constant(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
}
}
if (temp){
const unsigned char * pos4 = c->pos;
size_t left5 = ParserContext_saveTree(c);
size_t log6 = ParserContext_saveLog(c);
if (e43(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos4;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos4;
ParserContext_backTree(c,left5);
ParserContext_backLog(c,log6);
}
}
if (temp){
const unsigned char * pos7 = c->pos;
size_t left8 = ParserContext_saveTree(c);
size_t log9 = ParserContext_saveLog(c);
if (p_046FunctionExpression(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos7;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos7;
ParserContext_backTree(c,left8);
ParserContext_backLog(c,log9);
}
}
if (temp){
const unsigned char * pos10 = c->pos;
size_t left11 = ParserContext_saveTree(c);
size_t log12 = ParserContext_saveLog(c);
if (p_046Identifier(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos10;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos10;
ParserContext_backTree(c,left11);
ParserContext_backLog(c,log12);
}
}
if (temp){
return 0;
}
return 1;
}
static inline int p_046PrimaryExpression(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,16);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e33(c)){
ParserContext_memoTreeSucc(c,16,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,16);
return 0;
}
}
return memo == 1;
}
static inline int e31(ParserContext * c){
int temp = 1;
if (temp){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (p_046FunctionCall(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
}
}
if (temp){
const unsigned char * pos4 = c->pos;
size_t left5 = ParserContext_saveTree(c);
size_t log6 = ParserContext_saveLog(c);
if (p_046PrimaryExpression(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos4;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos4;
ParserContext_backTree(c,left5);
ParserContext_backLog(c,log6);
}
}
if (temp){
return 0;
}
return 1;
}
static inline int p_046PostfixExpression(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,14);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e31(c)){
ParserContext_memoTreeSucc(c,14,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,14);
return 0;
}
}
return memo == 1;
}
int e29(ParserContext * c){
ParserContext_beginTree(c,0);
{
size_t left = ParserContext_saveTree(c);
if (!p_046UnaryExpression(c)){
return 0;
}
ParserContext_linkTree(c,_Lleft);
ParserContext_backTree(c,left);
}
if (!p_046_AssignmentOperator(c)){
return 0;
}
{
size_t left1 = ParserContext_saveTree(c);
if (!p_046AssignmentExpression(c)){
return 0;
}
ParserContext_linkTree(c,_Lright);
ParserContext_backTree(c,left1);
}
ParserContext_endTree(c,0,_T,NULL, 0);
return 1;
}
static inline int e28(ParserContext * c){
int temp = 1;
if (temp){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e29(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
}
}
if (temp){
const unsigned char * pos4 = c->pos;
size_t left5 = ParserContext_saveTree(c);
size_t log6 = ParserContext_saveLog(c);
if (p_046ConditionalExpression(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos4;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos4;
ParserContext_backTree(c,left5);
ParserContext_backLog(c,log6);
}
}
if (temp){
return 0;
}
return 1;
}
int p_046AssignmentExpression(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,12);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e28(c)){
ParserContext_memoTreeSucc(c,12,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,12);
return 0;
}
}
return memo == 1;
}
static inline int e45(ParserContext * c){
ParserContext_foldTree(c,0,_L);
if (!p_046344434(c)){
return 0;
}
{
size_t left = ParserContext_saveTree(c);
if (!p_046AssignmentExpression(c)){
return 0;
}
ParserContext_linkTree(c,_L);
ParserContext_backTree(c,left);
}
ParserContext_tagTree(c,_TExpression);
ParserContext_endTree(c,0,_T,NULL, 0);
return 1;
}
static inline int e44(ParserContext * c){
if (!p_046AssignmentExpression(c)){
return 0;
}
while (1){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (!e45(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
break;
}
}
return 1;
}
int p_046Expression(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,22);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e44(c)){
ParserContext_memoTreeSucc(c,22,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,22);
return 0;
}
}
return memo == 1;
}
int e43(ParserContext * c){
if (!p_046344034(c)){
return 0;
}
if (!p_046Expression(c)){
return 0;
}
if (!p_046344134(c)){
return 0;
}
return 1;
}
static inline int e32(ParserContext * c){
if (!p_046PrimaryExpression(c)){
return 0;
}
if (!e48(c)){
return 0;
}
while (1){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (!e48(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
break;
}
}
return 1;
}
int p_046FunctionCall(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,15);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e32(c)){
ParserContext_memoTreeSucc(c,15,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,15);
return 0;
}
}
return memo == 1;
}
static inline int e30(ParserContext * c){
int temp = 1;
if (temp){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (p_046PostfixExpression(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
}
}
if (temp){
const unsigned char * pos4 = c->pos;
size_t left5 = ParserContext_saveTree(c);
size_t log6 = ParserContext_saveLog(c);
if (e50(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos4;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos4;
ParserContext_backTree(c,left5);
ParserContext_backLog(c,log6);
}
}
if (temp){
return 0;
}
return 1;
}
int p_046UnaryExpression(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,13);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e30(c)){
ParserContext_memoTreeSucc(c,13,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,13);
return 0;
}
}
return memo == 1;
}
static inline int e67(ParserContext * c){
if (!p_046UnaryExpression(c)){
return 0;
}
while (1){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (!e68(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
break;
}
}
return 1;
}
int p_046RelationalExpression(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,28);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e67(c)){
ParserContext_memoTreeSucc(c,28,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,28);
return 0;
}
}
return memo == 1;
}
int e73(ParserContext * c){
ParserContext_foldTree(c,0,_Lleft);
{
int temp = 1;
if (temp){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e74(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
}
}
if (temp){
const unsigned char * pos4 = c->pos;
size_t left5 = ParserContext_saveTree(c);
size_t log6 = ParserContext_saveLog(c);
if (e75(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos4;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos4;
ParserContext_backTree(c,left5);
ParserContext_backLog(c,log6);
}
}
if (temp){
return 0;
}
}
{
size_t left7 = ParserContext_saveTree(c);
if (!p_046RelationalExpression(c)){
return 0;
}
ParserContext_linkTree(c,_Lright);
ParserContext_backTree(c,left7);
}
ParserContext_endTree(c,0,_T,NULL, 0);
return 1;
}
static inline int e6(ParserContext * c){
int temp = 1;
if (temp){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (p_046Statement(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
}
}
if (temp){
const unsigned char * pos4 = c->pos;
size_t left5 = ParserContext_saveTree(c);
size_t log6 = ParserContext_saveLog(c);
if (p_046Declaration(c)){
temp = 0;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos4;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos4;
ParserContext_backTree(c,left5);
ParserContext_backLog(c,log6);
}
}
if (temp){
return 0;
}
return 1;
}
static inline int p_046TopLevel(ParserContext * c){
if (!e6(c)){
return 0;
}
while (1){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (!e6(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
break;
}
}
return 1;
}
static inline int e5(ParserContext * c){
{
size_t left = ParserContext_saveTree(c);
if (!p_046TopLevel(c)){
return 0;
}
ParserContext_linkTree(c,_L);
ParserContext_backTree(c,left);
}
if (!p_046_(c)){
return 0;
}
return 1;
}
static inline int p_046EOT(ParserContext * c){
if (!ParserContext_eof(c)){
return 0;
}
return 1;
}
static inline int e0(ParserContext * c){
if (!p_046_(c)){
return 0;
}
ParserContext_beginTree(c,0);
while (1){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (!e5(c)){
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
break;
}
}
ParserContext_tagTree(c,_TSource);
ParserContext_endTree(c,0,_T,NULL, 0);
if (!p_046EOT(c)){
return 0;
}
return 1;
}
static inline int p_046File(ParserContext * c){
int memo = ParserContext_memoLookupTree(c,0);
if (memo == 0){
const unsigned char * pos = c->pos;
size_t left = ParserContext_saveTree(c);
size_t log = ParserContext_saveLog(c);
if (e0(c)){
ParserContext_memoTreeSucc(c,0,pos);
return 1;
} else{
backtrack_count = backtrack_count + 1;
long length = c->pos-pos;
total_backtrack_length = total_backtrack_length + length;
if (backtrack_length < length){
backtrack_length = length;
}
c->pos = pos;
ParserContext_backTree(c,left);
ParserContext_backLog(c,log);
ParserContext_memoFail(c,0);
return 0;
}
}
return memo == 1;
}
void cnez_dump(void *v, FILE *fp)
{
size_t i;
Tree *t = (Tree*)v;
if(t == NULL) {
fputs("null", fp);
return;
}
// if(t->refc != 1) {
// fprintf(fp, "@%ld", t->refc);
// }
fputs("[#", fp);
fputs(_tags[t->tag], fp);
if(t->size == 0) {
fputs(" '", fp);
for(i = 0; i < t->len; i++) {
fputc(t->text[i], fp);
}
fputs("'", fp);
}
else {
for(i = 0; i < t->size; i++) {
fputs(" ", fp);
if(t->labels[i] != 0) {
fputs("$", fp);
fputs(_labels[t->labels[i]], fp);
fputs("=", fp);
}
cnez_dump(t->childs[i], fp);
}
}
fputs("]", fp);
}
#ifndef UNUSE_MAIN
#include<sys/time.h> // for using gettimeofday
static const char *get_input(const char *path, size_t *size)
{
FILE *fp = fopen(path, "rb");
if(fp != NULL) {
size_t len;
fseek(fp, 0, SEEK_END);
len = (size_t) ftell(fp);
fseek(fp, 0, SEEK_SET);
char *buf = (char *) calloc(1, len + 1);
size_t readed = fread(buf, 1, len, fp);
if(readed != len) {
fprintf(stderr, "read error: %s\n", path);
exit(1);
}
fclose(fp);
size[0] = len;
return (const char*)buf;
}
size[0] = strlen(path);
return path;
}
static double timediff(struct timeval *s, struct timeval *e)
{
double t1 = (e->tv_sec - s->tv_sec) * 1000.0;
double t2 = (e->tv_usec - s->tv_usec) / 1000.0;
return t1 + t2; /* ms */
}
int cnez_main(int ac, const char **av, void* (*parse)(const char *input, size_t len))
{
int j;
size_t len;
if(ac == 1) {
fprintf(stdout, "Usage: %s file [or input-text]\n", av[0]);
return 1;
}
for(j = 1; j < ac; j++) {
const char *input = get_input(av[j], &len);
if(getenv("BENCH") != NULL) {
double tsum = 0.0;
double t[5];
int i = 0;
for(i = 0; i < 5; i++) {
struct timeval s, e;
gettimeofday(&s, NULL);
void *data = parse(input, len);
gettimeofday(&e, NULL);
if(data == NULL) {
fprintf(stdout, "%s FAIL %f[ms]\n", av[j], timediff(&s, &e));
break;
}
t[i] = timediff(&s, &e);
tsum += t[i];
cnez_free(data);
}
if(tsum != 0.0) {
fprintf(stdout, "%s OK %.4f[ms] %.3f %.3f %.3f %.3f %.3f\n", av[j], tsum / 5, t[0], t[1], t[2], t[3], t[4]);
}
}
else {
void *data = parse(input, len);
cnez_dump(data, stdout);
fprintf(stdout, "\n");
if(getenv("MEM") != NULL) {
cnez_dump_memory("Memory Usage", data);
}
cnez_free(data);
}
}
return 0;
}
#endif/*UNUSE_MAIN*/
void* epsilon_parse(const char *text, size_t len, void *thunk, void* (*fnew)(symbol_t, const unsigned char *, size_t, size_t, void *), void (*fset)(void *, size_t, symbol_t, void *, void *), void (*fgc)(void *, int, void *)){
void* result = NULL;
ParserContext * c = ParserContext_new((const unsigned char*)text, len);
ParserContext_initTreeFunc(c,thunk,fnew,fset,fgc);
ParserContext_initMemo(c,64/*FIXME*/,29);
if (p_046File(c)){
printf("total backtrack count: %ld\n", backtrack_count);
printf("longest backtrack length: %ld\n", backtrack_length);
printf("total backtrack length: %ld\n", total_backtrack_length);
result = c->left;
if (result == NULL){
result = c->fnew(0, (const unsigned char*)text, (c->pos - (const unsigned char*)text), 0, c->thunk);
}
}
ParserContext_free(c);
return result;
}
static void* cnez_parse(const char *text, size_t len){
return epsilon_parse(text, len, NULL, NULL, NULL, NULL);
}
long epsilon_match(const char *text, size_t len){
long result = -1;
ParserContext * c = ParserContext_new((const unsigned char*)text, len);
ParserContext_initNoTreeFunc(c);
ParserContext_initMemo(c,64/*FIXME*/,29);
if (p_046File(c)){
result = c->pos-c->inputs;
}
ParserContext_free(c);
return result;
}
const char* epsilon_tag(symbol_t n){
return _tags[n];
}
const char* epsilon_label(symbol_t n){
return _labels[n];
}
#ifndef UNUSE_MAIN
int main(int ac, const char **argv){
return cnez_main(ac, argv, cnez_parse);
}
#endif/*MAIN*/
// End of File
|
C
|
#include <avr/io.h>
#include <String.h>
void usart_Init()
{
/*Set baud rate */
UBRR0 = 103;
/*Enable receiver and transmitter */
UCSR0B |= (1<<RXEN0)|(1<<TXEN0);
/* Set frame format: 8data, 1stop bit and no parity */
UCSR0C &= ~(1<<USBS0) ; //1 stop bit
UCSR0C |= (1<<UCSZ00) | (1<<UCSZ01); // 8 bit
UCSR0C &= ~(1<<UPM01); //no parity
UCSR0C &= ~(1<<UPM00); //no parity
}
void usart_send( unsigned char data )
{
/* Wait for empty transmit buffer */
while ( !( UCSR0A & (1<<UDRE0)) );
/* Put data into buffer, sends the data */
UDR0 = data;
}
unsigned char usart_receive( void )
{
/* Wait for data to be received */
while ( !(UCSR0A & (1<<RXC0)) );
/* Get and return received data from buffer */
return UDR0;
}
int main(){
usart_Init();
char ch;
int j;
char str_message;
int key = 3;
while (1) {
str_message = usart_receive();
// for(j = 0; str_message != '\0'; ++j){
ch = str_message;
if(ch >= 'a' && ch <= 'z'){
ch = ch + key;
if(ch > 'z'){
ch = ch - 'z' + 'a' - 1;
}
str_message = ch;
}
else if(ch >= 'A' && ch <= 'Z'){
ch = ch + key;
if(ch > 'Z'){
ch = ch - 'Z' + 'A' - 1;
}
str_message = ch;
}
usart_send(str_message);
// }
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_check_format.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mdiallo <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/02/23 12:57:13 by mdiallo #+# #+# */
/* Updated: 2021/02/23 12:57:20 by mdiallo ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/ft_printf.h"
int ft_is_conver(int c)
{
return ((c == 'c') || (c == 's') || (c == 'p') || (c == 'd') || (c == 'i')
|| (c == 'u') || (c == 'x') || (c == 'X') || (c == '%'));
}
int ft_is_flags(int c)
{
return ((c == '-') || (c == ' ') || (c == '0') || (c == '.') || (c == '*'));
}
int ft_check_format(int c, t_flags flag, va_list arg_list)
{
int count;
count = 0;
if (c == 'c')
count = ft_conversion_char(va_arg(arg_list, int), flag);
else if (c == 'd' || c == 'i')
count = ft_conversion_int(va_arg(arg_list, int), flag);
else if (c == 's')
count = ft_conversion_str(va_arg(arg_list, char *), flag);
else if (c == 'p')
count = ft_conversion_pointer(va_arg(arg_list,
unsigned long long), flag);
else if (c == 'u')
count += ft_conversion_unsi((unsigned int)va_arg(arg_list,
unsigned int), flag);
else if (c == 'x')
count += ft_conversion_hexa(va_arg(arg_list, unsigned int), 1, flag);
else if (c == 'X')
count += ft_conversion_hexa(va_arg(arg_list, unsigned int), 0, flag);
else if (c == '%')
count += ft_percent(flag);
return (count);
}
|
C
|
#ifndef HASH
#define HASH
#include <stdio.h>
#include <stdlib.h>
/**
* struct hash_node_s - holberton
*
* @key: int
* @value: int
* @next: int
*/
typedef struct hash_node_s
{
char *key;
char *value;
struct hash_node_s *next;
} hash_node_t;
/**
* struct hash_table_s - holberton
*
* @size: int
* @array: int
*/
typedef struct hash_table_s
{
unsigned long int size;
hash_node_t **array;
} hash_table_t;
hash_table_t *hash_table_create(unsigned long int size);
unsigned long int hash_djb2(const unsigned char *str);
unsigned long int key_index(const unsigned char *key, unsigned long int size);
int hash_table_set(hash_table_t *ht, const char *key, const char *value);
char *hash_table_get(const hash_table_t *ht, const char *key);
#endif
|
C
|
/******************************************************************************
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.
*******************************************************************************/
#include <stdio.h>
int main()
{
printf("Hello World! \n");
//Faça um programa que calcule e mostre a área de um círculo. Sabe-se que: área = π * R^2
//input de dados
int r;
printf("Digite o raio de um círculo em metros: ");
scanf("%d", &r);
//cálculo da área
double area;
area = 3.14159265358979323846264338327950288419716939937510 * r * r;
//output de dados
printf("A área da circunferência é equivalente à %f metros quadrados.", area);
return 0;
}
|
C
|
#include <stdio.h>
#include <conio.h>
#define n 80
int main()
{
int i, j, m;
char line[5][n],*min,*max,*p;
printf("write number of your lines:\n");
scanf("%d", &m);
m+=1;
if(m>5) m=5;
printf("write your simbols:\n");
for(i=0;i<m;i++)
gets(line[i]);
for(i=0;i<m;i++)
puts(line[i]);
for(i=0;i<m;i++)
{
min=max=&line[i][0];
for(j=1;j<n;j++)
{
p=&line[i][j];
if(*p>*max) max=p;
else if(*p<*min) min=p;
}
for(j=0;j<n;j++)
if(*p==*min||*p==*max)
*p='_';
}
for(i=0;i<m;i++)
puts(line[i]);
getch();
return 0;
}
|
C
|
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
//int ret, ret1;
//ret = fork();
//fork();
//fork();
//if(!ret)
//{
printf("This is child process:\n");
//}
//else
//{
//fork();
//fork();
//sleep(5);
//printf("This is parent process:\n");
//}
return 0;
}
|
C
|
#include <avr/io.h>
#include <stdio.h>
#include <stdlib.h>
#include "twi.h"
// Initial TWI
void TWIInit ( void ){
// set SCL to 400kHz
TWSR = 0x00;
TWBR = 0x0C;
// enable TWI
TWCR = ( 1 << TWEN );
}
//
// Start read/write
void TWIStart ( void ){
TWCR = ( 1 << TWINT ) | ( 1 << TWSTA ) | ( 1 << TWEN );
while (( TWCR & ( 1 << TWINT )) == 0 );
}
//
// Stop read/ write
void TWIStop ( void ){
TWCR = ( 1 << TWINT ) | ( 1 << TWSTO ) | ( 1 << TWEN );
}
//
// Write
void TWIWrite ( uint8_t u8data ){
TWDR = u8data;
TWCR = ( 1 << TWINT ) | ( 1 << TWEN );
while (( TWCR & ( 1 << TWINT )) == 0 );
}
//
// Read
uint8_t TWIReadACK ( void ){
TWCR = ( 1 << TWINT ) | ( 1 << TWEN )|( 1 << TWEA );
while (( TWCR & ( 1 << TWINT )) == 0 );
return TWDR;
}
//
//
uint8_t TWIReadNACK ( void ){
TWCR = ( 1 << TWINT ) | ( 1 << TWEN );
while (( TWCR & ( 1 << TWINT )) == 0 );
return TWDR;
}
//
// Status
uint8_t TWIGetStatus( void ){
uint8_t status;
// mask status
status = TWSR & 0xF8;
return status;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct node {int i; struct node *next;};
void print_list(struct node * l_list);
struct node * insert_front(struct node * l_list, int addend);
struct node * free_list(struct node * l_list);
|
C
|
#include <stdio.h>
int main (void)
{
int account_no=0;
float begin_balance, total_credit, total_charges, credit_limit, balance;
while(account_no!=-1)
{
printf("Enter account number(-1to end):");
scanf("%d", &account_no);
if(account_no!=-1)
{
printf("Enter beginning balance:");
scanf("%f", &begin_balance);
printf("Enter total charges:");
scanf("%f", &total_charges);
printf("Enter total credits:");
scanf("%f", &total_credit);
printf("Enter credþt limit:");
scanf("%f", &credit_limit);
balance= begin_balance+total_credit;
printf("Account :%d\n", account_no);
printf("Credit limit:%.2f\n", credit_limit);
printf("Balance :%.2f\n", balance);
if (balance>credit_limit)
printf("Credit Limit Exceeded\n");
printf("\n");
}
else
break;
}
return 0;
}
|
C
|
# c-programming
#include <stdio.h>
int main()
{
char str[100],i=0,length;
printf("\nEnter the string:");
gets(str);
while(str[i] !='\0')
i++;
length=i;
printf("\nThe length of the string is:%d",length);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void login ();
void reg ();
/*void adminlog (int variabel);
void adminreg (int variabel);
void akundelete (int variabel);
void tambahmodul (int variabel);
void userlog (int variabel);
void userreg (int variabel);
void usergantipass (int variabel);
void betalog(int variabel);
void betareg(int variabel);*/
FILE *reg_txt;
int x;
int n, loop = 0;
int looplog = 0;
char string[100];
//char string[];
int main()
{
FILE *cover;
cover = fopen("cover.txt", "r");
while (fgets(string, sizeof(string), cover) != NULL)
printf("%s",string);
fclose (cover);
system ("pause");
system ("cls");
while (loop == 0)
{
printf ("\n\t||||||||||||| RUANG DASKOM ||||||||||||||\n");
printf ("\t=========================================\n"
"\t\t\t MENU\t\t\n"
"\t=========================================\n\n");
printf ("\t <1> Login\n"
"\t <2> Register\n"
"\t <3> Exit\n\n");
printf ("\tPilih menu: ");
scanf ("%d", &n); system ("cls");
switch(n)
{
case 1:
while (looplog == 0)
{
login();
}
loop++;
break;
case 2:
while (looplog == 0)
{
reg();
}
if (looplog == 2)
loop;
else loop++;
break;
}
}
}
/* printf ("Selamat datang di Ruang Daskom\n"
"Silahkan pilih menu:\n\n");
printf ("\t1. Login ||\t2. Register\n");
scanf ("%d", n);
switch (n)
{
case 1:
while (loop == 0)
{
printf ("Selamat datang di halaman login\n"
"Ingin login sebagai apa?");
printf ("\t1. Admin\n"
"\t2. User Premium\n"
"\t3. User Beta\n");
scanf("%d", n);
switch(n)
{
case 1:
void adminlog(int variabel);
loop++
break;
case 2:
void userlog (int variabel);
loop++
break;
case 3:
void betalog(int variabel);
loop++
break;
default:
printf ("Menu tidak tersedia, silahkan ulangi\n");
}
break;
case 2:
printf ("Selamat datang di halaman register\n"
"Ingin register akun apa?");
reg_txt = fopen("Registercover.txt", "r");
while (fgets(string, sizeof(string), reg_txt) != NULL)
printf("%s",string);
fclose (reg_text);
printf ("\n");
scanf ("%d", n);
switch(n)
{
case 1:
}
}
}*/
void login (){
printf ("Selamat datang di halaman login\n"
"Ingin login sebagai apa?");
printf ("\n\t<1> Admin\n"
"\t<2> User Premium\n"
"\t<3> User Beta\n");
scanf("%d", &n);
switch(n)
{
case 1:
system ("cls");
// void adminlog(int variabel);
printf ("Test 1");
looplog++;
break;
case 2:
system ("cls");
// void userlog (int variabel);
printf ("Test 2");
looplog++;
break;
case 3:
system ("cls");
// void betalog(int variabel);
printf ("Test 3");
looplog++;
break;
default:
system ("cls");
printf ("Menu tidak tersedia, silahkan ulangi\n\n");
}
}
void reg(){
printf ("Selamat datang di halaman register\n"
"Silahkan pilih akun: \n\n");
reg_txt = fopen("Registercover.txt", "r");
while (fgets(string, sizeof(string), reg_txt) != NULL)
printf("%s",string);
fclose (reg_txt);
printf ("\n\nKembali tekan 3\n");
scanf ("%d", &n);
switch(n)
{
case 1:
system ("cls");
printf ("Premium yeah");
looplog++;
break;
case 2:
system ("cls");
printf ("Beta Hehe");
looplog++;
break;
case 3:
looplog = 2;
default:
system ("cls");
printf("Pilihan tidak tersedia, silahkan ulangi");
}
}
|
C
|
#include "resources.h"
#include "lang_common.h"
#include "lang_en.h"
#include <stdlib.h>
#include <string.h>
// 洢ַ/
StrObject* resources[COUNT];
// ȡַ/
StrObject* _readStrObj(const char** strarray, size_t width, size_t height)
{
StrObject* newobj = malloc(sizeof(StrObject));
if (newobj == NULL) return NULL;
newobj->str = strarray;
newobj->width = width;
newobj->height = height;
return newobj;
}
#define readStrObj(strarray) _readStrObj(strarray, strlen(strarray[0]), length(strarray))
void res_add(Resources id, StrObject* object)
{
if (id < MISSINGNO || id >= COUNT) return;
resources[id] = object;
}
#define res_add_auto(id) res_add(id, readStrObj(_##id))
StrObject* res_get(Resources id)
{
if (id <= MISSINGNO || id >= COUNT) id = MISSINGNO;
return resources[id];
}
void res_load()
{
res_add_auto(MISSINGNO);
res_add_auto(TITLE);
res_add_auto(GAMEOVER);
res_add_auto(PLANE);
res_add_auto(PLANE2);
res_add_auto(WCNB);
res_add_auto(WEBSITE);
res_add_auto(MENU);
res_add_auto(BUTTONS);
res_add_auto(DIFFICULTY);
res_add_auto(HELP);
res_add_auto(ABOUT);
res_add_auto(STRINGS);
}
void res_unload()
{
for (int i = 0; i < COUNT; ++i) free(resources[i]);
}
|
C
|
#include<linux/init.h>
#include<linux/module.h>
#include<linux/moduleparam.h>
MODULE_LICENSE("GPL");
static int a,b;
module_param(a,int,S_IRUGO);
module_param(b,int,S_IRUGO);
static int __init hello_init(void)
{
printk(KERN_INFO"INIT_MODULE: The sum of the two numbers is %d\n",a+b);
return 0;
}
static void __exit hello_exit(void)
{
printk(KERN_INFO"EXIT_MODULE: The difference of the two numbers is %d\n",a-b);
}
module_init(hello_init);
module_exit(hello_exit);
|
C
|
#include <stdio.h>
int main() {
char num1 = 28;
int num2 = 1000000002;
char num3 = num1 + num2; //(char ū ڴ )
//28+2 ڸ .
printf("%d\n", num3); // 30
return 0;
}
// https://dojang.io/mod/page/view.php?id=113
|
C
|
//
// vente.c
// PharmApp
//
// Created by Braksa - Boutaib on 12/25/15.
// Copyright © 2015 NSApps. All rights reserved.
//
#include "vente.h"
// Implémentation des fonctions
Vente* create_vente(time_t date_time, int nombre_medicaments, int medicaments[VENTE_MAX_MEDICAMENTS_IDS][2]) {
// Alloc new Commande
Vente* vente = (Vente*)malloc(sizeof(Vente));
// Set properties
vente -> vente_id = -1;
vente -> date_time = date_time;
vente -> nombre_medicaments = nombre_medicaments;
for (int i = 0; i < nombre_medicaments; i++) {
vente -> medicaments[i][0] = medicaments[i][0];
vente -> medicaments[i][1] = medicaments[i][1];
}
// Return
return vente;
}
|
C
|
#include<stdio.h>
#include<limits.h>
#include<stdlib.h>
#include<string.h>
#define min(a, b) (a<b?a:b);
#define s(x) scanf("%d", &x);
#define p(x) printf("%d\n", x);
typedef struct queue{
int front, rear, size, capacity;
int *array;
} queue;
queue* create(int capacity){
queue *q = (queue*)malloc(sizeof(queue));
q->capacity = capacity;
q->front = q->size = 0;
q->rear = q->capacity-1;
q->array = (int*)malloc(q->capacity*sizeof(int));
return q;
}
int isempty(queue *q){
return (q->size==0);
}
int isfull(queue *q){
return (q->size==q->capacity);
}
void push(queue *q, int item){
if(isfull(q))
return;
q->rear = (q->rear+1)%q->capacity;
q->array[q->rear] = item;
q->size++;
}
int pop(queue *q){
if(isempty(q))
return INT_MIN;
int item = q->array[q->front];
q->front = (q->front+1)%q->capacity;
q->size--;
return item;
}
int front(queue *q){
if(isempty(q))
return INT_MIN;
return q->array[q->front];
}
int main(){
int thresh, n;
double wait = 0;
s(thresh)
s(n)
int at[n], bt[n], wt[n], vis[n];
memset(vis, 0, n*sizeof(vis[0]));
for(int i = 0; i < n; i++)
{
s(at[i])
s(bt[i])
}
queue *q1 = create(n), *q2 = create(n);
push(q1, bt[0]);
push(q2, 0);
int t = 0; vis[0] = 1;
while(!isempty(q1)){
printf("current time ");
p(t)
int curr = pop(q1), time = pop(q2);
printf("curr ");
p(curr)
printf("time ");
p(time)
for(int i = 1; i < n; i++)
{
if(t<=at[i] && !vis[i])
{
push(q1, bt[i]);
push(q2, at[i]);
vis[i] = 1;
}
if(t>at[i] && !vis[i]){
wait-=at[i];
// visu[i] = 1;
}
}
wait += t-time;
t+=min(thresh, curr);
if(curr-thresh>0){
push(q1, curr-thresh);
push(q2, t);
// printf("front ");
// front(q1);
}
printf("%lf\n", wait);
}
printf("%lf\n", wait/n);
}
|
C
|
//
// Created by Matthieu Costa on 01/06/2021.
//
#include <string.h>
int correct_tail(const char *body, const char tail[1]) {
return body[strlen(body) - 1] == *tail;
}
|
C
|
#include<stdio.h>
#include<math.h>
int main()
{
void invert(int* a,int count);
int a[10]={1,3,5,7,9,8,6,4,2,0};
int *pa;
for(pa=a;pa<a+10;pa++)
{
printf("%d\t",*pa);
}
printf("\nafter invert\n");
invert(a,10);
for(pa=a;pa<a+10;pa++)
{
printf("%d\t",*pa);
}
return 0;
}
void invert(int* a,int count)
{
int *p_start;
int *p_end;
int mid;
int temp;
p_start=a;
p_end=a+count-1;
mid=count/2;
for(;p_start<a+mid;p_start++,p_end--)
{
temp=*p_start;
*p_start=*p_end;
*p_end=temp;
}
}
|
C
|
#include <stdio.h>
#include <layout.h>
#define MS_BPS 512
/*
* Calculate the length between the sectors, given the length of the track
* and the number of sectors that must fit on it.
* The proper formula would be
* (((TLEN/2) - INDEXLEN) / unit->mu_SectorsPerTrack) - BLOCKLEN;
*/
int
Gap(int tlen, int sectors)
{
int gap = (((tlen/2) - INDEXLEN) / sectors) - BLOCKLEN;
printf("%d %d -> %d\n", tlen, sectors, gap);
return gap;
}
int
main()
{
Gap(TLEN, 8);
Gap(TLEN, 9);
Gap(TLEN, 10);
Gap(TLEN, 11); /* won't work */
Gap(TLEN*2, 15);
Gap(TLEN*2, 16);
Gap(TLEN*2, 17);
Gap(TLEN*2, 18);
Gap(TLEN*2, 19);
Gap(TLEN*2, 20);
Gap(TLEN*2, 21);
Gap(TLEN*2, 22); /* won't work */
}
|
C
|
/*
* @Author: DESKTOP-0VVB0MB$
* @Date: 2018-09-27 19:02:55
* @Last Modified by: TD21forever
* @Last Modified time: 2018-09-28 23:17:47
*/
// a+b
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char const *argv[])
{
int n,sum;
while(scanf("%d",&n)==1)
{
sum = 0;
int i;
for (i = 0; i <= n; ++i)
{
sum+=i;
}
printf("%d\n\n", sum);
}
return 0;
}
|
C
|
#include <iostream>
using namespace std;
int main() {
int i, n;
cin >> n;
for (i=0; i<n; i++) {
cout << "hello world\n";
}
return 0;
}
Raw
gistfile2.cs
using System;
namespace Solution {
class Solution {
static void Main(string[] args) {
var line1 = System.Console.ReadLine().Trim();
var N = Int32.Parse(line1);
for (var i = 0; i < N; i++) {
System.Console.WriteLine("hello world");
}
}
}
}
Raw
gistfile3.java
import java.io.*;
public class Solution {
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int N = Integer.parseInt(line);
for (int i = 0; i < N; i++) {
System.out.println("hello world");
}
}
}
Raw
gistfile4.py
N = int(raw_input())
for i in xrange(N):
print "hello world"
Raw
gistfile5.rb
gets.to_i.times { puts "hello world" }
Raw
gistfile6.lisp
(setq strN (read-line))
(setq N (parse-integer strN))
(loop for i from 1 to N do
(write "hello world")
(terpri)
)
|
C
|
#include <stdint.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
#define DARK_SQUARES 0xAA55AA55AA55AA55ULL
#define LIGHT_SQUARES (~DARK_SQUARES)
#define FILE_H 0x0101010101010101ULL
#define FILE_G (FILE_H << 1)
#define FILE_F (FILE_H << 2)
#define FILE_E (FILE_H << 3)
#define FILE_D (FILE_H << 4)
#define FILE_C (FILE_H << 5)
#define FILE_B (FILE_H << 6)
#define FILE_A (FILE_H << 7)
#define RANK_8 0xFFULL
#define RANK_7 (RANK_8 << 8)
#define RANK_6 (RANK_8 << (8 * 2))
#define RANK_5 (RANK_8 << (8 * 3))
#define RANK_4 (RANK_8 << (8 * 4))
#define RANK_3 (RANK_8 << (8 * 5))
#define RANK_2 (RANK_8 << (8 * 6))
#define RANK_1 (RANK_8 << (8 * 7))
uint64_t bbPawnsW = RANK_2;
uint64_t bbPawnsB = RANK_7;
uint64_t bbKingW = 0x800000000000000ULL;
uint64_t bbKingB = 0x8ULL;
char* int_to_binary_str(uint64_t number) {
char buffer[65] = "000000000000000000000000000000000000000000000000000000000000000\0";
for (int i = 63; i >= 0; i--) {
buffer[i] = (number & 1ull) + '0';
number = number >> 1ull;
}
buffer[64] = '\0';
//return strdup(number);
return strdup(buffer);
}
void print_board() {
/*
|r|k|b|q|k|b|k|r|
|p|p|p|p|p|p|p|p|
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
|P|P|P|P|P|P|P|P|
|R|K|B|Q|K|B|K|R|
*/
}
int main(int argc, char** argv) {
//uintmax_t x = UINT64_MAX;
//printf("INT_MAX: %" PRIu64 "\n", x);
printf("rank1: %s\n", int_to_binary_str(RANK_1));
printf("rank8: %s\n", int_to_binary_str(RANK_8));
printf("filea: %s\n", int_to_binary_str(FILE_A));
printf("fileh: %s\n", int_to_binary_str(FILE_H));
printf("black pawns: %s\n", int_to_binary_str(bbPawnsB));
printf("white pawns: %s\n", int_to_binary_str(bbPawnsW));
printf("white king: %s\n", int_to_binary_str(bbKingW));
printf("black king: %s\n", int_to_binary_str(bbKingB));
/*
printf("Black: %" PRIu64 "\n", bbPawnsBlack);
printf("asbin: %s\n", int_to_binary_str(bbPawnsBlack));
printf("White: %" PRIu64 "\n", bbPawnsWhite);
printf("asbin: %s\n", int_to_binary_str(bbPawnsWhite));
printf("\n"); */
return 0;
}
|
C
|
#include<stdio.h>
//ͱ飬iȷѭtм
//ݵһһ
int main() {
int i,t;
int a[5] = { 0, 1, 2, 3, 4 };
int b[5] = { 5, 6, 7, 8, 9 };//ʼ
for (i = 0; i < 5; i++) { //ͨtνa[i]b[i]ֵ
t = a[i];
a[i] = b[i];
b[i] = t;
}
for (i = 0; i < 5; i++)
printf("%d\t", a[i]); //a[5]
printf("\n");
for (i = 0; i < 5; i++) //b[5]
printf("%d\t", b[i]);
return 0;
}
|
C
|
//模拟实现strcat
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
char *Strcat(char *dest, char *src)
{
char* ret = dest;
assert(*dest != NULL);
assert(*src != NULL);
//寻找dest的'\0'位置
while (*dest)
{
dest++;
}
//src的内容依次拷贝到dest的内容后面
while (*dest++ = *src++)
;
return ret;
}
int main()
{
char a[100] = "i love you";
char *b = " very much!";
Strcat(a,b);
printf("%s\n", a);
printf("%s\n", b);
system("pause");
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
void main()
{
char text[100],word[100],rpwd[100],str[10][10];
int k=0,i=0,j=0,w=0,p;
gets(text);
scanf("%s %s",word,rpwd);
p=strlen(text);
for(k=0;k<p;k++)
{
if((text[k]!= ' '))
{
str[i][j]=text[k];
k++;
}
else
{
str[i][j]='\0';
j=0;
i++;
}
}
w=i;
for(i=0;i<=w;i++)
{
if(strcmp(str[i],word)==0)
strcpy(str[i],rpwd);
printf("%s",str[i]);
}
}
|
C
|
#include "estoque.h"
#include <stdio.h>
TProduto leProduto(void){
TProduto p;
printf("\n");
printf("ID..: ");
scanf("%d", &p.id);
fflush(stdin);
printf("Nome: ");
scanf("%40s[^\n]", p.nome);
fflush(stdin);
printf("Quantidade: ");
scanf("%d", &p.quant);
fflush(stdin);
printf("Preco Compra: ");
scanf("%f", &p.precoCompra);
fflush(stdin);
printf("Preco Venda: ");
scanf("%f", &p.precoVenda);
fflush(stdin);
return p;
}
void imprimeProduto(TProduto p){
printf("\nID..: %d\n", p.id);
printf("Nome: %s\n", p.nome);
printf("Quantidade: %d\n", p.quant);
printf("Preco Compra: %.2f\n", p.precoCompra);
printf("Preco Venda: %.2f\n", p.precoVenda);
}
void reajusta( TProduto prods[], float porcentagem, int n){
int i;
for(i=0; i<n; i++)
prods[i].precoVenda *= (1 + (1/porcentagem));
}
TProduto prodLucrativo( TProduto prods[], int n){
int i;
float lucro = 0;
int iLucro = -1;
for(i=0; i<n; i++){
if( prods[i].precoVenda - prods[i].precoCompra > lucro){
lucro = prods[i].precoVenda - prods[i].precoCompra;
iLucro = i;
}
}
return prods[iLucro];
}
// Deve retornar:
// (1) o indice do produto mais lucrativo e
// (2) o valor do maior lucro encontrado
int prodLucrativo2( TProduto prods[], int n, float *mLucro){
int i;
float lucro = 0;
int iLucro = -1;
for(i=0; i<n; i++){
if( prods[i].precoVenda - prods[i].precoCompra > lucro){
lucro = prods[i].precoVenda - prods[i].precoCompra;
iLucro = i;
}
}
*mLucro = lucro;
return iLucro;
}
///Questo E- Aleterar o valor do produto
void alteraPreco(int index, float valor, TProduto prods[]){
prods[index].precoVenda = valor;
}
/// Questao F- Deletar ltimo registro
void apagaLastRegister(TProduto prods[], int indice){
printf("\n\nO iten %s foi removido\n\n", prods[indice].nome);
}
///Questo G Da baixa em uma quantidade fornecida pelo usuario
void baixaEstoque(int indice, int qtd, TProduto prods[]){
prods[indice].quant = prods[indice].quant - qtd;
}
///Lista os produtos que tem o estoque minimo
void menorQtdMinimo(int minimo, int indice, TProduto prods[]){
int i;
for (i=0; i< indice; i++){
if ( prods[i].quant < minimo){
printf("\n\nPRODUTO : %s\n\n", prods[i].nome);
}
}
}
|
C
|
/******** http://blog.csdn.net/robertkun ********/
/******* 客户端程序 client.c ************/
// linux 下读取大于2GB文件时,需指定
#define _FILE_OFFSET_BITS 64
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <fcntl.h> // 文件读写
// 定义包的大小为512KB
#define PACK_SIZE 1024*512
char* get_file_name(char* fn);
unsigned long get_file_size(const char *path);
int main()
{
// if(argc < 2)
// {
// printf("please input:<ip> <port> <filePath>.\n");
// return 0;
// }
// 设置输出缓冲
setvbuf(stdout, NULL, _IONBF, 0);
fflush(stdout);
char* filePath = "/Users/songshaoying/Desktop/struct.txt";
if(access(filePath, F_OK) != 0)
{
printf("file not existed!\n");
return 0;
}
int sockfd;
char buff[1024] = {'\0'};
struct sockaddr_in server_addr;
struct hostent *host;
int portnumber,nbytes;
const char* ip = "127.0.0.1";
if((host=gethostbyname(ip))==NULL)
{
fprintf(stderr,"Gethostname error\n");
exit(1);
}
const char* port = "48123";
if((portnumber=atoi(port))<0)
{
fprintf(stderr,"Usage:%s hostname portnumber\a\n",port);
exit(1);
}
/* 客户程序开始建立 sockfd描述符 */
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
fprintf(stderr,"Socket Error:%s\a\n",strerror(errno));
exit(1);
}
/* 客户程序填充服务端的资料 */
bzero(&server_addr,sizeof(server_addr));
server_addr.sin_family=AF_INET;
server_addr.sin_port=htons(portnumber);
server_addr.sin_addr=*((struct in_addr *)host->h_addr);
/* 客户程序发起连接请求 */
if(connect(sockfd,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr))==-1)
{
fprintf(stderr,"Connect Error:%s\a\n",strerror(errno));
exit(1);
}
/* 连接成功了 */
if((nbytes=read(sockfd,buff,1024))==-1)
{
fprintf(stderr,"Read Error:%s\n",strerror(errno));
exit(1);
}
buff[nbytes]='\0';
printf("I have received:%s\n",buff);
/******* 发送指令 ********/
bzero(buff,1024);
// 指令ID
int order = 0x0010;
int order_h = order >> 8;
buff[0] = (char)order_h;
buff[1] = (char)order;
// 文件长度
unsigned long len = get_file_size(filePath);
printf("file size = %lu\n", len);
// 高16位
int len_h = len >> 16;
int len_h_1 = len_h >> 8;
buff[2] = (char)len_h_1;
buff[3] = (char)len_h;
// 低16位
int len_l = len;
int len_l_1 = len_l >> 8;
buff[4] = (char)len_l_1;
buff[5] = (char)len_l;
// 文件名称
char* fileName = get_file_name(filePath);
printf("file name = %s\n", fileName);
strncpy(&buff[6], fileName, strlen(fileName));
write(sockfd,buff,1024);
/******* 发送文件 ********/
printf("file path = %s\n", filePath);
FILE* pf = fopen(filePath, "rb");
if(pf == NULL) {
printf("open file failed!\n");
exit(0);
}
char pack[PACK_SIZE] = {'\0'};
while((len = fread(pack, sizeof(char), PACK_SIZE, pf)) > 0)
{
system("clear");
printf("send data size = %d \t", len);
write(sockfd, pack, len);
bzero(pack,PACK_SIZE);
//sleep(1);
}
/* 结束通讯 */
close(sockfd);
exit(0);
}
char* get_file_name(char* fn)
{
int last = 0;
char* pfn = fn+strlen(fn)-1;
int i=0;
for(i=0; i<strlen(fn); ++i)
{
if(*pfn-- == '/')
{
last = strlen(fn)-i;
break;
}
}
char* name = (char*)malloc(sizeof(char)*256);
char* pname = name;
int j=0;
for(j=last; j<strlen(fn); ++j, ++pname)
{
*pname = fn[j];
}
return name;
}
unsigned long get_file_size(const char *path)
{
unsigned int filesize = 0;
struct stat statbuff;
if(stat(path, &statbuff) < 0) {
printf("Get file stat failed!\n");
return filesize;
}else{
filesize = statbuff.st_size;
}
return filesize;
}
|
C
|
#ifndef STRUCTS_H
#define STRUCTS_H
/**
* guarda coordenadas de um ponto no mapa
**/
typedef struct Point{
int row;
int column;
} Point;
/**
* guarda as coordenadas de um ponto, o custo para o atingir
* partindo da origem e um ponteiro para o Node do ponto que o
* precede. aquando a sua inserção no acervo é lhe atribuido um
* indice que facilita acessos futuros
*/
typedef struct Node{
struct Node *parent;
Point coords;
int cost;
int ix;
} Node;
/**
* tipo usado para gurdar a lista prioritaria.
* mantem a um int com a sua dimensao e a lista
* esta implementada como um acervo assente num
* vetor de ponteiros para Node's, acima descritos
*/
typedef struct PQueue{
int size;
Node **heap;
} PQueue;
/**
* no para uma lista simplesmente ligada destinada
* a registar caminhos
*/
typedef struct Path{
Point coords;
struct Path *next;
} Path;
/**
*
*/
typedef struct Edge{
int cost;
int num_points;
Path *path;
} Edge;
typedef struct HyperNode{
Edge **edges;
} HyperNode;
Node *createNode(Node *parent, int _row, int _column,
int **map);
PQueue *createQueue( int _height, int _width);
void freeQueue(PQueue *q);
void insert(PQueue *q, Node *p);
void popRoot(PQueue *q);
void heapifyDown(PQueue *q, int ix);
int smallerChildIndex( int ix, PQueue *q);
int swapChildIndex( int ix, PQueue *q);
int leftChildIndex( int ix);
int rightChildIndex( int ix);
char hasLeftChild( int ix, PQueue *q);
char hasRightChild( int ix, PQueue *q);
void heapifyUp(PQueue *q, int ix);
void swapParent( int ix, Node **heap);
void swap( int ix0, int ix1, Node **heap);
int pointCost( int ix, Node **heap);
int parentCost( int ix, Node **heap);
int parentIndex( int ix);
char empty(PQueue *q);
int currentCost(Node *p);
int newCost( int **map, Node *src, Point *dest);
int heapNodeCost( int ix, Node **heap);
Path *createPath(Node *cur, Path *previous, int _origin_row, int _origin_column, int *num_points);
Path *reversePath(Path *previous_path, int **tur_points, int new_dest_ix, int new_src_ix);
Path *initPath(int row, int column, Path *next);
Path *traversePath(Path *previous, int **tur_points, int new_src_ix, Path *old);
Edge *createEdge(Path *p, int cost, int num_points);
void initHyperNode(int ix, HyperNode *graph, int **map, int num_tur_points, int **tur_points);
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "arguments.h"
int num_ini_seq = 5;
double selection_rate = 0.0;
double M = 10.0;
void parseArguments(int argc, char **argv)
{
char *c;
int seed = time(NULL);
for (argc--;argc>0;argc--) {
c = argv[argc];
while (1) {
if (strncmp("seed=",c,5)==0) {
seed = atoi(c+5);
break;
}
if (strncmp("m=",c,2)==0) {
M = strtod(c+2,NULL);
break;
}
if (strncmp("n=",c,2)==0) {
num_ini_seq = atoi(c+2);
break;
}
if (strncmp("s=",c,2)==0) {
selection_rate = strtod(c+2,NULL);
break;
}
printf("Bad parameter %s\n",c);
exit(0);
break;
}
}
srand(seed);
srand48(seed);
}
|
C
|
#include <stdio.h>
#include <unistd.h>
int main(void){
printf("before fork\n");
fflush(stdout);
pid_t pid = fork();
if(pid > 0) {
// parent
printf("parent\n");
} else if(!pid) {
// child
// default pattern for fork()
printf("child\n");
execlp("lsaa", "ls", NULL);
_exit(1); // <- обязательно _exit(1)
}
printf("after\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/Copia a string str1 para a str2 sem o ultimo caractere/
void copyString(char *str1, char*str2) {
int n = strlen(str1), i;
for(i=0;i<n-1;i++){
str2[i] = str1[i];
}
str2[i] = '\0';
}
int main () {
FILE *fp1, *fp2;
char nomeArquivo[30], nomeArquivoNovo[30], string_lida[100], aux[100];
int cod, flag=0;
float media=0;
printf("Informe o nome do arquivo do programa anterior: ");
scanf("%s", nomeArquivo);
fp1 = fopen(nomeArquivo, "r+");
printf("Informe o nome do arquivo que ira calcular as medias: ");
scanf("%s", nomeArquivoNovo);
fp2 = fopen(nomeArquivoNovo, "w");
if (fp1 != NULL) {
while (fscanf(fp1, "%s", string_lida) > 0) {
if(string_lida[(strlen(string_lida)-1)] == ',' || string_lida[(strlen(string_lida)-1)] == '.') {
if(flag == 0) {
flag=1;
} else {
copyString(string_lida, aux);
cod = atoi(aux);
fscanf(fp1, "%s", string_lida);
copyString(string_lida, aux);
media += atof(aux);
fscanf(fp1, "%s", string_lida);
copyString(string_lida, aux);
media += atof(aux);
fscanf(fp1, "%s", string_lida);
copyString(string_lida, aux);
media += atof(aux);
fprintf(fp2, "%d, %.2f.\n", cod, media/3);
media = 0;
flag=0;
}
}
}
printf("Fim do programa\n");
fclose(fp2);
} else {
printf("Arquivo nao encontrado!\nFim do programa\n");
}
fclose(fp1);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* server.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: drabahi <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2014/02/08 19:25:28 by drabahi #+# #+# */
/* Updated: 2014/02/09 17:32:33 by drabahi ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include "server.h"
void ft_sigaction_init(void)
{
struct sigaction act;
ft_bzero(&act, sizeof(act));
act.sa_sigaction = &ft_sigusr1_callback;
act.sa_flags = SA_SIGINFO;
sigaction(SIGUSR1, &act, NULL);
ft_bzero(&act, sizeof(act));
act.sa_sigaction = &ft_sigusr2_callback;
act.sa_flags = SA_SIGINFO;
sigaction(SIGUSR2, &act, NULL);
}
void ft_sigaction_ignore(void)
{
struct sigaction act;
ft_bzero(&act, sizeof(act));
act.sa_handler = SIG_IGN;
sigaction(SIGUSR1, &act, NULL);
sigaction(SIGUSR2, &act, NULL);
}
void ft_sigusr1_callback(int signum, siginfo_t *siginfo, void *context)
{
t_flux *flux;
if (siginfo->si_pid == 0)
return ;
flux = ft_singleton_flux(SINGLETON_GET, NULL);
if (signum == FT_SIGZERO && siginfo->si_pid != 0)
{
ft_refresh_flux(0, flux);
usleep(1);
kill((pid_t)siginfo->si_pid, SIGUSR2);
}
(void)context;
}
void ft_sigusr2_callback(int signum, siginfo_t *siginfo, void *context)
{
t_flux *flux;
if (siginfo->si_pid == 0)
return ;
flux = ft_singleton_flux(SINGLETON_GET, NULL);
if (signum == FT_SIGONE && siginfo->si_pid != 0)
{
ft_refresh_flux(1, flux);
usleep(1);
kill((pid_t)siginfo->si_pid, SIGUSR2);
}
(void)context;
}
int main(void)
{
t_flux *flux;
flux = (t_flux *)malloc(sizeof(t_flux));
flux->server = getpid();
ft_sigaction_init();
ft_printf("SERVER PID => %d\n", flux->server);
while (42)
{
ft_init_flux(flux);
while (42)
{
pause();
if (flux->index != 0 && flux->buffer[flux->index - 1] == 0)
break ;
}
ft_putendl(flux->buffer);
free(flux->buffer);
flux->buffer = NULL;
}
free(flux);
return (0);
}
|
C
|
#include <stdio.h> // libreria estandar
#include <stdlib.h> // para usar exit y funciones de la libreria standard
#include <string.h>
#include <pthread.h> // para usar threads
#include <semaphore.h> // para usar semaforos
#include <unistd.h>
#define LIMITE 50
pthread_mutex_t mutex1;
pthread_mutex_t mutex2;
pthread_mutex_t mutex3;
int equipoganador= 0;
//creo estructura de semaforos
struct semaforos {
sem_t sem_cortarextra;
sem_t sem_hornearpan;
sem_t sem_cortar;
sem_t sem_mezclar;
sem_t sem_salar;
sem_t sem_armarmedallon;
sem_t sem_cocinar;
sem_t sem_armarhamburguesa;
sem_t sem_armarhamburguesa_aux;
sem_t sem_armarhamburguesa_aux2;
//poner demas semaforos aqui
};
//creo los pasos con los ingredientes
struct paso {
char accion [LIMITE];
char ingredientes[4][LIMITE];
};
//creo los parametros de los hilos
struct parametro {
int equipo_param;
struct semaforos semaforos_param;
struct paso pasos_param[8];
};
//funcion para imprimir las acciones y los ingredientes de la accion
void* imprimirAccion(void *data, char *accionIn) {
FILE* resul;
resul = fopen("resultado.txt", "a");
struct parametro *mydata = data;
//calculo la longitud del array de pasos
int sizeArray = (int)( sizeof(mydata->pasos_param) / sizeof(mydata->pasos_param[0]));
//indice para recorrer array de pasos
int i;
for(i = 0; i < sizeArray; i ++){
//pregunto si la accion del array es igual a la pasada por parametro (si es igual la funcion strcmp devuelve cero)
if(strcmp(mydata->pasos_param[i].accion, accionIn) == 0){
printf("\tEquipo %d - accion %s \n " , mydata->equipo_param, mydata->pasos_param[i].accion);
fprintf(resul,"\tEquipo %d - accion %s \n " , mydata->equipo_param, mydata->pasos_param[i].accion);
//calculo la longitud del array de ingredientes
int sizeArrayIngredientes = (int)( sizeof(mydata->pasos_param[i].ingredientes) / sizeof(mydata->pasos_param[i].ingredientes[0]) );
//indice para recorrer array de ingredientes
int h;
//printf("\tEquipo %d -----------ingredientes : ----------\n",mydata->equipo_param);
for(h = 0; h < sizeArrayIngredientes; h++) {
//consulto si la posicion tiene valor porque no se cuantos ingredientes tengo por accion
if(strlen(mydata->pasos_param[i].ingredientes[h]) != 0) {
printf("\tEquipo %d ingrediente %d : %s \n",mydata->equipo_param,h,mydata->pasos_param[i].ingredientes[h]);
fprintf(resul,"\tEquipo %d ingrediente %d : %s \n",mydata->equipo_param,h,mydata->pasos_param[i].ingredientes[h]);
}
}
}
}
fclose(resul);
}
//funcion para tomar de ejemplo
void* armarhamburguesa(void *data) {
//creo el nombre de la accion de la funcion
char *accion = "armarhamburguesa";
//creo el puntero para pasarle la referencia de memoria (data) del struct pasado por parametro (la cual es un puntero).
struct parametro *mydata = data;
sem_wait(&mydata->semaforos_param.sem_armarhamburguesa); //representa P(s_ma).
sem_wait(&mydata->semaforos_param.sem_armarhamburguesa_aux);
sem_wait(&mydata->semaforos_param.sem_armarhamburguesa_aux2);
//llamo a la funcion imprimir le paso el struct y la accion de la funcion
imprimirAccion(mydata,accion);
//uso sleep para simular que que pasa tiempo
usleep( 1000000 );
//doy la señal a la siguiente accion (cortar me habilita mezclar)
if(equipoganador==0){
equipoganador=mydata->equipo_param;
}
pthread_exit(NULL);
}
//funcion para tomar de ejemplo
void* cocinar(void *data) {
pthread_mutex_lock(&mutex2); //entrada a la sección crítica.
//creo el nombre de la accion de la funcion
char *accion = "cocinar";
//creo el puntero para pasarle la referencia de memoria (data) del struct pasado por parametro (la cual es un puntero).
struct parametro *mydata = data;
sem_wait(&mydata->semaforos_param.sem_cocinar); //representa P(s_ma).
//llamo a la funcion imprimir le paso el struct y la accion de la funcion
imprimirAccion(mydata,accion);
//uso sleep para simular que que pasa tiempo
usleep( 1000000 );
//doy la señal a la siguiente accion (cortar me habilita mezclar)
sem_post(&mydata->semaforos_param.sem_armarhamburguesa);
pthread_mutex_unlock(&mutex2); //salida sección crítica.
pthread_exit(NULL);
}
//funcion para tomar de ejemplo
void* armarmedallon(void *data) {
//creo el nombre de la accion de la funcion
char *accion = "armarmedallon";
//creo el puntero para pasarle la referencia de memoria (data) del struct pasado por parametro (la cual es un puntero).
struct parametro *mydata = data;
//llamo a la funcion imprimir le paso el struct y la accion de la funcion
sem_wait(&mydata->semaforos_param.sem_armarmedallon); //representa P(s_ma).
imprimirAccion(mydata,accion);
//uso sleep para simular que que pasa tiempo
usleep( 1000000 );
//doy la señal a la siguiente accion (cortar me habilita mezclar)
sem_post(&mydata->semaforos_param.sem_cocinar);
pthread_exit(NULL);
}
//funcion para tomar de ejemplo
void* salar(void *data) {
pthread_mutex_lock(&mutex1); //entrada a la sección crítica.
//creo el nombre de la accion de la funcion
char *accion = "salar";
//creo el puntero para pasarle la referencia de memoria (data) del struct pasado por parametro (la cual es un puntero).
struct parametro *mydata = data;
sem_wait(&mydata->semaforos_param.sem_salar); //representa P(s_ma).
//llamo a la funcion imprimir le paso el struct y la accion de la funcion
imprimirAccion(mydata,accion);
//uso sleep para simular que que pasa tiempo
usleep( 1000000 );
//doy la señal a la siguiente accion (cortar me habilita mezclar)
sem_post(&mydata->semaforos_param.sem_armarmedallon);
pthread_mutex_unlock(&mutex1); //salida sección crítica.
pthread_exit(NULL);
}
//funcion para tomar de ejemplo
void* mezclar(void *data) {
//creo el nombre de la accion de la funcion
char *accion = "mezclar";
//creo el puntero para pasarle la referencia de memoria (data) del struct pasado por parametro (la cual es un puntero).
struct parametro *mydata = data;
//llamo a la funcion imprimir le paso el struct y la accion de la funcion
sem_wait(&mydata->semaforos_param.sem_mezclar); //representa P(s_ma).
imprimirAccion(mydata,accion);
//uso sleep para simular que que pasa tiempo
usleep( 1000000 );
//doy la señal a la siguiente accion (cortar me habilita mezclar)
//sem_post(&mydata->semaforos_param.sem_salar);
sem_post(&mydata->semaforos_param.sem_salar);
pthread_exit(NULL);
}
//funcion para tomar de ejemplo
void* cortar(void *data) {
//creo el nombre de la accion de la funcion
char *accion = "cortar";
//creo el puntero para pasarle la referencia de memoria (data) del struct pasado por parametro (la cual es un puntero).
struct parametro *mydata = data;
//llamo a la funcion imprimir le paso el struct y la accion de la funcion
sem_wait(&mydata->semaforos_param.sem_cortar); //representa P(s_ma).
imprimirAccion(mydata,accion);
//uso sleep para simular que que pasa tiempo
usleep( 1000000 );
//doy la señal a la siguiente accion (cortar me habilita mezclar)
sem_post(&mydata->semaforos_param.sem_mezclar);
pthread_exit(NULL);
}
//funcion para tomar de ejemplo
void* cortarextra(void *data) {
//creo el nombre de la accion de la funcion
char *accion = "cortarextra";
//creo el puntero para pasarle la referencia de memoria (data) del struct pasado por parametro (la cual es un puntero).
struct parametro *mydata = data;
sem_wait(&mydata->semaforos_param.sem_cortarextra); //representa P(s_ma).
//llamo a la funcion imprimir le paso el struct y la accion de la funcion
imprimirAccion(mydata,accion);
//uso sleep para simular que que pasa tiempo
usleep( 1000000 );
//doy la señal a la siguiente accion (cortar me habilita mezclar)
sem_post(&mydata->semaforos_param.sem_armarhamburguesa_aux);
pthread_exit(NULL);
}
//funcion para tomar de ejemplo
void* hornearpan(void *data) {
pthread_mutex_lock(&mutex3); //entrada a la sección crítica.
//creo el nombre de la accion de la funcion
char *accion = "hornearpan";
//creo el puntero para pasarle la referencia de memoria (data) del struct pasado por parametro (la cual es un puntero).
struct parametro *mydata = data;
sem_wait(&mydata->semaforos_param.sem_hornearpan); //representa P(s_ma).
//llamo a la funcion imprimir le paso el struct y la accion de la funcion
imprimirAccion(mydata,accion);
//uso sleep para simular que que pasa tiempo
usleep( 1000000 );
pthread_mutex_unlock(&mutex3); //salida sección crítica.
//doy la señal a la siguiente accion (cortar me habilita mezclar)
sem_post(&mydata->semaforos_param.sem_armarhamburguesa_aux2);
pthread_exit(NULL);
}
void* mostrar_ganador() {
FILE* resul;
resul = fopen("resultado.txt", "a");
printf("\n ----------------Equipo Ganador: %d ---------------- \n",equipoganador);
fprintf(resul,"\nEquipo Ganador: %d \n",equipoganador);
fclose(resul);
}
void* ejecutarReceta(void *i) {
//variables semaforos
sem_t sem_cortarextra;
sem_t sem_hornearpan;
sem_t sem_cortar;
sem_t sem_mezclar;
sem_t sem_salar;
sem_t sem_armarmedallon;
sem_t sem_cocinar;
sem_t sem_armarhamburguesa;
sem_t sem_armarhamburguesa_aux;
sem_t sem_armarhamburguesa_aux2;
//crear variables semaforos aqui
//variables hilos
pthread_t p1;
pthread_t p2;
pthread_t p3;
pthread_t p4;
pthread_t p5;
pthread_t p6;
pthread_t p7;
pthread_t p8;
//crear variables hilos aqui
//numero del equipo (casteo el puntero a un int)
int p = *((int *) i);
printf("Ejecutando equipo %d \n", p);
//reservo memoria para el struct
struct parametro *pthread_data = malloc(sizeof(struct parametro));
//seteo los valores al struct
//seteo numero de grupo
pthread_data->equipo_param = p;
//seteo semaforos
pthread_data->semaforos_param.sem_mezclar = sem_cortarextra;
pthread_data->semaforos_param.sem_mezclar = sem_hornearpan;
pthread_data->semaforos_param.sem_mezclar = sem_cortar;
pthread_data->semaforos_param.sem_mezclar = sem_mezclar;
pthread_data->semaforos_param.sem_salar = sem_salar;
pthread_data->semaforos_param.sem_cocinar = sem_cocinar;
pthread_data->semaforos_param.sem_armarmedallon = sem_armarmedallon;
pthread_data->semaforos_param.sem_armarhamburguesa = sem_armarhamburguesa;
pthread_data->semaforos_param.sem_armarhamburguesa = sem_armarhamburguesa_aux;
pthread_data->semaforos_param.sem_armarhamburguesa = sem_armarhamburguesa_aux2;
//setear demas semaforos al struct aqui
FILE *archivo;
archivo = fopen("pasos.txt", "r");
if (archivo == NULL)
{
exit(EXIT_FAILURE);
}
char * line = NULL;
size_t len = 0;
ssize_t read;
int linea=0;
while ((read = getline(&line, &len, archivo)) != -1) { //-1 es que se termino
int init_size = strlen(line);
int i = 0;
char *ptr = strtok(line,";");
while (ptr != NULL)
{
if(i ==0){
strcpy(pthread_data->pasos_param[linea].accion, ptr);
ptr = strtok(NULL, ";");
}else{
strcpy(pthread_data->pasos_param[linea].ingredientes[i], ptr);
ptr = strtok(NULL, ";");
}
i++;
}
linea++;
}
fclose(archivo);
//seteo las acciones y los ingredientes (Faltan acciones e ingredientes) ¿Se ve hardcodeado no? ¿Les parece bien?
/* strcpy(pthread_data->pasos_param[0].accion, "cortar");
strcpy(pthread_data->pasos_param[0].ingredientes[0], "ajo");
strcpy(pthread_data->pasos_param[0].ingredientes[1], "perejil");
strcpy(pthread_data->pasos_param[0].ingredientes[2], "cebolla");
strcpy(pthread_data->pasos_param[1].accion, "mezclar");
strcpy(pthread_data->pasos_param[1].ingredientes[0], "ajo");
strcpy(pthread_data->pasos_param[1].ingredientes[1], "perejil");
strcpy(pthread_data->pasos_param[1].ingredientes[2], "cebolla");
strcpy(pthread_data->pasos_param[1].ingredientes[3], "carne picada");
strcpy(pthread_data->pasos_param[3].accion, "salar");
strcpy(pthread_data->pasos_param[4].accion, "armarmedallon");
strcpy(pthread_data->pasos_param[4].accion, "cocinar");
strcpy(pthread_data->pasos_param[5].accion, "hornearpan");
strcpy(pthread_data->pasos_param[6].accion, "cortarextra");
strcpy(pthread_data->pasos_param[7].accion, "armarhamburguesa");
*/
//inicializo los semaforos
sem_init(&(pthread_data->semaforos_param.sem_cortarextra),0,1);
sem_init(&(pthread_data->semaforos_param.sem_hornearpan),0,1);
sem_init(&(pthread_data->semaforos_param.sem_cortar),0,1);
sem_init(&(pthread_data->semaforos_param.sem_mezclar),0,0);
sem_init(&(pthread_data->semaforos_param.sem_salar),0,0);
sem_init(&(pthread_data->semaforos_param.sem_armarmedallon),0,0);
sem_init(&(pthread_data->semaforos_param.sem_cocinar),0,0);
sem_init(&(pthread_data->semaforos_param.sem_armarhamburguesa),0,0);
sem_init(&(pthread_data->semaforos_param.sem_armarhamburguesa_aux),0,0);
sem_init(&(pthread_data->semaforos_param.sem_armarhamburguesa_aux2),0,0);
//inicializar demas semaforos aqui
//creo los hilos a todos les paso el struct creado (el mismo a todos los hilos) ya que todos comparten los semaforos
int rc;
rc = pthread_create(&p1, //identificador unico
NULL, //atributos del thread
cortarextra, //funcion a ejecutar
pthread_data); //parametros de la funcion a ejecutar, pasado por referencia
//crear demas hilos aqui
rc = pthread_create(&p2, //identificador unico
NULL, //atributos del thread
hornearpan, //funcion a ejecutar
pthread_data); //parametros de la funcion a ejecutar, pasado por referencia
rc = pthread_create(&p3, //identificador unico
NULL, //atributos del thread
cortar, //funcion a ejecutar
pthread_data); //parametros de la funcion a ejecutar, pasado por referencia
rc = pthread_create(&p4, //identificador unico
NULL, //atributos del thread
mezclar, //funcion a ejecutar
pthread_data); //parametros de la funcion a ejecutar, pasado por referencia
//crear demas hilos aqui
rc = pthread_create(&p5, //identificador unico
NULL, //atributos del thread
salar, //funcion a ejecutar
pthread_data); //parametros de la funcion a ejecutar, pasado por referencia
rc = pthread_create(&p6, //identificador unico
NULL, //atributos del thread
armarmedallon, //funcion a ejecutar
pthread_data); //parametros de la funcion a ejecutar, pasado por referencia
rc = pthread_create(&p7, //identificador unico
NULL, //atributos del thread
cocinar, //funcion a ejecutar
pthread_data); //parametros de la funcion a ejecutar, pasado por referencia
//crear demas hilos aqui
rc = pthread_create(&p8, //identificador unico
NULL, //atributos del thread
armarhamburguesa, //funcion a ejecutar
pthread_data); //parametros de la funcion a ejecutar, pasado por referencia
//join de todos los hilos
pthread_join (p1,NULL);
pthread_join (p2,NULL);
pthread_join (p3,NULL);
pthread_join (p4,NULL);
pthread_join (p5,NULL);
pthread_join (p6,NULL);
pthread_join (p7,NULL);
pthread_join (p8,NULL);
//crear join de demas hilos
//valido que el hilo se alla creado bien
if (rc){
printf("Error:unable to create thread, %d \n", rc);
exit(-1);
}
//destruccion de los semaforos
sem_destroy(&sem_cortarextra);
sem_destroy(&sem_hornearpan);
sem_destroy(&sem_cortar);
sem_destroy(&sem_mezclar);
sem_destroy(&sem_salar);
sem_destroy(&sem_armarmedallon);
sem_destroy(&sem_cocinar);
sem_destroy(&sem_armarhamburguesa);
sem_destroy(&sem_armarhamburguesa_aux);
sem_destroy(&sem_armarhamburguesa_aux2);
//destruir demas semaforos
//salida del hilo
pthread_exit(NULL);
}
int main ()
{
//creo los nombres de los equipos
int rc;
int *equipoNombre1 =malloc(sizeof(*equipoNombre1));
int *equipoNombre2 =malloc(sizeof(*equipoNombre2));
int *equipoNombre3 =malloc(sizeof(*equipoNombre3));
*equipoNombre1 = 1;
*equipoNombre2 = 2;
*equipoNombre3 = 3;
pthread_mutex_init ( &mutex1, NULL); //se inicializa el mutex.
pthread_mutex_init ( &mutex2, NULL); //se inicializa el mutex.
pthread_mutex_init ( &mutex3, NULL); //se inicializa el mutex.
//creo las variables los hilos de los equipos
pthread_t equipo1;
pthread_t equipo2;
pthread_t equipo3;
//inicializo los hilos de los equipos
rc = pthread_create(&equipo1, //identificador unico
NULL, //atributos del thread
ejecutarReceta, //funcion a ejecutar
equipoNombre1);
rc = pthread_create(&equipo2, //identificador unico
NULL, //atributos del thread
ejecutarReceta, //funcion a ejecutar
equipoNombre2);
rc = pthread_create(&equipo3, //identificador unico
NULL, //atributos del thread
ejecutarReceta, //funcion a ejecutar
equipoNombre3);
if (rc){
printf("Error:unable to create thread, %d \n", rc);
exit(-1);
}
//join de todos los hilos
pthread_join (equipo1,NULL);
pthread_join (equipo2,NULL);
pthread_join (equipo3,NULL);
pthread_mutex_destroy(&mutex1);
pthread_mutex_destroy(&mutex2);
pthread_mutex_destroy(&mutex3);
mostrar_ganador();
pthread_exit(NULL);
}
//Para compilar: gcc HellsBurgers.c -o ejecutable -lpthread
//Para ejecutar: ./ejecutable
|
C
|
#include<stdio.h>
#include<math.h>
main()
{
int x,y,i,z,n = 0;
float arr[10];
float a = 0.0;
printf("Vavedete chisloto\n");
scanf("%d",&x);
for(i = 0; i < 10; i++)
{
for(z=x*n; (z < (n+1)*x); z++)
{
a = a + cos(z);
}
arr[i] = a;
n = n+1;
}
for(i=0; i < 10; i++)
{
printf("Arr{%d} : %f\n", i, arr[i]);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define ESPACO 5
typedef struct ArvoreBinaria{
int valor;
struct ArvoreBinaria * esquerda;
struct ArvoreBinaria * direita;
} Arvore;
// Funções pedidas no trabalho
//As comentadas estão faltando
Arvore * loadTreeFromFile(char *path);
void showTree(Arvore *arvore);
void isFull(Arvore *arvore);
void searchValue(Arvore *arvore, int valor);
void getHeight(Arvore *arvore);
Arvore * removeValue(Arvore *arvore, int value);
void printInOrder(Arvore *arvore);
void printPreOrder(Arvore *arvore);
void printPostOrder(Arvore *arvore);
Arvore * balanceTree(Arvore *arvore);
//Funções criadas para auxilio no programa
Arvore * busca(Arvore *arvore, int valor, int *aux); //busca valor e retorna nível de seu nó ao aux
int altura(Arvore *arvore);
Arvore * iniciar_arvore(int valor);
void insere_valor(Arvore * item, int valor);
void imprimeLinha(Arvore *arvore, int depth, char *path, int direita);
int tamanho(Arvore *arvore);
void imprimeNo(char c, int b);
bool isFullBool(Arvore *arvore, int index, int nodes);
int contaNos(Arvore *arvore);
void freeTree(Arvore * arvore);
bool isBalanced(Arvore *arvore);
void rotacionaDireita(Arvore *avo, Arvore *pai, Arvore *filho);
void rotacionaEsquerda(Arvore *avo, Arvore *pai, Arvore *filho);
Arvore * makeBackbone(Arvore *arvore, Arvore *avo, Arvore *pai, Arvore *filho);
void imprimiArvore(Arvore *arvore, int altura, int nivel);
void imprimi_elementos(Arvore *arvore, int altura, int nivel, int nivel_atual);
int espacos_esquerda(int atura, int nivel);
int espacos_entre_elementos(int atura, int nivel);
void imprimi_barras(Arvore *arvore, int altura, int nivel, int nivel_atual);
int main(){
Arvore *arvore = NULL;
arvore = NULL;
int opcao;
do{
printf("\n\n\n");
printf("1. Carrega arvore a partir de arquivo\n");
printf("2. Mostra árvore carregada\n");
printf("3. Verifica se árvore é cheia ou não\n");
printf("4. Procura valor na árvore (É mostrado valor pai, nível, e irmão caso possua)\n");
printf("5. Mostra altura da árvore\n");
printf("6. Remove valor da árvore\n");
printf("7. Printa valores usando algorítimo in order\n");
printf("8. Printa valores usando algorítimo pre order\n");
printf("9. Printa valores usando algorítimo post order\n");
printf("10. Realiza balanceamento da ávore carregada\n");
printf("0. Fecha programa\n");
scanf("%d", &opcao);
printf("\n\n\n");
switch(opcao){
case 1:
{
char path[500];
printf("Escreva o nome do arquivo: ./");
scanf("%s", path);
arvore = loadTreeFromFile(path);
break;
}
case 2:
showTree(arvore);
break;
case 3:
isFull(arvore);
break;
case 4:
{
int value;
printf("Escreva o valor que será buscado:");
scanf("%d", &value);
searchValue(arvore, value);
break;
}
case 5:
getHeight(arvore);
break;
case 6:
{
int value;
printf("Escreva o valor que será removido:");
scanf("%d", &value);
arvore = removeValue(arvore, value);
break;
}
case 7:
printInOrder(arvore);
break;
case 8:
printPreOrder(arvore);
break;
case 9:
printPostOrder(arvore);
break;
case 10:
{
arvore = balanceTree(arvore);
}
}
}while(opcao!=0);
freeTree(arvore);
return 0;
}
void rotacionaDireita(Arvore *avo, Arvore *pai, Arvore *filho){
if(avo != NULL){
if(avo->esquerda == pai)
avo->esquerda = filho;
else
avo->direita = filho;
}
pai->esquerda = filho->direita;
filho->direita = pai;
}
void rotacionaEsquerda(Arvore *avo, Arvore *pai, Arvore *filho){
if(avo != NULL){
if(avo->esquerda == pai)
avo->esquerda = filho;
else
avo->direita = filho;
}
pai->direita = filho->esquerda;
filho->esquerda = pai;
}
Arvore * makeBackbone(Arvore *arvore, Arvore *avo, Arvore *pai, Arvore *filho){
if(arvore==NULL)
return NULL;
if(filho==NULL){
arvore = makeBackbone(arvore, avo, pai, arvore);
}
//Tem filho a esquerda?
if(filho->esquerda != NULL){
//É raiz?
if(filho==arvore){
pai=filho;
filho=filho->esquerda;
rotacionaDireita(avo, pai, filho);
arvore = makeBackbone(filho, avo, pai, filho);
}
else{
pai=filho;
filho=filho->esquerda;
rotacionaDireita(avo, pai, filho);
arvore = makeBackbone(arvore, avo, pai, filho);
}
}
else{
if(avo==filho){
//Tem filho a direita?
if(filho->direita != NULL){
filho=filho->direita;
arvore = makeBackbone(arvore, avo, pai, filho);
}
else{
return arvore;
}
}
else{
avo=filho;
arvore = makeBackbone(arvore, avo, pai, filho);
}
}
return arvore;
}
Arvore * balanceTree(Arvore *arvore){
if(isBalanced(arvore)){
printf("A árvore já está balanceada\n");
return arvore;
}
else{
printf("A árvore foi balanceada\n");
Arvore *aux;
aux = makeBackbone(arvore, NULL, NULL, arvore);
return aux;
}
}
bool isBalanced(Arvore *arvore){
if(arvore == NULL)
return true;
int lh = altura(arvore->esquerda);
int rh = altura(arvore->direita);
if(abs(lh-rh) <= 1 &&
isBalanced(arvore->esquerda) &&
isBalanced(arvore->direita)
)
return true;
return false;
}
void freeTree(Arvore * arvore){
if(arvore==NULL){
return;
}
freeTree(arvore->esquerda);
freeTree(arvore->direita);
free(arvore);
}
Arvore * loadTreeFromFile(char *path){
FILE *arquivo;
arquivo = fopen(path, "r");
if (arquivo == NULL){
printf("Erro na leitura do arquivo\n");
return NULL;
}
int value;
Arvore *arvore;
if(fscanf(arquivo,"%d", &value)!=EOF){
arvore = iniciar_arvore(value);
//printf("Criando arvore com %d...\n", value);
}
else
return NULL;
while(fscanf(arquivo,"%d", &value)!=EOF){
insere_valor(arvore, value);
}
return arvore;
}
bool isFullBool(Arvore *arvore, int index, int nodes){
if (arvore == NULL)
return true;
if (index >= nodes)
return false;
return (isFullBool(arvore->esquerda, 2*index + 1, nodes) &&
isFullBool(arvore->direita, 2*index + 2, nodes)
);
}
void isFull(Arvore *arvore){
int nodes = contaNos(arvore);
if(isFullBool(arvore, 0, nodes))
printf("A arvore é cheia\n");
else
printf("A arvore não é cheia\n");
}
int contaNos(Arvore *arvore){
if (arvore == NULL)
return 0;
return (1 + contaNos(arvore->esquerda) + contaNos(arvore->direita));
}
Arvore * iniciar_arvore(int valor){
Arvore *nova_arvore;
nova_arvore = (Arvore *) malloc(sizeof(Arvore));
if(nova_arvore==NULL){
printf("Alocação falhou\n");
exit(-1);
}
nova_arvore->esquerda = NULL;
nova_arvore->direita = NULL;
nova_arvore->valor = valor;
return nova_arvore;
}
void insere_valor(Arvore * arvore, int valor){
if(valor == arvore->valor)
return;
else if(valor > arvore->valor){
if(arvore->direita==NULL){
//printf("%d > %d\n", valor, arvore->valor);
Arvore *novo_valor;
novo_valor=iniciar_arvore(valor);
arvore->direita=novo_valor;
//printf("Inserindo %d a direita...\n", valor);
}
else{
insere_valor(arvore->direita, valor);
}
}
else{
if(arvore->esquerda==NULL){
//printf("%d < %d\n", valor, arvore->valor);
Arvore *novo_valor;
novo_valor=iniciar_arvore(valor);
arvore->esquerda=novo_valor;
//printf("Inserindo %d a esquerda...\n", valor);
}
else{
insere_valor(arvore->esquerda, valor);
}
}
}
Arvore * removeValue(Arvore *arvore, int value){
int i=1;
Arvore * delete = busca(arvore, value, &i);
if(delete==NULL){
printf("O valor não foi encontrado para o excluir\n");
return arvore;
}
if(delete==arvore){
if(arvore->direita==NULL && arvore->esquerda==NULL){
free(arvore);
return NULL;
}
else if(arvore->direita==NULL && arvore->esquerda!=NULL){
free(delete);
return arvore->esquerda;
}
else if(arvore->direita!=NULL && arvore->esquerda==NULL){
free(delete);
return arvore->direita;
}
else{
Arvore *i=arvore->direita;
if(i->esquerda == NULL){
i->esquerda=arvore->esquerda;
free(arvore);
return i;
}
else{
for(; i->esquerda->esquerda != NULL; i=i->esquerda);
arvore->valor=i->esquerda->valor;
Arvore *aux=i->esquerda;;
i->esquerda=NULL;
free(aux);
}
}
}
else{
//printf("Elemento\n");
Arvore *aux;
if(delete->esquerda != NULL && delete->esquerda->valor == value){
//printf("Elemento da esquerda\n");
aux=delete->esquerda;
if(aux->direita == NULL && aux->esquerda == NULL){
delete->esquerda=NULL;
free(aux);
}
else if(aux->direita == NULL && aux->esquerda != NULL){
delete->esquerda=aux->esquerda;
free(aux);
}
else if(aux->direita != NULL && aux->esquerda == NULL){
delete->esquerda=aux->direita;
free(aux);
}
else{
Arvore *i;
for(i=aux->direita; i->esquerda->esquerda != NULL; i=i->esquerda);
aux->valor=i->esquerda->valor;
aux=i->esquerda;
i->esquerda=NULL;
free(aux);
}
}
else{
//printf("Elemento da direita\n");
aux=delete->direita;
if(aux->direita == NULL && aux->esquerda == NULL){
delete->direita=NULL;
free(aux);
}
else if(aux->direita == NULL && aux->esquerda != NULL){
delete->direita=aux->esquerda;
free(aux);
}
else if(aux->direita != NULL && aux->esquerda == NULL){
delete->direita=aux->direita;
free(aux);
}
else{
Arvore *i;
for(i=aux->direita; i->esquerda->esquerda != NULL; i=i->esquerda);
aux->valor=i->esquerda->valor;
aux=i->esquerda;
i->esquerda=NULL;
free(aux);
}
}
}
return arvore;
}
void searchValue(Arvore *arvore, int valor){
int i=1;
Arvore * aux = busca(arvore, valor, &i);
if(aux!=NULL){
if(arvore == aux){
printf("Valor encontrado\n");
printf("O valor é a raiz da árvora, portanto não tem pai nem irmãos\n");
}
else{
printf("Valor encontrado\n");
printf("Valor do pai %d\n", aux->valor);
if(aux->direita != NULL && aux->direita->valor != valor){
printf("Valor do irmão %d\n", aux->direita->valor);
}
else if(aux->esquerda != NULL && aux->esquerda->valor != valor){
printf("Valor do irmão %d\n", aux->esquerda->valor);
}
printf("Nível do seu nó:%d\n", i);
}
}
else{
printf("O valor não foi encontrado\n");
}
}
Arvore * busca(Arvore *arvore, int valor, int *aux){
(*aux)++;
if(valor<arvore->valor){
if(arvore->esquerda != NULL){
if(arvore->esquerda->valor==valor)
return arvore;
else
busca(arvore->esquerda, valor, aux);
}
else
return NULL;
}
else if(valor>arvore->valor){
if(arvore->direita != NULL){
if(arvore->direita->valor==valor)
return arvore;
else
busca(arvore->direita, valor, aux);
}
else
return NULL;
}
else
return arvore;
}
void showTree(Arvore *arvore){
//int tam = tamanho(arvore);
int h = altura(arvore);
int nivel = 1;
//char path[255] = {};
// imprimeLinha(arvore, 0, path, 0); // função de imprimir a arvore na horizontal
imprimiArvore (arvore, h, nivel);
printf("\n");
}
void imprimiArvore(Arvore *arvore, int altura, int nivel){
int qnt_espacos_esqueda = espacos_esquerda(altura, nivel)+1;
for (int i=0; i<qnt_espacos_esqueda; i++)
printf(" ");
imprimi_elementos(arvore, altura, nivel, 1);
if (altura == nivel)
return;
printf("\n");
int espacos = espacos_esquerda(altura, nivel)/2;
for (int i=0; i<espacos; i++){
printf(" ");
}
imprimi_barras (arvore, altura, nivel, 1);
printf("\n");
return imprimiArvore (arvore, altura, nivel+1);
}
void imprimi_elementos(Arvore *arvore, int altura, int nivel, int nivel_atual){
if (nivel == 1){
printf("%d", arvore->valor);
return;
}
if (arvore == NULL){
// if (nivel == nivel_atual)
printf(" ");
for (int i=nivel_atual; i<=nivel; i++){
int espacos = espacos_entre_elementos(altura, nivel)+1; //imprimi os espaços entre os dois elementos
for (int i=0; i<espacos; i++){
printf(" ");
}
}
return;
}
if (nivel == nivel_atual){
printf("%d", arvore->valor);
int espacos = espacos_entre_elementos(altura, nivel)+1; //imprimi os espaços entre os dois elementos
for (int i=0; i<espacos; i++){
printf(" ");
}
return;
}
else {
imprimi_elementos(arvore->esquerda, altura, nivel, nivel_atual+1);
// if (nivel == nivel_atual+1){
// int espacos = espacos_entre_elementos(altura, nivel); //imprimi os espaços entre os dois elementos
// for (int i=0; i<espacos; i++){
// printf(" ");
// }
// }
imprimi_elementos(arvore->direita, altura, nivel, nivel_atual+1);
// if (nivel == nivel_atual+1){
// int espacos = espacos_entre_elementos(altura, nivel)+2; //imprimi os espaços entre dois nos
// for (int i=0; i<espacos; i++){
// printf(" ");
// }
// }
return;
}
}
int espacos_esquerda(int altura, int nivel){
if (altura == nivel)
return 0;
return (espacos_esquerda(altura, nivel+1)+1)*2;
}
int espacos_entre_elementos(int altura, int nivel){
if (altura == nivel)
return 2;
return (espacos_entre_elementos(altura, nivel+1)+1)*2;
}
void imprimi_barras(Arvore *arvore, int altura, int nivel, int nivel_atual){
if (nivel == 1){
if (arvore->esquerda != NULL)
printf("/");
else
printf(" ");
int espaco = espacos_entre_elementos (altura, nivel+1); // calculando o espaço entre as barras
// printf("teste16\n");
for (int i = 0; i<espaco; ++i)
printf(" ");
if (arvore->direita != NULL)
printf("\\");
else
printf(" ");
return;
}
if (arvore == NULL){
// if (nivel == nivel_atual)
printf(" "); // representando o espaço da primeira barra
for (int i=nivel_atual; i<=nivel; i++){
int espaco = espacos_entre_elementos (altura, nivel+1); // calculando o espaço entre as barras
for (int i = 0; i<espaco; ++i)
printf(" ");
}
printf(" "); // representando o espaço da segunda barra
int espaco = espacos_entre_elementos(altura, nivel+1)+2; //calculando o espaço entre um conjunto de barras
for (int i = 0; i<espaco; ++i)
printf(" ");
return;
}
if (nivel == nivel_atual){
if (arvore->esquerda != NULL)
printf("/");
else
printf(" ");
int espaco = espacos_entre_elementos (altura, nivel+1); // calculando o espaço entre as barras
for (int i = 0; i<espaco; ++i)
printf(" ");
if (arvore->direita != NULL)
printf("\\");
else
printf(" ");
// printf("a");
espaco = espacos_entre_elementos(altura, nivel+1)+2; //calculando o espaço entre um conjunto de barras
for (int i = 0; i<espaco; ++i)
printf(" ");
return;
}
else {
imprimi_barras(arvore->esquerda, altura, nivel, nivel_atual+1);
// if (nivel == nivel_atual+1){
// int espaco = espacos_entre_elementos(altura, nivel+1)+2; //calculando o espaço entre um conjunto de barras
// for (int i = 0; i<espaco; ++i)
// printf(" ");
// }
imprimi_barras(arvore->direita, altura, nivel, nivel_atual+1);
}
}
void imprimeLinha(Arvore *arvore, int depth, char *path, int direita){
if(arvore==NULL){
return;
}
depth++;
imprimeLinha(arvore->direita, depth, path, 1);
// set | draw map
path[depth-2] = 0;
if(direita)
path[depth-2] = 1;
if(arvore->esquerda)
path[depth-1] = 1;
// print root after spacing
printf("\n");
for(int i=0; i<depth-1; i++)
{
if(i == depth-2)
printf("+");
else if(path[i])
printf("|");
else
printf(" ");
for(int j=1; j<ESPACO; j++){
if(i < depth-2)
printf(" ");
else
printf("-");
}
}
printf("%d\n", arvore->valor);
// vertical espacors below
for(int i=0; i<depth; i++)
{
if(path[i])
printf("|");
else
printf(" ");
for(int j=1; j<ESPACO; j++)
printf(" ");
}
imprimeLinha(arvore->esquerda, depth, path, 0);
}
int tamanho(Arvore*arvore){
if(arvore==NULL){
return 0;
}
else{
int tam1 = tamanho(arvore->esquerda);
int tam2 = tamanho(arvore->direita);
return tam1+tam2+1;
}
}
void getHeight(Arvore *arvore){
printf("Altura da arvore %d\n", altura(arvore));
}
int altura(Arvore*arvore){
if(arvore==NULL){
return 0;
}
else{
int he = altura(arvore->esquerda);
int hd = altura(arvore->direita);
if(he<hd)
return hd+1;
else
return he+1;
}
}
void printInOrder(Arvore *arvore){
if(arvore==NULL){
return;
}
printInOrder(arvore->esquerda);
printf("%d\n", arvore->valor);
printInOrder(arvore->direita);
}
void printPreOrder(Arvore *arvore){
if(arvore==NULL){
return;
}
printf("%d\n", arvore->valor);
printPreOrder(arvore->esquerda);
printPreOrder(arvore->direita);
}
void printPostOrder(Arvore *arvore){
if(arvore==NULL){
return;
}
printPostOrder(arvore->esquerda);
printPostOrder(arvore->direita);
printf("%d\n", arvore->valor);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 10 /* */
int main()
{
int a[N]; /* a N */
int i,boole; /* */
srand(time(NULL)); /* */
/* Array a */
for(i = 0; i < N; i++){
a[i] = rand()%100;
printf(" %d", a[i]);
}
printf(";\n");
boole = 1;
if(a[0]%2 == 0){
for(i=1;i<N;i++){
if(i%2 == 0 && a[i]%2 == 1){
boole = boole*0;
}
if(i%2 == 1 && a[i]%2 == 0){
boole = boole*0;
}
}
}
else{
for(i=1;i<N;i++){
if(i%2 == 0 && a[i]%2 == 0){
boole = boole*0;
}
if(i%2 == 1 && a[i]%2 == 1){
boole = boole*0;
}
}
}
if(boole == 1){
printf("Array is evenodd");
}
else{
printf("Array is not evenodd");
}
return 0;
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include <stronghold/point_mutations.h>
#include <lcthw/dbg.h>
int hamming_distance(char *s, char *t)
{
check(s != NULL, "'s' can't be NULL");
check(t != NULL, "'t' can't be NULL");
check(strlen(s) == strlen(t), "Lengths don't match");
int i = 0;
int diff = 0;
for(i = 0; i < strlen(s); i++) {
if(s[i] != t[i]) diff++;
}
return diff;
error:
return -1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
double altura = 0, pesoIdeal = 0;
printf("Informe a Altura: ");
scanf("%lf", &altura);
pesoIdeal = (72.7 * altura) - 58;
printf("Peso ideal: %.1lf\n", pesoIdeal);
//gletch();
return 0;
}
|
C
|
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#include <err.h>
#include "hirschberg.h"
double wall_time () {
struct timeval time;
gettimeofday(&time, NULL);
return ((double)time.tv_sec * (double)1e6 + (double)time.tv_usec);
}
char *hirschberg(const char *, const char*);
static void hirschberg_recursive(char *, const char *, unsigned int, const char *, unsigned int, char right);
static char *nwalign(char *, const char *, unsigned int, const char *, unsigned int, char right);
static void nwlcost(int *, const char *, unsigned int, const char *, unsigned int);
static void nwrcost(int *, const char *, unsigned int, const char *, unsigned int);
static unsigned int nwmin(int[3], char, char);
/*
* hirschberg calculates the global alignment of a and b with the
* cost scheme f using Hirschberg's algorithm. It returns the string
* of the edit operations required to change a into b:
*
* + insertion
* - deletion
* = match
* ! substitution
*
* The string should be free(3)'d when no longer needed. On failure,
* hirschberg returns NULL and sets errno to ENOMEM.
*/
char *
hirschberg(const char *a, const char *b)
{
char *c, *d;
unsigned int m = strlen(a);
unsigned int n = strlen(b);
/*
* The alignment string of a and b is at most as long as the
* concatenation of the two (delete all of a + insert all of b).
*/
c = malloc(m+n+1);
if (c == NULL)
return NULL;
if (m > n) {
/*
* hirschberg_recursive assumes that the first string
* passed to it is the shorter one, so if a is not, we
* flip it and b. The resulting alignment is otherwise
* equivalent to the non-flipped one, with the exception
* that insertion and deletion operators need to be
* flipped.
*/
hirschberg_recursive(c, b, n, a, m, 1);
for (d = c; *d != '\0'; d++)
switch (*d) {
case '+': *d = '-'; break;
case '-': *d = '+'; break;
}
return c;
}
hirschberg_recursive(c, a, m, b, n, 1);
return c;
}
/*
* hirschberg_recursive is the recursive part of Hirschberg's algorithm.
* The arguments are the same as hirschberg, with the exception that the
* length m of a and the length n of b are now explicitly passed, and c
* is a pointer to the buffer where the alignment string is to be
* written. hirschberg_recursive returns a pointer to the null byte
* written after the last alignment character.
*/
void
hirschberg_recursive(char *c, const char *a, unsigned int m, const char *b, unsigned int n, char right)
{
//printf("c = %x, m %d, n %d \n",c,m,n);
if (n > 1) {
unsigned int i, mmid, nmid;
int *lcost, *rcost;
int tmp, min;
lcost = malloc(sizeof(int)*(m+1));
rcost = malloc(sizeof(int)*(m+1));
nmid = n / 2;
nwlcost(lcost, a, m, b, nmid);
nwrcost(rcost, a, m, b+nmid, n-nmid);
mmid = 0;
min = lcost [0] + rcost[0];
for (i = 1; i <= m; i++) {
tmp = lcost[i] + rcost[i];
if (tmp < min){
mmid = i;
min = tmp;
}
}
free(lcost);
free(rcost);
hirschberg_recursive(c, a, mmid, b, nmid, 0);
hirschberg_recursive(c+mmid+nmid, a+mmid, m-mmid, b+nmid, n-nmid,right);
} else {
c = nwalign(c+m+n+right-1, a, m, b, n, right);
}
}
/*
* nwalign computes the Needleman-Wunsch alignment of a and b using the
* cost scheme f and writes it into the buffer c. It returns a pointer
* to the null byte written after the last character in the alignment
* string.
*
* This function uses O(mn) space. hirschberg_recursive guarantees its
* own O(m) space usage by only calling this when n <= 1.
*/
static char *
nwalign(char *c, const char *a, unsigned int m, const char *b, unsigned int n, char right)
{
#if _EXTRAE_
Extrae_event (PROGRAM, END);
Extrae_event (PROGRAM, NWALIGN);
#endif
unsigned int i, j;
int *s;
s = malloc(sizeof(int)*((m+1)*(n+1)));
s[0] = 0;
for (i = 1; i <= m; i++)
s[m*i] = s[m*(i-1)] + levenshtein(a[i-1], 0);
for (j = 1; j <= n; j++)
s[j] = s[j-1] + levenshtein(0, b[j-1]);
for (j = 1; j <= n; j++)
for (i = 1; i <= m; i++) {
int cost[3] = { s[m*(i-1)+j], s[m*(i-1)+j-1], s[m*(i)+j-1] };
s[m*i+j] = cost[nwmin(cost, a[i-1], b[j-1])];
}
i = m;
j = n;
if(right){
*c-- ='\0';
}
while (i > 0 && j > 0) {
int cost[3] = { s[m*(i-1)+j], s[m*(i-1)+j-1], s[m*(i)+j-1] };
switch (nwmin(cost, a[i-1], b[j-1])) {
case Del:
*c-- = '-';
i--;
break;
case Sub:
*c-- = a[i-1] == b[j-1] ? '=' : '!';
*c-- = a[i-1] == b[j-1] ? '=' : '!';
i--;
j--;
break;
case Ins:
*c-- = '+';
j--;
break;
}
}
for (; i > 0; i--)
*c-- = '-';
for (; j > 0; j--)
*c-- = '+';
#if _EXTRAE_
Extrae_event (PROGRAM, END);
Extrae_event (PROGRAM, SERIAL);
#endif
return c;
}
/*
* nwlcost stores the last column of the Needleman-Wunsch alignment
* cost matrix of a and b into s.
*/
static void
nwlcost(int *s, const char *a, unsigned int m, const char *b, unsigned int n)
{
#if _EXTRAE_
Extrae_event (PROGRAM, END);
Extrae_event (PROGRAM, NWLCOST);
#endif
unsigned int i, j;
int ss, tmp;
s[0] = 0;
for (i = 1; i <= m; i++)
s[i] = s[i-1] + levenshtein(a[i-1], 0);
for (j = 1; j <= n; j++) {
ss = s[0];
s[0] += levenshtein(0, b[j-1]);
for (i = 1; i <= m; i++) {
int cost[3];
cost[0] = s[i-1];
cost[1] = ss;
cost[2] = s[i];
tmp = cost[nwmin(cost, a[i-1], b[j-1])];
ss = s[i];
s[i] = tmp;
}
}
#if _EXTRAE_
Extrae_event (PROGRAM, END);
Extrae_event (PROGRAM, SERIAL);
#endif
}
/*
* nwrcost computes the reverse Needleman-Wunsch alignment of a and b,
* that is, matching their suffixes rather than prefixes. The last
* column of this alignment cost matrix is stored into s.
*/
static void
nwrcost(int *s, const char *a, unsigned int m, const char *b, unsigned int n)
{
#if _EXTRAE_
Extrae_event (PROGRAM, END);
Extrae_event (PROGRAM, NWRCOST);
#endif
int i, j;
int ss, tmp;
s[m] = 0;
for (i = m-1; i >= 0; i--)
s[i] = s[i+1] + levenshtein(a[i], 0);
for (j = n-1; j >= 0; j--) {
ss = s[m];
s[m] += levenshtein(0, b[j]);
for (i = m-1; i >= 0; i--) {
int cost[3];
cost[0] = s[i+1];
cost[1] = ss;
cost[2]= s[i];
tmp = cost[nwmin(cost, a[i], b[j])];
ss = s[i];
s[i] = tmp;
}
}
#if _EXTRAE_
Extrae_event (PROGRAM, END);
Extrae_event (PROGRAM, SERIAL);
#endif
}
#include <sys/stat.h>
/*
* main takes two strings a and b as arguments and prints their global
* alignment to standard output in three lines: the alignment of a, the
* edit sequence, and the alignment of b.
*/
int
main(int argc, char *argv[]) {
char *align, *c;
const char *file_a=argv[1];
struct stat st;
const char *file_b=argv[2];
char *line = NULL;
stat(file_a, &st);
unsigned int size_a = st.st_size;
char * a = malloc(size_a);
stat(file_b, &st);
unsigned int size_b = st.st_size;
char * b = malloc(size_b);
FILE* fd_a = fopen(file_a, "r");
a=fgets(a,size_a,fd_a);
FILE* fd_b = fopen(file_b, "r");
b=fgets(b,size_b,fd_b);
double t_start = wall_time();
#if _EXTRAE_
Extrae_event (PROGRAM, SERIAL);
#endif
align = hirschberg(a, b);
#if _EXTRAE_
Extrae_event (PROGRAM, END);
#endif
double t_end = wall_time();
if (align == NULL)
err(1, "hirschberg");
for (c = align; *c != '\0'; c++)
switch (*c) {
case '-':
putchar(*a++);
break;
case '!':
case '=':
putchar(*a++);
c++;
break;
default:
putchar(' ');
break;
}
putchar('\n');
for (c = align; *c != '\0'; c++)
switch (*c) {
case '-':
case '+':
putchar(*c);
break;
case '!':
case '=':
putchar(*c);
c++;
break;
default:
putchar(' ');
break;
}
putchar('\n');
for (c = align; *c != '\0'; c++)
switch (*c) {
case '+':
putchar(*b++);
break;
case '!':
case '=':
putchar(*b++);
c++;
break;
default:
putchar(' ');
break;
}
putchar('\n');
printf( "==================== RESULTS ===================== \n" );
printf( " Execution time (secs): %f\n", (t_end - t_start)/(double)1e6);
printf( "================================================== \n" );
return 0;
}
|
C
|
#include "gir_internals.h"
#include "gir.h"
/* String Interning
*****************************************************************************/
static uintptr_t intern(GirCtx* ctx, char* str) {
uintptr_t sym = (uintptr_t)hamt_lookup(&(ctx->intern_pool), str);
if (sym == 0) {
hamt_insert(&(ctx->intern_pool), str);
sym = (uintptr_t)str;
}
return sym;
}
static void intern_key(void* entry, uint8_t** addr, size_t* len) {
*addr = (uint8_t*)entry;
*len = strlen((char*)entry);
}
static void intern_del(void* entry) {
(void)entry; // noop
}
static int intern_cmp(void* a, void* b) {
return strcmp((char*)a, (char*)b);
}
/* Slot Management
*****************************************************************************/
static Slot* slot_new(uintptr_t sel, Obj* val) {
(void)sel;
(void)val;
return NULL;
}
static void slot_key(void* entry, uint8_t** addr, size_t* len) {
*addr = (uint8_t*)&(((Slot*)entry)->sel);
*len = sizeof(uintptr_t);
}
static void slot_del(void* entry) {
free(entry);
}
static int slot_cmp(void* a, void* b) {
Slot* sa = (Slot*)a;
Slot* sb = (Slot*)b;
return sa->sel - sb->sel;
}
/* Base Object Definition
*****************************************************************************/
Obj* obj_new(Obj* parent, uint32_t type, size_t datasz) {
Obj* obj = (Obj*)malloc(sizeof(struct Obj) + datasz);
obj->hdr.type = type;
obj->hdr.size = datasz;
obj->hdr.parent = parent;
hamt_init(&(obj->hdr.slots), &slot_key, &slot_del, &slot_cmp);
return obj;
}
void obj_set(Obj* obj, uintptr_t sel, Obj* val) {
Slot* slot = (Slot*)malloc(sizeof(Slot));
slot->sel = sel;
slot->val = val;
hamt_insert(&(obj->hdr.slots), slot);
}
Obj* obj_get(Obj* obj, uintptr_t sel) {
Slot slot = { sel, NULL };
Slot* entry = hamt_lookup(&(obj->hdr.slots), &slot);
return (entry != NULL) ? entry->val : NULL;
}
/* Base Environment Initialization
*****************************************************************************/
static void init_nil(GirCtx* ctx) {
ctx->Nil = obj_new(NULL, TYPE_BARE, 0);
obj_set(ctx->Lobby, intern(ctx, "Nil"), ctx->Nil);
}
static void init_bool(GirCtx* ctx) {
ctx->Bool = obj_new(NULL, TYPE_BARE, 0);
obj_set(ctx->Lobby, intern(ctx, "Bool"), ctx->Bool);
obj_set(ctx->Lobby, intern(ctx, "True"), obj_new(ctx->Bool, TYPE_BARE, 0));
obj_set(ctx->Lobby, intern(ctx, "False"), obj_new(ctx->Bool, TYPE_BARE, 0));
}
//static void init_num(GirCtx* ctx) {
// ctx->Num = obj_new(TYPE_BARE, 0);
// obj_set(ctx->Lobby, intern(ctx, "Num"), ctx->Num);
//}
//
//static void init_string(GirCtx* ctx) {
// ctx->String = obj_new(TYPE_BARE, 0);
// obj_set(ctx->Lobby, intern(ctx, "String"), ctx->String);
//}
//
//static void init_symbol(GirCtx* ctx) {
// ctx->Symbol = obj_new(TYPE_BARE, 0);
// obj_set(ctx->Lobby, intern(ctx, "Symbol"), ctx->Symbol);
//}
//
//static void init_list(GirCtx* ctx) {
// ctx->List = obj_new(TYPE_BARE, 0);
// obj_set(ctx->Lobby, intern(ctx, "List"), ctx->List);
//}
//
//static void init_array(GirCtx* ctx) {
// ctx->Array = obj_new(TYPE_BARE, 0);
// obj_set(ctx->Lobby, intern(ctx, "Array"), ctx->Array);
//}
//
//static void init_map(GirCtx* ctx) {
// ctx->Map = obj_new(TYPE_BARE, 0);
// obj_set(ctx->Lobby, intern(ctx, "Map"), ctx->Map);
//}
//
//static void init_set(GirCtx* ctx) {
// ctx->Set = obj_new(TYPE_BARE, 0);
// obj_set(ctx->Lobby, intern(ctx, "Set"), ctx->Set);
//}
//
//static void init_block(GirCtx* ctx) {
// ctx->Block = obj_new(TYPE_BARE, 0);
// obj_set(ctx->Lobby, intern(ctx, "Block"), ctx->Block);
//}
static void init_lobby(GirCtx* ctx) {
ctx->Lobby = obj_new(NULL, TYPE_BARE, 0);
init_nil(ctx);
init_bool(ctx);
//init_num(ctx);
//init_string(ctx);
//init_symbol(ctx);
//init_list(ctx);
//init_array(ctx);
//init_map(ctx);
//init_set(ctx);
//init_block(ctx);
}
/* Main API
*****************************************************************************/
GirCtx* gir_init(void) {
GirCtx* ctx = malloc(sizeof(struct GirCtx));
hamt_init(&(ctx->intern_pool), &intern_key, &intern_del, &intern_cmp);
init_lobby(ctx);
return ctx;
}
void gir_evalfile(FILE* input, const char* prompt) {
(void)input;
(void)prompt;
}
void gir_deinit(GirCtx* ctx) {
free(ctx);
}
//Obj* Lobby;
//Obj* Nil;
//Obj* Bool;
//Obj* True;
//Obj* False;
//Obj* Num;
//Obj* String;
//Obj* Symbol;
//Obj* List;
//Obj* Array;
//Obj* ByteArray;
//Obj* Map;
//Obj* Set;
//Obj* Block;
//
//hamt_t InternPool;
//
///* Private API Declarations
// *****************************************************************************/
//
///* Top-Level API
// *****************************************************************************/
//void gir_init(void* stack_btm)
//{
// (void)stack_btm;
//// hamt_init(&InternPool);
//}
//
//void gir_deinit(void)
//{
//}
//
//Obj* gir_evalexpr(FILE* input)
//{
// (void)input;
// return Nil;
//}
//
//void gir_evalfile(FILE* input, const char* prompt)
//{
// extern void exec_file(FILE* file, const char* prompt);
// exec_file(input, prompt);
//}
//
//Obj* gir_send(Obj* rcvr, const char* sel, ...)
//{
// (void)rcvr;
// (void)sel;
// return Nil;
//}
//
///* Constructors
// *****************************************************************************/
//Obj* gir_mkobject(double val)
//{
// (void)val;
// return Nil;
//}
//
//Obj* gir_mknum(double val)
//{
// (void)val;
// return Nil;
//}
//
//Obj* gir_mkstring(const char* val)
//{
// (void)val;
// return Nil;
//}
//
//Obj* gir_mksymbol(const char* val)
//{
// (void)val;
// return Nil;
//}
//
//Obj* gir_mklist(size_t num, ...)
//{
// (void)num;
// return Nil;
//}
//
//Obj* gir_mkarray(size_t num, ...)
//{
// (void)num;
// return Nil;
//}
//
//Obj* gir_mkbytearray(size_t num, uint8_t* val)
//{
// (void)num;
// (void)val;
// return Nil;
//}
//
//Obj* gir_mkmap(void)
//{
// return Nil;
//}
//
//Obj* gir_mkset(void)
//{
// return Nil;
//}
//
//Obj* gir_mkblock(void)
//{
// return Nil;
//}
/* Private API Definitions
*****************************************************************************/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.