language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <string.h> #include <stdbool.h> int main(){ char str[30]; int i; int length; printf("输入一段字符串\n"); for( i=0 ; i<30 ; i++ ) { str[i]=getchar(); if(str[i]==EOF) { str[i-1]='\0'; break; } if(i==28) { str[29]='\0'; break; } } length = strlen(str); bool a = true; if( !(str[0]=='_' || (str[0]>='a'&&str[0]<='z') || (str[0]>='A'&&str[0]<='Z')) ) { a = false; } else { for( i=1 ; i<length ; i++ ) { if( !(str[i]=='_' || (str[i]<='z'&&str[i]>='a') || (str[i]>='A'&&str[i]<='Z') || (str[i]>='0'&&str[i]<='9') ) ) { a = false; break; } } } if(a) { printf("此字符串构成标识符\n"); } else { printf("此字符串不构成标识符\n"); } return (0); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "grafo.h" /* Programa que detecta a similaridade entre dois textos (.txt) utilizando grafos Mateus Ferreira Gomes --------- Universidade de São Paulo Instituto de Ciências Matemáticas e de Computação */ int verifica(FILE* fp){ FILE *save; save = fp; char aux; while(1){ fscanf(fp, "%c", &aux); if(aux == '/'){ fp = save; return 1; } else if(aux == '#'){ fp = save; return 0; } } } void ler_arquivo(FILE* fp, char palavras[100]){ int i = 0; int j = 0; char aux; strcpy(palavras,""); while(fscanf(fp, "%c", &aux) != EOF){ palavras[j] = aux; j++; } } void remover_repetidas(char minusculas[10000][45], int tam_min, char maiusculas[10000][45], int* tam_maius, char** palavras, int n_palavras){ int count_removidas = 0; for(int i = 0; i < tam_min; i++){ for(int j = 0; j < (*tam_maius); j++){ if(strcmp(minusculas[i], maiusculas[j]) == 0){ memset(maiusculas[j], '\0', 45); count_removidas++; } } } for(int i = 0; i < (*tam_maius)-1; i++){ if(maiusculas[i][0] == '\0'){ for(int j = i; j < (*tam_maius); j++){ if(maiusculas[j][0] != '\0'){ strcpy(maiusculas[i], maiusculas[j]); memset(maiusculas[j], '\0', 45); break; } } } } *tam_maius -= count_removidas; } char** verbo_subst(char minusculas[10000][45], int tam_min, char maiusculas[10000][45], int tam_maius, int* classes_palavras, int* n_verbos, int* n_substantivos, int* n_classe, char** classes){ char** palavras_uteis; int n_palavras = 0; palavras_uteis = (char**) malloc(20000*sizeof(char*)); for(int i = 0; i < 20000; i++){ palavras_uteis[i] = (char*) malloc(45*sizeof(char)); } for(int x = 0; x < *n_classe; x++){ classes_palavras[x] = -1; } for(int x = 0; x < 20000; x++){ for(int r = 0; r < 45; r++){ palavras_uteis[x][r] = '\0'; } } remover_repetidas(minusculas, tam_min, maiusculas, &tam_maius, palavras_uteis, n_palavras); for(int x = 0; x < *n_classe; x++){ if(strcmp(classes[x], "CN") == 0){ strcpy(palavras_uteis[n_palavras], minusculas[x]); classes_palavras[n_palavras] = 1; n_palavras++; } else if(classes[x][0] == 'V'){ strcpy(palavras_uteis[n_palavras], maiusculas[(*n_verbos)]); classes_palavras[n_palavras] = 0; n_palavras++; (*n_verbos)++; } } (*n_substantivos) = n_palavras - (*n_verbos); return palavras_uteis; } char** verifica_classes(char** palavras, int* n_palavras, int* classes_palavras, int* n_substantivos, int* n_verbos, int* n_classe, char** classes){ int tampalavra; int pos1 = 0; int pos2 = 0; char maiusculas[10000][45]; char minusculas[10000][45]; for(int x = 0; x < 10000; x++){ for(int r = 0; r < 45; r++){ minusculas[x][r] = '\0'; } } for(int x = 0; x < 10000; x++){ for(int r = 0; r < 45; r++){ maiusculas[x][r] = '\0'; } } for(int x = 0; x < *n_palavras; x++){ if(palavras[x][0] >= 65 && palavras[x][0] <= 90){ strcpy(maiusculas[pos1], palavras[x]); pos1++; } else if(palavras[x][0] >= 97 && palavras[x][0] <= 122){ strcpy(minusculas[pos2], palavras[x]); pos2++; } } for(int x = 0; x < *n_palavras; x++){ tampalavra = strlen(maiusculas[x]); for(int r = 0; r < tampalavra; r++){ if(maiusculas[x][r] >= 65 && maiusculas[x][r] <= 90){ maiusculas[x][r] += 32; } } } return verbo_subst(minusculas, pos2, maiusculas, pos1, classes_palavras, n_verbos, n_substantivos, n_classe, classes); } void classe(char aux[45], int* size, int* n_classe, char** classes){ for(int h = (*size)-1; h >= 0; h--){ if(aux[h] >= 65 && aux[h] <= 90){ while(h >= 0){ classes[(*n_classe)][h] = aux[h]; h--; } (*n_classe)++; } } } void le_ate_barra(char* palavras, char aux[45], char** ans, int* i, int* j, int* n_classe, char** classes){ int g = 0; int flag = 1; while(palavras[*i] != '/' && palavras[*i] != '<'){ if(palavras[*i] != ' '){ aux[g] = palavras[*i]; g++; } else{ classe(aux, &g, n_classe, classes); for(int p = 0; p < 45; p++){ aux[p] = '\0'; } g = 0; flag = 0; } (*i)++; } g = 0; if(flag) strcpy(ans[*j], aux); if(flag){ (*j)++; } flag = 1; for(int p = 0; p < 45; p++){ aux[p] = '\0'; } } char** separar_string(char* palavras, int* n_palavras, int* n_classe, char** classes){ int i = 6; int j = *n_palavras; int k = 0; int tipos[100]; char aux[45]; int flag2 = 0; int flag_barra = 0; char** classes_palavras; char** ans = (char**) malloc(100000*sizeof(char*)); for(int b = 0; b < 100000; b++){ ans[b] = (char*) malloc(45*sizeof(char)); } for(int y = 0; y < 100000; y++){ for(int p = 0; p < 45; p++){ ans[y][p] = '\0'; } } for(int p = 0; p < 45; p++){ aux[p] = '\0'; } while(palavras[i] != '<'){ if(palavras[i] == ' '){ i++; while((palavras[i] >= 97 && palavras[i] <= 122) && palavras[i] != '/'){ ans[j][k] = palavras[i]; i++; k++; flag2 = 1; } k = 0; if(flag2){ j++; flag2 = 0; } i++; } i++; } i = 6; while(palavras[i] != '/' || palavras[i+1] != 's'){ if(palavras[i] == '/' && flag_barra == 0){ i++; le_ate_barra(palavras, aux, ans, &i, &j, n_classe, classes); flag_barra = 1; } else if(flag_barra == 1){ le_ate_barra(palavras, aux, ans, &i, &j, n_classe, classes); } i++; } *n_palavras = j; return ans; } int main(void){ char* dados; char* dados2; FILE* arquivo1; FILE* arquivo2; char** palavras; char** palavras2; char** palavras_uteis; char** palavras_uteis2; int n_palavras = 0; int n_palavras2 = 0; Grafo* G; Grafo* G2; int erro = 0; int substantivos[10000]; int substantivos2[10000]; int n_palavras_uteis; int n_palavras_uteis2; int* classes_palavras; int* classes_palavras2; int achou_verbo = 0; int peso = 0; int n_verbos = 0; int n_substantivos = 0; int n_verbos2 = 0; int n_substantivos2 = 0; char** classes; int n_classe = 0; char** classes2; int n_classe2 = 0; double resposta = 0; char nome1[40]; char nome2[40]; scanf("%s", nome1); scanf("%s", nome2); classes = (char**) malloc(10000*sizeof(char*)); for(int i = 0; i < 10000; i++) classes[i] = (char*) malloc(10*sizeof(char)); classes2 = (char**) malloc(10000*sizeof(char*)); for(int i = 0; i < 10000; i++) classes2[i] = (char*) malloc(10*sizeof(char)); classes_palavras = (int*) malloc(10000*sizeof(int)); classes_palavras2 = (int*) malloc(10000*sizeof(int)); for(int i = 0; i < 10000; i++){ classes_palavras[i] = -1; } for(int i = 0; i < 10000; i++){ substantivos2[i] = -1; } for(int i = 0; i < 10000; i++){ for (int j = 0; j < 10; j++) { classes[i][j] = '\0'; } } dados = (char*) malloc(100000*sizeof(char)); dados2 = (char*) malloc(100000*sizeof(char)); arquivo1 = fopen(nome1, "r"); ler_arquivo(arquivo1, dados); palavras = separar_string(dados, &n_palavras, &n_classe, classes); palavras_uteis = verifica_classes(palavras, &n_palavras, classes_palavras, &n_substantivos, &n_verbos, &n_classe, classes); G = criar_grafo(&n_substantivos, &erro); int contador = 0; int j = 0; n_palavras_uteis = n_substantivos + n_verbos; for(int i = 0; i < n_palavras_uteis; i++){ if(classes_palavras[i] == 1 && achou_verbo == 1 && j > 1){ inserir_aresta(G, &substantivos[j-1], &contador, &peso, &erro); substantivos[j-1] = -1; j--; achou_verbo = 0; } else if(classes_palavras[i]){ substantivos[j] = contador; contador++; j++; } else if(classes_palavras[i] == 0){ achou_verbo = 1; } } contador = 0; j = 0; achou_verbo = 0; arquivo2 = fopen(nome2, "r"); ler_arquivo(arquivo2, dados2); palavras2 = separar_string(dados2, &n_palavras2, &n_classe2, classes2); palavras_uteis2 = verifica_classes(palavras2, &n_palavras2, classes_palavras2, &n_substantivos2, &n_verbos2, &n_classe2, classes2); n_palavras_uteis2 = n_substantivos2 + n_verbos2; G2 = criar_grafo(&n_substantivos2, &erro); for(int i = 0; i < n_palavras_uteis2; i++){ if(classes_palavras2[i] == 1 && achou_verbo == 1 && j > 1){ inserir_aresta(G2, &substantivos2[j-1], &contador, &peso, &erro); substantivos2[j-1] = -1; j--; achou_verbo = 0; } else if(classes_palavras2[i]){ substantivos2[j] = contador; contador++; j++; } else if(classes_palavras2[i] == 0){ achou_verbo = 1; } } double receptor; receptor = compara_grafos(G, G2, n_verbos, n_verbos2); resposta += receptor*25; double count = 0; int batem = 0; double batem2 = 0; if(n_palavras_uteis > n_palavras_uteis2){ batem = n_palavras_uteis2; } else { batem = n_palavras_uteis; } if(n_palavras_uteis < n_palavras_uteis2){ batem2 = n_palavras_uteis2; } else { batem2 = n_palavras_uteis; } for(int i = 0; i < batem; i++){ if(classes_palavras[i] == classes_palavras2[i]) count++; } count /= batem; count *= 35; resposta += count; double count2 = 0; for(int i = 0; i < batem; i++){ if(strcmp(palavras_uteis[i], palavras_uteis2[i]) == 0) count2++; } count2 /= batem2; count2 *= 40; resposta += count2; printf("%.2lf%%\n", resposta); free(dados2); free(dados); free(classes_palavras); free(classes_palavras2); free(palavras); free(palavras_uteis); free(palavras2); free(palavras_uteis2); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <math.h> int power(int number, int nthpower) { int product=number; while(nthpower>1) { product=product*number; nthpower--; } return product; } void checkpre() { } void binarysearch(int min,int max,int number, int nthroot, int precision) { int temp=(min+max)/2; if(power(temp,nthroot)>number) { printf("%d\n",temp); binarysearch(min,temp,number,nthroot,precision); } else if(power(temp,nthroot)<number) { printf("%d\n",temp); binarysearch(temp,max,number,nthroot,precision); } else printf("root is :%d\n",temp ); } int main(int argc, char const *argv[]) { /* code */ if (argc<4) { printf("incomplete input\n"); return 0; } int number = atoi(argv[1]); int nthroot = atoi(argv[2]); int precision = atoi(argv[3]); binarysearch(0,number,number,nthroot,precision); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* test_map_border.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dboyer <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/04/24 15:19:35 by dboyer #+# #+# */ /* Updated: 2020/05/13 16:13:49 by dboyer ### ########.fr */ /* */ /* ************************************************************************** */ #include "cub3d.h" static inline t_element *find_onset_element(t_element *element) { char *content; int i; i = 0; if (element) { content = (char *)element->content; while (content[i]) { if (ft_cinset(content[i], "NSEW")) return (element); i++; } } return (find_onset_element(element->next)); } int test_map_border(t_list *map) { t_element *element; t_list memory; int result; int i; int j; i = 0; j = 0; memory = ft_list(); element = find_onset_element(map->first); if (ft_map_is_closed(map, element, &memory)) { ft_display_process_status("Map border", "ok"); result = 1; } else { ft_display_process_status("Map border", "error"); ft_display_error("Your map is not closed", __func__); result = 0; } return (result); }
C
/** POSIX DESCRIPTION Name: aio.h - asynchronous input and output. Description: The <aio.h> header shal define the aiocb structure, which shall inclide the following members int aio_fildes File descriptor. off_t aio_offset File offset. volatile void *aio_buf Location of buffer. size_t aio_nbytes Length of transfer. int aio_reqprio Request priority offset. struct sigevent aio_sigevent Signal number and value. int aio_lio_opcode Operation to be performed. The <aio.h> header shall define the off_t, pthread_attr_t, size_t, and ssize_t types as described in <sys/types.h>. The <aio.h> header shall define the struct timespec structure as described in <time.h>. The <aio.h> header shall define the sigevent structure and sigval union as described in <signal.h>. The <aio.h> header shall define the following symbolic constants: AIO_ALLDONE A return value indicating that none of the requested operations could be canceled since they are already complete. AIO_CANCELED A return value indicating that all requested operations have been canceled. AIO_NOTCANCELED A return value indicating that some of the requested operations could not be canceled since they are in progress. LIO_NOP A lio_listio() element operation option indicating that no transfer is requested. LIO_NOWAIT A lio_listio() synchronization operation indicating that the calling thread is to continue execution while the lio_listio() operation is being performed, and no notification is given when the operation is complete. LIO_READ A lio_listio() element operation option requesting a read. LIO_WAIT A lio_listio() synchronization operation indicating that the calling thread is to suspend until the lio_listio() operation is complete. LIO_WRITE A lio_listio() element operation option requesting a write. The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided. int aio_cancel(int, struct aiocb *); int aio_error(const struct aiocb *); [FSC|SIO][Option Start] int aio_fsync(int, struct aiocb *); [Option End] int aio_read(struct aiocb *); ssize_t aio_return(struct aiocb *); int aio_suspend(const struct aiocb *const [], int, const struct timespec *); int aio_write(struct aiocb *); int lio_listio(int, struct aiocb *restrict const [restrict], int, struct sigevent *restrict); Inclusion of the <aio.h> header may make visible symbols defined in the headers <fcntl.h>, <signal.h>, and <time.h>. */ #ifndef __POSIX_AIO_H__ #define __POSIX_AIO_H__ #include <sys/types.h> #include <fcntl.h> #include <signal.h> #include <time.h> int aio_fildes; //File descriptor. off_t aio_offset; //File offset. volatile void *aio_buf; //Location of buffer. size_t aio_nbytes; //Length of transfer. int aio_reqprio; //Request priority offset. struct sigevent aio_sigevent; //Signal number and value. int aio_lio_opcode; //Operation to be performed. /* Return values for aio_cancel */ #define AIO_CANCELED 0x1 //A return value indicating that all requested operations have been canceled. #define AIO_NOTCANCELED 0x2 //A return value indicating that some of the requested operations could not be canceled since they are in progress. #define AIO_ALLDONE 0x3 //A return value indicating that none of the requested operations could be canceled since they are already complete. /* LIO opcodes */ #define LIO_NOP 0x0 //A lio_listio() element operation option indicating that no transfer is requested. #define LIO_WRITE 0x1 //A lio_listio() element operation option requesting a write. #define LIO_READ 0x2 //A lio_listio() element operation option requesting a read. /* LIO modes */ #define LIO_NOWAIT 0x0 //A lio_listio() synchronization operation indicating that the calling thread is to continue execution while the lio_listio() operation is being performed, and no notification is given when the operation is complete. #define LIO_WAIT 0x1 //A lio_listio() synchronization operation indicating that the calling thread is to suspend until the lio_listio() operation is complete. int aio_cancel(int, struct aiocb *); int aio_error(const struct aiocb *); int aio_fsync(int, struct aiocb *); int aio_read(struct aiocb *); ssize_t aio_return(struct aiocb *); int aio_suspend(const struct aiocb * const list[], int, const struct timespec *); int aio_write(struct aiocb *); int lio_listio(int, struct aiocb *restrict const [restrict], int, struct sigevent *restrict); #endif
C
#include<stdio.h> #include<conio.h> #include<math.h> void main() { int a,b,c,d,e,f,g; clrscr(); printf("your quadratic equation looks like ax^2 +bx +c =0 \n"); printf("enter value of a"); scanf("%d",&a); printf("enter value of b"); scanf("%d",&b); printf("enter value of c"); scanf("%d",&c); d=pow(b,2)-(4*a*c); e=sqrt(d); f=(-b+e)/(2*a); g=(-b-e)/(2*a); printf("first root is %d and second root is %d",f,g); getch(); return 0; }
C
/* Copyright (c) 2020 Advanced Micro Devices, Inc.  All rights reserved. Sep 24, 2020 */ #define DRAND() ( ( double ) rand() / ( ( double ) RAND_MAX / 2.0F ) ) - 1.0F; #define SRAND() ( float ) ( ( double ) rand() / ( ( double ) RAND_MAX / 2.0F ) ) - 1.0F; /* Initialize matrix with random values */ void rand_matrix_s( float *A, integer M, integer N, integer LDA ); void rand_matrix_d( double *A, integer M, integer N, integer LDA ); void rand_matrix_c( scomplex *A, integer M, integer N, integer LDA ); void rand_matrix_z( dcomplex *A, integer M, integer N, integer LDA ); /* Initialize symmetric matrix with random values */ void rand_sym_matrix_s( float *A, integer M, integer N, integer LDA ); void rand_sym_matrix_d( double *A, integer M, integer N, integer LDA ); void rand_sym_matrix_c( scomplex *A, integer M, integer N, integer LDA ); void rand_sym_matrix_z( dcomplex *A, integer M, integer N, integer LDA ); /* Copy a matrix */ void copy_matrix_s( float *A, float *B, integer M, integer N, integer LDA, integer LDB ); void copy_matrix_d( double *A, double *B, integer M, integer N, integer LDA, integer LDB ); void copy_matrix_c( scomplex *A, scomplex *B, integer M, integer N, integer LDA, integer LDB ); void copy_matrix_z( dcomplex *A, dcomplex *B, integer M, integer N, integer LDA, integer LDB ); /* Pack a symmetric matrix in column first order */ void pack_matrix_lt_s( float *A, float *B, integer N, integer LDA ); void pack_matrix_lt_d( double *A, double *B, integer N, integer LDA ); void pack_matrix_lt_c( scomplex *A, scomplex *B, integer N, integer LDA ); void pack_matrix_lt_z( dcomplex *A, dcomplex *B, integer N, integer LDA ); /* Initialize a matrix with zeros */ void reset_matrix_s( float *A, integer M, integer N, integer LDA ); void reset_matrix_d( double *A, integer M, integer N, integer LDA ); void reset_matrix_c( scomplex *A, integer M, integer N, integer LDA ); void reset_matrix_z( dcomplex *A, integer M, integer N, integer LDA ); /* Set a matrix to identity */ void set_identity_s( float *A, integer M, integer N, integer LDA ); void set_identity_d( double *A, integer M, integer N, integer LDA ); void set_identity_c( scomplex *A, integer M, integer N, integer LDA ); void set_identity_z( dcomplex *A, integer M, integer N, integer LDA ); /* Division of complex types */ void c_div_t(scomplex *cp, scomplex *ap, scomplex *bp); void z_div_t(dcomplex *cp, dcomplex *ap, dcomplex *bp);
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include "code.h" double minimum(double * tab, int taille) { int i=1; double min=tab[0]; for (i=1;i<taille;i++){ if (tab[i]<=min){ min=tab[i]; } } return min; } double maximum(double * tab, int taille) { int i=1; double max=tab[0]; for (i=1;i<taille;i++){ if (tab[i]>=max){ max=tab[i]; } } return max; } double moyenne(double * tab, int taille) { double S=somme(tab,taille); return S/taille; } double somme(double * tab, int taille ) { int i=0; double S=0; for (i=0;i<taille;i++){ S+=tab[i]; } return S; } int lecture(char * nom, donnee_t ** ptab) { FILE * file = NULL; file = fopen(nom,"r"); char ligne[255]; int i=0; int taille=0; if (file!=NULL){ fgets(ligne,255,file); taille=atoi(ligne); donnee_t * tab_ligne = (donnee_t *)malloc(taille*sizeof(donnee_t)); if (tab_ligne!=NULL){ for (i=0;i<taille;i++){ fscanf(file,"%d",&tab_ligne[i].annee); fscanf(file,"%lf",&tab_ligne[i].valeur); //printf("%d\n",tab_ligne[i*sizeof(donnee_t)].annee); //printf("%lf\n",tab_ligne[i*sizeof(donnee_t)].valeur); } } *ptab=tab_ligne; fclose(file); } return taille; } void conversion_to_double(donnee_t * tabs, double **tabd, int taille) { double * tab_val = (double *)malloc(taille*sizeof(double)); if (tab_val!=NULL){ int i=0; for (i=0;i<taille;i++){ tab_val[i]=tabs[i].valeur; } *tabd=tab_val; } } int * affichage(donnee_t * tab, int taille) { double * tab_val = NULL; conversion_to_double(tab, &tab_val, taille); double min=minimum(tab_val,taille); double max=maximum(tab_val,taille); int * etoiles = (int *)malloc(taille*sizeof(int)); if (etoiles!=NULL){ int i=0; for (i=0;i<taille;i++){ if (40*(tab_val[i]-min)/(max-min)==0 && tab_val[i]!=0){ etoiles[i]=1; } else{ etoiles[i]=40*(tab_val[i]-min)/(max-min); } printf("%f\n",40*(tab_val[i]-min)/(max-min)); } } return etoiles; }
C
#include <stdio.h> #include <memory.h> #include <malloc.h> #include <string.h> #define NAME_LENGTH 20 typedef struct _Robot { char name[NAME_LENGTH]; int energy; float data; }Robot; /** methods for Robot Class **/ void RobotCreate(Robot **robot) { *robot = (Robot*)malloc(sizeof(Robot)); // initialize the arguments // unnamed robot char *name = "NOT SET"; memset((char*)(*robot)->name, 0, sizeof((*robot)->name)); memcpy((char*)(*robot)->name, (char*)name, strlen(name)*sizeof(char)); // dead robots (*robot)->energy = 0; // carry no data (*robot)->data = 0.0; } void RobotDestroy(Robot **robot) { // name has to be non-const free(*robot); *robot = NULL; } void RobotDump(Robot *robot) { printf("Name: %s\n", robot->name); printf("Energy: %d\n", robot->energy); printf("Data: %f\n", robot->data); } void RobotSetName(Robot *robot, char name[NAME_LENGTH]) { memcpy((char*)robot->name, (char*)name, strlen(name)*sizeof(char)); } typedef struct _Node { Robot* data; struct _Node* prev; }Node; void NodeCreate(Node **node) { *node = (Node*)malloc(sizeof(Node)*1); (*node)->data = NULL; (*node)->prev = NULL; } void NodeDestroy(Node **node) { RobotDestroy(&((*node)->data)); free(*node); *node = NULL; } void NodeDump(Node* node) { printf("Node Data:\n"); RobotDump(node->data); printf("Node Prev:\t%d\n", (int)node->prev); } typedef struct _Stack { Node *head; Node *tail; int count; }Stack; void StackCreate(Stack **stack) { *stack = (Stack*)malloc(sizeof(Stack)); // the first empty node, different from tail, it's not just a pointer. Node *node; NodeCreate(&node); (*stack)->head = node; (*stack)->head->data = NULL; (*stack)->head->prev = NULL; // the stack is empty, so the head meets the tail. (*stack)->tail = (*stack)->head; (*stack)->count = 0; } void StackDestroy(Stack **stack) { // unitl stack empty while((*stack)->head!=(*stack)->tail) { Node *prev = (*stack)->tail->prev; // destroy stack node, with given custom method NodeDestroy(&((*stack)->tail)); (*stack)->tail = prev; } // clear orginal nodes NodeDestroy(&((*stack)->head)); // free the stack shell free(*stack); *stack = NULL; } void StackPush(Stack *stack, Robot *robot) { Node* node; NodeCreate(&node); node->data = robot; node->prev = stack->tail; stack->tail = node; stack->count ++; } void StackPop(Stack *stack, Robot **robot) { if(stack->count){ Node *node = stack->tail; stack->tail = stack->tail->prev; // clear up node and return node data *robot = node->data; // one thing to remember, the robot object // should be released by the outside environment free(node); stack->count --; } else { // the stack is empty print out error information printf("error in StackPop(), stack is empty\n"); } } void StackDump(Stack *stack) { printf("Stack Information:\n"); while(stack->count) { Robot *robot; StackPop(stack, &robot); RobotDump(robot); RobotDestroy(&robot); } } int main(int argc, const char** argv) { // ROBOT TEST printf("ROBOT TEST:\n"); Robot *A, *B; RobotCreate(&A); RobotCreate(&B); char nameA[NAME_LENGTH] = "ROBOT A"; char nameB[NAME_LENGTH] = "ROBOT B"; RobotSetName(A, nameA); RobotSetName(B, nameB); // full energy is 100 A->energy = 38; B->energy = 76; // the secret of each robot A->data = 27.33; B->data = -67.868; RobotDump(A); RobotDump(B); // NODE TEST printf("\nNODE TEST:\n"); Node *node; NodeCreate(&node); node->data = A; node->prev = NULL; NodeDump(node); // STACK TEST printf("\nSTACK TEST:\n"); Stack *stack; StackCreate(&stack); StackPush(stack, A); StackPush(stack, B); StackDump(stack); // clear memory StackDestroy(&stack); return 0; }
C
/* ----------------------------------------------------------------------------- * $Id: Stable.h,v 1.14 2002/12/19 14:25:04 simonmar Exp $ * * (c) The GHC Team, 1998-2000 * * Stable Pointers: A stable pointer is represented as an index into * the stable pointer table in the low BITS_PER_WORD-8 bits with a * weight in the upper 8 bits. * * SUP: StgStablePtr used to be a synonym for StgWord, but stable pointers * are guaranteed to be void* on the C-side, so we have to do some occasional * casting. Size is not a matter, because StgWord is always the same size as * a void*. * * ---------------------------------------------------------------------------*/ #ifndef STABLE_H #define STABLE_H /* ----------------------------------------------------------------------------- External C Interface -------------------------------------------------------------------------- */ extern StgPtr deRefStablePtr(StgStablePtr stable_ptr); extern void freeStablePtr(StgStablePtr sp); extern StgStablePtr splitStablePtr(StgStablePtr sp); extern StgStablePtr getStablePtr(StgPtr p); /* ----------------------------------------------------------------------------- PRIVATE from here. -------------------------------------------------------------------------- */ typedef struct { StgPtr addr; /* Haskell object, free list, or NULL */ StgPtr old; /* old Haskell object, used during GC */ StgWord ref; /* used for reference counting */ StgClosure *sn_obj; /* the StableName object (or NULL) */ } snEntry; extern DLL_IMPORT_RTS snEntry *stable_ptr_table; extern void freeStablePtr(StgStablePtr sp); #ifndef RTS_STABLE_C extern inline #endif StgPtr deRefStablePtr(StgStablePtr sp) { ASSERT(stable_ptr_table[(StgWord)sp].ref > 0); return stable_ptr_table[(StgWord)sp].addr; } /* No deRefStableName, because the existence of a stable name doesn't * guarantee the existence of the object itself. */ #endif
C
#include <stdio.h> int main () { int num,i,sum=0; printf ("Please input a integer number : "); scanf ("%d",&num); for (i=0;num;i++){//find last most digit and these sum sum+= num%10; num/=10; } printf ("Sum of the digit of this number is : %d",sum); return 0; }
C
#include <stdio.h> extern double aTof(const char *s); /* 测试重写的 aTof() 函数 */ int main(void) { char *number[] = {"48829.34", "-3804.53", "123.45e-6", "1.2e2"}; int i; for (i = 0; i < 4; ++i) printf("%g\n", aTof(number[i])); return 0; }
C
// C Primer Plus // Chapter 9 Exercise 11: // Write and test a Fibonacci() function that uses a loop instead of recursion // to calculate Fibonacci numbers. #include <stdio.h> long Fibonacci(long n); int main(void) { long n; printf("Test Fibonacci() function\n"); printf("Enter an integer n: "); while (scanf("%ld", &n) == 1) { printf("Fibonacci #%ld = %ld\n", n, Fibonacci(n)); printf("Enter an integer n: "); } return 0; } long Fibonacci(long n) { // return nth Fibonacci number // handle invalid arguments if (n < 1) { printf("Error: n must be a positive integer.\n"); return -1; } long fib_n1 = 0, fib_n = 1, fib_n2; // n equals 1 or 2 if (n == 1) return 0; if (n == 2) return 1; // n greater than or equal to 3 for (long i = 3; i <= n; i++) { // update old values fib_n2 = fib_n1; fib_n1 = fib_n; fib_n = fib_n1 + fib_n2; } return fib_n; }
C
#include <stdint.h> int main() { int a, b, c, d, e, f, g, h; printf("Unesi ip adresu: \n"); scanf("%d.%d.%d.%d", &a, &b, &c, &d); printf("Unesi subnet masku: \n"); scanf("%d.%d.%d.%d", &e, &f, &g, &h); printf("ip adresa je: %d.%d.%d.%d", a & e, b & f, c & g, d & h); return 0; }
C
#include "graph.h" graph_t * graph_new (int count) { /* allocates and initializes memory for a new graph_t structure */ graph_t *g = calloc(1, sizeof(graph_t)); g->nodes = (int **) calloc(count, sizeof(int *)); g->count = count; g->names = (char **) calloc(count + 1, sizeof(char *)); g->edges = 0; g->total = 0; int i; char name[10]; /* NOTE: we are using an adjacence matrix to represent the graph edges */ for (i = 0; i < count; i ++) { /* allocates a line for the node i */ g->nodes[i] = malloc(count * sizeof(int)); /* initializes every position of the line i to -1 * NOTE: the value at line x, column y represents the cost of the edge * between node x and y. If there is no edge, this value is -1 */ memset(g->nodes[i], -1, count * sizeof(int)); /* the node has always an 'edge' to itself with cost 0 */ g->nodes[i][i] = 0; /* lets give a name to the node for easy identification when printing */ sprintf(name, "q%d", i); graph_name_node(g, i, name); } return g; } void graph_name_node (graph_t *g, int node, const char *name) { /* sets the name of a node to an specified value */ /* free the current char array that holds its name */ if (g->names[node]) free(g->names[node]); /* duplicates the char *name array setting it to be the new name */ g->names[node] = strdup(name); } void graph_edge (graph_t *g, int from, int to, int cost) { /* adds an edge between the two specified nodes with the given cost */ g->nodes[from][to] = cost; /* since we are dealing with undirected graphs, there is a two way edge * between them, which we represent by having two edges on the matrix */ g->nodes[to][from] = cost; /* updates the total cost of the graph */ g->total += cost; /* updates the number of edges */ g->edges ++; } void graph_free (graph_t *g) { /* desallocates the memory for a given graph_t structure */ int i; for (i = 0; i < g->count; i ++) { /* we must free the name and the line for each node */ if (g->nodes[i]) free(g->nodes[i]); if (g->names[i]) free(g->names[i]); } /* and free the arrays that held their addresses */ free(g->names); free(g->nodes); /* finally we can free the graph_t structure */ free(g); } void graph_show (graph_t *g) { /* prints the edges that form a graph */ int i, j; for (i = 0; i < g->count; i ++) { for (j = 0; j < g->count; j ++) { /* we don't need to show the connection from a node to itself since * it is an implicit property of graphs. */ if (i != j && g->nodes[i][j] > 0) { /* print the nodes and the cost between them */ printf("%s ---- %d ----> %s\n", g->names[i], g->nodes[i][j], g->names[j]); /* once we have shown the edge between i and j, we don't need * to display it between j and i (we already know it is a two * way edge), so we remove the other way and restore it later */ g->nodes[j][i] = -1; } } } /* now we loop through each edge and restore their counterpart */ for (i = 0; i < g->count; i++) { for (j = 0; j < g->count; j ++) g->nodes[j][i] = g->nodes[i][j]; } } int graph_has_edge(graph_t *g, int from, int to) { /* checks if there is an edge between to nodes on the graph */ if (!g || !g->nodes) return 0; return (g->nodes[from][to] >= 0) || (g->nodes[to][from] >= 0); }
C
/* * Simulates a physical layer from the TCP/IP model. * Following this tutorial: http://www.linuxhowtos.org/C_C++/socket.htm * possibly, the following too: http://www.dicas-l.com.br/arquivo/programando_socket_em_c++_sem_segredo.php#.V9lODHUrLDc */ /* Camada Física: Recebe arquivo Transforma em binário Conectar socket Recebe a quantidade de bits Envia em pacotes da sugerida quantidade FALTA: Delinear o comando ARP separado do fluxo normal de execução. Delinear o comando de verificar tamanho do buffer do fluxo normal de execução. */ #include "physical.h" int main(int argc, char *argv[]) { int sockfd; // socket file descriptor, auxiliary n int sockfdil; // socket file descriptor of the internet layer int listener; // Internet Layer listener, to send requests. int bread; // number of bytes read struct sockaddr_in network_layer; socklen_t network_len = 0; char buffer[BUF_SIZ]; char internalBuffer[MAX_FILESIZE], rawrequest[MAX_FILESIZE]; char *hostnameOrIp, src_mac[MAC_SIZE], dst_mac[MAC_SIZE]; char *temp; struct Frame frame = {}; printf("Client Physical layer started!\n"); listener = startListening(PHYSICAL_PORT_CLIENT); while(1){ printf("Physical layer listening to upper layers on port %d...\n", PHYSICAL_PORT_CLIENT); sockfdil = accept(listener, (struct sockaddr *) &network_layer, &network_len); printf("Connection stabilished!\n"); // reads network package and finds destiny IP inside it. printf("Getting request from internet layer...\n"); bzero(internalBuffer,MAX_FILESIZE); bread=recv(sockfdil,internalBuffer,MAX_FILESIZE,0) <= 0; strncpy(rawrequest, internalBuffer, MAX_FILESIZE); temp=strtok(internalBuffer,"|"); while(temp != NULL){ if(strstr(temp,"ipdest:") == temp){ strtok(temp,":"); hostnameOrIp=strtok(NULL,":"); hostnameOrIp=trim(hostnameOrIp); break; } printf("temp: %s\n", temp); temp=strtok(NULL," "); } // This simulates physical layer Sending package though medium... writeFile(rawrequest, strlen(rawrequest), REQUEST_CLIENT_FILE); // Connecting to server socket: printf("Connecting to server %s on port %d...\n", hostnameOrIp, PORT_NUMBER); sockfd = connectSocket(hostnameOrIp, PORT_NUMBER); // Cheating to get server's MAC addres // THE CORRECT WAY IS USING ARP COMMAND. printf("Getting MAC Addresses...\n"); bzero(buffer,10); getMAC(buffer); // getting own mac buffer[6] = '\0'; sendMessage(sockfd, buffer); // sending mac to server strncpy(src_mac, buffer, 6); receiveMessage(sockfd, buffer); // receiving server's mac strncpy(dst_mac, buffer, 6); // Connection stabilished. Sending message requesting frame size: printf("Negotiating Frame Size....\n"); strcpy(buffer,"Yo, bro! What's the Frame size?"); sendMessage(sockfd, buffer); // Reading message from server: receiveMessage(sockfd, buffer); printf("Message size: %s\n", buffer); // Finally Sends request from the file created (physical medium) frame by frame to server. printf("Sending request to server...\n"); sendFile(sockfd,REQUEST_CLIENT_FILE, src_mac, dst_mac); remove( REQUEST_CLIENT_FILE ); // Receive response frame by frame from server and creates a temp file. printf("Waiting for server response...\n"); receiveFile(sockfd,RESPONSE_CLIENT_FILE); // Read response from the temp file and readFile(internalBuffer, RESPONSE_CLIENT_FILE); // Send response trough internet layer socket printf("Sending response to Internet Layer...\n"); sendMessage(sockfdil, internalBuffer); receiveMessage(sockfdil, internalBuffer); remove( RESPONSE_CLIENT_FILE ); close(sockfd); close(sockfdil); printf("\nDONE!\n\n"); } return 0; }
C
#include <stdio.h> int main(void){ int H,W; scanf("%d%d",&H,&W); char data[H+2][W+2]; char ans[H+2][W+2]; char sample[W]; for(int i = 0;i < H+2;i++){ for(int j = 0;j < W+2;j++){ data[i][j] = '.'; ans[i][j] = '#'; } } for(int i = 1;i < H+1;i++){ scanf("%s",sample); for(int j = 0;j < W;j++){ data[i][j+1] = sample[j]; } } for(int i = 1;i < H+1;i++){ for(int j = 1;j < W+1;j++){ if(data[i][j] != '#'){ int counter = 0; if(data[i-1][j-1] == '#') counter++; if(data[i-1][j] == '#') counter++; if(data[i-1][j+1] == '#') counter++; if(data[i][j-1] == '#') counter++; if(data[i][j+1] == '#') counter++; if(data[i+1][j-1] == '#') counter++; if(data[i+1][j] == '#') counter++; if(data[i+1][j+1] == '#') counter++; ans[i][j] = counter; } } } for(int i = 1;i < H+1;i++){ for(int j = 1;j < W+1;j++){ if(ans[i][j] == '#') printf("#"); else printf("%d",ans[i][j]); } printf("\n"); } return 0; } ./Main.c: In function main: ./Main.c:5:3: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result] scanf("%d%d",&H,&W); ^ ./Main.c:18:5: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result] scanf("%s",sample); ^
C
/* Autor: Sabrina Beck Angelini RA: 157240 Disciplina: MC202 Turma: E Tarefa 06 Segundo semestre de 2014 */ /* * analisador.c: Mdulo de transformao de expresses em rvores * binrias e seus percursos. */ #include "analisador.h" #include <stdlib.h> #include <ctype.h> #include "balloc.h" #include <string.h> /* Variveis globais a este mdulo */ char *in; /* Cadeia e ndice para expresso infixa (entrada). */ int indIn; Erro resCorreto = {EXPR_VALIDA,0}; /* resultado correto */ /* Macro para desprezar espaos em branco na cadeia de entrada. */ /* Para evitar chamadas desnecessrias a esta macro, adotou-se */ /* seguinte conveo. A macro invocada uma vez imediatamente */ /* antes da primeira chamada funo Expressao e imediatamente */ /* aps todo o incremento de indIn. */ #define DESPREZA_ESPACOS() while (in[indIn] == ' ') indIn++ typedef enum bool { false, true } bool; /* Prottipos das funes mutuamente recursivas. */ /* O resultado devolvido atravs da varivel 'arv'. */ Erro Expressao(ArvBin *arv); Erro Termo(ArvBin *arv); Erro Fator(ArvBin *arv); Erro Primario(ArvBin *arv); Erro Unario(ArvBin *arv); void ignoraBrancos(); /* Funo auxiliar -- declarada mais adiante */ Erro montaErro(int codigo, int pos); bool fimDaCadeia(char c); /*************************************************************/ /* Funo principal */ /*************************************************************/ Erro InArv(char *infixa, ArvBin *arv) { /* Transforma a notao infixa em rvore binria. Em caso de erro, devolve o cdigo e a posio na cadeia de entrada onde o erro foi encontrado. */ Erro erro; /* Inicializa string infixa usada na converso */ in = infixa; indIn = 0; /* Inicializa rvore */ *arv = NULL; /* Verifica se no uma cadeia de caractere brancos */ ignoraBrancos(); if(!in[indIn]) return montaErro(CADEIA_DE_BRANCOS, 0); /* Transforma a expresso infixa em uma rvore binria de expresso */ erro = Expressao(arv); /* Verifica se houve algum erro na transformao */ if(erro.codigoErro != EXPR_VALIDA) return erro; /* * Se ainda tiver dados na cadeia infixa para serem interpretados, * significa que falta algum operador, uma vez que o algoritmo encerra * quando no acha o operador esperado */ if(!fimDaCadeia(in[indIn])) erro = montaErro(OPERADOR_ESPERADO, indIn); return erro; } /*************************************************************/ /* Funes de implementao do analisador */ /*************************************************************/ /* * Verifica se o caracter representa o fim de cadeia de caracteres */ bool fimDaCadeia(char c) { return c == '\0' || c == '\n'; } /* * Verifica se o caracter um caracter previsto pela implementao */ bool caracterValido(char c) { return fimDaCadeia(c) || (c >= 'a' && c <= 'z') || c == '(' || c == ')' || c == '+' || c == '-' || c == '*' || c == '/' || c == '^'; } /* * Ignora caractere em branco, uma vez que no significam erro * na cadeia de entrada e nem um dado de entrada */ void ignoraBrancos() { char atual = in[indIn]; if(atual == ' ') { indIn++; ignoraBrancos(); } } /* * Faz o tratamento da entrada ignorando caracteres em branco e * verificando caracteres invlidos */ Erro trataEntrada() { char atual; ignoraBrancos(); atual = in[indIn]; /* Verifica se o caracter atual previsto pela implementao, se vlido */ if(!caracterValido(atual)) return montaErro(CARACTERE_INVALIDO, indIn); return resCorreto; } Erro montaErro(int codigo, int posicao) { /* Devolve estrutura com cdigo de erro e posio */ Erro erro; erro.posicao = posicao; erro.codigoErro = codigo; return erro; } /* montaErro */ /* * Cria um N de rvore, com filhos nulos, * concentra cdigo de alocao dinmica */ void criaNoArv(ArvBin *arv) { *arv = MALLOC(sizeof(NoArvBin)); (*arv)->esq = NULL; (*arv)->dir = NULL; } Erro Expressao(ArvBin *arv) { /* Processa uma expresso da cadeia de entrada. */ char atual; Erro erro; /* noAtual ter a rvore resultante no fim do algoritimo */ ArvBin *noAtual = arv, filhoEsq; /* Se a expresso comear com um operador '+' ou '-', ele unrio */ if(in[indIn] == '+' || in[indIn] == '-') erro = Unario(noAtual); else /* * Caso no tenha um operador unrio no incio da expresso, ento * o primeiro termo tratado */ erro = Termo(noAtual); /* * Essa verificao necessria sempre que um mtodo retornar erro, pois neste caso, no necessrio * continuar a anlise (nem possvel continuar) , uma vez errada a expresso a recurso/mtodo/anlise deve * ser interrompida e o erro retornado para tratamento no programa principal. */ if(erro.codigoErro != EXPR_VALIDA) return erro; do { /* * Caso haja um operador de expresso ('+' ou '-') ento o primeiro termo analisado filho esquerdo * do operador na arvore binria de expresso resultante */ filhoEsq = *noAtual; /* Tratamento de caracteres invlidos e espaos em branco */ erro = trataEntrada(); if(erro.codigoErro != EXPR_VALIDA) return erro; atual = in[indIn]; if(atual == '+' || atual == '-') { /* * Cria rvore equivalente operao atual, ou seja, * a raiz ser o operador encontrado ('+' ou '-') seu * filho esquerdo ser a ltima operao (parte da expresso ou um termo) * analisada e seu filho direito ser o prximo termo analisado */ criaNoArv(noAtual); (*noAtual)->info = atual; (*noAtual)->esq = filhoEsq; /* Controle do ndice atual na cadeia de entrada */ indIn++; /* * Para cada operador '+' e '-' existe um termo a ser avaliado, * sendo este o filho direito do operador atual */ erro = Termo(&((*noAtual)->dir)); /* * Verificao necessria para no continuar a anlise em expresso errada * Tambm desaloca a memria necessria */ if(erro.codigoErro != EXPR_VALIDA) { LiberaArv(*noAtual); return erro; } } else /* Se no achar mais operadores, ento a expresso acabou */ break; } while (true); /* No fim, noAtual ter a rvore resultante */ *arv = *noAtual; return erro; } /* Expressao */ Erro Termo(ArvBin *arv) { /* Processa um termo da cadeia de entrada. */ /* noAtual ter a rvore resultante no fim do algoritimo */ ArvBin *noAtual = arv, filhoEsq; Erro erro; /* Todo termo comea com um fator a ser analisado */ erro = Fator(noAtual); /* Verificao necessria para no continuar a anlise em expresso errada */ if(erro.codigoErro != EXPR_VALIDA) return erro; do { char atual; /* * Se existir algum operador de termo '*' ou '/' o primeiro fator * analisado ser filho esquerdo deste operador */ filhoEsq = *noAtual; /* Tratamento de caracteres invlidos e espaos em branco */ erro = trataEntrada(); /* Verificao necessria para no continuar a anlise em expresso errada */ if(erro.codigoErro != EXPR_VALIDA) return erro; atual = in[indIn]; if(atual == '*' || atual == '/') { /* * Cria rvore equivalente operao atual, ou seja, * a raiz ser o operador encontrado ('*' ou '/') seu * filho esquerdo ser a ltima operao (parte do termo ou um fator) * analisada e seu filho direito ser o prximo fator analisado */ criaNoArv(noAtual); (*noAtual)->info = atual; (*noAtual)->esq = filhoEsq; /* Controle do ndice atual na cadeia de entrada */ indIn++; /* * Para cada operador '*' e '/' existe um fator a ser avaliado, * sendo este o filho direito do operador atual */ erro = Fator(&((*noAtual)->dir)); /* * Verificao necessria para no continuar a anlise em expresso errada * Tambm desaloca a memria necessria */ if(erro.codigoErro != EXPR_VALIDA) { LiberaArv(*noAtual); return erro; } } else /* Se no achar mais operadores, ento o termo acabou */ break; } while (true); /* No fim, noAtual ter a rvore resultante */ *arv = *noAtual; return erro; } /* Termo */ Erro Fator(ArvBin *arv) { /* Processa um fator da cadeia de entrada. */ char atual; Erro erro; /* Um fator comea com um primrio */ erro = Primario(arv); /* Verificao necessria para no continuar a anlise em expresso errada */ if(erro.codigoErro != EXPR_VALIDA) return erro; /* Tratamento de caracteres invlidos e espaos em branco */ erro = trataEntrada(); if(erro.codigoErro != EXPR_VALIDA) return erro; atual = in[indIn]; /* Um fator uma sequncia de potncias */ if(atual == '^') { /* * A rvore resultante ter como raiz o operador de potencia '^', * seu filho esquerdo ser o primrio lido nessa chamada e seu * filho esquerdo ser composta pelo fator analisado posteriormente */ ArvBin aux = *arv; criaNoArv(arv); (*arv)->esq = aux; (*arv)->info = atual; /* Controle do ndice atual na cadeia de entrada */ indIn++; /* * Para cada operador '^' existe um fator a ser avaliado, * sendo este o filho direito do operador atual */ erro = Fator(&((*arv)->dir)); /* Verificao necessria para no continuar a anlise em expresso errada */ if(erro.codigoErro != EXPR_VALIDA) return erro; } return erro; } /* Fator */ Erro Primario(ArvBin *arv) { /* Processa um primrio da cadeia de entrada. */ char atual; Erro erro = resCorreto; erro = trataEntrada(); if(erro.codigoErro != EXPR_VALIDA) return erro; atual = in[indIn]; if(atual >= 'a' && atual <= 'z') { indIn++; criaNoArv(arv); (*arv)->info = atual; } else if(atual == '(') { indIn++; erro = Expressao(arv); if(erro.codigoErro != EXPR_VALIDA) return erro; atual = in[indIn]; if(atual == ')') indIn++; else return montaErro(FECHA_PARENTESE_ESPERADO, indIn); } else return montaErro(OPERANDO_ESPERADO, indIn); return erro; } /* Primario */ Erro Unario(ArvBin *arv) { char atual = in[indIn]; Erro erro = resCorreto; criaNoArv(arv); /* Os nicos operadores unrios existentes so '+' e '-' */ if (atual == '+') { int anterior = indIn++; /* controle para ver se h realmente um operando para esse operador */ /* * Na rvore de expresso a raz ser o operador unrio e seu filho * direito ser o termo correspondente */ (*arv)->info = '&'; erro = Termo(&((*arv)->dir)); /* Verificao necessria para no continuar a anlise em expresso errada */ if(erro.codigoErro != EXPR_VALIDA) return erro; /* Verifica se h realmente um operando para esse operador */ if(anterior == indIn) return montaErro(OPERANDO_ESPERADO, indIn); } else if (atual == '-') { int anterior = indIn++; /* controle para ver se h realmente um operando para esse operador */ /* * Na rvore de expresso a raz ser o operador unrio e seu filho * direito ser o termo correspondente */ (*arv)->info = '~'; erro = Termo(&((*arv)->dir)); /* Verificao necessria para no continuar a anlise em expresso errada */ if(erro.codigoErro != EXPR_VALIDA) return erro; /* Verifica se h realmente um operando para esse operador */ if(anterior == indIn) return montaErro(OPERANDO_ESPERADO, indIn); } return erro; } /* Unario */ /* Percursos */ void ArvPre(ArvBin arv, char *pre) { /* Produz a representao pr-fixa a partir da rvore. */ if(arv != NULL) { /* * Como o resultado deve estar na cadeia pre, * o dado analisado atualmente o primeiro da cadeia, * depois ela usada para armazenar o percurso na subrvore esquerda * e posteriormente concatenada com o percurso da subrvore direito */ char preDir[TAM_MAX_EXPR + 1]; *pre = arv->info; ArvPre(arv->esq, pre + 1); ArvPre(arv->dir, preDir); strcat(pre, preDir); } else /* Por ltimo deve ser informado o fim da cadeia */ *pre = '\0'; } void ArvPos(ArvBin arv, char *pos) { /* Produz a representao ps-fixa a partir da rvore. */ if(arv != NULL) { /* * Como o resultado deve estar na cadeia pos, * primeiro ela usada para armazenar o percurso na subrvore esquerda * depois ela concatenada com o percurso da subrvore direita * e por ultimo, o dado atualmente lido concatenado a cadeia */ char posDir[TAM_MAX_EXPR + 1], atual[2]; atual[0] = arv->info; atual[1] = '\0'; /* Garante que a string final tenha o delimitador '\0' */ ArvPos(arv->esq, pos); ArvPos(arv->dir, posDir); strcat(pos, posDir); strcat(pos, atual); } else /* Por ltimo deve ser informado o fim da cadeia */ *pos = '\0'; } void LiberaArv(ArvBin arv) { /* Libera o espao ocupado pela rvore. */ /* * Para liberar o espao alocado da rvore devemos * desalocar a raiz por ultimo (para no perder a referencia * para seus filhos, para isso, usamos o percurso pos-ordem */ if(arv != NULL) { LiberaArv(arv->esq); LiberaArv(arv->dir); FREE(arv); } }
C
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> void main() { int count = 0; FILE* fp; fp = fopen(".txt", "w"); fputs("\nâ\nâ\nâ\n\nö\nŸ\nŸ\nܴٸũ\nũƮ\n Ÿ\n", fp); char imshee[200] = { NULL }; fclose(fp); fp = fopen(".txt", "r"); while (fgets(imshee, 200, fp)) { printf("%s", imshee); } fclose(fp); }
C
#include "math.h" #include "FFT.h" struct compx EE(struct compx a,struct compx b) { struct compx c; c.real=a.real*b.real-a.imag*b.imag; c.imag=a.real*b.imag+a.imag*b.real; return(c); } void FFT(struct compx *xin) { int f,m,nv2,nm1,i,k,l,j=0; struct compx u,w,t; // ַ㣬Ȼ˳ɵλ򣬲׵㷨 nv2=NPT/2; nm1=NPT-1; // i<j,бַ for (i=0;i<nm1;i++) { if (i<j) { t=xin[j]; xin[j]=xin[i]; xin[i]=t; } // jһλ k=nv2; // k<=j,ʾjλΪ1 while (k<=j) { // λ0 j=j-k; // k/2ȽϴθλƣȽϣֱijλΪ0 k=k/2; } j=j+k; // 0Ϊ1 } // FFTˣʹõFFT int le,lei,ip; f=NPT; // lֵμ for (l=1;(f=f/2)!=1;l++); // Ƶνἶ for (m=1;m<=l;m++) { // mʾmΣlΪμl=log2N // leν룬mεĵνle le=2<<(m-1); // ͬһνвμľ lei=le/2; // uΪνϵʼֵΪ1 u.real=1.0; u.imag=0.0; // wΪϵ̣ǰϵǰһϵ w.real=cos(PI/lei); w.imag=-sin(PI/lei); // Ƽ㲻ֵͬνᣬϵͬĵν for(j=0;j<=lei-1;j++) { // ͬһν㣬ϵͬν for(i=j;i<=NPT-1;i=i+le) { // iipֱʾμӵڵ ip=i+lei; // t=EE(xin[ip],u); xin[ip].real=xin[i].real-t.real; xin[ip].imag=xin[i].imag-t.imag; xin[i].real=xin[i].real+t.real; xin[i].imag=xin[i].imag+t.imag; } //ıϵһ u=EE(u,w); } } }
C
#include <stdio.h> #include <cs50.h> #include <math.h> int main(void) { float change; do { change = get_float("How much change is owed? "); } while (change < 0); int cents = round(change * 100); int coins = 0; int quarter, dime, nickel, penny; quarter = 25; dime = 10; nickel = 5; penny = 1; while (cents >= quarter) { cents = cents - quarter, coins++; } while (cents >= dime) { cents = cents - dime, coins++; } while (cents >= nickel) { cents = cents - nickel, coins++; } while (cents >= penny) { cents = cents - penny, coins++; } printf("Coins = %i\n", coins); }
C
/** @file Blob verifier library that uses SEV hashes table. The hashes table holds the allowed hashes of the kernel, initrd, and cmdline blobs. Copyright (C) 2021, IBM Corporation SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include <Library/BaseCryptLib.h> #include <Library/BaseLib.h> #include <Library/BaseMemoryLib.h> #include <Library/DebugLib.h> #include <Library/BlobVerifierLib.h> /** The SEV Hashes table must be in encrypted memory and has the table and its entries described by <GUID>|UINT16 <len>|<data> With the whole table GUID being 9438d606-4f22-4cc9-b479-a793d411fd21 The current possible table entries are for the kernel, the initrd and the cmdline: 4de79437-abd2-427f-b835-d5b172d2045b kernel 44baf731-3a2f-4bd7-9af1-41e29169781d initrd 97d02dd8-bd20-4c94-aa78-e7714d36ab2a cmdline The size of the entry is used to identify the hash, but the expectation is that it will be 32 bytes of SHA-256. **/ #define SEV_HASH_TABLE_GUID \ (GUID) { 0x9438d606, 0x4f22, 0x4cc9, { 0xb4, 0x79, 0xa7, 0x93, 0xd4, 0x11, 0xfd, 0x21 } } #define SEV_KERNEL_HASH_GUID \ (GUID) { 0x4de79437, 0xabd2, 0x427f, { 0xb8, 0x35, 0xd5, 0xb1, 0x72, 0xd2, 0x04, 0x5b } } #define SEV_INITRD_HASH_GUID \ (GUID) { 0x44baf731, 0x3a2f, 0x4bd7, { 0x9a, 0xf1, 0x41, 0xe2, 0x91, 0x69, 0x78, 0x1d } } #define SEV_CMDLINE_HASH_GUID \ (GUID) { 0x97d02dd8, 0xbd20, 0x4c94, { 0xaa, 0x78, 0xe7, 0x71, 0x4d, 0x36, 0xab, 0x2a } } STATIC CONST EFI_GUID mSevKernelHashGuid = SEV_KERNEL_HASH_GUID; STATIC CONST EFI_GUID mSevInitrdHashGuid = SEV_INITRD_HASH_GUID; STATIC CONST EFI_GUID mSevCmdlineHashGuid = SEV_CMDLINE_HASH_GUID; #pragma pack (1) typedef struct { GUID Guid; UINT16 Len; UINT8 Data[]; } HASH_TABLE; #pragma pack () STATIC HASH_TABLE *mHashesTable; STATIC UINT16 mHashesTableSize; STATIC CONST GUID * FindBlobEntryGuid ( IN CONST CHAR16 *BlobName ) { if (StrCmp (BlobName, L"kernel") == 0) { return &mSevKernelHashGuid; } else if (StrCmp (BlobName, L"initrd") == 0) { return &mSevInitrdHashGuid; } else if (StrCmp (BlobName, L"cmdline") == 0) { return &mSevCmdlineHashGuid; } else { return NULL; } } /** Verify blob from an external source. @param[in] BlobName The name of the blob @param[in] Buf The data of the blob @param[in] BufSize The size of the blob in bytes @retval EFI_SUCCESS The blob was verified successfully. @retval EFI_ACCESS_DENIED The blob could not be verified, and therefore should be considered non-secure. **/ EFI_STATUS EFIAPI VerifyBlob ( IN CONST CHAR16 *BlobName, IN CONST VOID *Buf, IN UINT32 BufSize ) { CONST GUID *Guid; INT32 Remaining; HASH_TABLE *Entry; if ((mHashesTable == NULL) || (mHashesTableSize == 0)) { DEBUG (( DEBUG_ERROR, "%a: Verifier called but no hashes table discoverd in MEMFD\n", __FUNCTION__ )); return EFI_ACCESS_DENIED; } Guid = FindBlobEntryGuid (BlobName); if (Guid == NULL) { DEBUG (( DEBUG_ERROR, "%a: Unknown blob name \"%s\"\n", __FUNCTION__, BlobName )); return EFI_ACCESS_DENIED; } // // Remaining is INT32 to catch underflow in case Entry->Len has a // very high UINT16 value // for (Entry = mHashesTable, Remaining = mHashesTableSize; Remaining >= sizeof *Entry && Remaining >= Entry->Len; Remaining -= Entry->Len, Entry = (HASH_TABLE *)((UINT8 *)Entry + Entry->Len)) { UINTN EntrySize; EFI_STATUS Status; UINT8 Hash[SHA256_DIGEST_SIZE]; if (!CompareGuid (&Entry->Guid, Guid)) { continue; } DEBUG ((DEBUG_INFO, "%a: Found GUID %g in table\n", __FUNCTION__, Guid)); EntrySize = Entry->Len - sizeof Entry->Guid - sizeof Entry->Len; if (EntrySize != SHA256_DIGEST_SIZE) { DEBUG (( DEBUG_ERROR, "%a: Hash has the wrong size %d != %d\n", __FUNCTION__, EntrySize, SHA256_DIGEST_SIZE )); return EFI_ACCESS_DENIED; } // // Calculate the buffer's hash and verify that it is identical to the // expected hash table entry // Sha256HashAll (Buf, BufSize, Hash); if (CompareMem (Entry->Data, Hash, EntrySize) == 0) { Status = EFI_SUCCESS; DEBUG (( DEBUG_INFO, "%a: Hash comparison succeeded for \"%s\"\n", __FUNCTION__, BlobName )); } else { Status = EFI_ACCESS_DENIED; DEBUG (( DEBUG_ERROR, "%a: Hash comparison failed for \"%s\"\n", __FUNCTION__, BlobName )); } return Status; } DEBUG (( DEBUG_ERROR, "%a: Hash GUID %g not found in table\n", __FUNCTION__, Guid )); return EFI_ACCESS_DENIED; } /** Locate the SEV hashes table. This function always returns success, even if the table can't be found. The subsequent VerifyBlob calls will fail if no table was found. @retval RETURN_SUCCESS The hashes table is set up correctly, or there is no hashes table **/ RETURN_STATUS EFIAPI BlobVerifierLibSevHashesConstructor ( VOID ) { HASH_TABLE *Ptr; UINT32 Size; mHashesTable = NULL; mHashesTableSize = 0; Ptr = (void *)(UINTN)FixedPcdGet64 (PcdQemuHashTableBase); Size = FixedPcdGet32 (PcdQemuHashTableSize); if ((Ptr == NULL) || (Size < sizeof *Ptr) || !CompareGuid (&Ptr->Guid, &SEV_HASH_TABLE_GUID) || (Ptr->Len < sizeof *Ptr) || (Ptr->Len > Size)) { return RETURN_SUCCESS; } DEBUG (( DEBUG_INFO, "%a: Found injected hashes table in secure location\n", __FUNCTION__ )); mHashesTable = (HASH_TABLE *)Ptr->Data; mHashesTableSize = Ptr->Len - sizeof Ptr->Guid - sizeof Ptr->Len; DEBUG (( DEBUG_VERBOSE, "%a: mHashesTable=0x%p, Size=%u\n", __FUNCTION__, mHashesTable, mHashesTableSize )); return RETURN_SUCCESS; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> int main() { int c; FILE *in, *out; struct timeval tempo1, tempo2; struct timezone tzp; double tempo; in = fopen("file1GB.in","r"); out = fopen("file1GB.out","w"); gettimeofday(&tempo1,&tzp); while((c = fgetc(in)) != EOF) { fputc(c,out); } gettimeofday(&tempo2,&tzp); tempo= (double)(tempo2.tv_sec-tempo1.tv_sec)+(((double)(tempo2.tv_usec-tempo1.tv_usec))/1000000); printf("==============================================\n"); printf("O tempo de copia do file1GB é de: %f\n", tempo); printf("==============================================\n"); return 0; }
C
//Program to implement : File Object W/R //Refer : FileHandling.png //See : fileObjectIO.png #include<stdio.h> typedef struct { char name[20]; int age; char gender; } Person; int main() { FILE *fio; int ch; Person p = {"Vikas", 25, 'M'}; Person p1; fio = fopen("d:\\objectIO.txt", "wb+"); if(fio == NULL) { printf("\n File Open Failed"); return 1;//exit main fn } //file open w/r object //write 1 object of given size (address given) into the file fwrite(&p,sizeof(Person),1,fio); rewind(fio); //read from the file data of 1 object (of given size) and transfer into the address of given object. fread(&p1,sizeof(Person),1,fio); printf("\n p{ %s %d %c }", p.name, p.age, p.gender); printf("\n p1{ %s %d %c }", p1.name, p1.age, p1.gender); fclose(fio); return 0; }
C
#include<stdio.h> /* ӡ */ void printArr(int nums[],int n){ printf("\n"); int i = 0; for(i=0;i<n;i++){ printf("%d\t",nums[i]); } printf("\n"); } /* ʹöֲ˳вԪk */ void insertK(int nums[],int n,int k){ int mid;// ¼м± int low=0,high=n-1; int flag=0;// ־¼Ƿеkֵ int pos;// ıΪλ while(low<=high&&flag==0){// ѭlow>highʱѭ mid=(low+high)/2; if(nums[mid]==k){ flag=1;// йؼֵk,򽫱־flagΪ1˳ѭȻk }else if(nums[mid]>k){ high=mid-1; }else if(nums[mid]<k){ low=mid+1; } } /* ȷλ */ if(flag==1){// flagΪ1йؼֵkʹλõmid pos=mid; }else{// flagΪ0ʾûؼkȵֵλΪlow λΪҪĵһ pos=low; } /* ؼk */ int i = 0; for(i=n-1;i>=pos;i--){ //ƶһλ nums[i+1]=nums[i]; } nums[pos]=k; } int main(){ int nums[]={1,12,16,24,35,46,67,0};//鳤Ҫһ int n= sizeof(nums)/sizeof(int); int k=24; insertK(nums,n-1,k);// k printArr(nums,n);// ӡ return 0; }
C
#include<stdio.h> int main() { int a = 0, b = 0, ch = 0, result = 0; scanf_s("%d", &a); scanf_s("%d", &b); printf("enter 1.add 2.sub 3.div 4.mul"); scanf_s("%d", &ch); switch (ch) { case 1: result = add(a, b); break; case 2: result = sub(a, b); break; case 3: result = div(a, b); break; case 4: result = mul(a, b); break; default: printf("choose a valid numebr"); } printf("%d", result); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int statCalc(int dice); int diceRoll(); void operation(int dice); int main() { printf("Welcome to the Stat Roller!\n"); printf("This Stat Roller can use the Standard, Classic, or Heroic rolls to determine stats\n"); int choice; int dice; do { printf("\n1. Standard\n2. Classic\n3. Heroic\nChoose a roll type: "); choice = 9; scanf("%i", &choice); if(choice == 1) { dice = 4; operation(dice); } if(choice == 2) { int dice = 3; operation(dice); } if(choice == 3) { int dice = 2; operation(dice); } }while(choice != 0); return 0; } void operation(int dice) { int stats[6]; char player_continue[4]; do { // Rolls for the six player stats using stat_roll function int x; for(x = 0; x <= 5; x++) { stats[x] = statCalc(dice); } // Prints all stats on one line. Create new blank line printf("\n%i, %i, %i, %i, %i, %i\n", stats[0], stats[1], stats[2], stats[3], stats[4], stats[5]); // Asks user if they wish to continue // At the moment, anything will allow the program to roll again printf("Enter \'n\' to exit. Enter \'y\' to continue: "); scanf("%s", player_continue); }while(strcmp(player_continue, "n")); } int diceRoll() { return rand()%6+1; } int statCalc(int dice) { // Initialization of variables // i and total int i, total, small; total = small = diceRoll(); //For loop for(i = 1; i < dice; i++) { int roll = diceRoll(); total += roll; } if (dice == 2) { total += 6; } else if (dice == 4) { total -= small; } return total; } /* Particular issue has been realized. I wish to broaden the scope of this so that Pathfinder/D&D's other systems for rolling stats is taken into account as well. Future steps would be to add a GUI interface on top of all this. What may need to be done is to have the function 'stat_roll' accept an X amount for the variable size for rolls and then to have the search functions also call upon this size. To elaborate, Pathfinder details at least three basic roll systems for Ability Score generation. Standard makes you roll 4d6 and discard the lowest, adding the rest of the numbers. Classic makes you roll only 3d6 and just add them there and then. Heroic makes you roll 2d6, add the dice, then add 6. So what I would want to do very much so is have 'stat_roll' accept two variables. A variable for dice and a variable signifying if the roll is for a heroic roll. Or maybe I could have an if statement that checks the variable for dice amount and signifies from there whether a flat six needs to be added to the roll. */
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_validation.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gkessler <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/03 12:07:22 by gkessler #+# #+# */ /* Updated: 2019/02/04 10:28:41 by gkessler ### ########.fr */ /* */ /* ************************************************************************** */ #include "fractol.h" void ft_check_error(char *str) { if (!(ft_strcmp("usage", str))) { ft_putendl("usage : Mandelbrot_set \ [m]\tJulia_set [j]\tBurning_ship [b]"); ft_putendl(" Lam_mandelbrot \ [l]\tSea_horse [h]\tSpider_set [s]"); ft_putendl(" Set_carpet \ [c]\tSet_umbrella [u]"); } else ft_putendl(str); exit(0); } int ft_fractol_kind(char **argv, t_fr *fr) { if (!(ft_strcmp("j", argv[1]))) fr->get_set = juliya_set; else if (!(ft_strcmp("m", argv[1]))) fr->get_set = mandelbrot_set; else if (!(ft_strcmp("b", argv[1]))) fr->get_set = set_burning; else if (!(ft_strcmp("h", argv[1]))) fr->get_set = sea_horse; else if (!(ft_strcmp("l", argv[1]))) fr->get_set = lambda_mandelbrot; else if (!(ft_strcmp("s", argv[1]))) fr->get_set = set_spider; else if (!(ft_strcmp("c", argv[1]))) fr->get_set = set_carpet; else if (!(ft_strcmp("u", argv[1]))) fr->get_set = set_umbrella; else return (0); return (1); } int ft_validate(int argc) { if (argc > 2) ft_check_error("Nope! Just one window Dude!"); if (argc < 2) { ft_check_error("usage"); } return (1); }
C
/** * @file webnav.c * @brief POJ 1057 */ #include <stdio.h> #include <string.h> char sites[101][71]={"http://www.acm.org/"}; char cmd[8]; int main(void) { int i=0; loop: scanf("%s",cmd); switch(*cmd){ case 'Q': return 0; case 'V': scanf("%s",sites[++i]); sites[i+1][0]='\0'; break; case 'B': i--; if(i<0){ puts("Ignored"); i++; goto loop; } break; case 'F': i++; if(sites[i][0]=='\0'){ puts("Ignored"); i--; goto loop; } break; } puts(sites[i]); goto loop; return 0; }
C
#include "common.h" int rem_dupl(slist **head) { //validation if(*head == NULL) { return LIST_EMPTY; } //initialize slist *temp, *temp1; temp = *head; slist *remp; //run an outer loop to compare each value one by one to other elements while(temp) { //start another pointer to start the run from the value the temp is pointing at and compare each value to temp's value. temp1 = temp; //run another pointer remp along with temp1 but it should always be pointing to previus node of temp1 remp = temp1; temp1 = temp1->link; //check whether the temp1 is null or not. while(temp1) { //check if the data matches or not , if matches then delete the node . if(temp->data == temp1->data) { //this is to store next elements address and delete the element. remp->link = temp1->link; free(temp1); //once the element is deleted. we killed the temp1 in order to delete the element. //the below line revives the temp1 and makes it pount to the next node. temp1 = remp->link; } else { if(temp1) { //if the data doesnt match then we will be moving the remp to temp1's place and temp1 to the the next node. remp = temp1; temp1 = temp1->link; } } } temp = temp->link; } return SUCCESS; }
C
#include <stdio.h> #include <string.h> int main(int argc, char** argv) { if(argc < 2) return -1; const char* str = argv[1]; unsigned int l = strlen(str), h = 2 ^ l, i = 0, k; while(l >= 4) { k = str[i] | str[i+1] << 8 | str[i+2] << 16 | str[i+3] << 24; k = (k & 0xffff) * 1540483477 + (((k >> 16) * 1540483477 & 0xffff) << 16); k ^= k >> 24; k = (k & 0xffff) * 1540483477 + (((k >> 16) * 1540483477 & 0xffff) << 16); h = (h & 0xffff) * 1540483477 + (((h >> 16) * 1540483477 & 0xffff) << 16) ^ k; l -= 4; i += 4; } switch(l) { case 3: h ^= (str[i + 2] & 0xff) << 16; case 2: h ^= (str[i + 1] & 0xff) << 8; case 1: h ^= str[i] & 0xff; h = (h & 0xffff) * 1540483477 + (((h >> 16) * 1540483477 & 0xffff) << 16); } h ^= h >> 13; h = (h & 0xffff) * 1540483477 + (((h >> 16) * 1540483477 & 0xffff) << 16); h ^= h >> 15; printf("%u", h >> 0); return 0; }
C
/* int L_saturate(double dVar1) { if( dVar1 > (double)0x7FFFFFFF ) { return 0x7FFFFFFF; } else if( dVar1 < (double)0x80000000){ return (int)0x80000000; } else { return (int)dVar1; } } int L_deposit_l(short var1) { return (int)var1; } int L_deposit_h(short var1) { int lvar; lvar = (int ) var1 << 16; return lvar; } short extract_l(short L_var1) { return (short) (0x0000ffffL & L_var1); } short extract_h(int L_var1) { return (short) (0x0000ffffL & (L_var1 >> 16)); } */
C
#include <stdio.h> // for stderr #include <stdlib.h> // for exit() #include "types.h" #include "utils.h" #include "riscv.h" void execute_rtype(Instruction, Processor *); void execute_itype_except_load(Instruction, Processor *); void execute_branch(Instruction, Processor *); void execute_jal(Instruction, Processor *); void execute_load(Instruction, Processor *, Byte *); void execute_store(Instruction, Processor *, Byte *); void execute_ecall(Processor *, Byte *); void execute_lui(Instruction, Processor *); unsigned get_bit_range(unsigned, unsigned, unsigned); unsigned set_bit(unsigned input, unsigned pos, unsigned val); void print_debug_instruction(uint32_t instruction_bits); void execute_instruction(uint32_t instruction_bits, Processor *processor,Byte *memory) { Instruction instruction = parse_instruction(instruction_bits); switch(instruction.opcode) { case 0x33: execute_rtype(instruction, processor); break; case 0x13: execute_itype_except_load(instruction, processor); break; case 0x73: execute_ecall(processor, memory); break; case 0x63: execute_branch(instruction, processor); break; case 0x6F: execute_jal(instruction, processor); break; case 0x23: execute_store(instruction, processor, memory); break; case 0x03: execute_load(instruction, processor, memory); break; case 0x37: execute_lui(instruction, processor); break; default: // undefined opcode handle_invalid_instruction(instruction); exit(-1); break; } } void execute_rtype(Instruction instruction, Processor *processor) { switch (instruction.rtype.funct3){ case 0x0: switch (instruction.rtype.funct7) { case 0x0: // Add processor->R[instruction.rtype.rd] = (int32_t) processor->R[instruction.rtype.rs1] + (int32_t) processor->R[instruction.rtype.rs2]; processor->PC += 4; break; case 0x1: // Mul processor->R[instruction.rtype.rd] = (int32_t) processor->R[instruction.rtype.rs1] * (int32_t) processor->R[instruction.rtype.rs2]; processor->PC += 4; break; case 0x20: // Sub processor->R[instruction.rtype.rd] = (int32_t) processor->R[instruction.rtype.rs1] - (int32_t) processor->R[instruction.rtype.rs2]; processor->PC += 4; break; default: handle_invalid_instruction(instruction); exit(-1); break; } break; case 0x1: switch (instruction.rtype.funct7) { case 0x0: // SLL processor->R[instruction.rtype.rd] = processor->R[instruction.rtype.rs1] << processor->R[instruction.rtype.rs2]; processor->PC += 4; break; case 0x1: // MULH fprintf(stderr, "%s", "CALLED mulH\n"); int64_t result = (int32_t) processor->R[instruction.rtype.rs1] * (int32_t) processor->R[instruction.rtype.rs2]; processor->R[instruction.rtype.rd] = (int32_t) (result >> 32); processor->PC += 4; break; } break; case 0x2: // SLT processor->R[instruction.rtype.rd] = (int32_t) processor->R[instruction.rtype.rs1] < (int32_t) processor->R[instruction.rtype.rs2]; processor->PC += 4; break; case 0x4: switch (instruction.rtype.funct7) { case 0x0: // XOR processor->R[instruction.rtype.rd] = processor->R[instruction.rtype.rs1] ^ processor->R[instruction.rtype.rs2]; processor->PC += 4; break; case 0x1: // DIV processor->R[instruction.rtype.rd] = (int32_t) processor->R[instruction.rtype.rs1] / (int32_t) processor->R[instruction.rtype.rs2]; processor->PC += 4; break; default: handle_invalid_instruction(instruction); exit(-1); break; } break; case 0x5: switch (instruction.rtype.funct7) { case 0x0: // SRL processor->R[instruction.rtype.rd] = processor->R[instruction.rtype.rs1] >> processor->R[instruction.rtype.rs2]; processor->PC += 4; break; case 0x20: // SRA processor->R[instruction.rtype.rd] = (int32_t) processor->R[instruction.rtype.rs1] >> processor->R[instruction.rtype.rs2]; processor->PC += 4; break; default: handle_invalid_instruction(instruction); exit(-1); break; } break; case 0x6: switch (instruction.rtype.funct7) { case 0x0: // OR processor->R[instruction.rtype.rd] = processor->R[instruction.rtype.rs1] | processor->R[instruction.rtype.rs2]; processor->PC += 4; break; case 0x1: // REM processor->R[instruction.rtype.rd] = (int32_t) processor->R[instruction.rtype.rs1] % (int32_t) processor->R[instruction.rtype.rs2]; processor->PC += 4; break; default: handle_invalid_instruction(instruction); exit(-1); break; } break; case 0x7: // AND processor->R[instruction.rtype.rd] = processor->R[instruction.rtype.rs1] & processor->R[instruction.rtype.rs2]; processor->PC += 4; break; default: handle_invalid_instruction(instruction); exit(-1); break; } } void execute_itype_except_load(Instruction instruction, Processor *processor) { int imm = sign_extend_number(instruction.itype.imm, 12); switch (instruction.itype.funct3) { case 0x0: // ADDI processor->R[instruction.itype.rd] = processor->R[instruction.itype.rs1] + imm; processor->PC += 4; break; case 0x1: // SLLI processor->R[instruction.itype.rd] = processor->R[instruction.itype.rs1] << imm; processor->PC += 4; break; case 0x2: // SLTI processor->R[instruction.itype.rd] = sign_extend_number(processor->R[instruction.itype.rs1], 5) < imm; processor->PC += 4; break; case 0x4: // XORI processor->R[instruction.itype.rd] = processor->R[instruction.itype.rs1] ^ imm; processor->PC += 4; break; case 0x5: ; //This is an empty statement // Shift Right (You must handle both logical and arithmetic) unsigned shamt = instruction.itype.imm & 0x1F; unsigned funct = instruction.itype.imm >> 10; if (funct) { //SRAI if (processor->R[instruction.itype.rs1] >> 31) { //MSB is 1 if (shamt >= 31) { processor->R[instruction.itype.rd] = 0xFFFFFFFF; } else { unsigned shifted = processor->R[instruction.itype.rs1] >> shamt; unsigned result = set_bit(0, 32 - shamt, 1); result = ~(result - 1); result = result | shifted; } } else { //MSB is 0 processor->R[instruction.itype.rd] = processor->R[instruction.itype.rs1] >> shamt; } //fprintf(stderr, "%s%d%s%d%s", "Register x", instruction.itype.rs1, ": ", processor->R[instruction.itype.rs1], "\n"); //fprintf(stderr, "%s%d%s", "SHAMT: ", shamt, "\n"); } else { //SRLI processor->R[instruction.itype.rd] = processor->R[instruction.itype.rs1] >> shamt; } processor->PC += 4; break; case 0x6: // ORI processor->R[instruction.itype.rd] = processor->R[instruction.itype.rs1] | imm; processor->PC += 4; break; case 0x7: // ANDI processor->R[instruction.itype.rd] = processor->R[instruction.itype.rs1] & imm; processor->PC += 4; break; default: handle_invalid_instruction(instruction); break; } } void execute_ecall(Processor *p, Byte *memory) { Register i; // syscall number is given by a0 (x10) // argument is given by a1 switch(p->R[10]) { case 1: // print an integer printf("%d",p->R[11]); break; case 4: // print a string for(i=p->R[11];i<MEMORY_SPACE && load(memory,i,LENGTH_BYTE);i++) { printf("%c",load(memory,i,LENGTH_BYTE)); } break; case 10: // exit printf("exiting the simulator\n"); exit(0); break; case 11: // print a character printf("%c",p->R[11]); break; default: // undefined ecall printf("Illegal ecall number %d\n", p->R[10]); exit(-1); break; } p->PC += 4; } void execute_branch(Instruction instruction, Processor *processor) { switch (instruction.sbtype.funct3) { case 0x0: // BEQ if (processor->R[instruction.sbtype.rs1] == processor->R[instruction.sbtype.rs2]) { processor->PC += get_branch_offset(instruction); } else { processor->PC += 4; } break; case 0x1: // BNE if (processor->R[instruction.sbtype.rs1] != processor->R[instruction.sbtype.rs2]) { processor->PC += get_branch_offset(instruction); } else { processor->PC += 4; } break; default: handle_invalid_instruction(instruction); exit(-1); break; } } void execute_load(Instruction instruction, Processor *processor, Byte *memory) { switch (instruction.itype.funct3) { case 0x0: // LB processor->R[instruction.itype.rd] = sign_extend_number(load(memory, processor->R[instruction.itype.rs1] + sign_extend_number(instruction.itype.imm, 12), LENGTH_BYTE), 8); processor->PC += 4; break; case 0x1: // LH processor->R[instruction.itype.rd] = sign_extend_number(load(memory, processor->R[instruction.itype.rs1] + sign_extend_number(instruction.itype.imm, 12), LENGTH_HALF_WORD), 16); processor->PC += 4; break; case 0x2: // LW processor->R[instruction.itype.rd] = load(memory, processor->R[instruction.itype.rs1] + sign_extend_number(instruction.itype.imm, 12), LENGTH_WORD); processor->PC += 4; break; default: handle_invalid_instruction(instruction); break; } } void execute_store(Instruction instruction, Processor *processor, Byte *memory) { switch (instruction.stype.funct3) { case 0x0: // SB store(memory, processor->R[instruction.stype.rs1] + get_store_offset(instruction), LENGTH_BYTE, processor->R[instruction.stype.rs2]); processor->PC += 4; break; case 0x1: // SH store(memory, processor->R[instruction.stype.rs1] + get_store_offset(instruction), LENGTH_HALF_WORD, processor->R[instruction.stype.rs2]); processor->PC += 4; break; case 0x2: // SW store(memory, processor->R[instruction.stype.rs1] + get_store_offset(instruction), LENGTH_WORD, processor->R[instruction.stype.rs2]); processor->PC += 4; break; default: handle_invalid_instruction(instruction); exit(-1); break; } } void execute_jal(Instruction instruction, Processor *processor) { processor->R[instruction.ujtype.rd] = processor->PC + 4; processor->PC += get_jump_offset(instruction); } void execute_lui(Instruction instruction, Processor *processor) { processor->R[instruction.utype.rd] = sign_extend_number(instruction.utype.imm, 20) << 12; processor->PC += 4; } void store(Byte *memory, Address address, Alignment alignment, Word value) { //fprintf(stderr, "%s", "STORING WORD\n"); if (alignment == LENGTH_WORD) { *(uint32_t*) (memory + address) = (uint32_t) value; } else if (alignment == LENGTH_HALF_WORD) { *(uint16_t*) (memory + address) = (uint16_t) value; } else if (alignment == LENGTH_BYTE) { *(uint8_t*) (memory + address) = (uint8_t) value; } else { fprintf(stderr, "%s", "ERROR: Unknown alignment type in store(...)"); exit(-1); } } Word load(Byte *memory, Address address, Alignment alignment) { if (alignment == LENGTH_WORD) { //fprintf(stderr, "%s", "LOADING WORD\n"); //fprintf(stderr, "%d%s", *(uint32_t*) (memory + address), "\n"); //print_debug_instruction(*(uint32_t*) (memory + address)); return *(uint32_t*) (memory + address); } else if (alignment == LENGTH_HALF_WORD) { //fprintf(stderr, "%s", "LOADING HALF WORD\n"); //fprintf(stderr, "%d%s", *(uint16_t*) (memory + address), "\n"); return *(uint16_t*) (memory + address); } else if (alignment == LENGTH_BYTE) { //fprintf(stderr, "%s", "LOADING BYTE\n"); //fprintf(stderr, "%d%s", *(uint8_t*) (memory + address), "\n"); return *(uint8_t*) (memory + address); } fprintf(stderr, "%s", "ERROR: Unknown alignment type in load(...)"); exit(-1); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_vector.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: artainmo <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/01/19 09:48:51 by artainmo #+# #+# */ /* Updated: 2020/01/19 09:52:34 by artainmo ### ########.fr */ /* */ /* ************************************************************************** */ #include "vector_matrix.h" /* ** A point vector is simply p0(x0,y0,z0), it has whatever magnitude */ t_vec ft_point_vector(double x, double y, double z) { t_vec p0; p0.x = x; p0.y = y; p0.z = z; return (p0); } /* ** Magnitude is similar to distance */ double ft_vector_magnitude(t_vec p0, t_vec p) { double magnitude; magnitude = sqrt((pow(p.x - p0.x, 2) + pow(p.y - p0.y, 2) + pow(p.z - p0.z, 2))); return (magnitude); } /* ** Magnitude is similar to distance */ double ft_magnitude(t_vec p) { double magnitude; magnitude = sqrt((pow(p.x, 2) + pow(p.y, 2) + pow(p.z, 2))); return (magnitude); } /* ** Find a direction vector or a normalized vector ** (normal vector is also perpendicular) or a unit vector ** Claculate the magnitude/lenght first with ** ||V|| = V.x∗V.x+V.y∗V.y+V.z∗V.z ** to find a direction vector magnitude needs to be one ** devide by magnitude -> p.x/magnitude p.y/magnitude p.z/magnitude ** now you have the direction vector */ t_vec ft_direction_vector(t_vec p0, t_vec p) { t_vec dir; double magnitude; magnitude = sqrt((pow(p.x - p0.x, 2) + pow(p.y - p0.y, 2) + pow(p.z - p0.z, 2))); dir.x = (p.x - p0.x) / magnitude; dir.y = (p.y - p0.y) / magnitude; dir.z = (p.z - p0.z) / magnitude; return (dir); } /* ** Move points around based on this formla ax * b */ t_vec ft_vec_move(t_vec p0, t_vec dir, double x) { return (ft_vector_add(p0, ft_vec_doub_multiplication(dir, x))); }
C
/* Grace */ #include <stdio.h> #define ENDL 10 #define C_ARRAY "/*%c Grace%c*/%c#include <stdio.h>%c%c#define ENDL 10%c#define C_ARRAY %c%s%c%c#define MAIN() int main(){FILE *fd; fd = fopen(%cGrace_kid.c%c, %cw%c); fprintf(fd, C_ARRAY, ENDL, ENDL, ENDL, ENDL, ENDL, ENDL, 34, C_ARRAY, 34, ENDL, 34, 34, 34, 34, ENDL, ENDL, ENDL); fclose(fd);return (0);}%c%cMAIN();%c" #define MAIN() int main(){FILE *fd; fd = fopen("Grace_kid.c", "w"); fprintf(fd, C_ARRAY, ENDL, ENDL, ENDL, ENDL, ENDL, ENDL, 34, C_ARRAY, 34, ENDL, 34, 34, 34, 34, ENDL, ENDL, ENDL); fclose(fd);return (0);} MAIN();
C
#include <stdio.h> #include <stdlib.h> #include <string.h> //MsgIdentifier functions void openFile(); char readNextCharacter(); void messageIdentifier(); void carryMessage(int msg_length); //Pre-processing functions void preProcessing(int msg_length, char message_type); void preProcessingMDFull(); void preProcessingMDIncr(); //Processing functions void marketDataHandler(int msg_length); int main(){ openFile(); messageIdentifier(); } /*BEGIN OF MESSAGE IDENTIFIER BLOCK*/ FILE* file; //variable shared by openFile and readNextCharacter void openFile(){ //file = fopen("fix.051.full_reflesh-simplified.log", "r"); //file = fopen("fix.051.snap-resumido.log", "r"); //file = fopen("fix.051.snap.log", "r"); file = fopen("fix.051.snapfull-1message.log", "r"); } char readNextCharacter(){ char character = ' '; if(fread(&character, 1, 1, file) > 0){ return character; } else{ return '\0'; //return NULL } } char fix_message[500000]; //variable shared by messageIdentifier and carryMessage char message[500000]; int next_message_length = 0; //variable shared by messageIdentifier and carryMessage char global_SecurityID[8] = {"3809696"}; //interface with the user void messageIdentifier(){ int status_tag_35 = 0; //false int status_eof = 0; //false int msg_index = 0; int msg_length = 0; for(int i=0; i<5000; i++){ message[i] = ' '; } while(!status_eof){ // char character = ' '; msg_index = next_message_length; while(status_tag_35 < 2 && status_eof == 0){ //false //the status 35 has to be false and the end of file too character = readNextCharacter(); if(character == '\0'){ //if character equals NULL status_eof = 1; //true } else if(character == '3'){ message[msg_index] = character; msg_index++; character = readNextCharacter(); if(character == '5'){ message[msg_index] = character; msg_index++; character = readNextCharacter(); if(character == '='){ message[msg_index] = character; msg_index++; status_tag_35++; //true //If the 35 tag is detected the status var is changed. This way the while funcion will be false. This means that the message is complete message[msg_index] = readNextCharacter(); msg_index++; } else{ message[msg_index] = character; msg_index++; } } else{ message[msg_index] = character; msg_index++; } } else{ message[msg_index] = character; msg_index++; } } status_tag_35 = 1; if(msg_index > 0){ msg_length = msg_index; carryMessage(msg_length); } } } char memory_message[200000]; //memory shared between the msgIdentifier and preProcessing block void carryMessage(int msg_length){ /*this function identify each FIX message, removing the information not necessary for the pre-processing function.*/ int i; int msg_index = msg_length; int interval = 0; int aux_interval = 0; int aux_msg_index; next_message_length = 0; //if the msg has '\n', uses -1 while(message[msg_index-1] != ''){ //count the index n of the message until find the SOH. This is the length of the next fix message //-1 bcs sometimes the msg_index get the SOH next_message_length++; msg_index--; } for(i = 0; i < msg_length - next_message_length + 1; i++){ //+ 1 to get the SOH character fix_message[i] = message[i]; //fix_message receives the message without the next one } interval = msg_length - next_message_length + 1; aux_interval = interval; //this var is used to increment in the next for without changing the oficial interval variable. This way, it's not bug the next function functioning. for(i = 0; i < next_message_length; i++){ message[i] = message[aux_interval-1]; aux_interval++; } for(int i=0; i < interval; i++){ //alocate only the fix message to the buffer for the pre-processing memory_message[i] = fix_message[i]; } char message_type = ' '; for(int i=0; i < interval; i++){ //alocate only the fix message to the buffer for the pre-processing if(memory_message[i] == '3'){ if(memory_message[i+1] == '5'){ if(memory_message[i+2] == '='){ message_type = memory_message[i+3]; break; } } } } preProcessing(interval, message_type); //send the message to the pre-processing function } /*END OF MESSAGE IDENTIFIER BLOCK*/ /* BEGIN OF PRE-PROCESSING BLOCK */ void preProcessing(int msg_length, char message_type){ switch(message_type){ case 'W': preProcessingMDFull(msg_length); break; case 'X': preProcessingMDIncr(); break; default: printf("Unidentified MessageType (%c)", message_type); } } void preProcessingMDFull(int msg_length){ //function that analyse the required tags of each type of message //required tag for MDFullReflesh: 269, 270, 271 printf("\n\nMarket Data Full Reflesh\n"); int aux_msg_length = msg_length; int i = 0; int status_msg = 1; //true - valid message if(strstr(memory_message, "269=") != NULL && strstr(memory_message, "270=") != NULL && strstr(memory_message, "271=") != NULL && strstr(memory_message, "48=") != NULL){ printf("\n\nThe message is valid \n"); } else{ printf("\n\nThe message is not valid \n"); } printf("\n"); marketDataHandler(msg_length); } void preProcessingMDIncr(){ printf("\n\nMarket Data Incremental Reflesh\n"); } void marketDataHandler(int msg_length){ char MDEntryType = ' '; float MDEntryPx = 0.0; char SecurityID[8]; int MDEntryPositionNo; char *char_pointer; long int index; int index_char = 0; char token[64]; int index_token = 1; float highest_bid = 0.0; float lowest_offer = 9999.9; float closingPrice; for(int i=0; i < msg_length; i++){ if(memory_message[i] == '') printf("|"); else printf("%c", memory_message[i]); } printf("\n\n"); token[0] = ''; //variables atributions for(int i=0; i<msg_length; i++){ //go through the message if(memory_message[i] == ''){ if(strstr(token, "48=") != NULL){ int j = 0; char_pointer = strstr(token, "48="); index_char = char_pointer - token; //pointers calculation to get the '4' position (position of "2" - position of the inicial fix message) for(int i = index_char + 3; i < 12; i++){ //+4 to get the number since the '=' SecurityID[j] = token[i]; j++; } j=0; printf("\n\nField identified: %s", &token[1]); printf(" || SecurityID: %s\n", SecurityID); index_token = 1; memset(token + 1, 0, sizeof(token)); //clean the token, except the first position } else if(strstr(token, "269=") != NULL){ char_pointer = strstr(token, "269="); index_char = char_pointer - token; //pointers calculation to get the '2' position (position of "2" - position of the inicial fix message) MDEntryType = token[index_char + 4]; printf("\n\nField identified: %s", &token[1]); printf(" || MDEntryType: %c\n", MDEntryType); index_token = 1; memset(token + 1, 0, sizeof(token)); //clean the token, except the first position } else if(strstr(token, "270=") != NULL){ char entryPx[8]; int j = 0; memset(entryPx, 0, sizeof(entryPx)); char_pointer = strstr(token, "270="); index_char = char_pointer - token; //pointers calculation to get the '2' position (position of "2" - position of the inicial fix message) for(int i = index_char + 4; i < 12; i++){ //+4 to get the number since the '=' entryPx[j] = token[i]; j++; } j=0; MDEntryPx = atof(entryPx); printf("\n\nField identified: %s", &token[1]); printf(" || MDEntryPx: %.2f\n", MDEntryPx); if(MDEntryType == '0'){ if(MDEntryPx > highest_bid){ highest_bid = MDEntryPx; printf("\n\nTESTE\n\n"); } } else if(MDEntryType == '5'){ closingPrice = MDEntryPx; } index_token = 1; memset(token + 1, 0, sizeof(token)); //clean the token, except the first position } else if(strstr(token, "290=") != NULL){ char_pointer = strstr(token, "290="); index_char = char_pointer - token; MDEntryPositionNo = (token[index_char + 4] - '0'); // char to int conversion printf("\n\nField identified: %s", &token[1]); printf(" || MDEntryPositionNo: %d\n", MDEntryPositionNo); index_token = 1; memset(token + 1, 0, sizeof(token)); //clean the token, except the first position } else{ printf("\n\nField do not identified: %s\n", &token[1]); index_token = 1; memset(token + 1, 0, sizeof(token)); //clean the token, except the first position } } else{ token[index_token] = memory_message[i]; index_token++; } } if(strcmp(SecurityID, global_SecurityID) == 0){ printf("\n######## Book ToB ########"); printf("\nSecurityID: %s", SecurityID); if(lowest_offer > 9999.0) printf("\nOffer: do not available."); else printf("\nOffer: %.2f", lowest_offer); if(highest_bid == 0.0) printf("\nBid: do not available."); else printf("\nBid: %.2f", highest_bid); printf("\n#########################\n\n\n\n"); } }
C
#include "holberton.h" /** * _abs - computes the absolute value of an integer * @r: this is the integral value * * Return: if r > 0, return r. 0 otherwise */ int _abs(int r) { if (r > 0) { return (r); } else { return (-r); } }
C
/* * @lc app=leetcode.cn id=11 lang=c * * [11] 盛最多水的容器 */ // @lc code=start //双指针 int maxArea(int* height, int heightSize){ if(heightSize == 0) return 0; int maxArea = 0; int left = 0; int right = heightSize - 1; int temp; while(left != right){ //短的一侧移动,找寻更高的 if(height[left] > height[right]){ temp = height[right] * (right - left); right--; }else{ temp = height[left] * (right - left); left++; } maxArea = temp > maxArea ? temp : maxArea; } return maxArea; } // @lc code=end
C
// // basiccube.c, a wireframe, 3D unit cube with one vertex at the origin // // compile: // gcc -L/usr/lib64 -O2 basiccube.c -lX11 -lGL -lGLU -lglut -lm -lXmu // -o basiccube // // #include <stdio.h> #include <GL/gl.h> #include <GL/glut.h> struct point { float x, y, z; }; void setup_the_viewvolume() { struct point eye, view, up; // specify size and shape of view volume glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0,1.0,0.1,20.0); // specify position for view volume glMatrixMode(GL_MODELVIEW); glLoadIdentity(); eye.x = 2.5; eye.y = 1.8; eye.z = 2.0; view.x = 0.0; view.y = 0.0; view.z = 0.0; up.x = 0.0; up.y = 1.0; up.z = 0.0; gluLookAt(eye.x,eye.y,eye.z,view.x,view.y,view.z,up.x,up.y,up.z); } void draw_stuff() { int i; struct point front[4] = { {0.0,0.0,1.0}, {0.0,1.0,1.0}, {1.0,1.0,1.0}, {1.0,0.0,1.0} }; struct point back[4] = { {1.0,0.0,0.0}, {1.0,1.0,0.0}, {0.0,1.0,0.0}, {0.0,0.0,0.0} }; struct point left[4] = { {0.0,0.0,0.0}, {0.0,1.0,0.0}, {0.0,1.0,1.0}, {0.0,0.0,1.0} }; struct point right[4] = { {1.0,0.0,1.0}, {1.0,1.0,1.0}, {1.0,1.0,0.0}, {1.0,0.0,0.0} }; struct point top[4] = { {0.0,1.0,1.0}, {0.0,1.0,0.0}, {1.0,1.0,0.0}, {1.0,1.0,1.0} }; struct point bottom[4] = { {0.0,0.0,0.0}, {0.0,0.0,1.0}, {1.0,0.0,1.0}, {1.0,0.0,0.0} }; // anti-aliasing glEnable(GL_MULTISAMPLE_ARB); // gray background glClearColor(0.35,0.35,0.35,0.0); glClear(GL_COLOR_BUFFER_BIT); // call for wireframe glPolygonMode(GL_FRONT,GL_LINE); glPolygonMode(GL_BACK,GL_LINE); // fat yellow lines glColor3f(1.0,1.0,0.0); glLineWidth(2.0); glBegin(GL_QUADS); for(i=0;i<4;i++) glVertex3f(front[i].x,front[i].y,front[i].z); for(i=0;i<4;i++) glVertex3f(back[i].x,back[i].y,back[i].z); for(i=0;i<4;i++) glVertex3f(left[i].x,left[i].y,left[i].z); for(i=0;i<4;i++) glVertex3f(right[i].x,right[i].y,right[i].z); for(i=0;i<4;i++) glVertex3f(top[i].x,top[i].y,top[i].z); for(i=0;i<4;i++) glVertex3f(bottom[i].x,bottom[i].y,bottom[i].z); glEnd(); glFlush(); } int main(int argc, char** argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_RGBA|GLUT_MULTISAMPLE); //multisample means render @ higher resolution //than called for and downsample (this is for anti-aliasing) glutInitWindowSize(768,768); //must match the view volume front face in aspect ratio (width/height). glutInitWindowPosition(100,50); glutCreateWindow("my_cool_cube"); setup_the_viewvolume(); glutDisplayFunc(draw_stuff); //glutIdleFunc() //glutKeyboardFunc() glutMainLoop();//infinite loop? return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: xacoquan <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/02/12 22:52:26 by xacoquan #+# #+# */ /* Updated: 2015/03/18 22:39:50 by xacoquan ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_select.h" static int exec_select(t_data *data, t_list *liste) { char buf[4]; ft_strclr(buf); while (42) { tputs(data->cl_str, 1, tputs_putchar); if (print_list(data, liste)) return (0); buf[1] = 0; buf[2] = 0; read(0, buf, 3); if (buf[0] == 27 && buf[1] == 0 && buf[2] == 0) return (0); if (buf[0] == 10 && buf[1] == 0 && buf[2] == 0) return (1); list(buf, data, liste); } return (0); } static void print_result(t_list *list) { t_file *tmp; int result; result = 0; tmp = list->first; while (tmp) { if (tmp->selected == 1) { if (result > 0) ft_putchar(' '); ft_putstr(tmp->name); result++; } tmp = tmp->next; } if (result != 0) ft_putchar('\n'); } static void ft_select2(t_data *d, t_list *l, struct termios t, struct termios o) { checksignal(); tputs(tgetstr("ti", NULL), 1, tputs_putchar); exec_select(d, l); tputs(tgetstr("te", NULL), 1, tputs_putchar); print_result(l); select_close_term(&t, &o); } static void ft_select(char **argv) { t_list *liste; t_data *data; int i; struct termios term; struct termios oldterm; i = 1; liste = ft_list_init(); select_init_term(&term, &oldterm); while (argv[i]) { add_to_list(liste, argv, i); i++; } data = ft_init_data(liste); singleton_liste(liste); singleton_data(data); ft_select2(data, liste, term, oldterm); } int main(int argc, char **argv) { if (argc > 1) ft_select(argv); else ft_error("ft_select choix1 choix2 choix3 choix4"); return (0); }
C
#include <stdio.h> #include <Windows.h> #pragma warning(disable:4996) char * _strcpy(char * destination, const char * source) { int i = 0; while (source[i] != '\0') { destination[i] = source[i]; i++; } destination[i] = '\0'; return destination; } int main() { char str1[] = "Sample string"; char str2[40]; _strcpy(str2, str1); printf("str1: %s\nstr2: %s\nstr: %s\n", str1, str2, _strcpy(str2, str1)); system("pause"); return 0; }
C
#include <check.h> #include "../main/roman-numerals-reducer.h" #include "test-constants.h" static void assertReduceNumerals(char *input, char *reduceBy, char *expected); START_TEST(testReduceSingleValue) { assertReduceNumerals("II","I","I"); assertReduceNumerals("VII","V","II"); } END_TEST START_TEST(testReduceMultipleValues) { assertReduceNumerals("III","II","I"); assertReduceNumerals("CVII","VI","CI"); } END_TEST START_TEST(testExpandRightSideWhenCannotReduceRemainder) { assertReduceNumerals("X","V","V");// VV-V -> V assertReduceNumerals("XX","XII","VIII");//X-II -> VV -> VIIIII-II -> VIII assertReduceNumerals("L","II","XXXXVIII");//XXXXX -> XXXXVV -> XXXXVIIIII } END_TEST START_TEST(testDoNotExpandSecondTimeIfNoRemaineder) { assertReduceNumerals("L","X","XXXX");//XXXXX -> XXXX Not XXXVV } END_TEST START_TEST(testMultiplePasses) { assertReduceNumerals("XX","XVII","III");// X-VII -> VV -> V-II -> IIIII -> IIIII-II -> III assertReduceNumerals("C","LXV","XXXV");//C -> LL-LXV -> L-XV -> XXXX-V -> XXXV assertReduceNumerals("C","LV","XXXXV");//C -> LL-LV -> L-V -> XXXXX-V -> XXXXVV-V -> XXXXV } END_TEST START_TEST(testStopOn30Loops) { assertReduceNumerals("VIIIIIIIIIIIIIIIIIIIIIIIIIIIII" ,"IIIIIIIIIIIIIIIIIIIIIIIIIIIII","V"); assertReduceNumerals("VIIIIIIIIIIIIIIIIIIIIIIIIIIIII", "IIIIIIIIIIIIIIIIIIIIIIIIIIIIII","REDUCER FAILED"); } END_TEST static void assertReduceNumerals(char *input, char *reduceBy, char *expected){ char result[TEST_BUFFER_SIZE] = {'\0'}; reduceMatchingNumerals(input, reduceBy, result); ck_assert_str_eq(result, expected); } Suite * makeRomanNumeralsReducerSuite(void) { Suite *s; TCase *tcCore; s = suite_create("Roman Numerals Reducer Suite"); tcCore = tcase_create("Core"); tcase_add_test(tcCore, testReduceSingleValue); tcase_add_test(tcCore, testReduceMultipleValues); tcase_add_test(tcCore, testExpandRightSideWhenCannotReduceRemainder); tcase_add_test(tcCore, testDoNotExpandSecondTimeIfNoRemaineder); tcase_add_test(tcCore, testMultiplePasses); tcase_add_test(tcCore, testStopOn30Loops); suite_add_tcase(s, tcCore); return s; }
C
/* 本程序将记录棒球运动员的文件内容输入至结构体中,且计算平均成绩,显示到屏幕。 计划:升级为菜单交互式程序。 */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <time.h> #include "extra.h" #define LEN 20 struct name { char fname[LEN]; char lname[LEN]; }; struct playerdate { int num[4]; double average; }; typedef struct match { int number; struct name nam; struct playerdate date; } MATCH; void showplay(MATCH arr[], int num); int main(void) { char temp[4][8][LEN]; int n, b; MATCH sum[4]; FILE *fp; if (fopen_s(&fp, "baseball.txt", "r+") != 0) { fputs("打开文件出错", stderr); exit(0); } for (n = 0; n < 4; n++) { for (b = 0; b < 7; b++) { fscanf(fp, "%s", temp[n][b]); } } for (n = 0; n < 4; n++) { sum[n].number = atoi(temp[n][0]); strcpy_s(sum[n].nam.fname, 20, temp[n][1]); strcpy_s(sum[n].nam.lname, 20, temp[n][2]); for (b = 0; b < 4; b++) { sum[n].date.num[b] = atoi(temp[n][b + 3]); } } fclose(fp); for (n = 0; n < 4; n++) sum[n].date.average = (double)sum[n].date.num[1] / (double)sum[n].date.num[0]; showplay(sum, 4); return 0; } void showplay(MATCH arr[], int num) { int n, b; printf("编号 姓 名 上场数 击中数 走垒数 跑点数 平均分\n"); for (n = 0; n < num; n++) { printf("%-6d %-6s %-6s %-10d %-10d %-10d %-10d %-9.2lf\n", arr[n].number, arr[n].nam.fname, arr[n].nam.lname, arr[n].date.num[0], arr[n].date.num[1], arr[n].date.num[2], arr[n].date.num[3], arr[n].date.average); } }
C
#include<stdio.h> int main() { int i; for(i=0; i<=5; i++) { if(i==4) break; printf("%d \n",i); } }
C
// // Created by gianluca on 18/12/19. // #include <stdio.h> #include <stdlib.h> typedef struct { int u, v; } arco; arco* leggiFile(int *n, int *e) { FILE *fp = fopen("grafo.txt","r"); arco *ar; fscanf(fp,"%d %d",n, e); ar = malloc(*e* sizeof(arco)); for (int i = 0; i < *e; i++) { fscanf(fp, "%d %d", &ar[i].u, &ar[i].v); } return ar; } int check(int *sol, int e, arco *a) { int ok = 1; for (int i = 0; i<e && ok; i++) { if (sol[a[i].u]!=1 && sol[a[i].v]!=1) ok=0; } return ok; } int powerset(int pos, int *sol, int k,int count, int e , arco *a) { if(pos>=k) { if(check(sol, e, a)) { printf("{ "); for (int i = 0; i < k; i++) { if(sol[i]!=0) printf("%d ", i); } printf("}\n"); return count+1; } return count; } sol[pos]=0; count = powerset(pos+1, sol, k, count, e, a); sol[pos]=1; count = powerset(pos+1, sol, k, count, e, a); return count; } int main() { arco *a; int n, e; a = leggiFile(&n, &e); int *sol = malloc(n*sizeof(int)); int count = powerset(0, sol, n, 0, e, a); printf("Totale soluzioni: %d\n", count); return 0; }
C
/* Properly formatted Quine. */ #include <stdio.h> const char *s[ ] = { "\n", "int main( )\n", "{\n", " printf( \"/* Properly formatted Quine. */\\n\" );\n", " printf( \"\\n\" );\n", " printf( \"#include <stdio.h>\\n\" );\n", " printf( \"\\n\" );\n", " printf( \"const char *s[ ] =\\n\" );\n", " printf( \"{\\n \\\"\" );\n", "\n", " for ( int i = 0; s[ i ] != NULL; )\n", " {\n", " for ( const char *ptr = s[ i ]; *ptr; ++ptr )\n", " {\n", " switch ( *ptr )\n", " {\n", " case '\\n': printf( \"\\\\n\" ); break;\n", " case '\\\\':\n", " case '\\\"': putchar( '\\\\' );\n", " default : putchar( *ptr );\n", " }\n", " }\n", "\n", " ++i;\n", "\n", " if ( s[ i ] != NULL )\n", " {\n", " printf( \"\\\",\\n \\\"\" );\n", " }\n", " else\n", " {\n", " printf( \"\\\",\" );\n", " }\n", " }\n", "\n", " printf( \"\\n};\\n\" );\n", "\n", " for ( int i = 0; s[ i ] != NULL; ++i )\n", " {\n", " printf( \"%s\", s[ i ] );\n", " }\n", "\n", " return 0;\n", "}\n", "", }; int main( ) { printf( "/* Properly formatted Quine. */\n" ); printf( "\n" ); printf( "#include <stdio.h>\n" ); printf( "\n" ); printf( "const char *s[ ] =\n" ); printf( "{\n \"" ); for ( int i = 0; s[ i ] != NULL; ) { for ( const char *ptr = s[ i ]; *ptr; ++ptr ) { switch ( *ptr ) { case '\n': printf( "\\n" ); break; case '\\': case '\"': putchar( '\\' ); default : putchar( *ptr ); } } ++i; if ( s[ i ] != NULL ) { printf( "\",\n \"" ); } else { printf( "\"," ); } } printf( "\n};\n" ); for ( int i = 0; s[ i ] != NULL; ++i ) { printf( "%s", s[ i ] ); } return 0; }
C
#include <stdio.h> void extOdDigits(long n, long *nd); int main(void) { long n, *nd; nd = &n; printf("Please enter a postive int: "); scanf("%ld", &n); extOdDigits(n, nd); printf("Output: %ld\n",n); return 0; } void extOdDigits(long n, long *nd) { long i = 1;long digits = 0;long j = 1; while(n / i != 0) { int d = (n%(i*10) - n%i) / i; //get digit from right if(d%2==1) //decide if the digit is odd { digits = digits + d * j; j *= 10; //put digits together } i *= 10; } if(digits==0) digits = -1; //if no odd digits output -1 *nd = digits; }
C
#include<stdio.h> int main() { int a,b,c,sum; printf("Enter Your Data:"); scanf("%d %d %d",&a,&b,&c); sum = a+b+c; if(sum == 180 && a != 0 && b != 0 && c != 0) { printf("Triangle is valid\n"); } else { printf("Triangle is not valid\n"); } return 0; }
C
#include <stdio.h> int main() { int a, b; char op; scanf("%d %c %d", &a, &op, &b); switch (op) { case '+' : printf("%d\n", a + b); break; case '-' : printf("%d\n", a - b); break; case '*' : printf("%d\n", a * b); break; case '/' : printf("%d\n", a / b); break; case '%' : printf("%d\n", a % b); break; default : printf("ERROR\n"); } return 0; }
C
#include <stdio.h> #include <stdlib.h> // please allocate a 10 long array and fill it with even numbers // please allocate a 10 long array and fill it with odd numbers // select an array, and push the elements into the another array // the resulting array should be 20 elements long // print the array in descending order // delete the arrays after you don't use them int main() { int* pointer_even = NULL; int* pointer_odd = NULL; pointer_even = malloc(10 * sizeof(int)); pointer_odd = malloc(10 * sizeof(int)); for (int i = 0; i < 10 ; ++i) { i % 2 == 0 ? (*(pointer_even + i) = i, *(pointer_odd + i) = (i + 1)) : (*(pointer_even + i) = (i + 1), *(pointer_odd + i) = i ); } realloc(pointer_even, 20 * sizeof(int)); for (int j = 10 ; j < 20 ; ++j) { *(pointer_even + j) = *(pointer_odd + (j - 10)); } free(pointer_odd); int temp = 0; for (int k = 0; k < 20 ; ++k) { for (int i = 0; i < 20 ; ++i) { if(pointer_even[k] > pointer_even[i]){ temp = pointer_even[i]; pointer_even[i] = pointer_even[k]; pointer_even[k] = temp; } } } for (int l = 0; l < 20 ; ++l) { printf("%d\n", pointer_even[l]); } free(pointer_even); return 0; }
C
#include <stdio.h> #include <math.h> int main(void) { float a,b; scanf("%f %f",&a,&b); printf("%.4f",pow(a,b)); return 0; }
C
#include <Tuareg_platform.h> #include <Tuareg.h> #include "serial_buffer.h" volatile ComRx_Buffer_t ComRx_Buffer= { .write= 0, .read= 0, .unread= 0 }; /** */ void ComRx_Buffer_reset() { ComRx_Buffer.write= 0; ComRx_Buffer.read= 0; ComRx_Buffer.unread= 0; } /** */ VU32 ComRx_Buffer_avail() { return ComRx_Buffer.unread; } /** */ exec_result_t ComRx_Buffer_push(VU8 Input) { //check write pointer for post fence if(ComRx_Buffer.write >= COMRX_BUFFER_SIZE) { //recover error ComRx_Buffer_reset(); return EXEC_ERROR; } //check if buffer has some space left if(ComRx_Buffer.unread >= COMRX_BUFFER_SIZE) { //buffer full return EXEC_ERROR; } //store data ComRx_Buffer.data[ComRx_Buffer.write]= Input; //count new data ComRx_Buffer.unread++; //calculate next free cell ComRx_Buffer.write= (ComRx_Buffer.write >= COMRX_BUFFER_SIZE -1)? 0 : ComRx_Buffer.write +1; return EXEC_OK; } /** */ exec_result_t ComRx_Buffer_pull(VU32 * Output) { //check if buffer holds data if(ComRx_Buffer.unread == 0) { //buffer empty return EXEC_ERROR; } //check read pointer for post fence if(ComRx_Buffer.read >= COMRX_BUFFER_SIZE) { //recover error ComRx_Buffer_reset(); return EXEC_ERROR; } //read data *Output= ComRx_Buffer.data[ComRx_Buffer.read]; //count new data ComRx_Buffer.unread--; //calculate next cell ComRx_Buffer.read= (ComRx_Buffer.read >= COMRX_BUFFER_SIZE -1)? 0 : ComRx_Buffer.read +1; return EXEC_OK; } /** */ exec_result_t ComRx_Buffer_pull_U16(VU32 * Output, bool BigEndian) { VU32 byte1, byte2; exec_result_t result; result= ComRx_Buffer_pull(&byte1); ASSERT_EXEC_OK(result); result= ComRx_Buffer_pull(&byte2); ASSERT_EXEC_OK(result); //set output if(BigEndian == true) { *Output= (byte2 << 8) | byte1; } else { *Output= (byte1 << 8) | byte2; } return EXEC_OK; } exec_result_t ComRx_Buffer_pull_U32(VU32 * Output, bool BigEndian) { VU32 byte1, byte2, byte3, byte4; exec_result_t result; result= ComRx_Buffer_pull(&byte1); ASSERT_EXEC_OK(result); result= ComRx_Buffer_pull(&byte2); ASSERT_EXEC_OK(result); result= ComRx_Buffer_pull(&byte3); ASSERT_EXEC_OK(result); result= ComRx_Buffer_pull(&byte4); ASSERT_EXEC_OK(result); //set output if(BigEndian == true) { *Output= (byte4 << 24) | (byte3 << 16) | (byte2 << 8) | byte1; } else { *Output= (byte1 << 24) | (byte2 << 16) | (byte3 << 8) | byte4; } return EXEC_OK; }
C
#include<stdio.h> void main() { int A , B, C , D, DIFERENCA; scanf("%d%d%d%d",&A ,&B ,&C ,&D); DIFERENCA=(A * B - C * D); printf("DIFERENCA = %d\n",DIFERENCA); }
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> #include<math.h> float DErivADelante(float h, float(xi)); float DErivaATras(float h, float(xi)); float DErivaCEntrada(float h, float(xi)); float xi,h,error1,error2,error3; int main() { xi=0.6; h=0.5; error1 = fabs((0.2489-DErivADelante(xi,h))/0.2489)*100; error2 = fabs((0.2489-DErivaATras(xi,h))/0.2489)*100; error3 = fabs((0.2489-DErivaCEntrada(xi,h))/0.2489)*100; printf("Hola, buen dia, al calcular la derivada de f(x)=1-e^(-x/0.2) del punto xi=0.6\n\n"); printf("El valor para h=%f hacia adelante es: %f, y su error realtivo de %f %% \n",h,DErivADelante(xi,h),error1); printf("El valor para h=%f hacia atras es: %f, y su error relativo de %f %%\n",h,DErivaATras(xi,h),error2); printf("El valor para h=%f centrada es: %f, y su error relativo de %f %%",h,DErivaCEntrada(xi,h),error3); } float DErivADelante(float h, float(xi)){ float dfxi, fxi, fxip1, fxip2,error1; xi=0.6; h=0.5; fxi = 1-exp(-xi/0.2); fxip1 = 1-exp(-(xi+h)/0.2); fxip2 = 1-exp(-(xi+(2*h))/0.2); dfxi = (-fxip2+4*fxip1-3*fxi)/(2*h); return dfxi; } float DErivaATras(float h, float(xi)){ float dfxi, fxi, fxip1, fxip2,error2; xi=0.6; h=0.5; fxi = 1-exp(-xi/0.2); fxip1 = 1-exp(-(xi-h)/0.2); fxip2 = 1-exp(-(xi-(2*h))/0.2); dfxi = (3*fxi-4*fxip1+fxip2)/(2*h); return dfxi; } float DErivaCEntrada(float h, float(xi)){ float dfxi, fxi, fxip1, fxip2,fxip3,fxip4,error3; xi=0.6; h=0.5; fxi = 1-exp(-xi/0.2); fxip1 = 1-exp(-(xi+h)/0.2); fxip2 = 1-exp(-(xi+(2*h))/0.2); fxip3 = 1-exp(-(xi-h)/0.2); fxip4 = 1-exp(-(xi-(2*h))/0.2); dfxi = (-fxip2+8*fxip1-8*fxip3+fxip4)/(12*h); return dfxi; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_reco.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: blefeuvr <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/11/17 16:33:04 by blefeuvr #+# #+# */ /* Updated: 2017/11/17 18:53:42 by blefeuvr ### ########.fr */ /* */ /* ************************************************************************** */ #include "fillit.h" int ft_undereco(char *str) { int i; char symbs[9][11]; ft_strcpy(symbs[1], "#..###"); ft_strcpy(symbs[2], "#..##..#"); ft_strcpy(symbs[3], "#..##...#"); ft_strcpy(symbs[4], "#...###"); ft_strcpy(symbs[5], "#...##..#"); ft_strcpy(symbs[6], "#...##...#"); ft_strcpy(symbs[7], "#...#..##"); ft_strcpy(symbs[0], "#...#...##"); ft_strcpy(symbs[8], "#.###"); i = 0; while (i < 9) { if (ft_strcmp(symbs[i++], str) == 0) return (1); } return (0); } int ft_reco(char *str) { int i; char symbs[10][14]; ft_strcpy(symbs[1], "####"); ft_strcpy(symbs[2], "###.#"); ft_strcpy(symbs[3], "###..#"); ft_strcpy(symbs[4], "###...#"); ft_strcpy(symbs[5], "##.##"); ft_strcpy(symbs[6], "##..##"); ft_strcpy(symbs[7], "##..#...#"); ft_strcpy(symbs[8], "##...##"); ft_strcpy(symbs[9], "##...#...#"); ft_strcpy(symbs[0], "#...#...#...#"); i = 0; while (i < 10) { if (ft_strcmp(symbs[i++], str) == 0) return (1); } return (ft_undereco(str)); }
C
/* Copyright 2013 Bliksem Labs. See the LICENSE file at the top-level directory of this distribution and at https://github.com/bliksemlabs/rrrr/. */ /* geometry.c */ #include "geometry.h" #include "config.h" #include <math.h> #include <stdio.h> // Mean of Earth's equatorial and meridional circumferences. #define EARTH_CIRCUMFERENCE 40041438.5 // UINT32_MAX is also the full range of INT32. #define INT32_RANGE UINT32_MAX // We could have more resolution in the latitude direction by mapping 90 degrees to the int32 range // instead of 180, but keeping both axes at the same scale enables efficent distance calculations. // In any case the extra Y resolution is unnecessary, since 1 brad is already just under 1cm. #define METERS_PER_BRAD (EARTH_CIRCUMFERENCE / INT32_RANGE) // Must be scaled according to latitude for use in the longitude direction. #define METERS_PER_DEGREE_LAT (EARTH_CIRCUMFERENCE / 360.0) static inline double radians (double degrees) { return degrees * M_PI / 180; } static inline double degrees (double radians) { return radians * 180 / M_PI; } // Sinusoidal / equirectangular projection. // Replace with fast estimation polynomial. static inline double xscale_at_y (uint32_t y_brads) { return cos(y_brads * M_PI * 2 / UINT32_MAX); } static inline double xscale_at_lat (double latitude) { return cos(radians(latitude)); } static inline double coord_diff_meters (int32_t o1, int32_t o2) { return (o2 - o1) * METERS_PER_BRAD; } /* Several mappings from lat/lon to integers to are possible. The three major decisions are: 1. Signed or unsigned brads. 2. Zero uint32_t in brads is at the prime meridian or its antipode. 3. Whether or not to store scaled x values. Design decisions and reflections: If we map zero brads to 0 longitude and xvalues are not scaled, unsigned and signed brads have identical binary representations. The main advantage of using unsigned brads is that is prevents hashgrids from "reflecting" around the origin when normal division is performed. The unsigned conversion could be performed within the hashgrid itself, and binning could be performed with masks (shift out bits within cell, zero out high bits, rest is cell number). If the x values are stored pre-scaled we will not get proper wrapping at the date line, but bins will be of a consistent size. If the x values are stored unscaled then we will get seamless wrapping at the date line, but bins will not be of a consistent size. Not all architectures will use twos complement signed integers... which don't? In order to efficiently calculate distances, we need the x and y coordinates to be in the same units / at the same scale. We can either sacrifice vertical resolution and store both coordinates at the x scale, or perform an additional multiply operation at every distance calculation to restore the y coordinate to the same scale. 2. Either we start x=0 at lon=-180 or lon=0. */ void coord_from_lat_lon (coord_t *coord, double lat, double lon) { coord->y = lat * UINT32_MAX / 360.0; coord->x = lon * UINT32_MAX / 360.0 * xscale_at_lat (lat); } void coord_from_meters (coord_t *coord, double meters_x, double meters_y) { coord->x = meters_x / METERS_PER_BRAD; coord->y = meters_y / METERS_PER_BRAD; } void coord_from_latlon (coord_t *coord, latlon_t *latlon) { coord_from_lat_lon (coord, latlon->lat, latlon->lon); } // Returns a monotone increasing function of the distance between points that is faster to calculate. // This is an order-preserving map, so it can be used to establish closer/farther relationships. // It is implemented as the square of the distance in latitude-scaled/projected binary radians. double coord_ersatz_distance (coord_t *c1, coord_t *c2) { double dx = c2->x - c1->x; double dy = c2->y - c1->y; return dx * dx + dy * dy; } // rename to coord_distance_ersatz, add ersatz_from_meters and meters_from_ersatz // Returns the equivalent ersatz distance for a given number of meters, for distance comparisons. double ersatz_distance (double meters) { double d_brads = meters / METERS_PER_BRAD ; return d_brads * d_brads; } double coord_distance_meters (coord_t *c1, coord_t *c2) { double dxm = coord_diff_meters(c1->x, c2->x); double dym = coord_diff_meters(c1->y, c2->y); return sqrt(dxm * dxm + dym * dym); } double latlon_distance_meters (latlon_t *ll1, latlon_t *ll2) { // Rather than finding and using the average latitude for longitude scaling, or scaling // the two latlons separately, just convert the to the internal projected representation. coord_t c1, c2; coord_from_latlon (&c1, ll1); coord_from_latlon (&c2, ll2); return coord_distance_meters (&c1, &c2); } void latlon_from_coord (latlon_t *latlon, coord_t *coord) { latlon->lat = coord->y * 180.0 / INT32_MAX ; latlon->lon = coord->x * 180.0 / INT32_MAX / xscale_at_y (coord->y); } void latlon_dump (latlon_t *latlon) { printf("latlon lat=%f lon=%f \n", latlon->lat, latlon->lon); } void coord_dump (coord_t *coord) { printf("coordinate x=%d y=%d \n", coord->x, coord->y); }
C
#include<stdio.h> int main(){ int num1, num2; printf("Enter 2 integers, and I will tell you\n"); printf("the relationships the satisfy: "); scanf("%d%d", &num1, &num2); if (num1 == num2) { printf("%d is equal to %d\n", num1, num2); }; if (num1 != num2) { printf("%d is not equal to %d\n", num1, num2); }; if (num1 > num2) { printf("%d is greater than to %d\n", num1, num2); }; if (num1 < num2) { printf("%d is smaller than to %d\n", num1, num2); }; if (num1 >= num2) { printf("%d is greater than or equal to %d\n", num1, num2); }; if (num1 <= num2) { printf("%d is smaller than or equal to %d\n", num1, num2); } return 0; }
C
#include <limits.h> #include <stdio.h> #include <stdlib.h> #define TRUE 1 #define FALSE 0 #define MAX_VERTICES 100 #define INF 1000000 //Ѵ. ( ) typedef struct GraphType { int n; // int weight[MAX_VERTICES][MAX_VERTICES]; } GraphType; int distance[MAX_VERTICES]; int found[MAX_VERTICES]; int trace[MAX_VERTICES]; int r_trace[MAX_VERTICES]; int choose(int distance[], int n, int found[]) { int i, min, minpos; min = INT_MAX; minpos = -1; for (i = 0; i < n; i++) { if (distance[i] < min && !found[i]) { min = distance[i]; minpos = i; } } return minpos; } void shortest_path(GraphType *g) { int i, u, w, start; for (int s = 0; s < g->n; s++) { start = s; for (i = 0; i < g->n; i++) { distance[i] = g->weight[start][i]; found[i] = FALSE; if (g->weight[start][i] != INF) trace[i] = start; } distance[start] = 0; for (int tmp = 0; tmp < g->n; tmp++) { for (i = 0; i < g->n; i++) { u = choose(distance, g->n, found); if (tmp == u) { if (start == u) continue; printf("%d %d Ʈ : %d", start, u, start); int n_route = trace[u]; int q = 0; while (1) { if (n_route == start) { while (q > 0) { printf("-%d", r_trace[--q]); } break; } r_trace[q++] = n_route; n_route = trace[n_route]; } printf("-%d \t : %d\n", u, distance[u]); for (int k = 0; k < g->n; k++) { distance[k] = g->weight[start][k]; found[k] = FALSE; } break; } found[u] = TRUE; for (w = 0; w < g->n; w++) { if (!found[w]) { if (distance[u] + g->weight[u][w] < distance[w]) { distance[w] = distance[u] + g->weight[u][w]; trace[w] = u; } } } } } printf("\n%d -----------------------------\n\n", s); } } int main(void) { GraphType g = {7, {{0, 7, INF, INF, 3, 10, INF}, {7, 0, 4, 10, 2, 6, INF}, {INF, 4, 0, 2, INF, INF, INF}, {INF, 10, 2, 0, 11, 9, 4}, {3, 2, INF, 11, 0, INF, 5}, {10, 6, INF, 9, INF, 0, INF}, {INF, INF, INF, 4, 5, INF, 0}}}; shortest_path(&g); return 0; }
C
/** * Forking a process * * Let n be the return of the fork * 1. if n < 0, fork failed * 2. if n == 0, child is running currently * 3. if n > 0, parent is running currently * * Note: Sometimes parent might exit before the execution of the child * Resolution: wait() */ #include <unistd.h> #include <string.h> int println(const char* str) { write(0, "\n", 1); write(0, str, strlen(str)); } int main() { int n = fork(); char str[] = "\nHello"; write(0, str, strlen(str)); if( n < 0 ) println("No child is created"); else if( n == 0 ) println("Child process"); else println("Parent process"); println("------------------"); return 0; }
C
/* Number of ones in an integer's binary representation. */ int number_ones(unsigned int n) { int ones = 0; while (n) { n = n & (n - 1); ones ++; } return ones; } void test() { cout << number_ones(7) << endl; }
C
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <float.h> #include <constant.h> #include <formulas.h> #include <matrix.h> /**/ static int arg_parse( int, char ** ); int main( int argc, char **argv ) { int i, axis; double Sxx, Sxy, Sxz, Syy, Syz, Szz; double ang; double input_array[3]; double output_array[9]; const double ang90 = 0.5 * PI; MATRIX *d = NULL; MATRIX *s = NULL; MATRIX *dt = NULL; MATRIX *ds = NULL; MATRIX *dsdt = NULL; /**/ if ( arg_parse( argc, argv ) ) return -1; s = matrix_new( 3, 3 ); d = matrix_new( 3, 3 ); Sxx = atof(argv[1]); Sxy = atof(argv[2]); Sxz = atof(argv[3]); Syy = atof(argv[4]); Syz = atof(argv[5]); Szz = atof(argv[6]); axis = atoi(argv[7]); ang = atof(argv[8]) * PI / 180.0; matrix_prefill_array( input_array, 3, Sxx, Sxy, Sxz ); matrix_assign_row( s, input_array, 1, 3 ); matrix_prefill_array( input_array, 3, Sxy, Syy, Syz ); matrix_assign_row( s, input_array, 2, 3 ); matrix_prefill_array( input_array, 3, Sxz, Syz, Szz ); matrix_assign_row( s, input_array, 3, 3 ); switch ( axis ) { case 0: matrix_prefill_array( input_array, 3, 1.0, 0.0, 0.0 ); matrix_assign_row( d, input_array, 1, 3 ); matrix_prefill_array( input_array, 3, 0.0, cos(ang), cos(ang90 + ang) ); matrix_assign_row( d, input_array, 2, 3 ); matrix_prefill_array( input_array, 3, 0.0, cos(ang90 - ang), cos(ang) ); matrix_assign_row( d, input_array, 3, 3 ); break; case 1: matrix_prefill_array( input_array, 3, cos(ang), 0.0, cos(ang90 + ang) ); matrix_assign_row( d, input_array, 1, 3 ); matrix_prefill_array( input_array, 3, 0.0, 1.0, 0.0 ); matrix_assign_row( d, input_array, 2, 3 ); matrix_prefill_array( input_array, 3, cos(ang90 - ang), 0.0, cos(ang) ); matrix_assign_row( d, input_array, 3, 3 ); break; case 2: matrix_prefill_array( input_array, 3, cos(ang), cos(ang90 + ang), 0.0 ); matrix_assign_row( d, input_array, 1, 3 ); matrix_prefill_array( input_array, 3, cos(ang90 - ang), cos(ang), 0.0 ); matrix_assign_row( d, input_array, 2, 3 ); matrix_prefill_array( input_array, 3, 0.0, 0.0, 1.0 ); matrix_assign_row( d, input_array, 3, 3 ); break; default: break; } dt = matrix_transpose( d ); ds = matrix_mul( d, s ); dsdt = matrix_mul( ds, dt ); matrix_extract_seq( dsdt, output_array, 9 ); for ( i=0; i<9; i++ ) printf("%e ", output_array[i]); printf("\n"); matrix_free( d ); matrix_free( s ); matrix_free( ds ); matrix_free( dt ); matrix_free( dsdt ); return 0; } /**/ static int arg_parse( int argc, char **argv ) { /**/ if ( argc < 9 ) { fprintf(stderr, "Usage: %s Sxx Sxy Sxz Syy Syz Szz Rotation_axis Rotation_angle\n", argv[0]); return -1; } return 0; }
C
#include <stdio.h> int main(void) { int counter, till; printf("カウントダウン: "); scanf("%d", &till); for(counter=till; counter >= 0; counter--) { printf("%d\n", counter); } printf("\a\n"); return 0; }
C
#ifndef SQLIST_H #define SQLIST_H /* 定义顺序表的头文件 */ //定义一个数据类型的宏,这样能在想修改数据类型时,只修改此处 #define ElementType int #define InitialSize 50 //此处是动态分配顺序表的定义 typedef struct { ElementType *data; int MaxSize, length; } Sqlist; //对顺序表进行初始化 extern void init(Sqlist *L); //动态地对顺序表进行构造 extern void construct(Sqlist *L); //在第i个位置插入新的元素,插入成功返回0,失败返回1 extern int insert_i(Sqlist *L, int i, ElementType e); //删除第i个位置的元素 extern int delete_i(Sqlist *L, int i); //按值查找,返回第一个值等于e的元素的位置 extern int locate_e(Sqlist *L, ElementType e); //顺序打印所有元素 extern void printSql(Sqlist *L); #endif
C
/************************************************************************************************* * Copyright 2019-2021 FieldComm Group, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *****************************************************************/ /********************************************************** * * File Name: * toolthreads.c * File Description: * Functions to create and delete the threads used in * the tool and do the necessary initializations and * setups for the tool. * **********************************************************/ #include <errno.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "common.h" #include "debug.h" #include "tooldef.h" #include "toolsems.h" #include "toolsigs.h" #include "toolthreads.h" #include "toolutils.h" /************ * Globals ************/ pthread_t mainThrID = (pthread_t) NULL; /************************************ * Private variables for this file ************************************/ /* Information about all tool threads except the main thread */ static thr_info_t htoolThrs[MAX_THRS]; /* array of threads */ static uint8_t numThrs = 0; /* total number of threads */ /***************************** * Function Implementations *****************************/ void delete_threads(void) { uint8_t n, count = numThrs; const char *thrName; pthread_t thrID; const char *funcName = "delete_threads"; dbgp_trace("~~~~~~ %s ~~~~~~\n", funcName); /* Avoid repeated deletion via different means */ if (count) { dbgp_init("\n**********************\n"); dbgp_logdbg("Deleting %s threads...\n", TOOL_NAME); for (n = 0; n < count; n++) { thrID = htoolThrs[n].thrID; thrName = htoolThrs[n].thrName; if (thrID != (pthread_t) NULL) { if (pthread_cancel(thrID) == NO_ERROR) { /* Wait for the cancelled thread to terminate */ if (pthread_join(thrID, NULL) == NO_ERROR) { /* Reset ID to prevent accidental misuse */ htoolThrs[n].thrID = (pthread_t) NULL; numThrs--; dbgp_thr(" ..%s\n", (char *)thrName); } else { print_to_both(p_toolLogPtr, "Error in pthread_join() for %s!! \n", (char *) thrName); } } // else nothing to delete } // if (thrID != NULL) } /* for */ dbgp_logdbg("Total %d threads deleted\n", n); dbgp_logdbg("**********************\n"); } /* if (count) */ else { dbgp_logdbg("\nNo threads exist\n"); } } uint8_t get_thread_count(void) { return (numThrs); } errVal_t start_a_thread(pthread_t *p_thrID, void *(*p_thrFunc)(void *), const char *thrName) { errVal_t errval = THREAD_ERROR; int32_t errNo; const char *funcName = "start_a_thread"; dbgp_trace("~~~~~~ %s ~~~~~~\n", funcName); do { if (numThrs >= MAX_THRS) { print_to_both(p_toolLogPtr, "Cannot create more threads\n"); print_to_both(p_toolLogPtr, "%d threads exist, max capacity %d threads\n", numThrs, MAX_THRS); break; } dbgp_thr("...Creating next thread (current total = %d) - %s\n", numThrs, thrName); errNo = pthread_create(p_thrID, NULL, p_thrFunc, (void *) thrName); if (errNo != NO_ERROR) { errval = THREAD_ERROR; print_to_both(p_toolLogPtr, "Error %d in creating thread!!\n", errNo); break; } /* Save thread info in the thread array */ htoolThrs[numThrs].thrID = *p_thrID; htoolThrs[numThrs].thrName = thrName; errval = NO_ERROR; numThrs++; dbgp_thr("...Created next thread (current total = %d) - %s\n", numThrs, thrName); } while (FALSE); return (errval); }
C
/* ************************************************************************** */ /* */ /* :::::::: */ /* ft_printf_lib.c :+: :+: */ /* +:+ */ /* By: tvan-cit <[email protected]> +#+ */ /* +#+ */ /* Created: 2019/12/11 09:51:37 by tvan-cit #+# #+# */ /* Updated: 2019/12/16 11:18:30 by tvan-cit ######## odam.nl */ /* */ /* ************************************************************************** */ #include "ft_printf.h" char *ft_strchr(const char *s, int c) { char *ptr; ptr = NULL; while (*s) { if (*s == c) { ptr = (char*)s; return (ptr); } s++; } if (c == '\0') return ((char*)s); return (ptr); } static long int ft_convert(const char *str, int i, unsigned long int result, int sign) { while (str[i] >= '0' && str[i] <= '9') { if ((result >= 922337203685477580 && (str[i] - '0') > 7) && sign == 1) return (-1); else if ((result >= 922337203685477580 && (str[i] - '0') > 8) && sign == -1) return (0); result = result * 10 + (str[i] - '0'); i++; } return (result); } int ft_atoi(const char *str) { unsigned long int result; int i; int sign; result = 0; i = 0; sign = 1; while (str[i] != '\0' && (str[i] == ' ' || (8 < str[i] && str[i] < 14))) i++; if ((str[i] == '+' && str[i + 1] == '-') || (str[i] == '-' && str[i + 1] == '+')) return (0); if (str[i] == '+') i++; if (str[i] == '-') { sign = -1; i++; if (str[i] == '+') return (0); } result = ft_convert(str, i, result, sign); return ((int)result * sign); } int ft_strlen(char *s) { int i; i = 0; while (s[i] != '\0') { i++; } return (i); } int ft_number_count(int n, t_list *data) { int numbercount; if (n < 0) data->is_neg = 1; numbercount = 0; if (n == 0 || n == -0) return (1); if (n < 0) { numbercount++; n = -n; } while (n > 0) { n = n / 10; numbercount++; } return (numbercount); }
C
#include <stdio.h> int main() { int num,rev=0,rem,tmp; printf("Enter num:"); scanf("%d",&num); tmp=num; while(tmp!=0) { rem=tmp%10; //rem=4 rev=rev*10+rem; //rev=4 tmp=tmp/10; // tmp= } printf("rev no.: %d \n",rev); }
C
#include <math.h> #if 1 typedef struct { unsigned char rgbtRed; unsigned char rgbtGreen; unsigned char rgbtBlue; } __attribute__((__packed__)) RGBTRIPLE; #endif // Blur image void blur(int height, int width, RGBTRIPLE image[height][width], RGBTRIPLE imgout[height][width]) { int wid = width - 1; int hgt = height - 1; RGBTRIPLE *pixel; // For each row.. for (int ycur = 0; ycur <= hgt; ++ycur) { int ylo = (ycur == 0) ? 0 : -1; int yhi = (ycur == hgt) ? 0 : 1; // ..and then for each pixel in that row... for (int xcur = 0; xcur <= wid; ++xcur) { int xlo = (xcur == 0) ? 0 : -1; int xhi = (xcur == wid) ? 0 : 1; int avgRed = 0; int avgGreen = 0; int avgBlue = 0; for (int yoff = ylo; yoff <= yhi; ++yoff) { for (int xoff = xlo; xoff <= xhi; ++xoff) { pixel = &image[ycur + yoff][xcur + xoff]; avgRed += pixel->rgbtRed; avgGreen += pixel->rgbtGreen; avgBlue += pixel->rgbtBlue; } } int tot = ((yhi - ylo) + 1) * ((xhi - xlo) + 1); pixel = &imgout[ycur][xcur]; pixel->rgbtRed = roundf((float) avgRed / tot); pixel->rgbtGreen = roundf((float) avgGreen / tot); pixel->rgbtBlue = roundf((float) avgBlue / tot); } } }
C
#include <stdio.h> int main(void) { int all; scanf("%d", &all); for (int y = 0; y < all; y++) { int store, quest; scanf("%d %d", &store, &quest); int price[store]; int money[quest]; for (int z = 0; z < store; z++) { scanf(" %d", &price[z]); } for (int x = 0; x < quest; x++) { scanf("%d", &money[x]); } for (int i = 0; i < quest; i++) { int canBuy = 0; for (int i2 = 0; i2 < store; i2++) { if (money[i] >= price[i2]) { canBuy++; } } printf("%d %d\n", canBuy, store - canBuy); } } return 0; }
C
int longestPalindrome(char * s){ if(strlen(s)==1) return 1; int tmp[128]={0}; int count=0; int i=0; for(i=0;i<strlen(s);i++) { tmp[s[i]]++; } for(i=0;i<128;i++) { //直接统计奇数的个数 最后结果就是其他的偶数再加一个中间位的奇数 if(tmp[i]%2==1) count++; } return count==0? strlen(s):strlen(s)-count+1; }
C
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <string.h> void *rout(void *arg) { int i; for(;;) { printf("I am thread1\n"); sleep(1); } } int main() { pthread_t tid; int ret=0; if((ret==pthread_create(&tid,NULL,rout,NULL))!=0) { fprintf(stderr,"pthread_creat:%s\n",strerror(ret)); exit(EXIT_FAILURE); } int i=0; for(;;) { printf("I an main thread\n"); sleep(1); } return 0; }
C
#include "registracion.h" #include <stdbool.h> #include <sys/ipc.h> #include <sys/sem.h> #include <sys/msg.h> #include <stdio.h> #define SOLO_C #include "../../common/common.h" bool ids_dispositivos_disponibles[MAX_DISPOSITIVOS_EN_SISTEMA]; //ver si ampliamos los ids int siguiente_id_dispositivo; bool ids_tester_disponibles[MAX_TESTERS_COMUNES + MAX_TESTERS_ESPECIALES]; //ver si ampliamos los ids int siguiente_id_tester_comun; int siguiente_id_tester_especial; bool inicializado = false; tabla_testers_disponibles_t* tabla; void inicializar(){ int i; for (i = 0; i < MAX_DISPOSITIVOS_EN_SISTEMA; i++){ ids_dispositivos_disponibles[i] = true; } siguiente_id_dispositivo = 0; //se le sumara uno, para no tener problemas con los mtypes for (i = 0; i < MAX_TESTERS_COMUNES + MAX_TESTERS_ESPECIALES; i++){ ids_tester_disponibles[i] = true; } siguiente_id_tester_comun = 0; //idem siguiente_id_tester_especial = MAX_TESTERS_COMUNES; //idem key_t key = ftok("/tmp/buchwaldipcs", SHM_TABLA_TESTERS); int shmtabla = shmget(key, sizeof(tabla_testers_disponibles_t) , IPC_CREAT | 0660); tabla = (tabla_testers_disponibles_t*)shmat(shmtabla, NULL, 0); inicializado = true; } int * get_id_dispositivo_1_svc(void *argp, struct svc_req *rqstp) { static int result; if (!inicializado) inicializar(); result = -1; //si no se consiguio id, como un mensaje de error int revisados = 0; int i; for (i = siguiente_id_dispositivo; revisados < MAX_DISPOSITIVOS_EN_SISTEMA && result == -1; i = (i + 1) % MAX_DISPOSITIVOS_EN_SISTEMA, revisados++){ if (ids_dispositivos_disponibles[i]){ result = i; } } siguiente_id_dispositivo = (siguiente_id_dispositivo + 1) % MAX_DISPOSITIVOS_EN_SISTEMA; if (result != -1){ ids_dispositivos_disponibles[result] = false; result++; } return &result; } int * get_id_tester_1_svc(int *argp, struct svc_req *rqstp) { static int result; if (!inicializado) inicializar(); result = -1; int tipo = *argp; int inicio, offset, cantidad, *siguiente; /* Para poder generalizar */ if (tipo == TIPO_COMUN){ inicio = siguiente_id_tester_comun; siguiente = &siguiente_id_tester_comun; offset = 0; cantidad = MAX_TESTERS_COMUNES; }else if (tipo == TIPO_ESPECIAL){ inicio = siguiente_id_tester_especial; siguiente = &siguiente_id_tester_especial; offset = MAX_TESTERS_COMUNES; cantidad = MAX_TESTERS_ESPECIALES; }else{ return &result; } int revisados = 0; int i; for (i = inicio; revisados < cantidad && result == -1; i = (i + 1) % cantidad + offset, revisados++){ if (ids_tester_disponibles[i]){ result = i; } } *siguiente = (*siguiente + 1) % cantidad + offset; if (result != -1){ ids_tester_disponibles[result] = false; result++; } return &result; } int * registrar_tester_activo_1_svc(int *argp, struct svc_req *rqstp) { static int result; result = 1; int id = *argp; if (id <= 0 || id > MAX_TESTERS_ESPECIALES + MAX_TESTERS_COMUNES){ result = -1; return &result; } if (ids_tester_disponibles[id-1]){ result = -2; //Si no lo pidio, como lo va a registrar? return &result; } /* OJO con esto, que es bloqueante, hay que ver si hay alguna otra forma de resolverlo */ key_t key = ftok("/tmp/buchwaldipcs",SEM_TABLA_TESTERS); int semid = semget(key,1,0660); //sem_tabla.p(); struct sembuf oper; oper.sem_num = 0; oper.sem_op = -1; oper.sem_flg = 0; semop(semid,&oper,1); oper.sem_op = 1; if (id <= MAX_TESTERS_COMUNES){ //es id correspondiente a un tester comun tabla->testers_comunes[tabla->end++] = id; tabla->cant++; //sem_comunes.v(); key = ftok("/tmp/buchwaldipcs",SEM_CANT_TESTERS_COMUNES); int semcomunes = semget(key,1,0660); semop(semcomunes,&oper,1); }else{ //es id correspondiente a un tester especial tabla->testers_especiales[id - MAX_TESTERS_COMUNES - 1] = true; key = ftok("/tmp/buchwaldipcs",SEM_ESPECIAL_DISPONIBLE + (id - MAX_TESTERS_COMUNES - 1)); int sem_especial = semget(key,1,0660); semop(sem_especial,&oper,1); //Semaphore sem_especial(SEM_ESPECIAL_DISPONIBLE + (id - MAX_TESTERS_COMUNES - 1)); //sem_especial.v(); } //sem_tabla.v(); oper.sem_op = 1; semop(semid,&oper,1); return &result; } int terminar_conexion(int id, int idcola){ key_t key = ftok("/tmp/buchwaldipcs", idcola); int cola = msgget(key, 0666); TMessageAtendedor msg; msg.mtype = id; msg.finalizar_conexion = FINALIZAR_CONEXION; msgsnd(cola, &msg, sizeof(TMessageAtendedor) - sizeof(long), 0); } int * devolver_id_dispositivo_1_svc(int *argp, struct svc_req *rqstp) { static int result; if (!inicializado) inicializar(); int id = *argp; if (id <= 0 || id > MAX_DISPOSITIVOS_EN_SISTEMA ){ result = -1; return &result; } if (ids_dispositivos_disponibles[id-1]){ result = -2; //El dispositivo estaba habilitado, asi que nadie lo pidio en realidad como para poder devolverlo... return &result; } ids_dispositivos_disponibles[id-1] = true; result = 1; //Mando mensaje de finalizacion para terminar la conexion con este dispositivo terminar_conexion(id, MSGQUEUE_BROKER_ENVIO_MENSAJES_DISPOSITIVOS); return &result; } int * devolver_id_tester_1_svc(int *argp, struct svc_req *rqstp) { static int result; if (!inicializado) inicializar(); int id = *argp; if (id <= 0 || id > MAX_TESTERS_COMUNES + MAX_TESTERS_ESPECIALES ){ result = -1; return &result; } if (ids_tester_disponibles[id - 1]){ result = -2; //El dispositivo estaba habilitado, asi que nadie lo pidio en realidad como para poder devolverlo... return &result; } ids_tester_disponibles[id - 1] = true; //Mando mensaje de finalizacion para terminar la conexion con este tester terminar_conexion(id, MSGQUEUE_BROKER_ENVIO_MENSAJES_TESTERS); result = 1; return &result; }
C
#include <stdio.h> int boo(); int bar(int a,int b); int baz(int *p,int n); int g = 31; int d[] = {1,2,3,4,5}; int main(int argc, char *argv[]) { int x,y,z; x = boo(); y = bar(3,7); z = baz(d,5); printf("%d %d %d\n",x,y,z); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "solidos.h" int main(int argc, char **argv) { int ncones = atoi(argv[1]); cone *p = (cone*) malloc(ncones * sizeof(cone)); for(int i = 0; i < ncones; i++) { novo_cone((p + i)); } printf("Cones: %d\n", ncones); for(int i = 0; i < ncones; i++) { printf("%d] raio: %.2f altura: %.2f\n", i + 1, (*(p + i)).raio, (*(p + i)).altura); } }
C
#include "../fibonacci.h" int sum_fibonacci_even(int first, int second, int max_term) /* Prints out sum of even terms of Fibonacci sequence less than max_term */ { int nxt, total=0; if ( first % 2 == 0 ) { total += first; } if ( second % 2 == 0 ) { total += second; } while ( ( nxt = fibonacci(first, second) ) < max_term ) { /* Check for even */ if ( nxt % 2 == 0 ) { total += nxt; } first = second; second = nxt; } return total; }
C
#include <stdio.h> void sortnum(int *arr,int n){ int i=0,j=0; for(j=1;j<n;j++){ int key=arr[j]; i=j-1; while(i>=0&&arr[i]>key){ arr[i+1]=arr[i]; i--; } arr[i+1]=key; } } int main(){ FILE *fp; if((fp=fopen("inpu.txt","rb+"))==NULL){ printf("Cannot read file\n"); exit(1); } int unsorted[40000]={0},i; for(i=0;i<30000;i++){ fscanf(fp,"%d",&unsorted[i]); } fclose(fp); sortnum(unsorted,30000); for(i=0;i<50;i++){ printf("%d\n", unsorted[i]); } return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <assert.h> int nametest(char a, char b, char c); int isvowel(char arg); int isconsonant(char arg); int sumtest(char a, char b, char c); int isprime(int a); //Test function void assertion(void); int main() { printf("print your name:\n"); char a = getchar(); char b = getchar(); char c = getchar(); if (nametest(a, b, c)) { printf("you're for planet bob\n"); } else { printf("you're not from bob!\n"); } return EXIT_SUCCESS; } int nametest(char a, char b, char c){ if (a != c) { printf("the first letter didn't equal the last!\n"); return 0; } if (isvowel(a) && isconsonant(b) && isvowel(c) && a == c && sumtest(a,b,c)) { return 1; } else if (isconsonant(a) && isvowel(b) && isconsonant(c) && a == c && sumtest(a,b,c)) { return 1; } else { return 0; } } //Checked for real lowercase char values int isvowel(char arg){ if (arg == 'a' || arg == 'e' || arg == 'i'|| arg == 'o' || arg == 'u') { return 1; } else { return 0; } } //checked for real lowercase char values int isconsonant(char arg){ if (arg != 'a' || arg != 'e' || arg != 'i'|| arg != 'o' || arg != 'u') { return 1; } else { return 0; } } int sumtest(char a, char b, char c){ char avalue = a - 96; char bvalue = b - 96; char cvalue = c - 96; printf("a = %d\n", avalue); printf("b = %d\n", bvalue); printf("c = %d\n", cvalue); char sum = avalue + bvalue + cvalue; if (isprime(sum)) { return 1; } else { return 0; } } //CHECKED int isprime(int a){ int i; if (a < 2) { return 0; } for (i = 2; i <= a/2; i++) { if (a%i == 0) { return 0; } } return 1; } void assertion(void){ //isprime function tests assert(isprime(1)==0); assert(isprime(2)==1); assert(isprime(3)==1); assert(isprime(4)==0); assert(isprime(5)==1); assert(isprime(97)==0); // isvowel function tests assert(isvowel('a')==1); assert(isconsonant('v')==1); assert(isvowel('g')==0); assert(isconsonant('b')==1); //sumtest function tests assert(sumtest('b','o','b') == 1); assert(sumtest('a','b','a')==0); //nametest function tests }
C
#include <types.h> #include "cpuid.h" #include "cpuid_data.h" /* * Detects the kind of CPU in the system. */ cpu_info_t* cpuid_detect() { uint32_t ebx, unused; cpuid(0, unused, ebx, unused, unused); switch(ebx) { case 0x756e6547: // Intel Magic Code return cpuid_detect_intel(); break; case 0x68747541: // AMD Magic Code return cpuid_detect_amd(); break; default: return 0; break; } return 0; } /* * Detects Intel-specific stuff. */ cpu_info_t* cpuid_detect_intel() { cpu_info_t* cpu_info = (cpu_info_t *) kmalloc(sizeof(cpu_info_t)); memset(cpu_info, 0x00, sizeof(cpu_info_t)); uint32_t eax, ebx, ecx, edx, max_eax, signature, unused; uint32_t model, family, type, brand, stepping, reserved; uint32_t extended_family = -1; cpuid(1, eax, ebx, unused, unused); // Read CPUID info into struct cpuid(1, cpu_info->cpuid_eax, cpu_info->cpuid_ebx, cpu_info->cpuid_ecx, cpu_info->cpuid_edx); model = (eax >> 4) & 0xf; family = (eax >> 8) & 0xf; type = (eax >> 12) & 0x3; brand = ebx & 0xff; stepping = eax & 0xf; reserved = eax >> 14; signature = eax; cpu_info->model = model; cpu_info->family = family; cpu_info->type = type; cpu_info->brand = brand; cpu_info->stepping = stepping; cpu_info->reserved = reserved; cpu_info->signature = signature; cpu_info->manufacturer = kCPUManufacturerIntel; if(family == 15) { extended_family = (eax >> 20) & 0xFF; cpu_info->extended_family = extended_family; } cpuid(0x80000000, max_eax, unused, unused, unused); /* Quok said: If the max extended eax value is high enough to support the processor brand string (values 0x80000002 to 0x80000004), then we'll use that information to return the brand information. Otherwise, we'll refer back to the brand tables above for backwards compatibility with older processors. According to the Sept. 2006 Intel Arch Software Developer's Guide, if extended eax values are supported, then all 3 values for the processor brand string are supported, but we'll test just to make sure and be safe. */ if(max_eax >= 0x80000004) { char *det_name = (char *) kmalloc(sizeof(char) * 65); memset(det_name, 0x00, sizeof(char) * 65); uint8_t str_offset = 0x00; if(max_eax >= 0x80000002) { cpuid(0x80000002, eax, ebx, ecx, edx); for(int w = 0; w < 4; w++) { det_name[w + str_offset] = eax >> (8 * w); det_name[w + 4 + str_offset] = ebx >> (8 * w); det_name[w + 8 + str_offset] = ecx >> (8 * w); det_name[w + 12 + str_offset] = edx >> (8 * w); } str_offset += 0x10; } if(max_eax >= 0x80000003) { cpuid(0x80000003, eax, ebx, ecx, edx); for(int w = 0; w < 4; w++) { det_name[w + str_offset] = eax >> (8 * w); det_name[w + 4 + str_offset] = ebx >> (8 * w); det_name[w + 8 + str_offset] = ecx >> (8 * w); det_name[w + 12 + str_offset] = edx >> (8 * w); } str_offset += 0x10; } if(max_eax >= 0x80000004) { cpuid(0x80000004, eax, ebx, ecx, edx); for(int w = 0; w < 4; w++) { det_name[w + str_offset] = eax >> (8 * w); det_name[w + 4 + str_offset] = ebx >> (8 * w); det_name[w + 8 + str_offset] = ecx >> (8 * w); det_name[w + 12 + str_offset] = edx >> (8 * w); } str_offset += 0x10; } cpu_info->detected_name = det_name; } return cpu_info; } /* * Detects AMD-specific stuff */ cpu_info_t* cpuid_detect_amd() { cpu_info_t* cpu_info = (cpu_info_t *) kmalloc(sizeof(cpu_info_t)); memset(cpu_info, 0x00, sizeof(cpu_info_t)); uint32_t extended, eax, ebx, ecx, edx, unused; uint32_t family, model, stepping, reserved; cpuid(1, eax, unused, unused, unused); // Read CPUID info into struct cpuid(1, cpu_info->cpuid_eax, cpu_info->cpuid_ebx, cpu_info->cpuid_ecx, cpu_info->cpuid_edx); model = (eax >> 4) & 0x0F; family = (eax >> 8) & 0x0F; stepping = eax & 0x0F; reserved = eax >> 12; cpu_info->family = family; cpu_info->stepping = stepping; cpu_info->model = model; cpu_info->reserved = reserved; cpu_info->manufacturer = kCPUManufacturerAMD; cpuid(0x80000000, extended, unused, unused, unused); if(extended == 0) { return cpu_info; } cpu_info->extended = extended; if(extended >= 0x80000002) { uint32_t j; char *det_name = (char *) kmalloc(sizeof(char) * 65); memset(det_name, 0x00, sizeof(char) * 65); uint8_t str_offset = 0x00; for(j = 0x80000002; j <= 0x80000004; j++) { cpuid(j, eax, ebx, ecx, edx); for(int w = 0; w < 4; w++) { det_name[w + str_offset] = eax >> (8 * w); det_name[w + 4 + str_offset] = ebx >> (8 * w); det_name[w + 8 + str_offset] = ecx >> (8 * w); det_name[w + 12 + str_offset] = edx >> (8 * w); } str_offset += 0x10; } cpu_info->detected_name = det_name; } if(extended >= 0x80000007) { cpuid(0x80000007, unused, unused, unused, edx); if(edx & 1) { cpu_info->temp_diode = true; } } return cpu_info; } /* * Sets the string variables to point to char buffers. */ void cpuid_set_strings(cpu_info_t* in) { if(in->manufacturer == kCPUManufacturerIntel) { switch(in->type) { case 0: in->str_type = "Original OEM"; break; case 1: in->str_type = "Overdrive"; break; case 2: in->str_type = "Dual-capable"; break; case 3: in->str_type = "Reserved"; break; } switch(in->family) { case 3: in->str_family = "i386"; break; case 4: in->str_family = "i486"; break; case 5: in->str_family = "Pentium"; break; case 6: in->str_family = "Pentium Pro"; break; case 15: in->str_family = "Pentium 4"; break; } switch(in->family) { case 3: break; case 4: switch(in->model) { case 0: case 1: in->str_model = "DX"; break; case 2: in->str_model = "SX"; break; case 3: in->str_model = "487/DX2"; break; case 4: in->str_model = "SL"; break; case 5: in->str_model = "SX2"; break; case 7: in->str_model = "Write-back enhanced DX2"; break; case 8: in->str_model = "DX4"; break; } break; case 5: switch(in->model) { case 1: in->str_model = "60/66"; break; case 2: in->str_model = "75-200"; break; case 3: in->str_model = "for 486 system"; break; case 4: in->str_model = "MMX"; break; } break; case 6: switch(in->model) { case 1: in->str_model = "Pentium Pro"; break; case 3: in->str_model = "Pentium II Model 3"; break; case 5: in->str_model = "Pentium II Model 5/Xeon/Celeron"; break; case 6: in->str_model = "Celeron"; break; case 7: in->str_model = "Pentium III/Pentium III Xeon - external L2 cache"; break; case 8: in->str_model = "Pentium III/Pentium III Xeon - internal L2 cache"; break; } break; case 15: break; } if(in->brand < 0x18) { if(in->signature == 0x000006B1 || in->signature == 0x00000F13) { in->str_brand = cpuid_intel_brands_other[in->brand]; } else { in->str_brand = cpuid_intel_brands[in->brand]; } } else { in->str_brand = "Reserved"; } } else if(in->manufacturer == kCPUManufacturerAMD) { switch(in->family) { case 4: in->str_model = "486 Model %d"; break; case 5: switch(in->model) { case 0: case 1: case 2: case 3: case 6: case 7: in->str_model = "K6 Model %d"; break; case 8: in->str_model = "K6-2 Model 8 %d"; break; case 9: in->str_model = "K6-III Model 9 %d"; break; default: in->str_model = "K5/K6 Model %d"; break; } break; case 6: switch(in->model) { case 1: case 2: case 4: in->str_model = "Athlon Model %d"; break; case 3: in->str_model = "Duron Model 3"; break; case 6: in->str_model = "Athlon MP/Mobile Athlon Model 6"; break; case 7: in->str_model = "Mobile Duron Model 7"; break; default: in->str_model = "Duron/Athlon Model %d"; break; } break; } } }
C
//#define _GNU_SOURCE #define _POSIX_C_SOURCE 200112L #include <stdlib.h> #include <stdio.h> #include "common.h" int myrank; void * myalloc(size_t size) { size_t align = 64; #if 0 char *a = malloc(size+32); int o = ((size_t)a) & 31; o = (32 - o) & 31; char *b = a + o; return (void *)b; #else void *b = NULL; int err = posix_memalign(&b, align, size); if(err) { printf("posix_memalign(&%p, %li, %li) failed!\n", b, align, size); exit(1); } return b; #endif } void threadSum(int n, ThreadCtx *TC) { int tid = TC->tid; int nid = TC->nid; int volatile *tbar = TC->tbar; int tb1 = tbar[tid] + 1; int b = 1; while((tid&b)==0) { int t1 = tid + b; if(t1>=nid) break; while(tbar[t1]<tb1); SYNC; double *x = TC->sum[tid]; double *y = TC->sum[t1]; for(int i=0; i<n; i++) x[i] += y[i]; b *= 2; } SYNC; tbar[tid] = tb1; } void gsum(double *x, int n, ThreadCtx *TC) { int tid = TC->tid; //printf("tid: %i x: %g\n", tid, *x); TC->sum[tid] = x; threadSum(n, TC); if(tid==0) { QMP_sum_double_array(x, n); } TWAIT0; if(tid!=0) { double *y = TC->sum[0]; for(int i=0; i<n; i++) x[i] = y[i]; } T0WAIT; //printf("tid: %i x: %g\n", tid, *x); //printf0("gsum:"); //for(int i=0; i<n; i++) printf0(" %g", x[i]); //printf0("\n"); }
C
#include<stdio.h> int main(int argc,char* argv[],char* env[]) { //argc : 命令行参数的个数, 本质上就是argv数组的元素个数 //argv :具体的命令行参数 // envp : 环境变量的值 for(int i=0;i<argc;i++) { printf("%s\n",argv[i]); } for(int i=0;env[i]!=NULL;i++) { printf("%s\n",env[i]); } return 0; }
C
/** * @file Option.c */ #include <stdio.h> #include <bolib.h> #if isWindows # include <windows.h> # include <tchar.h> #endif #include <stdlib.h> #include <string.h> #include <ctype.h> #include "common/Observer.h" #include "common/puts.h" #include "common/strres.h" #if !isWindows typedef char TCHAR; #endif #include "cui/Option.h" typedef bool (*SetOptionFunc_t)(void* param, const char* arg); /* private ====================================*/ static char* type2str_tbl[] = { NULL, /* OptionType_Unknown */ " bool ", /* OptionType_Bool */ " int ", /* OptionType_Int */ "float ", /* OptionType_Float */ "string", /* OptionType_String */ "string", /* OptionType_FunctionString */ /*==============================================*/ NULL, /* OptionType_Term */ }; static void RemoveArg(int* argcp, TCHAR*** argvp, const int inx) { int i,j; int argc = *argcp; TCHAR** argv = *argvp; for(i = inx, j = inx+1; j<argc; i++,j++) { argv[i] = argv[j]; } (*argcp)--; } static bool isValidNumber(const char* s) { int i; bool dot = false; for(i=0; '\0' != s[i]; i++) { if(!isdigit(s[i])) { if('.' != s[i]) { return false; } if(true == dot) { return false; } dot = true; } } return true; } static bool SetOpt_Bool(void* param, const char* arg) { bool* b = (bool*)param; (*b) = !(*b); return true; } static bool SetOpt_Int(void* param, const char* arg) { int* i = (int*)param; if(false == isValidNumber(arg)) { return false; } (*i) = (int)atoi(arg); return true; } static bool SetOpt_Float(void* param, const char* arg) { float* f = (float*)param; if(false == isValidNumber(arg)) { return false; } (*f) = (float)atof(arg); return true; } static bool SetOpt_String(void* param, const char* arg) { const char** s = (const char**)param; (*s) = arg; return true; } static bool SetOpt_FunctionString(void* param, const char* arg) { SetOptStruct* st; st = (SetOptStruct*)param; return st->func(st->dest, arg); } static SetOptionFunc_t SetOption[] = { NULL, /* OptionType_Unknown */ SetOpt_Bool, /* OptionType_Bool */ SetOpt_Int, /* OptionType_Int */ SetOpt_Float, /* OptionType_Float */ SetOpt_String, /* OptionType_String */ SetOpt_FunctionString, /* OptionType_String */ /*==============================================*/ NULL, /* OptionType_Term */ }; /* public =====================================*/ bool Option_Parse(int* argcp, TCHAR*** argvp, OptionStruct* opt) { int inx_opt = 1; int argc = *argcp; TCHAR** argv = *argvp; OptionStruct *o; char* cmd; bool detected; if((OptionType_Term + 1) > (sizeof(SetOption) / sizeof(SetOptionFunc_t))) { putfatal(0,GSID_OPTION_MISSPARSER,__func__); return false; } for(inx_opt = 1; inx_opt < argc; ) { cmd = argv[inx_opt]; detected = false; if('-' == cmd[0]) { for(o=opt; o->type!=OptionType_Term; o++) { /* option check */ if('-' == cmd[1]) { /* Long option */ if(0 == strcmp(&cmd[2], o->name)) { detected = true; } } else { /* Short option */ if(o->sname == cmd[1] && '\0' == cmd[2]) { detected = true; } } /* Apply option */ if(true == detected) { OptionType ot = o->type & (~OPT_Hyde); RemoveArg(&argc, &argv, inx_opt); if(OptionType_Bool == ot) { SetOption[ot](o->val, NULL); break; } if(inx_opt >= argc) { puterr(0,GSID_OPTION_ARGMISSING, cmd); return false; } if(false == SetOption[ot](o->val, argv[inx_opt])) { /*puterror("Invalid parameter for \"%s\" option: %s", cmd, argv[inx_opt]);*/ puterr(0,GSID_OPTION_INVALID, cmd, argv[inx_opt]); return false; } RemoveArg(&argc, &argv, inx_opt); break; } /* detected */ } /* OptionStruct loop */ if(false == detected) { puterr(0,GSID_UNKNOWN_OPTION, cmd); return false; } } /* Option check */ else { /* Not option */ inx_opt++; } } (*argcp) = argc; return true; } void Option_Usage(const OptionStruct* opt) { printf("Options:\n"); for(; OptionType_Term != opt->type; opt++) { if(0 == (opt->type & OPT_Hyde)) { printf(" -%c, --%-12s [%s] %.50s\n", opt->sname, opt->name, type2str_tbl[(opt->type & ~OPT_Hyde)], opt->desc); } } }
C
// C program to remove alternate nodes of a linked list #include<stdio.h> #include<stdlib.h> /* A linked list node */ struct Node { int data; struct Node *next; }; /* deletes alternate nodes of a list starting with head */ void deleteAlt(struct Node *head) { if (head == NULL) return; /* Initialize prev and node to be deleted */ struct Node *prev = head; struct Node *node = head->next; while (prev != NULL && node != NULL) { /* Change next link of previous node */ prev->next = node->next; /* Free memory */ free(node); /* Update prev and node */ prev = prev->next; if (prev != NULL) node = prev->next; } } /* UTILITY FUNCTIONS TO TEST fun1() and fun2() */ /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ void push(struct Node** head_ref, int new_data) { /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given linked list */ void printList(struct Node *node) { while (node != NULL) { printf("%d ", node->data); node = node->next; } } /* Drier program to test above functions */ int main() { /* Start with the empty list */ struct Node* head = NULL; /* Using push() to construct below list 1->2->3->4->5 */ push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); printf("\nList before calling deleteAlt() \n"); printList(head); deleteAlt(head); printf("\nList after calling deleteAlt() \n"); printList(head); return 0; }
C
//coded by Jason Thong for CoE3DQ5 2017 //convert a *.bmp (bitmap file) to a *.ppm (portable pixel map file) #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char **argv) { int i, j, k, width, height; char input_filename[200], output_filename[200]; unsigned char *r_image, *g_image, *b_image; FILE *file_ptr; //get input file name either from first command line argument or from the user interface (command prompt) if (argc<2) { printf("enter the input file name including the .bmp extension: "); gets(input_filename); } else strcpy(input_filename, argv[1]); //open input file file_ptr = fopen(input_filename, "rb"); if (file_ptr==NULL) { printf("can't open file %s for binary reading, exiting...\n", input_filename); exit(1); } else printf("opened input file %s\n", input_filename); //get output file name either from second command line argument or from the user interface (command prompt) if (argc<3) { printf("enter the output file name including the .ppm extension: "); gets(output_filename); } else strcpy(output_filename, argv[2]); //ignore unimportant parts of bmp header for (i=0; i<18; i++) fgetc(file_ptr); //read image width and height from bmp header width = fgetc(file_ptr); for (i=8; i<=24; i+=8) width += fgetc(file_ptr) << i; height = fgetc(file_ptr); for (i=8; i<=24; i+=8) height += fgetc(file_ptr) << i; if (height < 0 || width < 0) { printf("unsupported format, please (re)save the image as .bmp in Paint within Windows\n"); printf("as a trick to force Paint to resave the image, invert the colors twice\n"); printf("exiting...\n"); exit(1); } printf("image size is %d (width) by %d (height) pixels\n", width, height); //ignore unimportant parts of bmp header for (i=0; i<28; i++) fgetc(file_ptr); //buffer the entire image in memory because the output row order is different between bmp (backwards) and ppm (forwards) r_image = (unsigned char *)malloc(sizeof(unsigned char)*width*height); g_image = (unsigned char *)malloc(sizeof(unsigned char)*width*height); b_image = (unsigned char *)malloc(sizeof(unsigned char)*width*height); if (r_image==NULL || g_image==NULL || b_image==NULL) { printf("malloc failed :(\n)"); exit(1); } //read bmp image, when reading file sequentially, will get data for the bottom row first, go across this row, then go up a row, and so on... for (i=0; i<height; i++) for (j=0; j<width; j++) { //color order is BGR b_image[width*(height-1-i)+j] = fgetc(file_ptr); g_image[width*(height-1-i)+j] = fgetc(file_ptr); r_image[width*(height-1-i)+j] = fgetc(file_ptr); } if (fgetc(file_ptr)!=EOF) { printf("unsupported format, please (re)save the image as .bmp in Paint within Windows\n"); printf("as a trick to force Paint to resave the image, invert the colors twice\n"); printf("exiting...\n"); exit(1); } fclose(file_ptr); //open output file file_ptr = fopen(output_filename, "wb"); if (file_ptr==NULL) { printf("can't open file %s for binary writing, exiting...\n", output_filename); exit(1); } else printf("opened output file %s\n", output_filename); //write ppm header fprintf(file_ptr, "P6\n%d %d\n255\n", width, height); //write ppm image, pixel order is across first, then down, color order is RGB for (i=0; i<height; i++) for (j=0; j<width; j++) { fputc(r_image[width*i+j], file_ptr); fputc(g_image[width*i+j], file_ptr); fputc(b_image[width*i+j], file_ptr); } free(r_image); free(g_image); free(b_image); fclose(file_ptr); printf("done :)\n"); return 0; }
C
#include <stdio.h> //Standard input and output #include <math.h> #include "input.h" // declare function void decryption(char *x, int key); void CaesarDecrypt() { // Initialise variables and string char message[100]; int key, i=0; /*Prompts user to enter message and key and stores them as string array and integer value k*/ printf("Enter message you want decrypted\n"); scanf("%[^\n]", message); printf("Enter the encryption key between 0 and 26\n"); scanf("%d", &key); /* While loop Changes message from lower case to uppercase by testing if ascii value of the letters are between a and z and then taking away 32 to make them a capital letter*/ while(message[i] != '\0') {//while the i'th value of message does not equal null the loop continues if (message[i]>= 'a' && message[i] <= 'z') message[i] = message [i] - 32; ++i; } //calls function to encrypt message and then print the result. decryption(message, key); printf("%s\n", message); } /* Function definition. This function has a while loop that checks if the i'th value is a symbol or a letter via the first while if statements. If a symbol is found it sends out the value and continues to the next i value. The capital letters left over are then given a value from A=0 to Z=26 by subtracting 65 from the ascii value. The encryption key is then added and modulus 26 used which makes letters greater than 25 rotate back to A */ void decryption (char *x,int key) { int i = 0; //initialise integer i to 0 to allow it to start at first array input while (x[i] != '\0') {//while the i'th value does not equal null the loop continues if (x[i] < 'A' || x[i] > 'Z'){//All symbols below the ascii 'A' and above ascii 'Z' value are not encrypted x[i] = x[i]; i++;// adds 1 onto i to move onto the next value } } }
C
//This program gets ten real numbers from the user and //then prints them out in the reverse order. #include <stdio.h> int main(int argc, char* argv[]) { double array[10]; printf("Enter ten real numbers: "); int i; for (i = 0; i < 10; i++) { scanf("%lf", &array[i]); } printf("Reverse order:\n"); for (i = 9; i >= 0; i--) { printf("%5.1f", array[i]); } return 0; }
C
/* * Copyright 2021 Comcast Cable Communications Management, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ /*----------------------------------------------- * icFifoBuffer.c * * Simplistic FIFO (First In - First Out) Buffer that * dynamically increases memory required to store an * undetermined amount of information. * * Similar to a queue, but intended for chunks of * contiguous memory (such as a stream). * * As data is realized, it can be appended to this buffer, * then read from the front. Once enough data has been * read (pulled), it will attempt to cleanup the internal * storage to prevent an ever-growing buffer. * * Primarily used as a temporary memory storage area * when the buffering data between two different * components or threads. Could be thought of as the * inner portion of a pipe. * * NOTE: this does not perform any mutex locking to * allow for single-threaded usage without the * overhead. If locking is required, it should * be performed by the caller * * Author: jelderton - 6/18/15 *-----------------------------------------------*/ #include <stdlib.h> #include <string.h> #include <sys/errno.h> #include <icLog/logging.h> #include "icTypes/icFifoBuffer.h" #define LOG_TAG "FIFO" #define DEFAULT_BUFFER_SIZE 1024 /* * internal structure * our linear memory should look like: * * top readPos writePos size * | | | | * v v v v * :::::::::::------------------------------............... * |<- used -><----- data-in-buffer ------->|<-- unused --> * * as data is 'pushed', it will start at 'writePos' and occupy the 'unused' area * as data is 'pulled', it will start at 'readPos' and move the pointer as data is consumed */ struct _icFifoBuff { void *top; // top of allocated space uint32_t readPos; // the 'read' position uint32_t writePos; // the 'append' position uint32_t size; // end of the 'allocated memory' uint32_t chunkSize; }; /* * private function declarations */ static uint32_t ensureCapacity(icFifoBuff *buffer, uint32_t needSize); static void compact(icFifoBuff *buffer, uint32_t newSize); /* * Create a new FIFO buffer * * @param initialSize - number of bytes to pre-allocate for the buffer. If <= 0, then the default of 1024 will be used */ icFifoBuff *fifoBuffCreate(uint32_t initialSize) { // first allocate the struct (no size and all pointers at 0) // icFifoBuff *retVal = (icFifoBuff *)malloc(sizeof(icFifoBuff)); memset(retVal, 0, sizeof(icFifoBuff)); // make sure 'size' is a decent amount // if (initialSize < 64) { initialSize = DEFAULT_BUFFER_SIZE; } // now allocate memory for the buffer // retVal->chunkSize = initialSize; ensureCapacity(retVal, initialSize); return retVal; } /* * Deep clone a FIFO buffer * * @param orig - original buffer to make a copy of */ icFifoBuff *fifoBuffClone(icFifoBuff *orig) { // for simplicity, just copy everything // icFifoBuff *copy = fifoBuffCreate(orig->size); copy->readPos = orig->readPos; copy->writePos = orig->writePos; copy->chunkSize = orig->chunkSize; memcpy(copy->top, orig->top, orig->size); return copy; } /* * Destroy a FIFO buffer and free any used memory * * @param buffer - the buffer to destroy */ void fifoBuffDestroy(icFifoBuff *buffer) { if (buffer != NULL) { // free buffer & struct // if (buffer->top != NULL) { free(buffer->top); } buffer->readPos = 0; buffer->writePos = 0; buffer->size = 0; free(buffer); } } /* * Reset the buffer, but not release the allocated memory (i.e clear content) * Primarily used when re-purposing the buffer. * * @param buffer - the buffer to wipe */ void fifoBuffClear(icFifoBuff *buffer) { // simply set our pointers to the beginning // buffer->readPos = 0; buffer->writePos = 0; } /* * Return amount of free space available for 'fifoBuffPush'. * Note that if more space is required it will be automatically * allocated during the 'fifoBuffPush'. * * @param buffer - the buffer to get size info from */ uint32_t fifoBuffGetPushAvailable(icFifoBuff *buffer) { // remember our picture: // // top readPos writePos size // | | | | // v v v v // :::::::::::------------------------------............... // |<- used -><----- data-in-buffer ------->|<-- unused --> // // simply return the 'unused' amount // return (buffer->size - buffer->writePos); } /* * Append bytes to the end of the buffer. * Internally ensures there is enough capacity before copying * data from 'src' into the buffer. * * @param buffer - the buffer to push to * @param src - the memory to append to the end of the buffer * @param srcSize - number of bytes from 'src' to copy into the buffer */ void fifoBuffPush(icFifoBuff *buffer, void *src, uint32_t srcSize) { // ensure we have enough space to take on 'srcSize' bytes // ensureCapacity(buffer, srcSize); // remember our picture: // // top readPos writePos size // | | | | // v v v v // :::::::::::------------------------------............... // |<- used -><----- data-in-buffer ------->|<-- unused --> // // copy into the 'unused' area and update our 'writePos' // void *ptr = buffer->top + buffer->writePos; memcpy(ptr, src, srcSize); buffer->writePos += srcSize; } /* * append a singly byte to the end of the buffer. * generally used when building a large string and * need to ensure it's NULL terminated. */ void fifoBuffPushByte(icFifoBuff *buffer, char byte) { fifoBuffPush(buffer, (void *)&byte, 1); } /* * Returns a pointer to the internal buffer to allow a caller to * directly append bytes without needing an intermediate chunk of memory. * Primarily used in situations such as read() where a direct injection * into the buffer is more efficient then 'fifoBuffPush'. * * Once complete, the caller **MUST** follow up with a call to * fifoBuffAfterPushPointer() so that the internal structure can properly * reflect the newly appended data. * * @param buffer - the buffer to directly push to * @param numBytesNeeded - amount of memory that will be appended * @return the pointer to start directly appending at * @see fifoBuffAfterPushPointer() */ void *fifoBuffPushPointer(icFifoBuff *buffer, uint32_t numBytesNeeded) { // first ensure we have enough room // ensureCapacity(buffer, numBytesNeeded); // return the pointer // return buffer->top + buffer->writePos; } /* * Update internal structure after a call to 'fifoBuffPushPointer' is complete. * * @param buffer - the buffer to append to * @param numBytesAdded - amount of memory appended */ void fifoBuffAfterPushPointer(icFifoBuff *buffer, uint32_t numBytesAdded) { // the 'writePos' did not change from the fifoBuffPushPointer() call // so simply move that counter // buffer->writePos += numBytesAdded; } /* * Return total number of bytes available for 'fifoBuffPull' * (i.e. bytes added via 'fifoBuffPush') * * @param buffer - the buffer to get size info from */ uint32_t fifoBuffGetPullAvailable(icFifoBuff *buffer) { // remember our picture: // // top readPos writePos size // | | | | // v v v v // :::::::::::------------------------------............... // |<- used -><----- data-in-buffer ------->|<-- unused --> // // return the 'data-in-buffer' amount // return (buffer->writePos - buffer->readPos); } /* * Extract up to 'numBytes' from the buffer and place into 'dest' * Once extracted, that memory will no longer be accessible from the buffer. * * @param buffer - the buffer to adjust * @param dest - location to move the data into * @param numBytes - size of 'memory' * @return number of bytes actually copied to 'dest' */ uint32_t fifoBuffPull(icFifoBuff *buffer, void *dest, uint32_t numBytes) { // make sure there is data // uint32_t avail = fifoBuffGetPullAvailable(buffer); if (avail < numBytes) { // do not have as much data as we expected // return 0; } // remember our picture: // // top readPos writePos size // | | | | // v v v v // :::::::::::------------------------------............... // |<- used -><----- data-in-buffer ------->|<-- unused --> // // copy the 'data-in-buffer' area to 'dest' and update our 'readPos' // void *ptr = buffer->top + buffer->readPos; memcpy(dest, ptr, numBytes); buffer->readPos += numBytes; return numBytes; } /* * Returns a pointer to the internal buffer to allow a caller to * directly read bytes without needing an intermediate chunk of memory. * * Primarily used when an operation needs a pointer to read from * (such as zlib decompressing a buffer) vs copying from this buffer * into another. * * It is up to the caller to ensure they do not read more then * 'numBytesNeeded' and when done **MUST** make a subsequent call to * fifoBuffAfterPullPointer() to update the internal structure. * * @param buffer - the buffer to read from * @param numBytesNeeded - amount of memory that will be appended * @return the pointer to start directly reading from * @see fifoBuffAfterPullPointer() */ void *fifoBuffPullPointer(icFifoBuff *buffer, uint32_t numBytesNeeded) { // ensure we have this much available // uint32_t avail = fifoBuffGetPullAvailable(buffer); if (avail >= numBytesNeeded) { return buffer->top + buffer->readPos; } return NULL; } /* * Inform 'buffer' that the 'fifoBuffPullPointer' is complete and * exactly how many bytes were extracted. */ void fifoBuffAfterPullPointer(icFifoBuff *buffer, uint32_t numBytesPulled) { buffer->readPos += numBytesPulled; } /* * return if the 'used' space is large enough that we need to perform a 'compact()' operation */ static bool needsCompress(icFifoBuff *buffer) { // for now, keep this simple. if our 'used' area is more then half // of what we have allocated, then perform a compression so that // we can reclaim space without reallocating the memory // if (buffer->size > 0 && buffer->readPos > (buffer->size / 2)) { return true; } return false; } /* * ensure buffer has enough space to accommodate 'size' * returns the amount of available space */ static uint32_t ensureCapacity(icFifoBuff *buffer, uint32_t needSize) { // remember our picture: // // top readPos writePos size // | | | | // v v v v // :::::::::::------------------------------............... // |<- used -><----- data-in-buffer ------->|<-- unused --> // // see how much space is 'unused', so we can determine // if we need to allocate more room or not // uint32_t avail = fifoBuffGetPushAvailable(buffer); int lacking = (needSize - avail); if (lacking > 0) { // not enough room, so need to reallocate the buffer. // before we do that, see if we need to compact // if (needsCompress(buffer) == true) { // icLogDebug(LOG_TAG, "compacting FIFO buffer"); compact(buffer, needSize); return fifoBuffGetPushAvailable(buffer); } // need more space, so reallocate our 'top' // uint32_t newLen = buffer->size + lacking + buffer->chunkSize; void *tmp = realloc(buffer->top, newLen * sizeof(void)); if (tmp == NULL) { // allocation failed, have to make do with that we have // icLogWarn(LOG_TAG, "unable to resize FIFO buffer - %s, only allowing %d bytes", strerror(errno), avail); return avail; } // update length and the buffer // buffer->size = newLen; buffer->top = tmp; // return the amount of space now available within inputBuffer // (from position to end) // return fifoBuffGetPushAvailable(buffer); } // no reallocation needed, return the amount of space inputBuffer has // return avail; } /* * should ONLY be called if needsCompress() == true */ static void compact(icFifoBuff *buffer, uint32_t newSize) { // remember our picture: // // top readPos writePos size // | | | | // v v v v // :::::::::::------------------------------............... // |<- used -><----- data-in-buffer ------->|<-- unused --> // // since our needsCompress() was 'true' we can assume that the 'used' area // is larger then our 'data-in-buffer' area // void *ptr = buffer->top + buffer->readPos; uint32_t ptrLen = buffer->writePos - buffer->readPos; memcpy(buffer->top, ptr, ptrLen); buffer->readPos = 0; buffer->writePos = ptrLen; }
C
/** @file Component.h @brief A base class for components that's used so components can be stored in a large blocks of memory, together. */ #pragma once /** \brief A based structure to represent a component. */ struct Component { Component() = default; //!< Default constructor. virtual ~Component() = default; //!< Default destructor. };
C
#include "../rover.h" char *strdup(const char *str) { char *a; char *str1; int i; str1 = (char *)str; i = 0; a = (char *)malloc(strlen(str1) + 1); if (a == NULL) return (NULL); while (str[i] != '\0') { a[i] = str1[i]; i++; } a[i] = '\0'; return (a); }
C
#include<stdio.h> void main() { int n,i; int sum = 0; printf("Enter the n i.e max values of series:\n"); scanf("%d",&n); sum = (n*(n + 1))/2; printf("Sum of the series :\n"); for(i=1;i<=n;i++) { if(i!=n) printf("%d +",i); else printf("%d = %d",i,sum); } printf("\n"); }
C
#include<stdio.h> void main(){ for (int i = 1; i < 5; i++) { printf(i*5); printf("\n"); /* code */ } }
C
#include <SDL2/SDL.h> #include <stdio.h> #include <math.h> void spherePrimitiveByPoints(SDL_Renderer* gRenderer, SDL_Point center, int radius, int thickness){ //int count_between_Ys = 0; int circleY = center.y; int circleX = center.x; int yPosOfCirclePointDown; int yPosOfCirclePointUp; int xPosOfCirclePoint = circleX - radius; int radiusLimit = radius - thickness; int area_of_circle = floor((2.0*pow((double)radius,2.0)*M_PI) - (2.0*pow((double)radiusLimit,2.0)*M_PI)); int number_of_inner_circles = radius; int j; int k; int rightX; int leftX; int count_of_points = 0; SDL_Point* points = (SDL_Point*)(malloc(sizeof(SDL_Point)*area_of_circle)); //SDL_Point points[area_of_circle]; while(radius>radiusLimit) { //j = 0; rightX = circleX + radius; leftX = circleX - radius; k = rightX; int previousY = circleY ; for(int i=leftX; i<=circleX; i++) { yPosOfCirclePointDown = (int)round((2.0*(double)circleY+sqrt(pow((double)circleY*2.0,2.0)-4.0*((pow((double)i-(double)circleX,2.0)+pow((double)circleY,2.0)-pow((double)radius,2.0)))))/2.0); points[j*4] = (SDL_Point){i, yPosOfCirclePointDown}; points[j*4+1] =(SDL_Point){k, yPosOfCirclePointDown}; yPosOfCirclePointUp = (int)round((2.0*(double)circleY-sqrt(pow((double)circleY*2.0,2.0)-4.0*((pow((double)i-(double)circleX,2.0)+pow((double)circleY,2.0)-pow((double)radius,2.0)))))/2.0); points[j*4+2] = (SDL_Point){i, yPosOfCirclePointUp}; points[j*4+3] = (SDL_Point){k, yPosOfCirclePointUp}; //SDL_RenderDrawPoint(gRenderer, i, yPosOfCirclePointDown); //SDL_RenderDrawPoint(gRenderer, k, yPosOfCirclePointDown); //SDL_RenderDrawPoint(gRenderer, i, yPosOfCirclePointUp); //SDL_RenderDrawPoint(gRenderer, k, yPosOfCirclePointUp); j++; count_of_points++; if((previousY-yPosOfCirclePointUp)>0.0) for(int l=previousY-yPosOfCirclePointUp; l>0; l--) { //printf("inthere l: %d\n",l); points[j*4] = (SDL_Point){i, yPosOfCirclePointDown-l}; points[j*4+1] =(SDL_Point){k, yPosOfCirclePointDown-l}; points[j*4+2] = (SDL_Point){i, yPosOfCirclePointUp+l}; points[j*4+3] = (SDL_Point){k, yPosOfCirclePointUp+l}; //SDL_RenderDrawPoint(gRenderer, i, yPosOfCirclePointDown-l); //SDL_RenderDrawPoint(gRenderer, k, yPosOfCirclePointDown-l); //SDL_RenderDrawPoint(gRenderer, i, yPosOfCirclePointUp+l); //SDL_RenderDrawPoint(gRenderer, k, yPosOfCirclePointUp+l); //count_of_points = count_of_points+4; j++; count_of_points++; } previousY = yPosOfCirclePointUp; k--; } radius--; } //printf("size of array: %d\n",sizeof(points)/sizeof(SDL_Point)); SDL_RenderDrawPoints(gRenderer,points,count_of_points*4); free(points); points = NULL; //SDL_RenderDrawPoints(gRenderer,points,number_of_points); }
C
#include<stdio.h> void main() { int arr[20],*ptr,i,size; printf("Enter size of array :"); scanf("%d",&size); printf("Enter array elements :"); for(i=0;i<size;i++) { scanf("%d",&arr[i]); } ptr=arr; printf("Array elements are :\n"); for(i=0;i<size;i++) { /*printf("%d\t",*ptr); ptr++;*/ printf("%d\t",*(ptr+i)); } printf("\n"); }
C
#include <stdio.h> #include <unistd.h> int my_is_prime(int nb) { int re = nb / 2; if(nb == 2) return 1; while(re > 1) { if(nb % re == 0) return 0; else return 1; re--; } return 0; }
C
// Copyright (C) 76 Enterprises LLC - All Rights Reserved // See the file "license.txt" for the full copyright notice #pragma once #include <library/collections/vector.h> #include <boost/preprocessor/library.hpp> typedef VECTOR(U8) ae_serializer; // To make sizeof work, we say a varint is the largest it can be. typedef U8 varint[10]; // This is a dummy to allow sizeof(block) to compile. typedef U8 block; typedef U8 string; typedef U8 blank; // Create and destroy a serializer, which allows you to write data // on to a U8 vector. void create_serializer(in_out ae_serializer* obj); void destroy_serializer(in_out ae_serializer* obj); // Reserve space for an object, without increasing the length of the // vector, which allows for safe direct manipulation of the data array void serializer_reserve(in_out ae_serializer* obj, in U32 length); // Get the length of the serialized data U32 serializer_length(in ae_serializer* obj); // Get the actual data pointer from the serializer U8* serializer_data(in ae_serializer* obj); // Helper macro to deal with special types whose serialized size is not sizeof(type) #define CHECK_TYPE(type, test) \ ((void*)BOOST_PP_CAT(serialize_, type) == (void*)BOOST_PP_CAT(serialize_, test)) // Serializes data of a given type to the destination serializer #define serialize(dest, type, ...) \ BOOST_PP_CAT(serialize_, BOOST_PP_VARIADIC_SIZE(__VA_ARGS__))(dest, type, __VA_ARGS__) #define serialize_1(dest, type, value) \ DISABLE_DIAGNOSTIC(INVALID_INT_CONVERSION) \ DISABLE_DIAGNOSTIC(DISCARDS_QUALIFIERS) \ serializer_reserve(dest, \ CHECK_TYPE(type, string) ? strlen(value) + 1 : \ CHECK_TYPE(type, blank) ? (U32)value : \ sizeof(type)); \ VECTOR_FINISH_CHECKOUT(U8)(dest, BOOST_PP_CAT(serialize_, type)(VECTOR_START_CHECKOUT(U8)(dest), value)); \ ENABLE_DIAGNOSTIC(DISCARDS_QUALIFIERS) \ ENABLE_DIAGNOSTIC(INVALID_INT_CONVERSION) #define serialize_2(dest, type, val1, val2) \ serializer_reserve(dest, val2); \ VECTOR_FINISH_CHECKOUT(U8)(dest, BOOST_PP_CAT(serialize_, type)(VECTOR_START_CHECKOUT(U8)(dest), val1, val2)); // Internal functions for serializing different types U32 serialize_U8(out U8* dest, in U8 value); U32 serialize_U16(out U8* dest, in U16 value); U32 serialize_U32(out U8* dest, in U32 value); U32 serialize_U64(out U8* dest, in U64 value); // Internal functions for serializing varints U32 serialize_varint(out U8* dest, in U64 value); U32 serialize_varint_signed(out U8* dest, in S64 value); // Internal function for serializing a number of zero bytes U32 serialize_blank(out U8* dest, in U32 length); // Internal function for serializing a zero terminated string U32 serialize_string(out U8* dest, in cstring val); // Internal function of serializing a block of fixed size U32 serialize_block(out U8* dest, in U8* data, in U32 len);
C
#include <stdio.h> #include <string.h> int convert(char* n, int m) { int l = strlen(n), sum = 0, i; for (i = 0; i < l; i++) { sum *= m; if (n[i] >= '0' && n[i] <= '9') sum += n[i] - '0'; else sum += n[i] - 'A' + 10; } return sum; } char* reverse(int n, int m) { int num[40], l = 0, i; if (n) { while (n) { num[l++] = n % m; n /= m; } } else num[l++] = 0; char *s = (char*)malloc(sizeof(char) * (l + 1)); for (i = 0; i < l; i++) { if (num[l - i - 1] < 10) s[i] = num[l - i - 1] + '0'; else s[i] = num[l - i - 1] + 'A' - 10; } s[l] = '\0'; return s; } int main() { int t, m, n1, n2; char a[40], b[40], *p, *q; scanf("%d", &t); while (t--) { scanf("%d%s%s", &m, a, b); n1 = convert(a, m); n2 = convert(b, m); p = reverse(n1 / n2, m); q = reverse(n1 % n2, m); printf("%s\n%s\n", p, q); } return 0; }
C
#include <stdio.h> #include <stdlib.h> int func(int x) { int a, a0, a1, a2; a0 = x * x * 2 + 1; a1 = x + 2 - a0; a2 = x / 2 + a1; a = a0 + a1 + a2; printf("a: %d\n", a); return a; } int main(void) { int i = 1; while(1) { i = func(i); sleep(3); } return EXIT_SUCCESS; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef char element; typedef struct stackNode { element data; struct stackNode *link; } stackNode; stackNode *top; void push(element item) { stackNode* temp = (stackNode*)malloc(sizeof(stackNode)); temp->data = item; temp->link = top; top = temp; } element pop() { element item; stackNode *temp = top; if (top == NULL) return 0; item = temp->data; top = temp->link; free(temp); return item; } int testPair(char *exp) { char symbol, open_pair; int i, length = strlen(exp); top = NULL; for (i = 0; i < length; i++) { symbol = exp[i]; switch (symbol) { case '(': case '[': case '{': //peek을 이용한 순서 검사 추가 push(symbol); break; case ')': case ']': case '}': if (top == NULL) return 0; else { open_pair = pop(); if ((open_pair == '(' && symbol != ')') || (open_pair == '[' && symbol != ']') || (open_pair == '{' && symbol != '}') ) return 0; else break; } } } if (top == NULL) return 1; else return 0; } void main(void) { char *express = "{(A+B)-3}*5+[{cos(x+y)+7}-1]*4 "; printf("%s", express); if (testPair(express)) printf("\n\n 수식의 괄호가 맞게 사용되었습니다.\n"); else printf("\n\n 수식의 괄호가 틀렸습니다!\n"); }
C
/* This file contains code to calculate Kendall's Tau in O(N log N) time in * a manner similar to the following reference: * * A Computer Method for Calculating Kendall's Tau with Ungrouped Data * William R. Knight Journal of the American Statistical Association, Vol. 61, * No. 314, Part 1 (Jun., 1966), pp. 436-439 * * Copyright 2010 David Simcha * * License: * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. f * */ #include <stdint.h> #include <stdlib.h> #include <string.h> #include <math.h> uint64_t insertionSort(double*, size_t); #define kendallTest #ifdef kendallTest #include <stdio.h> #include <assert.h> #include <time.h> /* Kludge: In testing mode, just forward R_rsort to insertionSort to make this * module testable without having to include (and compile) a bunch of other * stuff. */ void R_rsort(double* arr, int len) { insertionSort(arr, len); } #else #include <R_ext/Utils.h> /* For R_rsort. */ #endif /* Sorts in place, returns the bubble sort distance between the input array * and the sorted array. */ uint64_t insertionSort(double* arr, size_t len) { size_t maxJ, i; uint64_t swapCount = 0; if(len < 2) { return 0; } maxJ = len - 1; for(i = len - 2; i < len; --i) { size_t j = i; double val = arr[i]; for(; j < maxJ && arr[j + 1] < val; ++j) { arr[j] = arr[j + 1]; } arr[j] = val; swapCount += (j - i); } return swapCount; } static uint64_t merge(double* from, double* to, size_t middle, size_t len) { size_t bufIndex, leftLen, rightLen; uint64_t swaps; double* left; double* right; bufIndex = 0; swaps = 0; left = from; right = from + middle; rightLen = len - middle; leftLen = middle; while(leftLen && rightLen) { if(right[0] < left[0]) { to[bufIndex] = right[0]; swaps += leftLen; rightLen--; right++; } else { to[bufIndex] = left[0]; leftLen--; left++; } bufIndex++; } if(leftLen) { memcpy(to + bufIndex, left, leftLen * sizeof(double)); } else if(rightLen) { memcpy(to + bufIndex, right, rightLen * sizeof(double)); } return swaps; } /* Sorts in place, returns the bubble sort distance between the input array * and the sorted array. */ uint64_t mergeSort(double* x, double* buf, size_t len) { uint64_t swaps; size_t half; if(len < 10) { return insertionSort(x, len); } swaps = 0; if(len < 2) { return 0; } half = len / 2; swaps += mergeSort(x, buf, half); swaps += mergeSort(x + half, buf + half, len - half); swaps += merge(x, buf, half, len); memcpy(x, buf, len * sizeof(double)); return swaps; } static uint64_t getMs(double* data, size_t len) { /* Assumes data is sorted.*/ uint64_t Ms = 0, tieCount = 0; size_t i; for(i = 1; i < len; i++) { if(data[i] == data[i-1]) { tieCount++; } else if(tieCount) { Ms += (tieCount * (tieCount + 1)) / 2; tieCount++; tieCount = 0; } } if(tieCount) { Ms += (tieCount * (tieCount + 1)) / 2; tieCount++; } return Ms; } /* This function calculates the Kendall covariance (if cor == 0) or * correlation (if cor != 0), but assumes arr1 has already been sorted and * arr2 has already been reordered in lockstep. This can be done within R * before calling this function by doing something like: * * perm <- order(arr1) * arr1 <- arr1[perm] * arr2 <- arr2[perm] */ double kendallNlogN(double* arr1, double* arr2, size_t len, int cor) { uint64_t m1 = 0, m2 = 0, tieCount, swapCount, nPair; int64_t s; size_t i; nPair = (uint64_t) len * ((uint64_t) len - 1) / 2; s = nPair; tieCount = 0; for(i = 1; i < len; i++) { if(arr1[i - 1] == arr1[i]) { tieCount++; } else if(tieCount > 0) { R_rsort(arr2 + i - tieCount - 1, tieCount + 1); m1 += tieCount * (tieCount + 1) / 2; s += getMs(arr2 + i - tieCount - 1, tieCount + 1); tieCount++; tieCount = 0; } } if(tieCount > 0) { R_rsort(arr2 + i - tieCount - 1, tieCount + 1); m1 += tieCount * (tieCount + 1) / 2; s += getMs(arr2 + i - tieCount - 1, tieCount + 1); tieCount++; } swapCount = mergeSort(arr2, arr1, len); m2 = getMs(arr2, len); s -= (m1 + m2) + 2 * swapCount; if(cor) { double denominator1 = nPair - m1; double denominator2 = nPair - m2; double cor = s / sqrt(denominator1) / sqrt(denominator2); return cor; } else { /* Return covariance. */ return 2 * s; } } /* This function uses a simple O(N^2) implementation. It probably has a smaller * constant and therefore is useful in the small N case, and is also useful * for testing the relatively complex O(N log N) implementation. */ double kendallSmallN(double* arr1, double* arr2, size_t len, int cor) { /* Not using 64-bit ints here because this function is meant only for small N and for testing. */ int m1 = 0, m2 = 0, s = 0, nPair; size_t i, j; double denominator1, denominator2; for(i = 0; i < len; i++) { for(j = i + 1; j < len; j++) { if(arr2[i] > arr2[j]) { if (arr1[i] > arr1[j]) { s++; } else if(arr1[i] < arr1[j]) { s--; } else { m1++; } } else if(arr2[i] < arr2[j]) { if (arr1[i] > arr1[j]) { s--; } else if(arr1[i] < arr1[j]) { s++; } else { m1++; } } else { m2++; if(arr1[i] == arr1[j]) { m1++; } } } } nPair = len * (len - 1) / 2; if(cor) { denominator1 = nPair - m1; denominator2 = nPair - m2; return s / sqrt(denominator1) / sqrt(denominator2); } else { /* Return covariance. */ return 2 * s; } } #ifdef kendallTest #endif
C
#include "../src/sds.h" #include <stdio.h> #include <assert.h> int main(int argc, char *argv[]) { printf("size:%ld\n", sizeof(struct sdshdr)); sds sname = sdsnew("hello sds"); printf("%s\n", sname); assert(sdslen(sname) == 9); assert(sdsavail(sname) == 0); sds sdup = sdsdup(sname); printf("%s\n", sdup); assert(sdslen(sdup) == 9); assert(sdsavail(sdup) == 0); sdsclear(sname); printf("%s\n", sname); assert(sdslen(sname) == 0); assert(sdsavail(sname) == 9); sdscat(sname, "newdat"); printf("%s\n", sname); assert(sdslen(sname) == 6); assert(sdsavail(sname) == 3); sdscat(sname, ",data"); printf("%s\n", sname); assert(sdslen(sname) == 11); assert(sdsavail(sname) == 11); sdscat(sname, sdup); printf("%s\n", sname); assert(sdslen(sname) == 20); assert(sdsavail(sname) == 2); sdscpy(sdup, "copytest"); printf("%s\n", sdup); assert(sdslen(sdup) == 8); assert(sdsavail(sdup) == 1); sdscpy(sdup, "cxxtest add"); printf("%s\n", sdup); assert(sdslen(sdup) == 11); assert(sdsavail(sdup) == 11); sds s2 = sdsnew("cxxtest"); assert(sdscmp(sdup, s2) == 4); sdsfree(sdup); // when free, can't be used anymore sdsfree(sname); // when free, can't be used anymore return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* show_alloc_mem.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: nmougino <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/11/14 22:47:07 by nmougino #+# #+# */ /* Updated: 2018/08/13 22:33:08 by nmougino ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_malloc.h" static char *get_type(size_t s) { if (s <= TINY) return ("TINY"); if (s <= SMALL) return ("SMALL"); return ("LARGE"); } void show_alloc_mem(void) { t_page *page; t_mblkid *mtab; size_t tot; size_t i; page = *get_book(); tot = 0; while (page) { i = 0; mtab = page->blks; ft_printf("%s : %p\n", get_type(page->blksize), page); while (i < page->blkcount) { if (mtab[i].used) ft_printf("%p - %p : %zu octets\n", mtab[i].ptr, (unsigned long)(mtab[i].ptr) + mtab[i].used, mtab[i].used); tot += mtab[i].used; i++; } page = page->next; } ft_printf("Total : %zu octets\n", tot); }
C
#include <stdio.h> #include <stdlib.h> long filesize(FILE *stream); void main() { long size,pos; char ch; FILE *fp_in,*fp_out; if((fp_in =fopen("data.dat","r"))==NULL) { printf("can't open file stud.dat\n"); exit(1); } if((fp_out =fopen("trans.dat","w"))==NULL) { fclose(fp_in); printf("can't open file trans.dat\n"); exit(1); } pos=0; size = filesize(fp_in); while(pos++<size) { fseek(fp_in,-pos,SEEK_END); ch=fgetc(fp_in); putchar(ch); fputc(ch,fp_out); } fclose(fp_in); fclose(fp_out); } long filesize(FILE *stream) { int curpos, length; curpos = ftell(stream); fseek(stream, 0L, SEEK_END); length = ftell(stream); fseek(stream, curpos, SEEK_SET); return length; }