language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include<stdio.h> #include<time.h> #define SIZE 50000 void main() { int a[SIZE],pos,i,j,n,temp; double total; clock_t start,end; printf("Enter n :\n"); scanf("%d",&n); //printf("Enter elements :\n"); for(i=0;i<n;i++) a[i]=rand(); //scanf("%d",&a[i]); start=clock(); for(i=0;i<n;i++) { pos=i; for(j=i+1;j<n;j++) { if(a[pos]>a[j]) { pos=j; } } temp=a[pos]; a[pos]=a[i]; a[i]=temp; } end=clock(); /*printf("Elements after sorting are :\n"); for(i=0;i<n;i++) printf("%d\n",a[i]);*/ total=(double)(end-start)/CLOCKS_PER_SEC; printf("Time taken = %lf seconds\n",total); }
C
/* Header file for regular expression compiler Copyright (C) 2016 Kyle Gagner All Rights Reserved */ #include "unicode.h" #ifndef REGEX_H #define REGEX_H typedef struct { UNICODE_Char *expression; unsigned long accepts; } REGEX_Expression; typedef struct { REGEX_Expression *expressions; unsigned long expressions_count; } REGEX_Expressions; typedef struct { UNICODE_Char on; unsigned long to; } REGEX_Transition; typedef struct { REGEX_Transition *transitions; unsigned short transitions_count; unsigned long accepts; } REGEX_State; typedef struct { REGEX_State *states; unsigned long states_count; } REGEX_Machine; REGEX_Machine *REGEX_CreateMachine(REGEX_Expressions *expressions); void REGEX_DestroyMachine(REGEX_Machine *machine); #endif
C
/*28. Hacerelprogramaantelapreguntadeseacontinuarslonospermitaintroducircomorespuesta'S'o'N'*/ #include <stdio.h> int main(){ char r='S'; while(r=='S'){ printf("desea seguir S/N \n"); fflush(stdin); scanf("%c",&r); while(r !='S' && r =='N');{ printf("error ingrese S/N \n"); } } system("pause"); return 0; }
C
// This code is created by Ahmed A. Eltahan /* ----------------------------- Program Description ----------------------------------------- This code motivates the importance of using functions, here a function for pringtin the hashtags and stars will ease the code readability and make it concise. This is the desired output: ################################################## ************************************************** Welcome to our program ################################################## ************************************************** Programing course is so boring! ################################################## ************************************************** I will go to sleep now, Goodbye! ################################################## ************************************************** */ #include<stdio.h> // Library to include c functions for the compiler. main() { // Declaration and Inintialization int i; // counter // Write your instructions here. // printing hashtags and stars for (i = 1; i<=50; i++) { printf("#"); } printf("\n"); for (i = 1; i<=50; i++) { printf("*"); } // Message no 1 printf("\n \n "); printf("\t Welcome to our program \n \n"); // printing hashtags and stars for (i = 1; i<=50; i++) { printf("#"); } printf("\n"); for (i = 1; i<=50; i++) { printf("*"); } // Message no 2 printf("\n \n "); printf("\t Programing course is so boring! \n \n"); // printing hashtags and stars for (i = 1; i<=50; i++) { printf("#"); } printf("\n"); for (i = 1; i<=50; i++) { printf("*"); } // Message no 3 printf("\n \n "); printf("\t I will go to sleep now, Goodbye! \n \n"); // printing hashtags and stars for (i = 1; i<=50; i++) { printf("#"); } printf("\n"); for (i = 1; i<=50; i++) { printf("*"); } // Output }
C
#include "menu_principal.h" #include <stdio.h> #include "utilidad.h" #include "estructura.h" #include "entrada&salida.h" #include "partida.h" /** \brief Funcion de inicio de programa * * \return No devuelve nada * */ void entrar() { int d; printf("\tBienvenido a ESINAIT \n 1.Entrar en el sistema\n 0.Salir del sistema\n"); scanf("%d",&d); if(d==0){ exit(1); } } /** \brief Inicio de sesion de cada usuario * * \return No devuelve nada * */ void iniciar_sesion() { int c; printf(" 1.Cuenta existente\n "); printf(" 2.Crear un usuario nuevo\n"); printf("\t Su eleccion:"); scanf("%i",&c); do { switch(c) { case 1: comprobar_jugador(); break; case 2: crear_usuario(); break; //return 0; default: printf("Opcion no valida"); } } while(c<1 || c>2); } /** \brief Funcion para crear perfil nuevo * * \return No devuelve nada, modifica por referencia el vector de jugadores * */ void crear_usuario() { char contra[50]; char contra1[50]; int comprobante=0; int N=0; N=contar_linea_fichero("usuarios.txt"); N=N+1; jugadores=(jugador*)malloc(N*sizeof(jugador)); puts("Bienvenido a Esinait, rellene los datos para crear su cuenta"); puts("Introduzca su nick de juego; "); fflush(stdin); fgets(jugadores[N].sobrenombre,50,stdin); correcionM(jugadores[N].sobrenombre); puts("Introduzca su nombre completo: "); fflush(stdin); fgets(jugadores[N].nombre,50,stdin); correcionM(jugadores[N].nombre); while(comprobante==0) { puts("Introduzca su contrasea: "); fflush(stdin); fgets(contra,50,stdin); correcionM(contra); puts("Repita la contrasea: "); fflush(stdin); fgets(contra1,50,stdin); correcionM(contra1); if(strcmp(contra,contra1)==0) { strcpy(jugadores[N].contrasena,contra); comprobante=1; } else { puts("La contrasea no coincide"); } } jugadores[N].nivel=1; printf("Su nivel actual es %d por ser un nuevo usuario\n\n",jugadores[N].nivel); jugadores[N].vida=100; printf("Su vida actual es de %d por ser un nuevo usuario\n\n",jugadores[N].vida); jugadores[N].escudo=0; printf("Su escudo actual es de %d por ser un nuevo usuario\n\n",jugadores[N].escudo); strcpy(jugadores[N].estado,"OFF"); printf("Al ser un nuevo usuario, su estado preterminado es %s \n\n",jugadores[N].estado); jugadores[N].cartera=0; printf("Sus monedas actuales son %d debido a ser un nuevo usuario \n\n",jugadores[N].cartera); jugadores[N].np=0; jugadores[N].ng=0; jugadores[N].admin=0; menu_usuarios(&jugadores[N]); } /** \brief Comprueba la informacion de inicio del jugador * * \return No devuelve nada * */ void comprobar_jugador() { int N=0; int i=0; int j=0; int decision=0; int comprobar=0; char contra[50]; char nom[50]; int intentos=2; N=contar_linea_fichero("usuarios.txt"); while(comprobar==0) { i=0; puts("Introduzca su nombre de usuario: "); fflush(stdin); fgets(nom,50,stdin); correcionM(nom); printf("%s \n\n",jugadores[i].sobrenombre); while((i<N)&&(comprobar==0)) { correcionM(jugadores[i].sobrenombre); if(strcmp(jugadores[i].sobrenombre,nom)==0) { j=i; comprobar=1; printf("%d \n\n",comprobar); } else { i++; } } if(comprobar==0) { puts("Usuario No encontrado porfavor intentelo de nuevo"); puts("Pulse 1 para volver a la pantalla inicial"); scanf("%d",&decision); fflush(stdin); if(decision==1) { system("cls"); } } } comprobar=0; while((comprobar==0)&&(intentos>=0)) { puts("Introduzca su contrasena: "); fflush(stdin); fgets(contra,50,stdin); correcionM(contra); comprobar=0; printf("%s",jugadores[j].contrasena); if(strcmp(jugadores[j].contrasena,contra)==0) { comprobar=1; puts("Contrasena correcta, bienvenido\n\n"); } else { puts("Contrasena incorrecta, vuelva a intentarlo\n"); printf("Le quedan %d intentos",intentos); intentos--; } } if(jugadores[j].admin==1) { menu_administrador(&jugadores[j]); } else { menu_usuarios(&jugadores[j]); } } /** \brief Menu de control del administrador * * \param *jug Puntero a jugador * \return No devuelve nada * */ void menu_administrador(jugador *jug) { int decision; int comprobar=0; char decision1[20]; int i=0; int N=0; int j=0; N=contar_linea_fichero("usuarios.txt"); //printf("%s",jug->sobrenombre); printf("\n\tMenu-Administrador\n"); printf("--------------------------\n"); puts("OPCIONES DEL ADMINISTRADOR : "); puts("Que desea hacer?\n\n"); puts(" 1.Editar un perfil"); puts(" 2.Empezar la partida: "); puts(" 3.Eliminar jugador"); puts(" 4.Editar configuracion"); puts(" 5.Editar objetos"); puts("OPCIONES USUARIO"); printf(" 6.Cambiar de usuario\n"); printf(" 7.Jugar/Continuar Partida\n"); printf(" 8.Comprar objetos\n"); printf(" 9.Ver perfil\n"); printf(" 10.Salir del sistema\n"); printf("\n\t Su eleccion:"); scanf("%d",&decision); switch (decision) { case 1: editar_usuario(); break; case 2: game_loop(); //Se inicia la partida break; case 3: puts("Introduce el nickname el jugador al que quiere eliminar"); fflush(stdin); fgets(decision1,50,stdin); correcionM(decision1); for(i=0; i<N; i++) { if(strcmp(decision1,jugadores[i].sobrenombre)==0) { j=i; i=N; comprobar=1; } } if(comprobar==1) { strcpy(jugadores[j].sobrenombre,jugadores[N-1].sobrenombre); strcpy(jugadores[j].nombre,jugadores[N-1].nombre); jugadores[j].nivel=jugadores[N-1].nivel; jugadores[j].vida=jugadores[N-1].vida; jugadores[j].escudo=jugadores[N-1].escudo; strcpy(jugadores[j].estado,jugadores[N-1].estado); jugadores[j].cartera=jugadores[N-1].cartera; jugadores[j].np=jugadores[N-1].np; jugadores[j].ng=jugadores[N-1].ng; jugadores[j].admin=jugadores[N-1].admin; strcpy(jugadores[j].contrasena,jugadores[N-1].contrasena); N--; jugadores=(jugador*)realloc(jugadores,N*sizeof(jugador)); } else { puts("Ese jugador no existe"); } puts("ANTES DE ESTPO"); menu_administrador(&jugadores[j]); break; case 4: editar_configuracion(); break; case 5: editar_objetos(); break; case 6: iniciar_sesion(); break; case 7: printf("Usted esta en espera"); strcpy(jug->estado, "EE"); num_jugadores_activos++; menu_administrador(&jugadores[j]); break; case 8: comprar_objeto(jug); break; case 9: ver_perfil(jug); break; case 10: printf(" Saliendo..."); entrar(); break; default: printf("\nOpcion no valida\n"); break; } } /** \brief Menu de edicion de usuarios para el administrador * * \return No devuelve nada * */ void editar_usuario() { int comprobacion=0; char decision[50]; char cambiarP[50]; int cambiarN; int decision1=0; int decision2=0; int N=0; int j=0; int i=0; N=contar_linea_fichero("usuarios.txt"); while(comprobacion==0) { puts("Introduzca el nick del jugador del cual quiere editar su perfil: "); fflush(stdin); fgets(decision,50,stdin); correcionM(decision); while((comprobacion==0)&&(i<N)) { if(strcmp(jugadores[i].sobrenombre,decision)==0) { comprobacion=1; j=i; } else { // printf("%d",i); i++; } } if(comprobacion==0) { puts("Ese jugador no existe\n\n"); puts("Pulse 1 para introducir otro usuario"); puts("Pulse cualquier otro boton para volver al menu administrador"); scanf("%d",&decision1); if(decision1!=1) { menu_administrador(&jugadores[j]); } } } printf("Introduzca el campo que quiere modificar del jugador %s \n\n",jugadores[j].sobrenombre); puts("Pulse 1 para editar el nick"); puts("Pulse 2 para editar el nombre"); puts("Pulse 3 para editar el nivel"); puts("Pulse 4 para editar la vida"); puts("Pulse 5 para editar el escudo"); puts("Pulse 6 para editar el estado"); puts("Pulse 7 para editar la cartera"); puts("Pulse 8 para editar el numero partida jugadas"); puts("Pulse 9 para editar el numero partida ganadas"); puts("Pulse 10 para editar el rol"); puts("Pulse 11 para editar la contrasea"); scanf("%d",&decision2); switch(decision2) { case 1: printf("El nick actual es %s \n\n",jugadores[j].sobrenombre); puts("Introduzca el nuevo nick del jugador: "); fflush(stdin); fgets(cambiarP,50,stdin); correcionM(cambiarP); strcpy(jugadores[j].sobrenombre,cambiarP); printf("El nuevo valor del nickname es %s \n\n",jugadores[j].sobrenombre); editar_usuario(); case 2: printf("El nombre actual es %s \n\n",jugadores[j].nombre); puts("Introduzca el nuevo nombre del jugador: "); fflush(stdin); fgets(cambiarP,50,stdin); correcionM(cambiarP); strcpy(jugadores[j].nombre,cambiarP); printf("El nuevo valor del nombre es %s \n\n",jugadores[j].nombre); editar_usuario(); case 3: printf("El nivel actual es %d \n\n",jugadores[j].nivel); puts("Introduzca el nuevo nivel del jugador: "); scanf("%d",&cambiarN); jugadores[j].nivel=cambiarN; printf("El nuevo nivel del jugador es %d \n\n",jugadores[j].nivel); editar_usuario(); case 4: printf("La vida actual es %d \n\n",jugadores[j].vida); puts("Introduzca la nueva vida del jugador: "); scanf("%d",&cambiarN); jugadores[j].vida=cambiarN; printf("La nueva vida del jugador es %d \n\n",jugadores[j].vida); editar_usuario(); case 5: printf("El escudo actual del escudo es %d \n\n",jugadores[j].escudo); puts("Introduzca el nuevo escudo del jugador: "); scanf("%d",&cambiarN); jugadores[j].escudo=cambiarN; printf("El nuevo escudo del jugador es %d \n\n",jugadores[j].escudo); editar_usuario(); case 6: printf("El estado actual es %s \n\n",jugadores[j].estado); puts("Introduzca el nuevo estado del jugador: "); fflush(stdin); fgets(cambiarP,50,stdin); correcionM(cambiarP); strcpy(jugadores[j].estado,cambiarP); printf("El nuevo estado es %s \n\n",jugadores[j].estado); editar_usuario(); case 7: printf("El valor actual de la cartera es %d \n\n",jugadores[j].cartera); puts("Introduzca el nuevo valor de la cartera del jugador: "); scanf("%d",&cambiarN); jugadores[j].cartera=cambiarN; printf("El nuevo valor de la cartera es es %d \n\n",jugadores[j].cartera); editar_usuario(); case 8: printf("El numero de partidas jugadas es %d \n\n",jugadores[j].np); puts("Introduzca el nuevo valor de partidas jugadas por el jugador: "); scanf("%d",&cambiarN); jugadores[j].np=cambiarN; printf("El numero de partidas jugadas por el jugador es %d \n\n",jugadores[j].np); editar_usuario(); case 9: printf("El numero de partidas ganadas es %d \n\n",jugadores[j].ng); puts("Introduzca el nuevo valor de partidas ganadas por el jugador: "); scanf("%d",&cambiarN); jugadores[j].ng=cambiarN; printf("El nuumero de partidas ganadas por el jugador es %d \n\n",jugadores[j].ng); editar_usuario(); case 10: puts("1 para administrador, 0 para usuario corriente"); printf("El rol del usuario es %d \n\n",jugadores[j].admin); puts("Introduzca el nuevo rol del jugador: "); scanf("%d",&cambiarN); jugadores[j].admin=cambiarN; printf("El nuevo rol del jugador es %d \n\n",jugadores[j].admin); editar_usuario(); case 11: printf("La contrasea actual es %s \n\n",jugadores[j].contrasena); puts("Introduzca la nueva contrasea del jugador: "); fflush(stdin); fgets(cambiarP,50,stdin); correcionM(cambiarP); strcpy(jugadores[j].contrasena,cambiarP); printf("La nueva contrasea es %s \n\n",jugadores[j].contrasena); editar_usuario(); default: editar_usuario(); } } /** \brief Menu de control para los usuarios * * \param *jug Puntero a jugador * \return No devuelve nada * */ void menu_usuarios(jugador *jug) { int c; printf("%s",jug->sobrenombre); printf("\n\tMenu-Usuarios\n"); printf("--------------------------\n"); if(strcmp(jug->estado,"EJ")!=0) { printf(" 1.Cambiar de usuario\n"); } else { printf(" 1.#Opcion bloqueada durante la partida#\n"); } if(strcmp(jug->estado,"EJ")!=0) { printf(" 2.Jugar partida\n"); } else { printf(" 2.Continuar partida\n"); } if(strcmp(jug->estado,"EJ")!=0) { printf(" 3.Comprar Objeto\n"); } else { printf(" 3.#Opcion bloqueada durante la partida#\n"); } printf(" 4.Ver perfil\n"); if(strcmp(jug->estado,"EJ")!=0) { printf(" 5.Salir del sistema\n"); } else { printf(" 5.#Opcion bloqueada durante la partida#\n"); } printf("\n\t Su eleccion:"); if(strcmp(jug->estado,"EJ")!=0) { scanf("%d",&c); } else { do { scanf("%d",&c); } while(c!=5 || c!=3 || c!=1); } do { switch(c) { case 1: iniciar_sesion(); break; case 2: printf("\n Todavia no hecha\n"); strcpy(jug->estado, "EE"); num_jugadores_activos++; break; case 3: comprar_objeto(jug); break; case 4: ver_perfil(jug); break; case 5: printf(" Saliendo..."); //volver a entrar break; default: printf("\nOpcion no valida\n"); break; } } while(c<1 && c>5); } /** \brief Muestra por pantalla la informacion de perfil del usuario * * \param *jug Puntero a jugador * \return No devuelve nada * */ void ver_perfil(jugador *jug) { system("cls"); printf("\tTu perfil:\n"); printf("Nick: %s\n",jug->sobrenombre); printf("Nombre: %s\n",jug->nombre); printf("Contrasena: %s\n",jug->contrasena); printf("Cartera: %i monedas\n",jug->cartera); printf("Estado: %s\n",jug->estado); printf("Vida: %i",jug->vida); printf("Escudo: %i\n",jug->escudo); printf("Nivel: %i\n",jug->nivel); printf("Numero de partidas ganadas: %i\n",jug->ng); printf("Numero de aprtidas jugadas: %i\n",jug->np); printf("Numero de objetos de la mochila: %i\n",jug->num_objetos); printf("\n"); system("pause"); } /** \brief Muestra la tienda para comprar objetos * * \param *jug Puntero a jugador * \return No devuelve nada * */ void comprar_objeto(jugador *jug) { int j,N,k,NM,W,n=1,y,z,comp,comp2; char p; char id[10],u[10],c[2],c2[2]; N=total_objetos; system("cls"); printf("\t\nBIENVENIDO A LA TIENDA\n"); printf("\n"); for(j=0; j<N; j++) { printf("%i. %s\t",j+1,objetos[j].identificadorobjeto); if(j==4) { printf("\n"); } } printf("\n\nDesea comprar alguno de estos objetos?[si/no]: "); scanf("%s",c); comp=compara_palabra(c,"si","Si"); //Datos estaticos pre bucle NM=jug->num_objetos; W=0; do { if(comp==1) { printf("\n\nIndica el identificador del objeto: "); scanf("%s",id); fflush(stdin); //Buscamos el objeto k = objeto for(k=0; k<=N; k++) { //objeto existe if(strcmp(id,objetos[k].identificadorobjeto)==0) { if(objetos[k].coste<=jug->cartera) { //Lugar donde se repite el objeto= Y for(y=0; y<objeto_juego[0].tamano_mochila; y++) { if(strcmp(id,jug->mochila[y].identificadorobjeto)==0) { W=1;//Esta repetidp printf("\nEl objeto ''%s''esta repetido",objetos[k].descripcion); jug->cartera=jug->cartera-objetos[k].coste; //pierdes dinero al comprar el objeto if(strcmp("arma",jug->mochila[y].tipo)==0) { printf(" y adquiere 20 mas de municion\n"); jug->mochila[y].cantidad=jug->mochila[y].cantidad+20; } else { printf(" y acumulas 1 mas\n"); jug->mochila[y].cantidad++; } } } //No esta repetido W=si se repite o no 1/0 if(W==0) { if(objeto_juego[0].tamano_mochila>=jug->num_objetos) { //con espacio printf("\nEl objeto ''%s'' sera aadido a su mochila\n",objetos[k].descripcion); jug->cartera=jug->cartera-objetos[k].coste; NM=jug->num_objetos; strcpy(jug->mochila[NM].identificadorobjeto,objetos[k].identificadorobjeto); strcpy(jug->mochila[NM].descripcion,objetos[k].descripcion); jug->mochila[NM].alcance=objetos[k].alcance; jug->mochila[NM].coste=objetos[k].coste; jug->mochila[NM].dano=objetos[k].dano; strcpy(jug->mochila[NM].tipo,objetos[k].tipo); jug->mochila[NM].cantidad=objetos[k].cantidad; printf("//Objeto aadido con exito//\n"); } else { //Mochila llena printf("\nSu mochila esta llena\nDesea comprar el objeto sustituyendolo por uno suyo?[s/n]:"); scanf("%c",&p); switch(p) { //Si sustituimos case 's' : //Muestra tus objetos = j for(j=0; j<jug->num_objetos; j++) { printf("\nEstos son tus objeto:\n"); printf("%d.%s:\n",n,jug->mochila[j].identificadorobjeto); printf(" Tipo: %s\n",jug->mochila[j].tipo); printf(" Alcance: %f\n",jug->mochila[j].alcance); printf(" Dano: %i\n",jug->mochila[j].dano); printf(" Coste: %i\n",jug->mochila[j].coste); printf(" Cantidad: %i\n",jug->mochila[j].cantidad); printf(" Descripcion: %s\n",jug->mochila[j].descripcion); n++; } do { printf("\n\tQue objeto quieres sustituir?(indique la id):"); fgets(u,10,stdin); fflush(stdin); //Busca el objeto usando la id proporcionada= n for(n=0; n<=jug->num_objetos; n++) { if(strcmp(u,jug->mochila[n].identificadorobjeto)==0) { jug->cartera=jug->cartera-objetos[k].coste; strcpy(jug->mochila[n].identificadorobjeto,objetos[k].identificadorobjeto); strcpy(jug->mochila[n].descripcion,objetos[k].descripcion); jug->mochila[n].alcance=objetos[k].alcance; jug->mochila[n].coste=objetos[k].coste; jug->mochila[n].dano=objetos[k].dano; strcpy(jug->mochila[n].tipo,objetos[k].tipo); jug->mochila[n].cantidad=objetos[k].cantidad; n=jug->num_objetos;//para que no realice mas iteraciones z=1;//objeto encontrado } } if(z==0) printf("\nObjeto no encontrado indique una id valida\n"); } while(z==0); printf("\nSustitucion realizada\n"); break; //No queremos case 'n': printf("\nNo se comprara el objeto y no se le quitara dinero\n"); break; default: printf("\nNo se comprara el objeto y no se le quitara dinero\n"); break; } } } } else { printf("\nNo tienes suficiente dinero\n"); } } } } printf("Desea comprar algo mas?[si/no]"); scanf("%s",c2); comp2=compara_palabra(c2,"si","Si"); } while(comp2==1); printf("\n\tSaliendo de la tienda\n"); system("pause"); } /** \brief Menu para editar la configuracion de partida * * \return No devuelve nada * */ void editar_configuracion() { int c,x,comp; float x1; char c2[2]; system("cls"); printf("\n\tConfiguracion Partida\n"); printf("\n---------------------------------------\n"); printf(" 1.Tamao mapa(Radio)\n"); printf(" 2.Distancia maxima para recoger objeto\n"); printf(" 3.Distancia para alcanzar a un oponente con el arma por defecto\n"); printf(" 4.Monedas por defecto\n"); printf(" 5.Minimo de jugadores\n"); printf(" 6.Valor del desplazamiento\n"); printf(" 7.Tamao mochila\n"); printf(" 8.Numero de partidas para subir de nivel\n"); printf(" 9.Maximo acciones por turno\n"); printf("10.Salir"); printf("\n\t Su eleccion:"); scanf("%i",&c); do { do { switch(c) { case 1: printf("\n\tQue valor desea poner en la opcion 1:"); scanf("%f",&x1); objeto_juego->radio=x1; printf("\nCambio realizado\n"); break; case 2: printf("\n\tQue valor desea poner en la opcion 2:"); scanf("%f",&x1); objeto_juego->alcance_recoger=x1; printf("\nCambio realizado\n"); break; case 3: printf("\n\tQue valor desea poner en la opcion 3:"); scanf("%f",&x1); objeto_juego->rango_arma_base=x1; printf("\nCambio realizado\n"); break; case 4: printf("\n\tQue valor desea poner en la opcion 4:"); scanf("%i",&x); objeto_juego->cartera_defecto=x; printf("\nCambio realizado\n"); break; case 5: printf("\n\tQue valor desea poner en la opcion 5:"); scanf("%i",&x); objeto_juego->jugadores_min=x; printf("\nCambio realizado\n"); break; case 6: printf("\n\tQue valor desea poner en la opcion 6:"); scanf("%f",&x1); objeto_juego->tamano_paso=x1; printf("\nCambio realizado\n"); break; case 7: printf("\n\tQue valor desea poner en la opcion 7:"); scanf("%i",&x); objeto_juego->tamano_mochila=x; printf("\nCambio realizado\n"); break; case 8: printf("\n\tQue valor desea poner en la opcion 8:"); scanf("%i",&x); objeto_juego->numero_partidas_por_nivel=x; printf("\nCambio realizado\n"); break; case 9: printf("\n\tQue valor desea poner en la opcion 9:"); scanf("%i",&x); objeto_juego->numero_acciones_por_turno=x; printf("\nCambio realizado\n"); break; case 10: printf("\nSaliendo....\n"); break; default: printf("\nOpcion no valida\n"); break; } } while(c<1 && c>10); printf("Desea cambiar otra cosa[si|no]"); scanf("%s",c2); comp=compara_palabra(c2,"si","Si"); } while(comp==1); } /** \brief Menu para editar la informacion de los objetos registrados * * \return No devuelve nada * */ void editar_objetos() { int i,k=0,comp,c,aproved=0,j,m; char c1[10],c2[2]; system("cls"); printf("\n\tObjetos\n"); printf("\n---------------------------------------\n"); for(i=0; i<total_objetos; i++) { printf("%d. %s ",i,objetos[i].identificadorobjeto); k++; if(k==3) { printf("\n"); k=0; } } do { printf("1.Nuevo Objeto\n"); printf("2.Eliminar Objeto\n"); printf("3.Salir\n"); printf("\tSu eleccion:"); scanf("%d",&c); printf("\n"); switch(c) { case 1: total_objetos++; objetos=(objeto*)realloc(objetos,total_objetos*sizeof(objeto)); printf("\n\nIntroduzca id:"); scanf("%s",objetos[total_objetos-1].identificadorobjeto); printf("\nIntroduzca descripcion:"); scanf("%s",objetos[total_objetos-1].descripcion); printf("\nIntroduzca tipo:"); scanf("%s",objetos[total_objetos-1].tipo); printf("\nIntroduzca coste:"); scanf("%i",&objetos[total_objetos-1].coste); printf("\nIntroduzca alcance:"); scanf("%f",&objetos[total_objetos-1].alcance); printf("\nIntroduzca dano:"); scanf("%i",&objetos[total_objetos-1].dano); printf("\n"); objetos[total_objetos].cantidad=1; printf("\n\n Objeto Creado \n"); break; case 2: printf("\n\nIntroduzca id:"); scanf("%s",c1); for(j=0; j<total_objetos; j++) { if(strcmp(c1,objetos[j].identificadorobjeto)==0) { aproved=1; m=j; j=total_objetos; } } if(aproved==1) { strcpy(objetos[m].identificadorobjeto,objetos[j-1].identificadorobjeto); strcpy(objetos[m].descripcion,objetos[j-1].descripcion); strcpy(objetos[m].tipo,objetos[j-1].tipo); objetos[m].alcance=objetos[j-1].alcance; objetos[m].dano=objetos[j-1].dano; objetos[m].coste=objetos[j-1].coste; objetos[m].cantidad=objetos[j-1].cantidad; total_objetos--; objetos=(objeto*)realloc(objetos,total_objetos*sizeof(objeto)); printf("\n\n Objeto Eliminado \n"); } else { printf("\n\n Fallo al borrar el objeto\n"); } break; case 3: return; break; } printf("Desea cambiar otra cosa[si|no]"); scanf("%s",c2); comp=compara_palabra(c2,"si","Si"); } while(comp==1); }
C
#include <stdio.h> int main(void){ int start, end, sum=0; int idxTable[46]; int n=0; for(int i=0;i<46;i++){ n+=i; idxTable[i] = n; } scanf("%d %d",&start,&end); start--; end--; for(int i=start;i<=end;i++){ for(int j=0;j<46;j++){ if(idxTable[j] <= i && i < idxTable[j+1]){ sum += (j+1); break; } } } printf("%d\n",sum); return 0; }
C
#include <stdio.h> unsigned long f(unsigned long N); int main() { unsigned long N,sum=0; scanf("%lu",&N); for(unsigned long i=1;i<=N;i++) { sum=sum+f(i); } printf("%lu\n",sum); return 0; } unsigned long f(unsigned long N) { while(N%2==0) { N=N/2; } return N; }
C
/* Write a program which accept one number and position from user and on that bit. Return modified number. Input : 10 3 Output : 14 */ #include<stdio.h> int OnBit(int iNo,int iPos) { int iMask=0X00000001; int iResult=0; if(iNo<0) { iNo=-iNo; } if((iPos<0)||(iPos>32)) { return 0; } iMask=iMask<<(iPos-1); iResult=iMask|iNo; } int main() { int iNo=0; int iPos=0; int iAns=0; printf("Enter number: "); scanf("%d",&iNo); printf("Enter Position: "); scanf("%d",&iPos); iAns=OnBit(iNo,iPos); printf("Modified number is: %d",iAns); return 0; }
C
/* * Copyright(C) 2014 Pedro H. Penna <pedrohenriquepenna@gmail.com> * * friendly-numbers.c - Friendly numbers kernel. */ #include "../libs/global.h" #include <omp.h> #include <stdlib.h> #include "../libs/util.h" #include "fn.h" __global__ sumdiv ( int n, int sum ){ int index = threadIdx.x + BlockIdx.x * BlockDim.x; int value = 0; if ( index < n && index > 1){ for (factor = 2; factor < n; factor++){ if ((n%factor) == 0) value += factor; } //then sum each thread value } /* * Computes the Greatest Common Divisor of two numbers. */ static int gcd(int a, int b) { int c; /* Compute greatest common divisor. */ while (a != 0) { c = a; a = b%a; b = c; } return (b); } /* * Some of divisors. */ static int sumdiv(int n) { int sum; /* Sum of divisors. */ int factor; /* Working factor. */ sum = 1 + n; /* Compute sum of divisors. */ for (factor = 2; factor < n; factor++) { /* Divisor found. */ if ((n%factor) == 0) sum += factor; } return (sum); } /* * Computes friendly numbers. */ int friendly_numbers(int start, int end) { int n; /* Divisor. */ int *num; /* Numerator. */ int *den; /* Denominator. */ int range; /* Range of numbers. */ int i, j; /* Loop indexes. */ int nfriends; /* Number of friendly numbers. */ int *tasks; /* Tasks. */ int tid; /* Thread id. */ range = end - start + 1; num = smalloc(sizeof(int)*range); den = smalloc(sizeof(int)*range); tasks = smalloc(sizeof(int)*range); /* Compute abundances. */ # for (i = start; i <= end; i++) { j = i - start; num[j] = sumdiv(i); den[j] = i; n = gcd(num[j], den[j]); num[j] /= n; den[j] /= n; } /* Check friendly numbers. */ nfriends = 0; for (i = 1; i < range; i++) { for (j = 0; j < i; j++) { /* Friends. */ if ((num[i] == num[j]) && (den[i] == den[j])) nfriends++; } } free(tasks); free(num); free(den); return (nfriends); }
C
/* * This program adds a vector binary file that first lists the number of * elements in the vector followed by the values * Parallel implemntation using MPI */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <time.h> #include <mpi.h> #include "MyMPI.h" void floyd (int ***subs, int *coords, int *dims, MPI_Comm row, MPI_Comm col, int nnodes); int IsPowerOfTwo(int x); int main(int argc, char **argv) { int rows, cols, size, rank, dim_size[2], periodic[2], grid_coords[2]; char *in_file = NULL, *out_file = NULL; void **subs, *storage; MPI_Comm cart_comm, r_comm, c_comm; FILE *fp; //MPI_Status status; clock_t tp1, tp2, beg, end; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); // if (IsPowerOfTwo(size) == 0) // { // printf("Processor count must be 2, 4, 8, 16, or 32\n"); // MPI_Finalize(); // exit(1); // } if (argc == 3) { in_file = (char *) malloc (sizeof(char) * 100); strcpy(in_file, argv[1]); out_file = (char *) malloc (sizeof(char) * 100); strcpy(out_file, argv[2]); } else { printf("\nUsage: ./floyd-parallel input_file output_file\n"); exit(1); } beg = clock(); dim_size[0] = dim_size[1] = 0; MPI_Dims_create(size, 2, dim_size); periodic[0] = periodic[1] = 0; MPI_Cart_create(MPI_COMM_WORLD, 2, dim_size, periodic, 1, &cart_comm); MPI_Cart_coords(cart_comm, rank, 2, grid_coords); //printf("%d (%d %d) (%d %d)\n", rank, grid_coords[0], grid_coords[1], dim_size[0], dim_size[1]); MPI_Comm_split(cart_comm, grid_coords[0], grid_coords[1], &r_comm); MPI_Comm_split(cart_comm, grid_coords[1], grid_coords[0], &c_comm); read_checkerboard_matrix(in_file, &subs, &storage, MPI_INT, &rows, &cols, cart_comm); // debug print //print_checkerboard_matrix(subs, MPI_INT, rows, cols, cart_comm); int **mat = (int **)subs; tp1 = clock(); floyd(&mat, grid_coords, dim_size, r_comm, c_comm, rows); tp2 = clock(); // write header of file fp = fopen(out_file, "wb"); fwrite(&rows, sizeof(int), 1, fp); fwrite(&cols, sizeof(int), 1, fp); subs = (void **)mat; write_checkerboard_matrix(subs, MPI_INT, rows, cols, cart_comm, fp); end = clock(); if (rank == 0) { printf("floyd-serial execution time:\n"); printf("\tn = %d nodes\n", rows); printf("\tp = %d cpus\n", size); printf("\tptime = %8f secs\n", ((double)(end - beg)) / CLOCKS_PER_SEC); printf("\tftime = %8f secs\n\n", ((double)(tp2 - tp1)) / CLOCKS_PER_SEC); } MPI_Finalize(); //printf("process %d has sum of %f\n", rank, sum); return 0; } void floyd (int ***subs, int *coords, int *dims, MPI_Comm rowcom, MPI_Comm colcom, int nnodes) { int k, i, j, local_r, local_c, r, c; int *buf_r = (int *) malloc (BLOCK_SIZE(coords[1], dims[1], nnodes) * sizeof(int)); int *buf_c = (int *) malloc (BLOCK_SIZE(coords[0], dims[0], nnodes) * sizeof(int)); for (k = 0; k < nnodes; k++) { if (BLOCK_OWNER(k, dims[0], nnodes) == coords[0]) { local_r = k - BLOCK_LOW(coords[0], dims[0], nnodes); //memcpy(buf_r, (*subs)[local_r], BLOCK_SIZE(coords[1], dims[1], nnodes) * sizeof(int)); for (r = 0; r < BLOCK_SIZE(coords[1], dims[1], nnodes); r++) buf_r[r] = (*subs)[local_r][r]; } //printf("owner is %d coord is %d\n", BLOCK_OWNER(k, dims[0], nnodes), coords[0]); if (BLOCK_OWNER(k, dims[1], nnodes) == coords[1]) { local_c = k - BLOCK_LOW(coords[1], dims[1], nnodes); //printf("block size is %d\n", BLOCK_SIZE(coords[0], dims[0], nnodes)); for (c = 0; c < BLOCK_SIZE(coords[0], dims[0], nnodes); c++) buf_c[c] = (*subs)[c][local_c]; } //printf("Hello! from %d %d aka block owner %d\n", coords[0], coords[1], BLOCK_OWNER(k, dims[0], nnodes)); MPI_Bcast(buf_r, BLOCK_SIZE(coords[1], dims[1], nnodes), MPI_INT, BLOCK_OWNER(k, dims[0], nnodes), colcom); //printf("------------size %d----------------\n", BLOCK_SIZE(coords[0], dims[0], nnodes)); MPI_Bcast(buf_c, BLOCK_SIZE(coords[0], dims[0], nnodes), MPI_INT, BLOCK_OWNER(k, dims[1], nnodes), rowcom); //printf("------------swag %d----------------\n", BLOCK_SIZE(coords[0], dims[0], nnodes)); for (i = 0; i < BLOCK_SIZE(coords[0], dims[0], nnodes); i++) { for (j = 0; j < BLOCK_SIZE(coords[1], dims[1], nnodes); j++) { if (buf_r[j] + buf_c[i] < (*subs)[i][j]) (*subs)[i][j] = buf_r[j] + buf_c[i]; } } } } int IsPowerOfTwo(int x) { return (x & (x - 1)) == 0; }
C
/** * \file print_comparisons.c * * \brief Compares and formats messages describing each FFT result * \details See README * * \copyright Copyright (c) 2018, DornerWorks, Ltd. * \license See LICENSE for full licensing and copying information */ /****************************************************************************** * Inclusions * ******************************************************************************/ #include "print_comparisons.h" #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <math.h> /****************************************************************************** * Defines * ******************************************************************************/ #define MAX_ERROR_PRINTS (100) #define PRINT_CORRECT_VALS (false) /****************************************************************************** * Function declarations * ******************************************************************************/ static void printSingleFftXComparison(kiss_fft_cpx *master, kiss_fft_cpx *other, int32_t len, verboseness_t verbose); /****************************************************************************** * External functions * ******************************************************************************/ void printFftComparisons(results_t master_results, results_t other_results[NUM_FFT_COMPARISONS]) { int i; printf("=== FFT Comparison Results ===\n"); printf("Master results are from %s FFT\n", master_results.name); if(ALLOWABLE_ERROR) { printf("(allowable error is %d)\n", ALLOWABLE_ERROR); } for(i = 0; i < NUM_FFT_COMPARISONS; i++) { printf("\n%s results:\n", other_results[i].name); float runtimePct = 100.0f * other_results[i].runtime_ns / master_results.runtime_ns; printf("Runtime as a percentage of baseline: %1.2f%%\n", runtimePct); printf("Accuracy:\n"); printSingleFftXComparison((kiss_fft_cpx *)*master_results.output.pfft, (kiss_fft_cpx *)*other_results[i].output.pfft, FFT_LEN, other_results[i].verbose); } printf("\n\n"); } void printFftrComparisons(results_t master_results, results_t other_results[NUM_FFT_COMPARISONS]) { int i; printf("=== FFTR Comparison Results ===\n"); printf("Baseline results are from %s FFTR\n", master_results.name); if(ALLOWABLE_ERROR) { printf("(allowable error is %d)\n", ALLOWABLE_ERROR); } for(i = 0; i < NUM_FFT_COMPARISONS; i++) { printf("\n%s results:\n", other_results[i].name); float runtimePct = 100.0f * other_results[i].runtime_ns / master_results.runtime_ns; printf("Runtime as a percentage of baseline: %1.2f%%\n", runtimePct); printf("Accuracy:\n"); printSingleFftXComparison((kiss_fft_cpx *)*master_results.output.pfftr, (kiss_fft_cpx *)*other_results[i].output.pfftr, FFTR_OUT_LEN, other_results[i].verbose); } printf("\n\n"); } /****************************************************************************** * Internal functions * ******************************************************************************/ static void printSingleFftXComparison(kiss_fft_cpx *master, kiss_fft_cpx *other, int32_t len, verboseness_t verbose) { int32_t num_wrong = 0; int32_t abs_error = 0; int32_t net_error = 0; int32_t num_zero_values = 0; float pct_wrong, pct_abs_error, pct_net_error, avg_value, avg_abs_error, avg_net_error; int32_t sum_total = 0; int16_t m_re, m_im, o_re, o_im; int16_t *comparing[2][2] = { {&m_re, &o_re}, {&m_im, &o_im}, }; const char *names[2] = { "real", "imag", }; for(int32_t i = 0; i < len; i++) { m_re = master[i].r; m_im = master[i].i; o_re = other[i].r; o_im = other[i].i; sum_total += abs(m_re) + abs(m_im); num_zero_values += (0 == m_re) ? 1 : 0; num_zero_values += (0 == m_im) ? 1 : 0; for(int32_t j = 0; j < 2; j++) { int32_t master_val = *(comparing[j][0]); int32_t other_val = *(comparing[j][1]); if (ALLOWABLE_ERROR < abs(other_val - master_val)) { num_wrong++; abs_error += abs(other_val - master_val); net_error += other_val - master_val; if(verbose && MAX_ERROR_PRINTS >= num_wrong) { printf("MISMATCH %04u: %s: orig %5d, got %5d\n", i, names[j], master_val, other_val); if (MAX_ERROR_PRINTS == num_wrong) { printf("Not printing any more entries...\n\n"); } } } else if (PRINT_CORRECT_VALS) { if (verbose && MAX_ERROR_PRINTS > num_wrong) { printf("match %04u: %s: %5d\n", i, names[j], other_val); } } } } pct_wrong = 100.0f*(float)num_wrong/(float)(len*2); avg_abs_error = (float)abs_error/(float)num_wrong; avg_net_error = (float)net_error/(float)num_wrong; avg_value = (float)sum_total/(float)((len*2) - num_zero_values); pct_abs_error = 100.0f*avg_abs_error/avg_value; pct_net_error = 100.0f*fabs(avg_net_error/avg_value); if(0 == num_wrong) { printf("\tMATCH\n"); } else { printf("\tnum different: %d (%1.2f%%)\n", num_wrong, pct_wrong); printf("\tavg abs error: %1.2f (%1.2f%%)\n", avg_abs_error, pct_abs_error); printf("\tavg net error: %1.2f (%1.2f%%)\n", avg_net_error, pct_net_error); } }
C
#include <stdio.h> int main() { typedef struct{ int hh; int mm; int ss; }Jam; Jam J; const int penambah=1; int tampung; scanf("%d %d %d", &J.hh, &J.mm, &J.ss); J.ss+=penambah; if(J.ss>=60) { J.mm=J.mm+(J.ss/60); J.ss=J.ss%60; if(J.mm>=60) { J.hh=J.hh+(J.mm/60); J.mm=J.mm%60; if(J.hh>24) { J.hh=J.hh%24; } } } printf("%d %d %d \n", J.hh, J.mm, J.ss); return(0); }
C
/***************************************************** * structures.c * * * * Structures file. * * Implement functions to manage list and * * print elements of structures. * * * * Author: Tymoteusz Bartnik * * Copyright: 2019 * *****************************************************/ #include "structures.h" /* * Init regs. * * Set that all regs are not pointers. */ void initRegs(Reg reg[]) { int i; regChanged = -1; for (i=0; i<15; i++) reg[i].isEmpty = true; } /* * Search var. * * Search for specific var in vars list. */ Var *searchVar(Var *head, char *label) { Var *x = head; while (x != NULL && strcmp(label, x->label) != 0) x = x->next; return x; } /* * Add var. * * Add new var to vars list. */ Var *addVar(Var *head, char *label, int index, int elements) { Var *x = head; Var *newVar = (Var*)malloc(sizeof(Var)); strcpy(newVar->label, label); newVar->index = index; newVar->elements = elements; if (x != NULL) { while (x->next != NULL) x = x->next; x->next = newVar; newVar->prev = x; newVar->next = NULL; } /* List is NOT empty */ else { head = newVar; head->prev = NULL; head->next = NULL; } /* List is empty */ return head; } /* * Set var. * * If is new execute addVar function, otherwise change its value. */ Var *setVar(Var *head, int **varsTab, char *label, int elements, int value, int shift) { Var *x = head; Var *lastVar; int i = 0; int *newVarsTab; if (searchVar(head, label) == NULL) { lastVar = getLastVar(head); if (*varsTab == NULL) *varsTab = malloc(elements * sizeof(int)); else *varsTab = realloc(*varsTab, (lastVar->index + lastVar->elements + elements) * sizeof(int)); if (lastVar != NULL) { for (i; i<elements; i++) (*varsTab)[lastVar->index + lastVar->elements + i] = value; x = addVar(head, label, lastVar->index + lastVar->elements, elements); } else { for (i; i<elements; i++) (*varsTab)[0 + i] = value; x = addVar(head, label, 0, elements); } head = x; } /* Add new var */ else { if (shift == -1) { while (x->next != NULL) { if (strcmp(label, x->label) == 0) { (*varsTab)[x->index] = value; break; } x = x->next; } } else { while (x->next != NULL) { if (strcmp(label, x->label) == 0) { (*varsTab)[x->index + shift] = value; break; } x = x->next; } } } /* Change existing var value */ return head; } /* * Get last var. * * Return pointer to last var in the list. */ Var *getLastVar(Var *head) { Var *x = head; while (x != NULL && x->next != NULL) x = x->next; return x; } /* * Found var. * * Found var by its label. */ Var *foundVar(Var *head, char *label) { Var *x = head; while (x != NULL && x->next != NULL) { if (strcmp(x->label, label) == 0) return x; x = x->next; } return NULL; } /* * Add operation. * * Add new operation to operations list. */ Operation *addOperation(Operation *head, Operation op) { Operation *x = head; Operation *newOperation = (Operation*)malloc(sizeof(Operation)); *newOperation = op; if (x != NULL) { while (x->next != NULL) x = x->next; x->next = newOperation; newOperation->prev = x; newOperation->next = NULL; } /* List is NOT empty */ else { head = newOperation; head->prev = NULL; head->next = NULL; } /* List is empty */ return head; } /* * Get last operation. * * Return pointer to last operation in the list. */ Operation *getLastOperation(Operation *head) { Operation *x = head; while (x->next != NULL) x = x->next; return x; }
C
#include <stdio.h> int main() { int a,b; printf("\n enter the value of a"); printf("\n enter the value of b"); scanf("%d %d",&a,&b); for(i=a,i<=b,i++) { if(i%2==1) { printf("odd"); } else { printf("even"); } } }
C
/* * queue.c * * Created on: 2011-4-29 * Author: root */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include "queue.h" static void _lock(QUEUE* _queue) { pthread_mutex_lock(&_queue->lock); } static void _unlock(QUEUE* _queue) { pthread_mutex_unlock(&_queue->lock); } static void* _find_blank_item(QUEUE* _queue) { QUEUE_ITEM_HEAD* item_head = (QUEUE_ITEM_HEAD*)_queue->buf; int current_len = 0; while(current_len < QUEUE_BUF_MAX) { if(item_head->used == QUEUE_UNUSED_FLAG) { return (void*)item_head; } current_len += sizeof(QUEUE_ITEM_HEAD) + _queue->item_size; item_head = (QUEUE_ITEM_HEAD*)(_queue->buf + current_len); } return NULL; } QUEUE* queue_init(QUEUE_COMPARE _compare, int _item_size) { QUEUE* queue = malloc(sizeof(QUEUE)); memset(queue, 0, sizeof(QUEUE)); queue->item_size = _item_size; queue->item_count = 0; queue->compare = _compare; queue->head = NULL; queue->tail = NULL; pthread_mutex_init(&queue->lock, NULL); queue->buf = malloc(QUEUE_BUF_MAX); memset(queue->buf, 0, QUEUE_BUF_MAX); return queue; } int queue_detory(QUEUE* _queue) { if(_queue != NULL) { if(_queue->buf != NULL) { free(_queue->buf); } pthread_mutex_destroy(&_queue->lock); free(_queue); } return 0; } int queue_print(QUEUE* _queue) { return 0; } int queue_add(QUEUE* _queue, void* _data) { retry: _lock(_queue); QUEUE_ITEM_HEAD* tmp; if(_queue->item_count == 0) { _queue->head = _queue->buf; _queue->tail = _queue->buf; _queue->item_count ++; tmp = _queue->head; tmp->used = QUEUE_USED_FLAG; tmp->next = NULL; tmp->prev = NULL; memcpy(tmp+1, _data, _queue->item_size); } else { tmp = _find_blank_item(_queue); if(tmp != NULL) { tmp->used = QUEUE_USED_FLAG; tmp->next = NULL; tmp->prev = _queue->tail; memcpy(tmp+1, _data, _queue->item_size); ((QUEUE_ITEM_HEAD*)_queue->tail)->next = tmp; _queue->tail = tmp; _queue->item_count ++; } else //queue full { _unlock(_queue); usleep(5000); goto retry; } } _unlock(_queue); return 0; } int queue_get(QUEUE* _queue, void* _data) { int found = -1; if (_queue == NULL) return -1; _lock(_queue); QUEUE_ITEM_HEAD* tmp = _queue->head; while(tmp != NULL) { if(_queue->compare(tmp+1, _data) == 0) { memcpy(_data, tmp+1, _queue->item_size); if(tmp->prev == NULL) { _queue->head = tmp->next; } else { ((QUEUE_ITEM_HEAD*)tmp->prev)->next = tmp->next; } if(tmp->next == NULL) { _queue->tail = tmp->prev; } else { ((QUEUE_ITEM_HEAD*)tmp->next)->prev = tmp->prev; } _queue->item_count --; memset(tmp, 0, sizeof(QUEUE_ITEM_HEAD)+_queue->item_size); found = 1; break; } tmp = tmp->next; } _unlock(_queue); if(found == 1) { return 0; } else { return -1; } } int queue_clear(QUEUE* _queue) { _lock(_queue); _queue->item_count = 0; _queue->head = NULL; _queue->tail = NULL; memset(_queue->buf, 0, QUEUE_BUF_MAX); _unlock(_queue); return 0; }
C
#include <stdio.h> int main() { long a, b, i; scanf("%d%d", &a, &b); i = a % 2 == 0 ? a + 1 : a; do { printf("%d\n", i); i += 2; } while (i <= b); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> struct book { int number_of_book; char name_of_book[20]; int sale_of_book; char state_of_book[10]; }; struct students { int number_of_student; char name_of_student[20]; int number_of_book_who_take; char state_of_student[10]; char did_he_pay[10]; //char name_of_taken_book[20]; }; /*void enter_books (char * file_name ) { file_name = fopen("library.txt","w"); char c = 'y'; struct book x ; while(c!= 'n') { printf(" enter the number of new book \n"); scanf("%d",&x.number_of_book); fflush(stdin); printf(" enter the sale of new book \n"); scanf("%d",&x.sale_of_book); fflush(stdin); printf(" enter the name of new book \n"); scanf("%s",&x.name_of_book); fflush(stdin); printf(" enter the state of new book \n"); scanf("%s",&x.state_of_book); fflush(stdin); fprintf(file_name,"number : %d name : %s sale : %d state : %s \n",x.number_of_book,x.name_of_book,x.sale_of_book,x.state_of_book); printf(" do you want to add another book ?? \n"); printf(" yes use y \t no use n \n"); scanf("%c",&c); } fclose(file_name); } void add_books (char * file_name) { char c = 'y'; struct book z ; file_name = fopen("library.txt","a"); while(c!='n') { printf(" enter the number of new book \n "); scanf("%d",&z.number_of_book); fflush(stdin); printf(" enter the name of new book \n "); scanf("%s",&z.name_of_book); fflush(stdin); printf(" enter the sale of new book \n "); scanf("%d",&z.sale_of_book); fflush(stdin); printf(" enter the state of new book \n "); scanf("%s",&z.state_of_book); fflush(stdin); fprintf(file_name,"number : %d name : %s sale : %d state : %s \n",z.number_of_book,z.name_of_book,z.sale_of_book,z.state_of_book); printf(" do you want to add another book ?? \n"); printf(" yes use y \t no use n \n"); scanf("%c",&c); } fclose(file_name); } int main() { FILE * library; library = fopen("library.txt","r"); int number,sale,aii=0; char state[100],name[100]; for(aii=0;aii<4;aii++) { fscanf(library,"number : %d name : %s sale : %d state : %s\n",&number,name,&sale,state); printf("%d %s %d %s\n",number,name,sale,state); } int what_you_want_do,n,i=0,j=0; char c = 'y',s; struct book z; int bb=0; char show[100][100],copp[100]; /*while(!feof(library)) { fgets(copp,100,library); n=strlen(copp); strcpy(show[i],copp); show[i][n-1]='\0'; i++; j++; } for(i=0;i<j-1;i++) { puts(show[i]); } while(!feof(library)) { s=getc(library); putchar(s); } printf(" \n "); while(what_you_want_do!=0) { printf(" what you want doing ? \n "); printf(" if you choice 1 you will add your books \n "); printf(" 1. insert your books \n "); printf(" 2. adding your books \n"); scanf("%d",&what_you_want_do); switch (what_you_want_do) { case 1: printf(" you will add your books now \n"); enter_books(library); break; case 2: printf(" adding your books \n "); add_books(library); break; default: bb=1; } if(bb)break; } */ void new_book (char *file_name ) { FILE * file_ptr; file_ptr = fopen(file_name,"a"); char c='y'; struct book x; while (c!='n') { printf(" enter the number of new book \n"); scanf("%d",&x.number_of_book); printf(" enter the sale of new book \n"); scanf("%d",&x.sale_of_book); printf(" enter the name of new book \n"); scanf("%s",&x.name_of_book); printf(" enter the state of new book \n"); scanf("%s",&x.state_of_book); fflush(stdin); fprintf(file_ptr,"number : %d name : %s sale : %d state : %s \n",x.number_of_book,x.name_of_book,x.sale_of_book,x.state_of_book); printf(" do you want to add another book ?? \n"); printf(" yes use y \t no use n \n"); scanf("%c",&c); } fclose(file_ptr); } void search_book (char * file_name , int search_do) { FILE * file_ptr; struct book boooks[30]; int i=0,temp=0; file_ptr= fopen(file_name,"r"); while(!feof(file_ptr)) { fscanf(file_ptr,"number : %d name : %s sale : %d state : %s ",&boooks[i].number_of_book,&boooks[i].name_of_book,&boooks[i].sale_of_book,&boooks[i].state_of_book); i++; temp++; } for(i=0;i<temp;i++) { if(search_do == boooks[i].number_of_book ) { printf(" the name of book you search on is : %s ",boooks[i].name_of_book); } } fclose(file_ptr); } void search_state (char * file_name ) { FILE * file_ptr; file_ptr = fopen(file_name,"r"); struct book boooks[30]; int i=0,temp=0; char bb[4]={'y','e','s'}; while(!feof(file_ptr)) { fscanf(file_ptr,"number : %d name : %s sale : %d state : %s ",&boooks[i].number_of_book,&boooks[i].name_of_book,&boooks[i].sale_of_book,&boooks[i].state_of_book); printf(" %d %s %d %s \n",boooks[i].number_of_book,boooks[i].name_of_book,boooks[i].sale_of_book,boooks[i].state_of_book); i++; temp++; } for(i=0;i<temp;i++) { if(strcmp(boooks[i].state_of_book,bb)==0) { printf(" the name of book is taken : %s \n",boooks[i].name_of_book); } } fclose(file_ptr); } void change_state_of_book (char * file_name,int change_state) { struct book boooks[30]; int i=0,temp=0; char bb[4]={'y','e','s'},nn[4]={'n','o','n'}; FILE * file_ptr; file_ptr = fopen(file_name,"r"); while(!feof(file_ptr)) { fscanf(file_ptr,"number : %d name : %s sale : %d state : %s ",&boooks[i].number_of_book,&boooks[i].name_of_book,&boooks[i].sale_of_book,&boooks[i].state_of_book); printf("%d %s %d %s \n",boooks[i].number_of_book,boooks[i].name_of_book,boooks[i].sale_of_book,boooks[i].state_of_book); i++; temp++; } if(strcmp(boooks[change_state-1].state_of_book,nn)==0) { printf(" it is non it will be yes \n "); strcpy(boooks[change_state-1].state_of_book,bb); } else { printf(" it is yes it will be non \n "); strcpy(boooks[change_state-1].state_of_book,nn); } fclose(file_ptr); file_ptr = fopen(file_name,"w"); for(i=0;i<temp;i++) { fprintf(file_ptr,"number : %d name : %s sale : %d state : %s \n",boooks[i].number_of_book,boooks[i].name_of_book,boooks[i].sale_of_book,boooks[i].state_of_book); } fclose(file_ptr); } void insert_student (char * file_name ) { FILE * file_ptr; FILE * file_ptr2; file_ptr = fopen(file_name,"a"); struct students y; char c = 'y'; while (c!='n') { printf(" enter the number of student \n"); scanf("%d",&y.number_of_student); printf(" enter the name of student \n"); scanf("%s",&y.name_of_student); printf(" enter the number of book who the student take \n"); scanf("%d",&y.number_of_book_who_take); printf(" enter the state of student \n"); scanf("%s",&y.state_of_student); printf(" did he pay ?? \n "); scanf("%s",&y.did_he_pay); fflush(stdin); fprintf(file_ptr,"number of student : %d name of student : %s number of book take : %d state of student : %s pay : %s \n",y.number_of_student,y.name_of_student,y.number_of_book_who_take,y.state_of_student,y.did_he_pay); printf(" do you want to add another student ?? \n"); printf(" yes use y \t no use n \n"); scanf("%c",&c); } fclose(file_ptr); change_state_of_book("library.txt",y.number_of_book_who_take); } void search_student ( char * file_name ) { FILE * file_ptr; file_ptr = fopen(file_name,"r"); struct students student[30]; int i=0,temp=0; char bb[4]={'y','e','s'}; while (!feof(file_ptr)) { fscanf(file_ptr,"number of student : %d name of student : %s number of book take : %d state of student : %s pay : %s ",&student[i].number_of_student,&student[i].name_of_student,&student[i].number_of_book_who_take,&student[i].state_of_student,&student[i].did_he_pay); i++; temp++; } for(i=0;i<temp;i++) { if(strcmp(student[i].state_of_student,bb)==0 ) { printf("\n the number : %d\n the name : %s\n number of book took : %d\n the state : %s\n did he pay : %s\n \n ",student[i].number_of_student,student[i].name_of_student,student[i].number_of_book_who_take,student[i].state_of_student,student[i].did_he_pay); search_book("library.txt",student[i].number_of_book_who_take); } } fclose(file_ptr); } void who_dont_pay (char * file_name ) { FILE * file_ptr; file_ptr = fopen(file_name,"r"); int i=0,j=0,temp=0,temp1=0; int not_pay[30]; struct students student[30]; char bb[4]={'y','e','s'}; char no[4]={'n','o'}; while (!feof(file_ptr)) { fscanf(file_ptr,"number of student : %d name of student : %s number of book take : %d state of student : %s pay : %s ",&student[i].number_of_student,&student[i].name_of_student,&student[i].number_of_book_who_take,&student[i].state_of_student,&student[i].did_he_pay); i++; temp++; } for(i=0;i<temp;i++) { if(strcmp(student[i].state_of_student,bb)==0) { if(strcmp(student[i].did_he_pay,no)==0) { not_pay[j]=student[i].number_of_student; j++; temp1++; } } } for(j=0;j<temp1;j++) { printf("the number of student who do not pay is : %d \n",not_pay[j]); } fclose(file_ptr); } int main() { struct book x,boooks[30]; struct students y,student[30]; int i=0, what_do,search_do,temp=0,change_state; int not_pay[30],j=0,temp1=0; char no[4]={'n','o'}; char c='y',t,bb[4]={'y','e','s'},nn[4]={'n','o','n'}; FILE * library; FILE * studentss; library = fopen("library.txt","r"); while (!feof(library)) { t=getc(library); putchar(t); } fclose(library); while(what_do!=10) { printf("\n\n what you want do ? \n"); printf(" 1. show the file \n "); printf(" 2. enter new book \n"); printf(" 3. search of number \n "); printf(" 4. show the taken book \n "); printf(" 5. change the state \n "); printf(" 6. show file student \n "); printf(" 7. insert new student \n "); printf(" 8. show the student who taken a book from library \n"); printf(" 9. who do not pay :( \n"); printf(" to go out enter number 0 \n"); scanf("%d",&what_do); switch (what_do) { case 1: library = fopen("library.txt","r"); while (!feof(library)) { t=getc(library); putchar(t); } fclose(library); break; case 2: new_book("library.txt"); break; case 3: printf(" enter the number of book you want to search on : "); scanf("%d",&search_do); search_book("library.txt",search_do); break; case 4: search_state("library.txt"); break; case 5: printf(" enter the book you want to change his state : "); scanf("%d",&change_state); change_state_of_book("library.txt",change_state); break; case 6: studentss = fopen("students.txt","r"); while(!feof(studentss)) { t=getc(studentss); putchar(t); } fclose(studentss); break; case 7: insert_student("students.txt"); break; case 8: search_student("students.txt"); break; case 9: who_dont_pay("students.txt"); break; default : what_do = 10; } } return 0; }
C
#include <stdio.h> /*int main() { int num; scanf("%d",&num); int col = ((num+num)-1); int midValue = col/2; int arr[col][col]; int arrFinal[col][col]; for(int i=0; i<num; i++) { for(int j=0; j<col; j++) { if(j>=i) { //printf("%d",num-i); arr[i][j] = num-i; } else { //printf("%d",num-j); arr[i][j] = num-j; } } //printf("\n"); } // printf("\n"); // ----> Printing the array <--------- // // for(int i=0; i<num; i++) // { // for(int j=0; j<col; j++) // { // printf("%d",arr[i][j]); // } // printf("\n"); // } // printf("\n"); // ----> Changing the Value of the array <--------- // for(int i=0; i<num; i++) { for(int j=0; j<col; j++) { if(j<midValue) { //printf("%d" , arr[i][j]); arr[i][(col-1)-j] = arr[i][j]; } else { //printf("br"); break; } } } //printf("\n"); // ----> Printing the array <--------- // // for(int i=0; i<num; i++) // { // for(int j=0; j<col; j++) // { // printf("%d",arr[i][j]); // } // printf("\n"); // } // --> Creating the Final array ----------- Copy Logic int startFrom = midValue+1; int copyFrom = midValue-1; for(int i=0; i<=(num-1); i++) { for(int j=0; j<col; j++) { arr[startFrom+i][j] = arr[copyFrom-i][j]; } } //printf("\nFinal Array : \n"); // ----> Printing the array <--------- // for(int i=0; i<col; i++) { for(int j=0; j<col; j++) { printf("%d",arr[i][j]); } printf("\n"); } return 0; } */ /* int main() { int count; scanf("%d",&count); for(int k=0; k<count; k++) { int num; scanf("%d",&num); int col = ((num+num)-1); int midValue = col/2; int arr[col][col]; for(int i=0; i<num; i++) { for(int j=0; j<col; j++) { if(j>=i) { arr[i][j] = num-i; } else { arr[i][j] = num-j; } } } for(int i=0; i<num; i++) { for(int j=0; j<col; j++) { if(j<midValue) { arr[i][(col-1)-j] = arr[i][j]; } else { break; } } } int startFrom = midValue+1; int copyFrom = midValue-1; for(int i=0; i<=(num-1); i++) { for(int j=0; j<col; j++) { arr[startFrom+i][j] = arr[copyFrom-i][j]; } } for(int i=0; i<col; i++) { for(int j=0; j<col; j++) { printf("%d",arr[i][j]); } printf("\n"); } } return 0; } */ // Correct version int main() { int testCaseCount; scanf("%d",&testCaseCount); int num; int col; int midValue; for(int count=0; count<testCaseCount; count++) { scanf("%d" , &num); col = ((num+num)-1); midValue = col/2; int arr[col][col]; for(int i=0; i<num; i++) { for(int j=0; j<col; j++) { if(j>=i) { arr[i][j] = num-i; } else { arr[i][j] = num-j; } } } for(int i=0; i<num; i++) { for(int j=0; j<col; j++) { if(j<midValue) { arr[i][(col-1)-j] = arr[i][j]; } else { break; } } } int startFrom = midValue+1; int copyFrom = midValue-1; for(int i=0; i<=(num-1); i++) { for(int j=0; j<col; j++) { arr[startFrom+i][j] = arr[copyFrom-i][j]; } } for(int i=0; i<col; i++) { for(int j=0; j<col; j++) { printf("%d",arr[i][j]); } printf("\n"); } col = 0; midValue = 0; arr[0][0]; } return 0; }
C
#define _GNU_SOURCE #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/errno.h> #include <sys/syscall.h> #include <faup/datadir.h> #include <faup/modules.h> int shell_modules_list_cb(faup_modules_t *modules, char *modules_dir, char *module, void *user_data, int count) { printf("[%d] %s%s%s\n", count, modules_dir, FAUP_OS_DIRSEP, module); return 0; } int faup_handle_shell_modules(int argc, char **argv) { #ifdef FAUP_LUA_MODULES if (argc < 5) { printf("Usage: %s $ modules action\n", argv[0]); printf("\nWhere action can be:\n"); printf("list all : List all modules\n"); printf("list enabled : List enabled modules\n"); printf("list available: List available modules\n\n"); printf("enable module_name : Enable the module 'module_name'\n"); printf("disable module_name: Disable the module 'module_name'\n"); printf("\n"); return -1; } if (!strcmp(argv[3], "list") || !strcmp(argv[3], "l")) { if (!strcmp(argv[4], "all")) { printf("Modules enabled:\n"); faup_modules_foreach_filelist(NULL, NULL, shell_modules_list_cb, NULL); printf("\n"); printf("Modules available:\n"); char *global_available = faup_datadir_get_global_file("modules_available"); faup_modules_foreach_filelist(NULL, global_available, shell_modules_list_cb, NULL); printf("\n"); free(global_available); } if (!strcmp(argv[4], "enabled")) { printf("\n"); faup_modules_foreach_filelist(NULL, NULL, shell_modules_list_cb, NULL); printf("\n"); } if (!strcmp(argv[4], "available")) { char *global_available = faup_datadir_get_global_file("modules_available"); printf("\n"); faup_modules_foreach_filelist(NULL, global_available, shell_modules_list_cb, NULL); printf("\n"); free(global_available); } } if (!strcmp(argv[3], "enable") || !strcmp(argv[3], "e")) { int retval; char *enabled_filename; char *symlink_file; char *origin_filename; char *available_filename; retval = asprintf(&enabled_filename, "modules_enabled%s%s", FAUP_OS_DIRSEP, argv[4]); symlink_file = faup_datadir_file_to_write(enabled_filename, true); if (!symlink_file) { // I have no symlink, because there is nowhere I can write. Let's create the homedir path and do it again retval = faup_datadir_make_dir_from_home("modules_enabled"); symlink_file = faup_datadir_file_to_write(enabled_filename, true); } free(enabled_filename); retval = asprintf(&origin_filename, "modules_available%s%s", FAUP_OS_DIRSEP, argv[4]); available_filename = faup_datadir_get_global_file(origin_filename); free(origin_filename); retval = symlink(available_filename, symlink_file); if (!retval) { printf("Module '%s' enabled with success!\n", argv[4]); } else { printf("Module '%s' cannot be enabled: %s\n", argv[4], strerror(errno)); } free(available_filename); free(symlink_file); } if (!strcmp(argv[3], "disable") || !strcmp(argv[3], "d")) { int retval; char *enabled_filename; char *symlink_file; retval = asprintf(&enabled_filename, "modules_enabled%s%s", FAUP_OS_DIRSEP, argv[4]); symlink_file = faup_datadir_get_file(enabled_filename, false); free(enabled_filename); retval = unlink(symlink_file); if (!retval) { printf("Module '%s' disabled with success!\n", argv[4]); } else { printf("Module '%s' cannot be deactivated: %s\n", argv[4], strerror(errno)); } free(symlink_file); } #endif // FAUP_LUA_MODULES return 0; } int faup_handle_shell(int argc, char **argv) { if (argc <= 2) { printf("Usage: %s $ shell_command [parameters]\n", argv[0]); printf("\nAvailable shell comands: modules\n"); printf("\n"); return -1; } if (!strcmp(argv[2], "modules")) { faup_handle_shell_modules(argc, argv); } return 0; }
C
/* ** EPITECH PROJECT, 2020 ** server ** File description: ** get_or_error2.c */ #include <stdlib.h> #include <stringext.h> #include "channel/channel_util.h" #include "get_or_error.h" #include "server/server_util.h" #include "team/team_util.h" #include "user/user_util.h" #include "util/string.h" team_t *get_or_error_team( client_t *client, const char *message, server_t *server, const char *uuid) { team_t *item = server_get_team_id(server, uuid); char *trim_uuid = strtrim(uuid, "\""); if (item == NULL) { char *error = strfmt(message, "Team doesn't exist", trim_uuid); list_push(client->queue, error); } free(trim_uuid); return (item); } thread_t *get_or_error_thread( client_t *client, const char *message, channel_t *channel, const char *uuid) { thread_t *item = channel_get_thread_id(channel, uuid); char *trim_uuid = strtrim(uuid, "\""); if (item == NULL) { char *error = strfmt(message, "Thread doesn't exist", trim_uuid); list_push(client->queue, error); } free(trim_uuid); return (item); } user_t *get_or_error_user_id( client_t *client, const char *message, server_t *server, const char *uuid) { user_t *item = server_get_user_id(server, uuid); char *trim_uuid = strtrim(uuid, "\""); if (item == NULL) { char *error = strfmt(message, "User doesn't exist", trim_uuid); list_push(client->queue, error); } free(trim_uuid); return (item); } user_t *get_or_error_user_name( client_t *client, const char *message, server_t *server, const char *name) { user_t *item = server_get_user_id(server, name); if (item == NULL) { char *error = strfmt(message, "User doesn't exist"); list_push(client->queue, error); } return (item); }
C
#include "fonts.h" /* the font, where each code line is a character from 0-F */ const byte chipbox_font[CHIPBOX_FONT_TOTAL_BYTES] = { 0xF0, 0x90, 0x90, 0x90, 0xF0, 0x20, 0x60, 0x20, 0x20, 0x70, 0xF0, 0x10, 0xF0, 0x80, 0xF0, 0xF0, 0x10, 0xF0, 0x10, 0xF0, 0x90, 0x90, 0xF0, 0x10, 0x10, 0xF0, 0x80, 0xF0, 0x10, 0xF0, 0xF0, 0x80, 0xF0, 0x90, 0xF0, 0xF0, 0x10, 0x20, 0x40, 0x40, 0xF0, 0x90, 0xF0, 0x90, 0xF0, 0xF0, 0x90, 0xF0, 0x10, 0xF0, 0xF0, 0x90, 0xF0, 0x90, 0x90, 0xE0, 0x90, 0xE0, 0x90, 0xE0, 0xF0, 0x80, 0x80, 0x80, 0xF0, 0xE0, 0x90, 0x90, 0x90, 0xE0, 0xF0, 0x80, 0xF0, 0x80, 0xF0, 0xF0, 0x80, 0xF0, 0x80, 0x80 };
C
#include <stdio.h> #include <unistd.h> int main(){ int fd[2]; int pid; pipe(fd); pid = fork(); if (pid == 0){ //cerrar entrada de estandar close (0); //cerrar entrada del pipe dup(fd[0]); //cerrar salida del pipe close(fd[1]); // conectar entrada pipe execlp("wc", "wc", "-l", NULL); } else { //cerrar salida estándar close (1); //cerrar salida del pipe dup(fd[1]); //cerrar entrada del pipe close(fd[0]); // conectar salida de ls al pipe execlp("ls", "ls", NULL); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #define swap(a, b) {int tmp = a; a = b; b = tmp;} int partition(int *arr, int left, int right) { int pivot = arr[right]; int p_idx = left; for (int i = left; i < right; i++) { if (arr[i] <= pivot) { swap(arr[i], arr[p_idx]); p_idx++; } } swap(arr[right], arr[p_idx]); return p_idx; } void quicksort(int *arr, int left, int right) { if (left >= right) return; int p_idx = partition(arr, left, right); quicksort(arr, left, p_idx - 1); quicksort(arr, p_idx + 1, right); } int main(int argc, char **argv) { if (argc < 2) return 0; srand(time(NULL)); int n = atoi(argv[1]); int *arr = (int*)malloc(sizeof(int) * n); for (int i = 0; i < n; i++) { arr[i] = rand() % 100000; printf("%d ", arr[i]); } quicksort(arr, 0, n - 1); printf("\n"); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } free(arr); return 0; }
C
#ifndef _IMAGE_H_ #define _IMAGE_H_ //Bibliotecas padrão #include <stdio.h> #include <stdlib.h> #include <string.h> //Bilbioteca para usar leitor de impressões digitais #include <libfprint/fprint.h> //Estrutura das imagens usadas typedef struct image{ int height; //Altura int width; //Largura unsigned char *data; //Vetor contendo os pixels }image; //defines variados #define SUCCESS 1 #define FAILURE 0 /* ---get_image--- Inicia o hardware de aquisição e pega uma imagem da impressão digital e apenas uma Entrada: void Saida: -Um ponteiro para a imagem adiquirida */ image* get_image(); /* ---free_image--- Retira a imagem da memória Entrada: -image *img: Estrutura contendo a imagem da impressão digital Saida: void */ void free_image(image* img); /* ---save_image--- Salva a imagem em arquivo Entrada: -image *img: Estrutura contendo a imagem da impressão digital -char *filename: Nome do arquivo da imagem Saida: void */ void save_image(image* img, char* filename); /* ---loadPGM--- Carrega uma imagem no formato PGM Entrada: -char *filename: Endereçod o arquivo a ser aberto Saida: -Ponteiro para a imagem carregada */ image * loadPGM(char *filename); /* ---clone_image--- Cria uma imagem nova como cópia de uma pré existente. Deve-se usar um ponteiro desalocado para receber a imagem nova, pois essa função já aloca a memória necessaria. Entrada: -image *img: Imagem a ser copiada Saida: -image *: ponteiro para a imagem nova */ image *clone_image(image *img); #endif
C
/* vim: set noet nosta sw=4 ts=4 ft=c : */ /* Copyright (c) 2011-2015, Mahlon E. Smith <mahlon@martini.nu> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Mahlon E. Smith nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "volta.h" /* * Output basic usage information. */ void usage( char *prg ) { printf( "%s [-vh] [-f <filename>] [-d <level>]\n", prg ); printf( " -d <level> Show debug information on stderr\n" ); printf( " -c <filename> Create the volta database from a rules file\n" ); printf( " -f <filename> Specify the database file to use (default is './volta.db')\n"); printf( " -h Usage (you're lookin' at it)\n" ); printf( " -v Display version\n" ); printf( "\n" ); return; } /* * Debug function, only output to stderr if the debug level is * equal or greater to the set output level. * * level: The minimum debug level that must be set for the * line to be logged. * file: The current code file that is emitting the log * line: The line number of the code file that is emitting the log * ... : any printf style strings and formats that constitute the log message */ void debug( int level, char *file, int line, const char *fmt, ... ) { if ( v.debugmode < level ) return; char timestamp[20]; time_t t = time( NULL ); struct tm *now = localtime( &t ); strftime( timestamp, 20, "%F %T", now ); va_list args; va_start( args, fmt ); fprintf( stderr, "%s [%s] #%d %d (%s:%d): ", PROG, timestamp, getpid(), level, file, line ); vfprintf( stderr, fmt, args ); va_end( args ); fflush( stderr ); return; } /* * Given a string, reverse it in place. */ void reverse_str( char *str ) { int i = 0; int tmp = 0; int j = strlen( str ) - 1; while ( i < j ) { tmp = str[i]; str[i] = str[j]; str[j] = tmp; i++; j--; } return; } /* * Lowercase a string in place. * */ void lowercase_str( char *str, unsigned short int len ) { unsigned short int i = 0; char c; for ( ; i < len; i++ ) { c = str[i]; str[i] = tolower( c ); } return; } /* * Append 'buf' to the end of 'line', a la strcat, except dynamically * grow memory for the target string. * * 'buf' should be null terminated. Returns the modified line. */ char * extend_line( char *line, const char *buf ) { char *line_realloc; unsigned short int offset; size_t new_len; /* find offset and lengths, first assignment */ if ( line == NULL ) { offset = 0; new_len = strlen( buf ); } /* find offset and lengths, append to existing string */ else { offset = strlen( line ); /* not including '\0' */ new_len = offset + LINE_BUFSIZE; } debug( 5, LOC, "Extending line %d to %d bytes at offset %d\n", v.timer.lines+1, new_len, offset ); if ( new_len > LINE_MAX || (line_realloc = realloc(line, sizeof(char) * new_len)) == NULL ) { debug( 5, LOC, "Ignoring line %d, error while allocating memory: %s\n", v.timer.lines+1, (line_realloc == NULL ? strerror(errno) : "Line too large") ); free( line ), line = NULL; printf( "\n" ); fflush( stdout ); } else { line = line_realloc; memcpy( line + offset, buf, LINE_BUFSIZE ); } return( line ); } /* * Allocate memory and copy +length+ bytes (plus 1 for null) from the given * +string+ into a new string, returning a pointer to it. * */ char * copy_string_token( char *string, unsigned short int length ) { char *alloc_ptr = NULL; if ( string == NULL || length == 0 ) return ( NULL ); if ( (alloc_ptr = calloc( length + 1, sizeof(char) )) == NULL ) { debug( 5, LOC, "Unable to allocate memory for token: %s\n", strerror(errno) ); return( NULL ); } (void)memcpy( alloc_ptr, string, length ); return( alloc_ptr ); } /* * Allocate memory and copy +length+ bytes from the given dotted quad style * +ip_string+ into an in_addr struct, returning a pointer to it. * */ /* struct in_addr * copy_ipv4_token( char *ip_string, unsigned short int length ) { struct in_addr *alloc_ptr = NULL; char c_ip[ INET_ADDRSTRLEN ]; if ( ip_string == NULL ) return ( NULL ); (void)strncpy( c_ip, ip_string, length ); c_ip[ length ] = '\0'; if ( (alloc_ptr = calloc( length, sizeof(struct in_addr) )) == NULL ) { debug( 5, LOC, "Unable to allocate memory for ip '%s': %s\n", c_ip, strerror(errno) ); } if ( inet_pton( AF_INET, c_ip, alloc_ptr ) < 1 ) { debug( 1, LOC, "Unable to create in_addr struct for client ip '%s': %s\n", c_ip, strerror(errno) ); free( alloc_ptr ), alloc_ptr = NULL; } return( alloc_ptr ); } */ /* * Report how many lines were processed per second. * */ void report_speed( void ) { if ( v.debugmode < 3 ) return; time_t end_time = time( NULL ); double elapsed = difftime( end_time, v.timer.start ); if ( elapsed > 0 ) { debug( 3, LOC, "Processed %lu lines in %0.1f seconds. (%0.1f lines/sec)\n", v.timer.lines, elapsed, v.timer.lines/elapsed ); } else { debug( 3, LOC, "Processed %lu lines in under a second.\n", v.timer.lines ); } return; }
C
#include<stdio.h> int main() { int t, n,i,h,k=2; scanf("%d",&t); for(i=0;i<t;i++) { scanf("%d",&n); h=1; while(k!=(n+2)) { if(k%2==0) h*=2; else h+=1; k++; } printf("%d",h); } return 0; }
C
#include "contour.h" Contour* create_contour(void *c_contour){ if(c_contour == NULL){ print_msg(ERR_OBJ_NULL_LIST,"contour.c/create_contour"); return NULL; } Contour *contour = (Contour*) malloc(sizeof(Contour)); int err = INF_NOT_ERR; contour->cv_contour = c_contour; err = calc_and_set_contour_measure(contour); if(err != INF_NOT_ERR){ print_msg(err,"contour.c/create_contour"); free_contour(&contour); return NULL; } return contour; } void* get_contour_data(Contour *contour){ if(contour == NULL){ print_msg(ERR_PTR_NULL, "contour.c/get_contour_data."); return NULL; } return contour->cv_contour; } int calc_and_set_contour_measure(Contour *contour){ if(contour == NULL) return *print_msg(ERR_PTR_NULL, "contour.c\ /calc_and_set_contour_measure."); if(contour->cv_contour == NULL) return *print_msg(ERR_PTR_NULL, "contour.c\ /calc_and_set_contour_measure."); CvSeq *cv_contour = (CvSeq*) (contour->cv_contour); CvPoint* p = CV_GET_SEQ_ELEM(CvPoint, cv_contour, 0); contour->x_more_left = p->x; contour->x_more_right = p->x; contour->y_more_down = p->y; contour->y_more_up = p->y; contour->x_mean_value = 0; contour->y_mean_value = 0; int i; for(i = 1; i < cv_contour->total; i++ ) { p = CV_GET_SEQ_ELEM( CvPoint, cv_contour, i); contour->x_more_left = p->x < contour->x_more_left ? p->x : contour->x_more_left; contour->x_more_right = p->x > contour->x_more_right ? p->x : contour->x_more_right; contour->y_more_down = p->y > contour->y_more_down ? p->y : contour->y_more_down; contour->y_more_up = p->y < contour->y_more_up ? p->y : contour->y_more_up; } contour->x_mean_value = (contour->x_more_left + contour->x_more_right) / 2; contour->y_mean_value = (contour->y_more_down + contour->y_more_up) / 2; contour->width = contour->x_more_right - contour->x_more_left; contour->height = contour->y_more_down - contour->y_more_up; return INF_NOT_ERR; } int get_contour_x_more_left(Contour *contour, int *x){ if(contour == NULL){ print_msg(ERR_PTR_NULL,"contour.c/get_img_obj_x_more_left"); return ERR_PTR_NULL; } *x = contour->x_more_left; return INF_NOT_ERR; } int get_contour_x_more_right(Contour *contour, int *x){ if(contour == NULL){ print_msg(ERR_PTR_NULL,"contour.c/get_img_obj_x_more_right"); return ERR_PTR_NULL; } *x = contour->x_more_right; return INF_NOT_ERR; } int get_contour_y_more_up(Contour *contour, int *y){ if(contour == NULL){ print_msg(ERR_PTR_NULL,"contour.c/get_img_obj_y_more_up"); return ERR_PTR_NULL; } *y = contour->y_more_up; return INF_NOT_ERR; } int get_contour_y_more_down(Contour *contour, int *y){ if(contour == NULL){ print_msg(ERR_PTR_NULL,"contour.c/get_img_obj_y_more_down"); return ERR_PTR_NULL; } *y = contour->y_more_down; return INF_NOT_ERR; } int calc_contour_area(Contour *contour){ if(contour == NULL){ print_msg(ERR_PTR_NULL,"contour.c/calc_contour_area"); return ERR_PTR_NULL; } int x = contour->x_more_right - contour->x_more_left; int y = contour->y_more_down - contour->y_more_up; //printf("Xd = %d, Xe = %d \n Yc = %d , Yb = %d\n", contour->x_more_right, contour->x_more_left // , contour->y_more_up, contour->y_more_down); int area = x * y; return area; } int is_contour_convex(Contour *contour){ int res = 0; res = cvCheckContourConvexity((CvSeq*) contour->cv_contour); return res; } int is_contour_data_null(Contour *contour){ if(contour == NULL) return *print_msg(ERR_PTR_NULL,"contour.c/is_contour_data_null"); return contour->cv_contour == NULL ? TRUE : FALSE; } int is_contour_1_all_left_contour_2(Contour *contour_1, Contour *contour_2, int *result){ if(contour_1 == NULL || contour_2 == NULL) return *print_msg(ERR_PTR_NULL, "objDaImg.c/is_objs_same_place"); *result = contour_1->x_more_right <= contour_2->x_more_left; return INF_NOT_ERR; } int is_contour_1_all_right_contour_2(Contour *contour_1, Contour *contour_2, int *result){ if(contour_1 == NULL || contour_2 == NULL) return *print_msg(ERR_PTR_NULL, "objDaImg.c/is_objs_same_place"); *result = contour_1->x_more_left >= contour_2->x_more_right; return INF_NOT_ERR; } int is_contour_1_inside_left_contour_2(Contour *contour_1, Contour *contour_2, int *result){ if(contour_1 == NULL || contour_2 == NULL) return *print_msg(ERR_PTR_NULL, "objDaImg.c/is_objs_same_place"); int is_left = 0; int is_right = 0; is_contour_1_all_left_contour_2(contour_1, contour_2, &is_left); is_contour_1_all_right_contour_2(contour_1, contour_2, &is_right); if(!is_left && !is_right){ *result = contour_1->x_more_left <= contour_2->x_more_left ? TRUE : FALSE; }else *result = FALSE; return INF_NOT_ERR; } int is_contour_1_inside_right_contour_2(Contour *contour_1, Contour *contour_2, int *result){ if(contour_1 == NULL || contour_2 == NULL) return *print_msg(ERR_PTR_NULL, "objDaImg.c/is_objs_same_place"); int is_left = 0; int is_right = 0; is_contour_1_all_left_contour_2(contour_1, contour_2, &is_left); is_contour_1_all_right_contour_2(contour_1, contour_2, &is_right); if(!is_left && !is_right){ *result = contour_1->x_more_right >= contour_2->x_more_right ? TRUE : FALSE; }else *result = FALSE; return INF_NOT_ERR; } int is_contours_same_place(Contour *contour_1, Contour *contour_2, int lim_dist, int *result){ if(contour_1 == NULL || contour_2 == NULL) return *print_msg(ERR_PTR_NULL, "objDaImg.c/is_objs_same_place"); int x1_ext_esq = contour_1->x_more_left; int x1_ext_dir = contour_1->x_more_right; int x2_ext_esq = contour_2->x_more_left; int x2_ext_dir = contour_2->x_more_right; int y1_maior = contour_1->y_more_down; int y1_menor = contour_1->y_more_up; int y2_maior = contour_2->y_more_down; int y2_menor = contour_2->y_more_up; if(x1_ext_esq < x2_ext_esq) x2_ext_esq = contour_2->x_more_left - lim_dist; else x1_ext_esq = contour_1->x_more_left - lim_dist; if(x1_ext_dir > x2_ext_dir) x2_ext_dir = contour_2->x_more_right + lim_dist; else x1_ext_dir = contour_1->x_more_right + lim_dist; if(y1_maior > y2_maior) y2_maior = contour_2->y_more_down + lim_dist; else y1_maior = contour_1->y_more_down + lim_dist; if(y1_menor < y2_menor) y2_menor = contour_2->y_more_up - lim_dist; else y1_menor = contour_1->y_more_up - lim_dist; int p1_c1[2] = {x1_ext_esq, y1_maior}; int p2_c1[2] = {x1_ext_esq, y1_menor}; int p3_c1[2] = {x1_ext_dir, y1_maior}; int p4_c1[2] = {x1_ext_dir, y1_menor}; int p1_c2[2] = {x2_ext_esq, y2_maior}; int p2_c2[2] = {x2_ext_esq, y2_menor}; int p3_c2[2] = {x2_ext_dir, y2_maior}; int p4_c2[2] = {x2_ext_dir, y2_menor}; int is_c1_dentro_c2 = is_p2_entre_p1_e_p3(p1_c1, p1_c2, p4_c2) == TRUE || is_p2_entre_p1_e_p3(p2_c1, p1_c2, p4_c2) == TRUE || is_p2_entre_p1_e_p3(p3_c1, p1_c2, p4_c2) == TRUE || is_p2_entre_p1_e_p3(p4_c1, p1_c2, p4_c2) == TRUE; int is_c2_dentro_c1 = is_p2_entre_p1_e_p3(p1_c2, p1_c1, p4_c1) == TRUE || is_p2_entre_p1_e_p3(p2_c2, p1_c1, p4_c1) == TRUE || is_p2_entre_p1_e_p3(p3_c2, p1_c1, p4_c1) == TRUE || is_p2_entre_p1_e_p3(p4_c2, p1_c1, p4_c1) == TRUE; *result = is_c1_dentro_c2 || is_c2_dentro_c1; return INF_NOT_ERR; } int is_contours_same_x_place(Contour *contour_1, Contour *contour_2, int *result){ *result = TRUE; if(contour_1->x_more_left < contour_2->x_more_left){ if(contour_1->x_more_right < contour_2->x_more_left) *result = FALSE; }else if(contour_1->x_more_left > contour_2->x_more_left){ if(contour_1->x_more_left > contour_2->x_more_right) *result = FALSE; } return INF_NOT_ERR; } int is_contour_an_accent(Contour *contour_1, Contour *contour_2, int *result){ *result = TRUE; if(contour_1->x_more_left < contour_2->x_more_left){ if(contour_1->x_more_right < contour_2->x_more_left - (contour_1->width/2)) *result = FALSE; }else if(contour_1->x_more_left > contour_2->x_more_left){ if(contour_1->x_more_left > (contour_2->x_more_right + (contour_2->width/2))) *result = FALSE; } return INF_NOT_ERR; } int compare_x_relative_position_contours(Contour *contour_1, Contour *contour_2, int *result){ int cod_err_1 = INF_NOT_ERR, cod_err_2 = INF_NOT_ERR; int x_left_1 = 0, x_left_2 = 0; int x_right_1 = 0, x_right_2 = 0; cod_err_1 = get_contour_x_more_left(contour_1, &x_left_1); cod_err_2 = get_contour_x_more_left(contour_2, &x_left_2); if(cod_err_1 != INF_NOT_ERR || cod_err_2 != INF_NOT_ERR) return *print_msg(ERR_GENERIC, "contour/compare_x_relative_position_contours"); if(x_left_1 > x_left_2) *result = OBJ_1_IS_MAJOR; else if(x_left_1 < x_left_2) *result = OBJ_2_IS_MAJOR; else{ cod_err_1 = get_contour_x_more_right(contour_1, &x_right_1); cod_err_2 = get_contour_x_more_right(contour_2, &x_right_2); if(cod_err_1 != INF_NOT_ERR || cod_err_2 != INF_NOT_ERR) return *print_msg(ERR_GENERIC, "contour/compare_x_relative_position_contours"); if(x_right_1 > x_right_2) *result = OBJ_1_IS_MAJOR; else if(x_right_1 < x_right_2) *result = OBJ_2_IS_MAJOR; else *result = OBJ_1_AND_2_ARE_EQUAL; } return INF_NOT_ERR; } int y_diff_contour_1_to_contour_2(Contour *contour_1, Contour *contour_2, int *result){ //contour_2 is up contour_1 if(contour_2->y_more_up < contour_1->y_more_up){ *result = contour_1->y_more_up - contour_2->y_more_down; }else if(contour_1->y_more_up < contour_2->y_more_up){ *result = contour_2->y_more_up - contour_1->y_more_down; }else *result = -1; return INF_NOT_ERR; } int compare_y_relative_position_contours(Contour *contour_1, Contour *contour_2, int *result){ int cod_err_1 = INF_NOT_ERR, cod_err_2 = INF_NOT_ERR; int y_up_1 = 0, y_up_2 = 0; cod_err_1 = get_contour_y_more_up(contour_1, &y_up_1); cod_err_2 = get_contour_y_more_up(contour_2, &y_up_2); if(cod_err_1 != INF_NOT_ERR || cod_err_2 != INF_NOT_ERR) return *print_msg(ERR_GENERIC, "contour/compare_y_relative_position_contours"); if(y_up_1 > y_up_2) *result = OBJ_1_IS_MAJOR; else if(y_up_1 < y_up_2) *result = OBJ_2_IS_MAJOR; else *result = OBJ_1_AND_2_ARE_EQUAL; return INF_NOT_ERR; } int calc_dist_x_contours(Contour *contour_1, Contour *contour_2, int *result){ int cod_err = INF_NOT_ERR; cod_err = compare_x_relative_position_contours(contour_1, contour_2, result); if(*result == OBJ_1_IS_MAJOR || cod_err != INF_NOT_ERR) return *print_big_msg(ERR_GENERIC, "contour/calc_dist_x_contours", "compare_x_relative_position_contours"); int x_right_1 = 0, x_left_2 = 0; get_contour_x_more_right(contour_1, &x_right_1); get_contour_x_more_left (contour_2, &x_left_2 ); int dist = x_left_2 - x_right_1; //If the distance between the contours is negative, //they probably belong to the same object and should //be unified by the corresponding filtering *result = dist < 0 ? 0 : dist; return INF_NOT_ERR; } int free_contour(Contour **mContorno){ if(mContorno != NULL){ if((*mContorno) != NULL){ if((*mContorno)->cv_contour != NULL) cvClearSeq(((CvSeq*) ((*mContorno)->cv_contour))); free((*mContorno)); (*mContorno) = NULL; } } return INF_NOT_ERR; }
C
#include <stdio.h> #include <time.h> #define DEBUG 1 inline unsigned long tsc(void) { register unsigned int lo, hi; asm volatile ("rdtsc" : "=a" (lo), "=d" (hi)); return ((unsigned long)hi << 32UL) | (unsigned long)lo; } #ifdef DEBUG int main() { unsigned long t1, t2; //sleep (1); t1 = tsc(); t2 = tsc(); printf("%ld\n",t2 - t1); } #endif
C
#include<stdio.h> int main() { unsigned int num,num_temp,i; unsigned int temp; while(1) { printf("Enter the Hexadecimal number: "); scanf("%x",&num); num_temp=num; //Clea the buffer while(getchar() != '\n'); printf("\n"); printf("Number is %x\n",num); //Extract each bit and display it for(i=0;i<(sizeof(num)*8);i++) { num=num_temp; temp=0x80000000; num=num<<i; temp &= num; if(temp==0) printf("0"); else printf("1"); } printf("\n"); //Ask user for options printf("Do you want to continue(Y/N):"); char ch=getchar(); while(getchar() != '\n'); if((ch == 'N' || ch == 'n')) { break; } } return 0; }
C
#include<stdio.h> int main() { int n[10],i,Sum=0; for(i=0;i<10;i++) { printf("Enter the numbers \n"); scanf("%d",&n[i]); } for(i=0;i<10;i++) { Sum=Sum+n[i]; } printf("The sum of numbers in array is:%d \n",Sum); return 0; }
C
#include "stdio.h" #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include "arpa/inet.h" int main(int argc,char **argv) { char ch ='A'; int client,return_val,client_len; struct sockaddr_in address; client = socket(AF_INET,SOCK_STREAM,0); address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr("127.0.0.1"); address.sin_port = htons(7734); client_len = sizeof(address); return_val = connect (client, (struct sockaddr*)&address, &client_len); if(return_val == -1) { printf("error in connection"); exit(1); } write(client,&ch,1); read(client,&ch,1); printf("-->%c \n \r",ch); close(client); }
C
#include <stdlib.h> #include <utils/heap.h> /** * @file heap.c */ /** * Description d'un tas. */ struct heap { int (*compar)(void*, void*); int (*id)(void*); size_t heap_size; void **buf; int *position; int free_buf; }; /** * Créer un tas. * @param buffer_size - Taille du tas. * @param buffer - Buffer externe. * @param compar__ - Fonction de comparaison de deux éléments. * @param id__ - Fonction permettant de récupérer l'identifiant d'un * élément. * @return struct heap * - Le tas créé. */ struct heap *heap_create(size_t buffer_size, void **buffer, int (*compar__)(void*, void*), int (*id__)(void *)) { struct heap *heap = malloc(sizeof(*heap)); heap->compar = compar__; heap->id = id__; heap->heap_size = 0; if (buffer == NULL) { heap->buf = malloc(sizeof(*(heap->buf)) * (buffer_size + 1)); heap->free_buf = 1; } else { heap->buf = buffer; heap->free_buf = 0; } if (id__ != NULL) heap->position = malloc(buffer_size * sizeof(*heap->position)); else heap->position = NULL; return heap; } /** * Libérer la mémoire occupée par un tas. * @param heap - Le tas à supprimer. */ void heap_destroy(struct heap *heap) { if (heap->free_buf) free(heap->buf); free(heap->position); free(heap); } /** * * */ static inline int heap_greater_child(struct heap *heap, int i) { if (2*i == heap->heap_size) return 2*i; if (heap->compar(heap->buf[2*i], heap->buf[2*i+1]) > 0) return 2*i; return 2*i+1; } /** * * */ static inline void heap_swap(struct heap *heap, int i, int k) { if (heap->id != NULL) { int id_i = heap->id(heap->buf[i]); int id_k = heap->id(heap->buf[k]); heap->position[id_i] = k; heap->position[id_k] = i; } void *tmp = heap->buf[i]; heap->buf[i] = heap->buf[k]; heap->buf[k] = tmp; } /** * * */ static inline int heap_extract_problem(struct heap *heap, int i) { return ((2*i == heap->heap_size && heap->compar(heap->buf[2*i], heap->buf[i]) > 0) || (2*i+1 <= heap->heap_size && (heap->compar(heap->buf[2*i], heap->buf[i]) > 0 || heap->compar(heap->buf[2*i+1], heap->buf[i]) > 0))); } /** * * */ static int heap_extract_resolve(struct heap *heap, int i) { int k = heap_greater_child(heap, i); heap_swap(heap, i, k); return k; } /** * * */ void *heap_extract_max(struct heap *heap) { void *max = heap->buf[1]; heap->buf[1] = heap->buf[heap->heap_size--]; int i = 1; while (heap_extract_problem(heap, i)) { i = heap_extract_resolve(heap, i); } return max; } /** * * */ void *heap_max(struct heap *heap) { return heap->buf[1]; } /** * * */ static inline int heap_insert_problem(struct heap *heap, int i) { if (i == 1) return 0; return heap->compar(heap->buf[i], heap->buf[i/2]) > 0; } /** * * */ static inline int heap_insert_resolve(struct heap *heap, int i) { heap_swap(heap, i, i/2); return i/2; } /** * * */ void heap_insert(struct heap *heap, void *k) { int i = ++heap->heap_size; heap->buf[i] = k; if (heap->id != NULL) { int id = heap->id(k); heap->position[id] = i; } while (heap_insert_problem(heap, i)) { i = heap_insert_resolve(heap, i); } } /** * * */ void heap_update(struct heap *heap, void *k) { if (heap->id == NULL) return; int id = heap->id(k); int i = heap->position[id]; while (heap_insert_problem(heap, i)) { i = heap_insert_resolve(heap, i); } while (heap_extract_problem(heap, i)) { i = heap_extract_resolve(heap, i); } // WARNING: may not work } /** * Obtenir la taille d'un tas. * @param heap - Le tas à analiser. * @return size_t - La taille de tas. */ size_t heap_size(struct heap *heap) { return heap->heap_size; }
C
#include <stdio.h> #include <stdlib.h> #include "uncmnt.h" void main(int argc,char **argv) { FILE *fptr; int line_no; int line_len; int comment_start; int comment_stop; bool bInComment; bool bInDoubleQuote; int curly_brace_depth; int debug_line_no; if (argc != 2) { printf("usage: uncmnt filename\n"); return; } if ((fptr = fopen(argv[1],"r")) == NULL) { printf("couldn't open %s\n",argv[1]); return; } line_no = 0; bInComment = false; bInDoubleQuote = false; curly_brace_depth = 0; for ( ; ; ) { if (get_uncommented_line_info(fptr,line,&line_len,MAX_LINE_LEN, &comment_start,&comment_stop, &bInComment,&bInDoubleQuote,&curly_brace_depth) == -1) break; if (feof(fptr)) break; line_no++; if (line_no == debug_line_no) debug_line_no = 0; make_uncommented_line(uncommented_line,line,line_len, comment_start,comment_stop); printf("%s\n",uncommented_line); } fclose(fptr); }
C
#include "scheduler.h" int main(int argc, char *argv[]){ if (argc!=5){ printf("must enter 4 command line inputs\n"); exit(1); } FILE* input_file = fopen(argv[3], "r"); if (input_file==NULL){ printf("file %s does not exist\n", argv[3]); exit(1); } FILE* output_file = fopen(argv[4], "w"); connection *connections_by_priority[MAX_NUMBER_OF_CONNECTIONS]={NULL}; connection_hash_table_item *connections_hash_table[MAX_NUMBER_OF_CONNECTIONS]={NULL}; char buffer[LINE_LENGTH]; char buffer_copy[LINE_LENGTH]; packet *current_packet; packet* (*chosen_scheduler)(connection**); if (strcmp(argv[1],"RR")==0){ chosen_scheduler=rr_scheduler; }else if (strcmp(argv[1],"WRR")==0){ chosen_scheduler=wrr_scheduler; }else{ quantum=atoi(argv[2]); chosen_scheduler=drr_scheduler; } unsigned int packet_number=0; unsigned long current_packet_time; char *fgets_output=fgets(buffer, LINE_LENGTH, input_file); while (fgets_output!=NULL){ strcpy(buffer_copy,buffer); time=get_current_package_time(buffer_copy); initialize_packet(buffer,connections_by_priority,connections_hash_table); //this while loop initializes all packets that share a spesific time //once the packet time is diffrente from the rest there is a break statement //1 packet is sent according to the scheduler and the time is updated in the write_packet function //in the next iteration of the while loop the time is set again by the current packet while ((fgets_output=fgets(buffer, LINE_LENGTH, input_file)!=NULL)) { strcpy(buffer_copy,buffer); if (time==get_current_package_time(buffer_copy)){ initialize_packet(buffer,connections_by_priority,connections_hash_table); } else{ break; } } current_packet=chosen_scheduler(connections_by_priority); write_packet(output_file, current_packet); } //after all the packets until the lastest time have been sent this while loop goes all over the remaining packets and sends them according to the scheduler current_packet=chosen_scheduler(connections_by_priority); while(current_packet!=NULL){ write_packet(output_file, current_packet); current_packet=chosen_scheduler(connections_by_priority); } free_connections(connections_by_priority,connections_hash_table); return 0; } unsigned long get_current_package_time(char* buffer){ const char delim[2] = " "; return (unsigned long) atoi(strtok(buffer, delim)); } void write_packet(FILE* output_file, packet *current_packet){ if (current_packet->weight==NULL){ printf("%lu: %lu %s %hu %s %hu %hu\n\n",time,current_packet->arrival_time, current_packet->identifier->sender_ip, current_packet->identifier->sender_port, current_packet->identifier->destiny_ip, current_packet->identifier->destiny_port, current_packet->length); fprintf(output_file,"%lu: %lu %s %hu %s %hu %hu\n",time,current_packet->arrival_time, current_packet->identifier->sender_ip, current_packet->identifier->sender_port, current_packet->identifier->destiny_ip, current_packet->identifier->destiny_port, current_packet->length); }else{ printf("%lu: %lu %s %hu %s %hu %hu\n\n",time,current_packet->arrival_time, current_packet->identifier->sender_ip, current_packet->identifier->sender_port, current_packet->identifier->destiny_ip, current_packet->identifier->destiny_port, current_packet->length); fprintf(output_file,"%lu: %lu %s %hu %s %hu %hu %hu\n",time,current_packet->arrival_time, current_packet->identifier->sender_ip, current_packet->identifier->sender_port, current_packet->identifier->destiny_ip, current_packet->identifier->destiny_port, current_packet->length, current_packet->weight); } time+=current_packet->length; free(current_packet); } //this function implements round robin scheduling //a while loop that goes over all the connections until a packet is found and then returns it to be written to the output file //if a packet has been found the global variable current_connection_priority is incremented by 1 so that the next time this function is called the the connection with the next priority will be the first to searched packet *rr_scheduler(connection **connections_by_priority){ packet *current_packet=get_packet_from_connection(connections_by_priority[current_connection_priority]); unsigned short connections_passed=0; while (current_packet==NULL && connections_passed<number_of_connections){ increment_current_connection_priority(); current_packet=get_packet_from_connection(connections_by_priority[current_connection_priority]); connections_passed++; } if (current_packet!=NULL){ increment_current_connection_priority(); } return current_packet; } //this function implements weighted round robin scheduling //a while loop the goes over all the connections until a packet is found //if the packet has a weight, then the connection current_weight and remainder_to_send_by_weight variables are updated according to it //whether or not the connection weight has been updated, the remainder is decremented by 1. //if after that the remainder is 0, meaning this connection has no more packets to send according to its weight the global variable current_connection_priority is incremented by 1 so that the next time this function is called the the connection with the next priority will be the first to searched packet *wrr_scheduler(connection **connections_by_priority){ packet *current_packet=get_packet_from_connection(connections_by_priority[current_connection_priority]); unsigned short connections_passed=0; while (current_packet==NULL && connections_passed<number_of_connections){ increment_current_connection_priority(); current_packet=get_packet_from_connection(connections_by_priority[current_connection_priority]); connections_passed++; } if(current_packet!=NULL){ if(current_packet->weight!=NULL){ connections_by_priority[current_connection_priority]->current_weight=connections_by_priority[current_connection_priority]->remainder_to_send_by_weight=current_packet->weight; } connections_by_priority[current_connection_priority]->remainder_to_send_by_weight--; if (connections_by_priority[current_connection_priority]->remainder_to_send_by_weight==0){ connections_by_priority[current_connection_priority]->remainder_to_send_by_weight=connections_by_priority[current_connection_priority]->current_weight; increment_current_connection_priority(); } } return current_packet; } //this function implements deficit round robin scheduling //a while loop the goes over all the connections until a packet is found //if the packet has been found in a new connection the flag current_connection_not_yet_credited is set to true, so the new connection will receive credit according to the quantum //if the connection does not have enough credit to send the current packet, the packet is inserted again at the head of the connection packets queue, current_connection_priority is incremented by 1 and the functions runs again //if the connection has enough credit to send the current packet, the packet's length is reduced from the connection's credit and the packet returns to be written to the output file packet *drr_scheduler(connection **connections_by_priority){ packet *current_packet=get_packet_from_connection(connections_by_priority[current_connection_priority]); if (current_packet==NULL){ increment_current_connection_priority(); current_packet=get_packet_from_connection(connections_by_priority[current_connection_priority]); current_connection_not_yet_credited=true; unsigned short connections_passed=0; while (current_packet==NULL && connections_passed<number_of_connections){ connections_by_priority[current_connection_priority]->credit=0; increment_current_connection_priority(); current_packet=get_packet_from_connection(connections_by_priority[current_connection_priority]); connections_passed++; } } if(current_packet!=NULL){ if(current_packet->weight!=NULL){ connections_by_priority[current_connection_priority]->current_weight=current_packet->weight; } if(current_connection_not_yet_credited){ connections_by_priority[current_connection_priority]->credit+=(quantum*connections_by_priority[current_connection_priority]->current_weight); current_connection_not_yet_credited=false; } if(connections_by_priority[current_connection_priority]->credit<current_packet->length){ insert_packet_in_head(current_packet,current_connection_priority, connections_by_priority); current_connection_not_yet_credited=true; increment_current_connection_priority(); return drr_scheduler(connections_by_priority); }else{ connections_by_priority[current_connection_priority]->credit-=current_packet->length; } }else{ connections_by_priority[current_connection_priority]->credit=0; } return current_packet; } void increment_current_connection_priority(){ current_connection_priority++; current_connection_priority%=number_of_connections; } void decrement_current_connection_priority(){ current_connection_priority--; } //this function gets a packet from the connection's packets queue packet *get_packet_from_connection(connection *current_connection){ packet *return_packet=current_connection->packets_head; if (return_packet!=NULL){ current_connection->packets_head=current_connection->packets_head->next; if (current_connection->packets_head==NULL){ current_connection->packets_tail=NULL; } } return return_packet; } //this function initializes the data structure packet according to the values in the buffer //if the packet's connection is not found in the hash table a new connection is created void initialize_packet(char *buffer, connection **connections_by_priority, connection_hash_table_item **connections_hash_table){ packet *new_packet=(packet*) malloc(sizeof(packet)); const char delim[2] = " "; new_packet->arrival_time = atoi(strtok(buffer, delim)); connection_identifier *identifier=(connection_identifier*)malloc(sizeof(connection_identifier)); strcpy(identifier->sender_ip, strtok(NULL, delim)); identifier->sender_port=atoi(strtok(NULL, delim)); strcpy(identifier->destiny_ip,strtok(NULL, delim)); identifier->destiny_port=atoi(strtok(NULL, delim)); new_packet->length=atoi(strtok(NULL, delim)); new_packet->next=NULL; char* weight=strtok(NULL, delim); weight==NULL?(new_packet->weight=NULL):(new_packet->weight=atoi(weight)); unsigned short hash_index=hash_function(identifier); connection_hash_table_item *searched_connection_item=search_connections_hash_table(hash_index, identifier, connections_hash_table); if (searched_connection_item==NULL){ create_a_new_connection(identifier,new_packet,hash_index,connections_by_priority,connections_hash_table); }else{ insert_packet_in_tail(new_packet,searched_connection_item->priority_index,connections_by_priority); free(identifier); } } //this function creates a new connection according to its first packet //the creation of a new connection includes: //1. creating a new value in the hash table.the hash table is designed for a O(1) search of a connection when a new packet is initialized and needs to find the connection it belongs to // if the index returned by the hash function already has a connection in the hash table a linked list is initiated in that hash table index according to the chaining method //2. creating a connection data structure that holds the ideitifying values of the connection and the packet queue void create_a_new_connection(connection_identifier *identifier, packet *new_packet, unsigned short hash_index, connection **connections_by_priority, connection_hash_table_item **connections_hash_table){ connection_hash_table_item *new_item=(connection_hash_table_item*)malloc(sizeof(connection_hash_table_item)); new_item->priority_index=number_of_connections++; new_item->next=NULL; connection_hash_table_item *current_item=connections_hash_table[hash_index]; if (current_item==NULL){ *(connections_hash_table+hash_index)=new_item; } else{ while(current_item->next!=NULL){ current_item=current_item->next; } current_item->next=new_item; } connection *new_connection=(connection*)malloc(sizeof(connection)); new_connection->identifier=new_item->identifier=new_packet->identifier=identifier; new_connection->hash_index=hash_index; new_connection->credit=0; new_connection->packets_head=new_connection->packets_tail=NULL; *(connections_by_priority+new_item->priority_index)=new_connection; initialize_connection(connections_by_priority[new_item->priority_index],new_packet); } //initializing a new connection includes setting the first packet at the queue's head and tail and setting the connection's weight according to the packet's weight void initialize_connection(connection *current_connection, packet *new_packet){ current_connection->packets_head=current_connection->packets_tail=new_packet; (new_packet->weight)==NULL?(current_connection->current_weight=current_connection->remainder_to_send_by_weight=1):(current_connection->current_weight=current_connection->remainder_to_send_by_weight=new_packet->weight); } void insert_packet_in_tail(packet *new_packet, unsigned short priority_index, connection **connections_by_priority){ connection *current_connection=connections_by_priority[priority_index]; new_packet->identifier=current_connection->identifier; if (current_connection->packets_tail==NULL){ initialize_connection(current_connection,new_packet); }else{ current_connection->packets_tail->next=new_packet; current_connection->packets_tail=new_packet; } } void insert_packet_in_head(packet *new_packet, unsigned short priority_index, connection **connections_by_priority){ connection *current_connection=connections_by_priority[priority_index]; if (current_connection->packets_tail==NULL){ initialize_connection(current_connection,new_packet); }else{ new_packet->next=current_connection->packets_head; current_connection->packets_head=new_packet; } } unsigned short hash_function(connection_identifier *identifier){ float hash_index=3*identifier->sender_port+(-2)*identifier->destiny_port; for (int i=0;i<strlen(identifier->sender_ip);i++){ if (identifier->sender_ip[i]!='.'){ hash_index+=(2.5*identifier->sender_ip[i]); } } for (int i=0;i<strlen(identifier->destiny_ip);i++){ if (identifier->destiny_ip[i]!='.'){ hash_index+=(-1.5*identifier->destiny_ip[i]); } } unsigned short rounded_hash_index=(unsigned short)round(hash_index); rounded_hash_index%=MAX_NUMBER_OF_CONNECTIONS; return rounded_hash_index; } connection_hash_table_item *search_connections_hash_table(unsigned short hash_index, connection_identifier *identifier, connection_hash_table_item **connections_hash_table){ connection_hash_table_item *searched_connection=connections_hash_table[hash_index]; while(searched_connection!=NULL){ if (compare_identifiers(searched_connection->identifier, identifier)){ return searched_connection; }else{ searched_connection=searched_connection->next; } } return searched_connection; } bool compare_identifiers(connection_identifier *first_identifier, connection_identifier *second_identifier){ return strcmp(first_identifier->sender_ip,second_identifier->sender_ip)==0 && first_identifier->sender_port==second_identifier->sender_port && strcmp(first_identifier->destiny_ip,second_identifier->destiny_ip)==0 && first_identifier->destiny_port==second_identifier->destiny_port; } void free_connections(connection **connections_by_priority, connection_hash_table_item **connections_hash_table){ unsigned short hash_index; connection_hash_table_item *current_item; for(int i=0;i<number_of_connections;i++){ hash_index=connections_by_priority[i]->hash_index; free(connections_by_priority[i]->identifier); free(connections_by_priority[i]); current_item=connections_hash_table[hash_index]; while(current_item!=NULL){ current_item=current_item->next; free(current_item); } } }
C
///////////////////////////////////////////////////////////////// // // CCISEL // 2007-2011 // // UThread library: // User threads supporting cooperative multithreading. // // Authors: // Carlos Martins, Joo Trindade, Duarte Nunes, Jorge Martins // #include <crtdbg.h> #include "UThreadInternal.h" #include <stdio.h> ////////////////////////////////////// // // UThread internal state variables. // // // The number of existing user threads. // static ULONG NumberOfThreads; // // The sentinel of the circular list linking the user threads that are // currently schedulable. The next thread to run is retrieved from the // head of this list. // static LIST_ENTRY ReadyQueue; static LIST_ENTRY AliveQueue; // // The currently executing thread. // #ifndef UTHREAD_X64 static #endif PUTHREAD RunningThread; // // The user thread proxy of the underlying operating system thread. This // thread is switched back in when there are no more runnable user threads, // causing the scheduler to exit. // static PUTHREAD MainThread; //////////////////////////////////////////////// // // Forward declaration of internal operations. // // // The trampoline function that a user thread begins by executing, through // which the associated function is called. // static VOID InternalStart (); #ifdef UTHREAD_X64 // // Performs a context switch from CurrentThread to NextThread. // In x64 calling convention CurrentThread is in RCX and NextThread in RDX. // VOID __fastcall ContextSwitch (PUTHREAD CurrentThread, PUTHREAD NextThread); // // Frees the resources associated with CurrentThread and switches to NextThread. // In x64 calling convention CurrentThread is in RCX and NextThread in RDX. // VOID __fastcall InternalExit (PUTHREAD Thread, PUTHREAD NextThread); #else static VOID __fastcall ContextSwitch (PUTHREAD CurrentThread, PUTHREAD NextThread); // // Frees the resources associated with CurrentThread and switches to NextThread. // __fastcall sets the calling convention such that CurrentThread is in ECX // and NextThread in EDX. // static VOID __fastcall InternalExit (PUTHREAD Thread, PUTHREAD NextThread); #endif //////////////////////////////////////// // // UThread inline internal operations. // // // Returns and removes the first user thread in the ready queue. If the ready // queue is empty, the main thread is returned. // static FORCEINLINE PUTHREAD ExtractNextReadyThread () { return IsListEmpty(&ReadyQueue) ? MainThread : CONTAINING_RECORD(RemoveHeadList(&ReadyQueue), UTHREAD, Link); } // // Schedule a new thread to run // static FORCEINLINE VOID Schedule () { PUTHREAD NextThread; NextThread = ExtractNextReadyThread(); RunningThread->Running += (GetTickCount() - RunningThread->LastChanged); RunningThread->LastChanged = GetTickCount(); NextThread->State = Running; NextThread->Ready += (GetTickCount() - NextThread->LastChanged); NextThread->LastChanged = GetTickCount(); ContextSwitch(RunningThread, NextThread); } /////////////////////////////// // // UThread public operations. // // // Initialize the scheduler. // This function must be the first to be called. // VOID UtInit() { InitializeListHead(&ReadyQueue); InitializeListHead(&AliveQueue); } // // Cleanup all UThread internal resources. // VOID UtEnd() { /* (this function body was intentionally left empty) */ } // // Run the user threads. The operating system thread that calls this function // performs a context switch to a user thread and resumes execution only when // all user threads have exited. // VOID UtRun () { UTHREAD Thread; // Represents the underlying operating system thread. // // There can be only one scheduler instance running. // _ASSERTE(RunningThread == NULL); // // At least one user thread must have been created before calling run. // if (IsListEmpty(&ReadyQueue)) { return; } // // Switch to a user thread. // MainThread = &Thread; RunningThread = MainThread; Schedule(); // // When we get here, there are no more runnable user threads. // _ASSERTE(IsListEmpty(&ReadyQueue)); _ASSERTE(NumberOfThreads == 0); // // Allow another call to UtRun(). // RunningThread = NULL; MainThread = NULL; } // // Terminates the execution of the currently running thread. All associated // resources are released after the context switch to the next ready thread. // VOID UtExit () { NumberOfThreads -= 1; PUTHREAD self = (PUTHREAD)UtSelf(); self->Running += (GetTickCount() - self->LastChanged); self->LastChanged = GetTickCount(); while (!IsListEmpty(&self->JoinList)) { // Remover da cabea de JoinList PUTHREAD newRdy = CONTAINING_RECORD(RemoveHeadList(&self->JoinList), UTHREAD, Link); // Adicionar cauda de ReadyQueue UtActivate(newRdy); } printf("Uthread Elapsed Time (Actual) = %lu\n", UtGetTimeAlive(self) + UtGetTimeAlive(self) + UtGetTimeAlive(self)); printf("Thread %c Ready: %lu\n", self->Argument, UtGetTimeReady(self)); printf("Thread %c Blocked: %lu\n", self->Argument, UtGetTimeBlocked(self)); printf("Thread %c Active: %lu\n", self->Argument, UtGetTimeAlive(self)); RemoveEntryList(&self->AliveList); InternalExit(RunningThread, ExtractNextReadyThread()); _ASSERTE(!"Supposed to be here!"); } // // Relinquishes the processor to the first user thread in the ready queue. // If there are no ready threads, the function returns immediately. // VOID UtYield () { if (!IsListEmpty(&ReadyQueue)) { RunningThread->Running += (GetTickCount() - RunningThread->LastChanged); RunningThread->State = Ready; InsertTailList(&ReadyQueue, &RunningThread->Link); Schedule(); } } // // Returns a HANDLE to the executing user thread. // HANDLE UtSelf () { return (HANDLE)RunningThread; } // // Halts the execution of the current user thread. // VOID UtDeactivate() { Schedule(); } // // Places the specified user thread at the end of the ready queue, where it // becomes eligible to run. // VOID UtActivate (HANDLE ThreadHandle) { PUTHREAD pthread = ((PUTHREAD)ThreadHandle); pthread->LastChanged = GetTickCount(); pthread->State = Ready; InsertTailList(&ReadyQueue, &((PUTHREAD)ThreadHandle)->Link); } /////////////////////////////////////// // // Definition of internal operations. // // // The trampoline function that a user thread begins by executing, through // which the associated function is called. // VOID InternalStart () { RunningThread->Function(RunningThread->Argument); UtExit(); } // // functions with implementation dependent of X86 or x64 platform // #ifndef UTHREAD_X64 // // Creates a user thread to run the specified function. The thread is placed // at the end of the ready queue. // HANDLE UtCreate (UT_FUNCTION Function, UT_ARGUMENT Argument) { PUTHREAD Thread; // // Dynamically allocate an instance of UTHREAD and the associated stack. // Thread = (PUTHREAD) malloc(sizeof (UTHREAD)); Thread->Stack = (PUCHAR) malloc(STACK_SIZE); _ASSERTE(Thread != NULL && Thread->Stack != NULL); // // Zero the stack for emotional confort. // memset(Thread->Stack, 0, STACK_SIZE); // // Memorize Function and Argument for use in InternalStart. // Thread->Function = Function; Thread->Argument = Argument; // // Map an UTHREAD_CONTEXT instance on the thread's stack. // We'll use it to save the initial context of the thread. // // +------------+ // | 0x00000000 | <- Highest word of a thread's stack space // +============+ (needs to be set to 0 for Visual Studio to // | RetAddr | \ correctly present a thread's call stack). // +------------+ | // | EBP | | // +------------+ | // | EBX | > Thread->ThreadContext mapped on the stack. // +------------+ | // | ESI | | // +------------+ | // | EDI | / <- The stack pointer will be set to this address // +============+ at the next context switch to this thread. // | | \ // +------------+ | // | : | | // : > Remaining stack space. // | : | | // +------------+ | // | | / <- Lowest word of a thread's stack space // +------------+ (Thread->Stack always points to this location). // Thread->ThreadContext = (PUTHREAD_CONTEXT) (Thread->Stack + STACK_SIZE - sizeof (ULONG) - sizeof (UTHREAD_CONTEXT)) -8; // // Set the thread's initial context by initializing the values of EDI, // EBX, ESI and EBP (must be zero for Visual Studio to correctly present // a thread's call stack) and by hooking the return address. // // Upon the first context switch to this thread, after popping the dummy // values of the "saved" registers, a ret instruction will place the // address of InternalStart on EIP. // Thread->ThreadContext->EDI = 0x33333333; Thread->ThreadContext->EBX = 0x11111111; Thread->ThreadContext->ESI = 0x22222222; Thread->ThreadContext->EBP = 0x00000000; Thread->ThreadContext->RetAddr = InternalStart; // // Ready the thread. // NumberOfThreads += 1; Thread->Blocked = 0; Thread->Ready = 0; Thread->Running = 0; UtActivate((HANDLE)Thread); InsertHeadList(&AliveQueue, &Thread->AliveList); InitializeListHead(&Thread->JoinList); return (HANDLE)Thread; } // // Performs a context switch from CurrentThread to NextThread. // __fastcall sets the calling convention such that CurrentThread is in ECX and NextThread in EDX. // __declspec(naked) directs the compiler to omit any prologue or epilogue. // __declspec(naked) VOID __fastcall ContextSwitch (PUTHREAD CurrentThread, PUTHREAD NextThread) { __asm { // Switch out the running CurrentThread, saving the execution context on the thread's own stack. // The return address is atop the stack, having been placed there by the call to this function. // push ebp push ebx push esi push edi // // Save ESP in CurrentThread->ThreadContext. // mov dword ptr [ecx].ThreadContext, esp // // Set NextThread as the running thread. // mov RunningThread, edx // // Load NextThread's context, starting by switching to its stack, where the registers are saved. // mov esp, dword ptr [edx].ThreadContext pop edi pop esi pop ebx pop ebp // // Jump to the return address saved on NextThread's stack when the function was called. // ret } } // // Frees the resources associated with Thread. // __fastcall sets the calling convention such that Thread is in ECX. // static VOID __fastcall CleanupThread (PUTHREAD Thread) { free(Thread->Stack); free(Thread); } // // Frees the resources associated with CurrentThread and switches to NextThread. // __fastcall sets the calling convention such that CurrentThread is in ECX and NextThread in EDX. // __declspec(naked) directs the compiler to omit any prologue or epilogue. // __declspec(naked) VOID __fastcall InternalExit (PUTHREAD CurrentThread, PUTHREAD NextThread) { __asm { // // Set NextThread as the running thread. // mov RunningThread, edx // // Load NextThread's stack pointer before calling CleanupThread(): making the call while // using CurrentThread's stack would mean using the same memory being freed -- the stack. // mov esp, dword ptr [edx].ThreadContext call CleanupThread // // Finish switching in NextThread. // pop edi pop esi pop ebx pop ebp ret } } #else // // Creates a user thread to run the specified function. The thread is placed // at the end of the ready queue. // HANDLE UtCreate (UT_FUNCTION Function, UT_ARGUMENT Argument) { PUTHREAD Thread; // // Dynamically allocate an instance of UTHREAD and the associated stack. // Thread = (PUTHREAD) malloc(sizeof (UTHREAD)); Thread->Stack = (PUCHAR) malloc(STACK_SIZE); _ASSERTE(Thread != NULL && Thread->Stack != NULL); // // Zero the stack for emotional confort. // memset(Thread->Stack, 0, STACK_SIZE); // // Memorize Function and Argument for use in InternalStart. // Thread->Function = Function; Thread->Argument = Argument; // // Map an UTHREAD_CONTEXT instance on the thread's stack. // We'll use it to save the initial context of the thread. // // +------------+ <- Highest word of a thread's stack space // | 0x00000000 | (needs to be set to 0 for Visual Studio to // +------------+ correctly present a thread's call stack). // | 0x00000000 | \ // +------------+ | // | 0x00000000 | | <-- Shadow Area for Internal Start // +------------+ | // | 0x00000000 | | // +------------+ | // | 0x00000000 | / // +============+ // | RetAddr | \ // +------------+ | // | RBP | | // +------------+ | // | RBX | > Thread->ThreadContext mapped on the stack. // +------------+ | // | RDI | | // +------------+ | // | RSI | | // +------------+ | // | R12 | | // +------------+ | // | R13 | | // +------------+ | // | R14 | | // +------------+ | // | R15 | / <- The stack pointer will be set to this address // +============+ at the next context switch to this thread. // | | \ // +------------+ | // | : | | // : > Remaining stack space. // | : | | // +------------+ | // | | / <- Lowest word of a thread's stack space // +------------+ (Thread->Stack always points to this location). // Thread->ThreadContext = (PUTHREAD_CONTEXT) (Thread->Stack + STACK_SIZE -sizeof (UTHREAD_CONTEXT)-sizeof(ULONGLONG)*5); // // Set the thread's initial context by initializing the values of // registers that must be saved by the called (R15,R14,R13,R12, RSI, RDI, RBCX, RBP) // // Upon the first context switch to this thread, after popping the dummy // values of the "saved" registers, a ret instruction will place the // address of InternalStart on EIP. // Thread->ThreadContext->R15 = 0x77777777; Thread->ThreadContext->R14 = 0x66666666; Thread->ThreadContext->R13 = 0x55555555; Thread->ThreadContext->R12 = 0x44444444; Thread->ThreadContext->RSI = 0x33333333; Thread->ThreadContext->RDI = 0x11111111; Thread->ThreadContext->RBX = 0x22222222; Thread->ThreadContext->RBP = 0x11111111; Thread->ThreadContext->RetAddr = InternalStart; // // Ready the thread. // NumberOfThreads += 1; UtActivate((HANDLE)Thread); return (HANDLE)Thread; } // // Frees the resources associated with Thread. // In X64 calling convention Thread comes in RCX. // VOID CleanupThread (PUTHREAD Thread) { free(Thread->Stack); free(Thread); } #endif int UtJoin(HANDLE thread) { PUTHREAD pthread = (PUTHREAD)thread; PUTHREAD self = (PUTHREAD)UtSelf(); if (pthread == self) return 0; if (!UtAlive(thread)) return 1; // Bloquear thread InsertTailList(&pthread->JoinList, &self->Link); self->State = Blocked; self->Running += (GetTickCount() - self->LastChanged); self->LastChanged = GetTickCount(); self->JoinCanceled = FALSE; UtDeactivate(); self->Blocked += (GetTickCount() - self->LastChanged); self->LastChanged = GetTickCount(); return self->JoinCanceled ? -1 : 1; } BOOL UtJoinCancel(HANDLE thread) { if (!UtAlive(thread) || UtGetState(thread) != Blocked) return FALSE; PUTHREAD pthread = (PUTHREAD)thread; RemoveEntryList(&pthread->Link); pthread->JoinCanceled = TRUE; pthread->Blocked += (GetTickCount() - pthread->LastChanged); UtActivate(thread); return TRUE; } //1. a) add function to api INT UtGetState(HANDLE thread) { return ((PUTHREAD)thread)->State; } //1. b) Uma thread est viva se: // - o seu estado running e a thread que chama esta funo // - o seu estado ready e est na ready queue // - o seu estado blocked e est numa join_list //bool utalive2(handle thread) { // puthread pthread = (puthread)thread; // if (utself() == thread && pthread->state == running) // return true; // if (pthread->state == ready && isinlist(&readyqueue, thread)) // return true; // puthread self = (puthread)utself(); // if (pthread->state == blocked && (isinlist(&self->joinlist, thread) || isinblockedlist(&readyqueue, thread))) // return true; // return false; //} BOOL UtAlive(HANDLE thread) { PLIST_ENTRY curr = AliveQueue.Flink; while (curr != &AliveQueue) { if (CONTAINING_RECORD(curr, UTHREAD, AliveList) == thread) return TRUE; curr = curr->Flink; } return FALSE; } BOOL IsInList(PLIST_ENTRY head, HANDLE thread) { PLIST_ENTRY curr = head->Flink; while (curr != head) { if (CONTAINING_RECORD(curr, UTHREAD, Link) == thread) return TRUE; curr = curr->Flink; } return FALSE; } BOOL IsInBlockedList(PLIST_ENTRY head, HANDLE thread) { PLIST_ENTRY currNode = head->Flink; while (currNode != head) { PUTHREAD uthread = (PUTHREAD)CONTAINING_RECORD(currNode, UTHREAD, Link); if (!IsListEmpty(&uthread->JoinList) && IsInList(&uthread->JoinList, thread)) return TRUE; currNode = currNode->Flink; } return FALSE; } CHAR * UtStateToString(INT threadState) { THREAD_STATE ts = (THREAD_STATE)threadState; if(ts == Blocked) return "Blocked"; if (ts == Ready) return "Ready"; if (ts == Running) return "Running"; } //1. c) ULONG UtGetTimeReady(HANDLE h) { return ((PUTHREAD)h)->Ready; } ULONG UtGetTimeBlocked(HANDLE h) { return ((PUTHREAD)h)->Blocked; } ULONG UtGetTimeAlive(HANDLE h) { PUTHREAD pthread = (PUTHREAD)h; ULONG TimeAlive = pthread->Blocked + pthread->Ready + pthread->Running; return TimeAlive; } //1. d) VOID UtTerminate(HANDLE thread) { NumberOfThreads -= 1; PUTHREAD pthread = (PUTHREAD)thread; pthread->Running += (GetTickCount() - pthread->LastChanged); pthread->LastChanged = GetTickCount(); while (!IsListEmpty(&pthread->JoinList)) { // Remover da cabea de JoinList PUTHREAD newRdy = CONTAINING_RECORD(RemoveHeadList(&pthread->JoinList), UTHREAD, Link); // Adicionar cauda de ReadyQueue UtActivate(newRdy); } RemoveEntryList(&pthread->AliveList); } VOID UtFinish() { while (!IsListEmpty(&AliveQueue)) { PUTHREAD pthread = CONTAINING_RECORD(RemoveHeadList(&AliveQueue), UTHREAD, AliveList); if (UtSelf() != pthread) { RemoveEntryList(&pthread->Link); UtTerminate(pthread); CleanupThread(pthread); } } UtExit(); }
C
/* * Data Structure - Stack(array) * * Author : ChangWook Kim * Modified : Sep. 29. 2017 * */ #include <stdio.h> #include <stdlib.h> #include "arrayStack.h" void stackInit(Stack *pStack){ pStack->top = -1; } int sIsEmpty(Stack *pStack){ if(pStack->top < 0) return TRUE; else return FALSE; } void sPush(Stack *pStack, int data){ if(pStack->top == (STACK_SIZE - 1)){ printf("Stack is FULL\n"); exit(-1); } else{ int index = pStack->top + 1; pStack->stackArray[index] = data; pStack->top++; } } int sPop(Stack *pStack){ if(sIsEmpty(pStack)){ printf("Stack is EMPTY\n"); exit(-1); } else{ int index = pStack->top; pStack->top = index - 1; return pStack->stackArray[index]; } } int sPeek(Stack *pStack){ if(sIsEmpty(pStack)){ printf("Stack is EMPTY\n"); exit(-1); } else return pStack->stackArray[pStack->top]; }
C
/** * @file decagon.c * @brief Implements functions for Decagon GS3 soil moisture sensor * @author Brandon Wong, Matt Bartos, Ivan Mondragon * @version TODO * @date 2017-06-19 */ #include "decagon.h" uint8_t Decagon_Take_Reading(DecagonGS3* decagon_reading) { char *dielectric, *temp, *conductivity; uint8_t err = 0u; sensors_uart_clear_string(); sensors_uart_set_baud(1200u); sensors_uart_start(); // Power cycle sensor to gather readings SDI12_Power_Write(1u); CyDelay(300u); SDI12_Power_Write(0u); sensors_uart_stop(); char *raw_serial_data_d = sensors_uart_get_string(); // Convert the raw data if ((dielectric = strtok(raw_serial_data_d, " ")) == NULL) { err += 1u; } if ((temp = strtok(NULL, " ")) == NULL) { err += 2u; } if ((conductivity = strtok(NULL, " ")) == NULL) { err += 4u; } decagon_reading->dielectric = atof(dielectric); decagon_reading->temp = atof(temp); decagon_reading->conductivity = atoi(conductivity); decagon_reading->valid = (err == 0u); decagon_reading->err = err; return err; } DecagonGS3 Decagon_Convert_Raw_Reading(char* raw_D) { DecagonGS3 final_reading; final_reading.valid = 0u; final_reading.valid = sscanf(raw_D, "\x09%f %f %d\r%*s", &final_reading.dielectric, &final_reading.temp, &final_reading.conductivity); // if you know the the calibration equation, you can caalcualte the soil // moisutre here, too if (final_reading.valid != 4) { final_reading.valid = 0; } return final_reading; } uint8 zip_decagon(char* labels[], float readings[], uint8* array_ix, uint8 take_average, int decagon_loops, uint8 max_size) { // Ensure we don't access nonexistent array index uint8 nvars = 3; if (*array_ix + nvars >= max_size) { return *array_ix; } int valid_count = 0u, read_iter = 0u; float conductivity = 0.0f, temp = 0.0f, dielectric = 0.0f; DecagonGS3 decagon_reading = {0u, 0u, 0u, 0u, 0u}; // with the begin/end paradigm, end must always be `one past the end` char** begins = labels + *array_ix; char** ends = begins + nvars; zips(begins, ends, "decagon_soil_conduct", "decagon_soil_temp", "decagon_soil_dielec"); // Set the mux to read from the decagon pin mux_controller_Wakeup(); mux_controller_Write(3u); for (read_iter = 0; read_iter < decagon_loops; read_iter++) { Decagon_Take_Reading(&decagon_reading); if (decagon_reading.valid == 1u) { valid_count++; conductivity += decagon_reading.conductivity; temp += decagon_reading.temp; dielectric += decagon_reading.dielectric; if (take_average == 0u) { break; } } } if (take_average == 1u && valid_count > 0) { conductivity /= valid_count; temp /= valid_count; dielectric /= valid_count; } else if (valid_count == 0u) { conductivity = 9999; temp = 9999; dielectric = 9999; } // Save mux configuration and put mux to sleep mux_controller_Sleep(); // with the begin/end paradigm, end must always be `one past the end` float* beginf = readings + *array_ix; float* endf = beginf + nvars; zipf(beginf, endf, conductivity, temp, dielectric); *array_ix += 3; return *array_ix; }
C
/*------------------------------------------------------- List Mode Format -- correctUnknownField.c -- Magalie.Krieguer@iphe.unil.ch Crystal Clear Collaboration Copyright (C) 2003 IPHE/UNIL, CH-1015 Lausanne This software is distributed under the terms of the GNU Lesser General Public Licence (LGPL) See LMF/LICENSE.txt for further details -------------------------------------------------------*/ /*------------------------------------------------------- Description of correctUnknownField.c: Fill in the LMF record carrier with the data contained in the LMF ASCII header file correctUnknownField - Correct unknown field described in the input file with reference the lmf data base -------------------------------------------------------*/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "lmf.h" /**** Function correctUnknowField ****/ int correctUnknownField(i8 field[charNum]) { int result = 0; i8 answer[charNum], headerFileName[charNum]; while (result == 0) { initialize(answer); if (strlen(field) >= charNum) { printf(ERROR4, (charNum - 1)); printf(ERROR5, cchFileName); return (EXIT_FAILURE); } initialize(headerFileName); strcpy(headerFileName, HEADER_FILE); printf(ERROR34, field, headerFileName); printf("Correct this field ? (y/n): "); if (gets(answer) == 'y') { result = 1; break; } else if (answer[0] == 'n') { result = 2; break; } } return (result); }
C
#include "bmp.h" #include <stdio.h> #include <string.h> bmp_t* bmp_init(char *image){ int fd, success, mask = 0b1101; bmp_t *bmp = malloc(sizeof(bmp_t)); if( (fd = open(image, O_RDONLY)) == -1 ){ return NULL; } if( (success = pread(fd, bmp, BMP_HEADER_SIZE, 0)) <= 0 ){ return NULL; } reverse_endian(sizeof(bmp->magic), &bmp->magic); if( bmp->magic != BMP_MAGIC ){ return NULL; } bmp->colorTableSize = 0; bmp->colorTable = NULL; //Check if bitsPerPx is 1,4, or 8 and that the dataOffset is greater than the header size //bigger chance of a color Table actually existing if( (bmp->bitsPerPx & mask) >= 1 && bmp->dataOffset > BMP_HEADER_SIZE ){ //set color table size bmp->colorTableSize = pow(2, bmp->bitsPerPx)*4; //nPixels (4 bytes per px) bmp->colorTable = calloc(bmp->colorTableSize, sizeof(uint8_t)); //printf("COLOR TABLE! %d ---- %d ----- %d --- %p (%d)\n\n", (bmp->bitsPerPx&mask), bmp->dataOffset, BMP_HEADER_SIZE, bmp->colorTable, bmp->colorTableSize); success = pread(fd, &bmp->colorTable, bmp->colorTableSize, BMP_HEADER_SIZE); } bmp->data = calloc(bmp->dataSize, sizeof(uint8_t)); if( (success = pread(fd, bmp->data, bmp->dataSize, bmp->dataOffset)) == -1 ){ return NULL; } //bmp->reserved = 0xA0000000; //0001 1101 1001 0000 0010 1010 0111 0111 close(fd); return bmp; } void reverse_endian(uint64_t size, void* value){ char *result = (char*)calloc(size, sizeof(char)); for( int i = 0; i < size; ++i ){ result[i] = ((char*)value)[size-i-1]; } for( int i = 0; i < size; ++i ){ ((char*)value)[i] = result[i]; } } void bmp_print(bmp_t* bmp){ uint32_t reserved = 0xFF000000, startFree = (bmp->reserved)&(~reserved); uint8_t fileCount = ((bmp->reserved)&(reserved))>>24; fprintf(stderr, "MAGIC: %" PRIx16 "\n" "SIZE: %" PRIu32 "\n" "RESERVED: %" PRIu32 "\n" "FILE COUNT (RESERVED): %" PRIu8 "\n" "START OF FREE (RESERVED) %" PRIu32 "\n" "START OF PIXEL(S): %" PRIu32 "\n" "HEADER SIZE: %" PRIu32 "\n" "WIDTH: %" PRIu32 "\n" "HEIGHT: %" PRIu32 "\n" "PLANE(S): %" PRIu16 "\n" "BITS PER PIXEL: %" PRIu16 "\n" "COMPRESSION: %" PRIu32 "\n" "PIXEL TOTAL SIZE: %" PRIu32 "\n" "X RESOLUTION: %" PRId32 "\n" "Y RESOLUTION: %" PRId32 "\n" "N COLOR(S): %" PRIu32 "\n" "N COLOR(S) IMPORTANT: %" PRIu32 "\n", bmp->magic, bmp->imageSize, bmp->reserved, fileCount, startFree, bmp->dataOffset, bmp->hdrSize, bmp->width, bmp->height, bmp->planes, bmp->bitsPerPx, bmp->compression, bmp->dataSize, bmp->xResolution, bmp->yResolution, bmp->nColors, bmp->nColorsImportant); } int bmp_write_data(bmp_t *bmp, uint8_t *data, uint64_t size, uint8_t mode){ uint32_t mask = 0xFC, reserved = 0xFF000000, startFree = (bmp->reserved)&(~reserved), i, j, k; uint8_t fileCount = ((bmp->reserved)&(reserved))>>24; i = startFree; j = k = 0; switch(mode){ case 0: //1:1 if( size+startFree > bmp->dataSize){ return -1; } for( i = startFree; i < size; ++i ){ bmp->data[i] = data[i]; } break; case 1: //lsb2 if( (size*4)+startFree > bmp->dataSize ){ return -1; } while( i < size ){ for( k = 0; k < 8; k+=2 ){ bmp->data[i] &= mask; bmp->data[i] |= ((data[j]>>k)&(~mask)); ++i; } ++j; } break; default: return 0; } ++fileCount; //per function call should be a per file. startFree += i; //set new position of free byte. memset(&reserved, 0, sizeof(uint32_t)); reserved = (reserved|fileCount)<<24; reserved = (reserved|startFree); bmp->reserved = reserved; return 1; } void bmp_free(bmp_t* bmp){ if( bmp->colorTable != NULL ){ free(bmp->colorTable); } free(bmp->data); free(bmp); } int bmp_out(bmp_t *bmp, char *name){ int fd, success; //reverse-reverse magic reverse_endian(sizeof(bmp->magic), &bmp->magic); if( (fd = open(name, O_WRONLY|O_CREAT|O_TRUNC, 0700)) == -1 ){ return 0; } if( (success = write(fd, bmp, BMP_HEADER_SIZE)) <= 0 ){ return 0; } if( bmp->colorTable != NULL && (success = write(fd, bmp->colorTable, bmp->colorTableSize)) <= 0 ){ return 0; } if( (success = write(fd, bmp->data, bmp->dataSize)) <= 0 ){ return 0; } close(fd); return 1; }
C
/* * mash_profile.c * * Created on: 19 nov 2015 * Author: rmcar */ #define _GNU_SOURCE #include <stdint.h> #include <stdio.h> #include <unistd.h> #include <time.h> #include <string.h> #include <assert.h> #include "control.h" #include "data_logger.h" #include "mash_profile.h" #include "profile_reader.h" /* * Tw = (.41/r)(T2 - T1) + T2 * * r = 4 [kg water] / 1.3 [kg grains] = 2.8 * * thermodynamic constant = 0.41 * * T1 = grain temp * T2 = target mash temp * * Tw = strike water temp * */ #define mash_water_volume ((double)(3.9)) #define grain_weight ((double)(1.3)) const double r = (mash_water_volume/grain_weight); const double grain_temp = 20; const double tdc = 0.41; int state; enum state_t { INIT, WAIT_FOR_GRAINS, MASHING, HEATING, DONE }; mash_profile_t mp[MAX_MASH_STEPS]; int mash_step = 0; int nrof_mash_steps = 10; time_t step_start = 0; void handle_heating() { if (control_get_state() == CONTROL_STABLE) { state = MASHING; printf( "Heating done, for %s at %.1lf C. Will stay for %.0lf minutes.\n", mp[mash_step].name, mp[mash_step].temp, mp[mash_step].time); } } void handle_done() { } void handle_mashing() { time_t now = time(NULL); if (step_start == 0) step_start = time(NULL); double diff_time = difftime(now, step_start); if (diff_time >= (double) (mp[mash_step].time * 60)) { step_start = 0; mash_step++; if (mash_step >= nrof_mash_steps) { state = DONE; printf("Mash done\n"); da_dump(); control_set_target(0); } else { state = HEATING; control_set_target(mp[mash_step].temp); printf("Starting next step, %s. Heating to %.1lf C\n", mp[mash_step].name, mp[mash_step].temp); } } } void handle_wait_for_grains() { char *line = NULL; size_t size; /* Reset temperature control from strike water temperature to first mash step temperature */ control_set_target(mp[0].temp); printf( "Strike water temperature reached, targeting first mash step at %.1lf C. Please add grains.\n", mp[0].temp); printf("Hit any key when done.\n"); (void) getline(&line, &size, stdin); printf("Starting first mash step, %s, at %.lf C\n", mp[mash_step].name, mp[mash_step].temp); state = MASHING; } void handle_init() { if (control_get_state() == CONTROL_STABLE) state = WAIT_FOR_GRAINS; } void mash_init() { memset(&mp[0], 0, (sizeof(mash_profile_t) * MAX_MASH_STEPS)); read_mash_profile(&mp[0], &nrof_mash_steps); temperature_t strike_water_temp = (tdc / r) * (mp[0].temp - grain_temp) + mp[0].temp; printf( "Heating to strike water temperature at %.1lf C to hit first mash step, %s, at %.1lf C\n", strike_water_temp, mp[0].name, mp[0].temp); control_set_target(strike_water_temp); state = INIT; } void mash_exec() { switch (state) { case INIT: handle_init(); break; case WAIT_FOR_GRAINS: handle_wait_for_grains(); break; case HEATING: handle_heating(); break; case MASHING: handle_mashing(); break; case DONE: handle_done(); break; default: assert(0); break; } }
C
// Meant to be played on Terminal not 'command prompt' // // Simple Model of typing master program // // Maximum Custom Keys Size is 500 #include<stdio.h> #include<string.h> #include<stdlib.h> #include<time.h> #include <sys/time.h> int scoreNT; char all[500]; void doitcap(char *ch){ int len = strlen(ch), i; for(i=0; i<len; i++){ all[i] = ch[i]; } all[i] = '\0'; } void home(){ char ch[16] = "asdf g h jkl;'j"; doitcap(ch); } void bttm(){ char ch[16] = "zxcvbn m ,./ "; doitcap(ch); } void topd(){ char ch[20] = "qwe rtyu iop "; doitcap(ch); } void nmbr(){ char ch[20] = "1234 56789 0-= "; doitcap(ch); } void hobo(){ char ch[] = "asdf ghjk l;'z xcvbn m,./"; doitcap(ch); } void hoto(){ char ch[] = "asdf ghjkl;'qw ertyu io p[]"; doitcap(ch); } void boto(){ char ch[] = "z xcvbn m,./qw ertyu iop[]"; doitcap(ch); } void honu(){ char ch[] = "as dfghj kl;'123 45678 90-="; doitcap(ch); } void altr(){ char ch[] = "asdfg hjkl zxcv bnm qwe rtyuio p"; doitcap(ch); } void arws(){ char ch[] = "z xcvb nm,./a sdf ghjk l;'qw ert yuio p[]1 234 567 890-="; doitcap(ch); } void custom(int i){ system("clear"); char c; if(!i)printf("Press Your keys to play with\n"); else printf("You Are in onthespot customize mode\n"); printf("press escape key to end your input\n\n"); while(1){ system("/bin/stty raw"); c = getchar(); system("/bin/stty cooked"); if(c == 27){all[i] = '\0'; break;} all[i++] = c; } system("clear"); printf("Now Play The Game :)\n\n"); } void about(); void tricks(); int increaseString(char* str); char interface(); void PlayNT(); int main(){ system("clear"); char choice; while(1){ choice = interface(); switch(choice){ case '0': home();PlayNT();break; case '1': bttm();PlayNT();break; case '2': topd();PlayNT();break; case '3': nmbr();PlayNT();break; case '4': hobo();PlayNT();break; case '5': hoto();PlayNT();break; case '6': boto();PlayNT();break; case '7': honu();PlayNT();break; case '8': altr();PlayNT();break; case '9': arws();PlayNT();break; case 'c': case 'C': custom(0);PlayNT();break; case 'h': tricks();break; case 'q': case 'x': case 'Q': case 'X': return 0; default : break; } } return 0; } char interface(){ printf("+----------------------------+\n\n"); printf("To Improve Your Typing Skills.\n\n"); printf("We Present Letter Typing Program.\n\n"); printf("Press escape key to leave the game at any point\n\n"); printf("Wrong key leads to negative marks\n\n"); printf("Press any of these keys as your choice\n"); printf("==> 0. Home Row\n"); printf("==> 1. Bottom Row\n"); printf("==> 2. Top Row\n"); printf("==> 3. Number Row\n"); printf("==> 4. 0 & 1\n"); printf("==> 5. 0 & 2\n"); printf("==> 6. 1 & 2\n"); printf("==> 7. 0 & 3\n"); printf("==> 8. All Letters\n"); printf("==> 9. All Rows\n"); printf("==> c. custom random keys\n"); printf("==> h. geeky tricks\n"); printf("==> Q or X to exit\n"); char input; system("/bin/stty raw"); input = getchar(); system("/bin/stty cooked"); system("clear"); return input; } void PlayNT(){ scoreNT = 0; char str[15], input, lenall=strlen(all); int get; str[14] = '\0'; srand(time(0)); for(int i=0; i<14; i++) str[i] = all[rand()%lenall]; while(1){ printf("Score : '%d'\n\n", scoreNT); printf("%s\n", str); system("/bin/stty raw"); input = getchar(); system("/bin/stty cooked"); system("clear"); if(input == str[0]){ scoreNT++; get = increaseString(str); str[13] = all[get%lenall]; }else{ printf("==> Scored : %d\n\n", scoreNT); if(input == 27){scoreNT = 0; return ;} scoreNT--; if(input == 127){custom(lenall); lenall=strlen(all);} else{ system("clear"); printf("WRONG!!!\n\n"); } } } } int increaseString(char* str){ for(int i=1; i<14; i++) str[i - 1] = str[i]; struct timeval time; gettimeofday(&time,NULL); srand((time.tv_sec * 100) + (time.tv_usec / 100)); // srand(time(0)); int a = rand()%26 , b = rand()%10; return a*(2*b + 1); } void tricks(){ char ch; printf("NOTE: This game is only designed to be played with all TEN fingers\n"); printf(" It's Just to improve your typing skill\n"); printf(" small finger or ring finger becomes useless in typing (beginers)\n"); printf("\n1. You can press 'backspace' key anywhere in the game.\n"); printf(" And You will be able to customize Your Keys on the spot.\n"); printf("2. In customization Edit mode repeating the same key, will\n"); printf(" increase it's chances as many times in the game.\n"); printf("3. customize keys to 'zaqw.;p' and try to play only with your small\n"); printf(" fingers :).DO IT for any fingers which you feel useless in typing\n"); printf(" "); printf("\npress '0' to know about the gamemaker\n"); printf("press anyother key to return\n"); system("/bin/stty raw"); ch = getchar(); system("/bin/stty cooked"); system("clear"); if(ch == '0') about(); } void about(){ char ch; printf(" V 1.0\n"); printf("\n -->Vivek Kumar Gupta<--\n"); printf("--->vivekgt@iitk.ac.in<---\n"); printf("--->B.Tech 1stYear cse<---\n"); printf(" IIT KANPUR\n"); printf("\nPress any key to return game.\n"); system("/bin/stty raw"); ch = getchar(); system("/bin/stty cooked"); system("clear"); }
C
/* * File: hash.h * Author: gferreira * * Created on June 22, 2017, 2:57 PM */ #ifndef HASH_H #define HASH_H #ifdef __cplusplus extern "C" { #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #define MAXP 640 #define MAXT 12700 int linha = 1; int flag = 0; typedef struct palavra palavra_t; struct palavra { char palavra[MAXP]; int qtd; int ocorrencias[MAXP]; palavra_t *prox; }; typedef palavra_t * hash[MAXT]; static int le_palavra(FILE *fp, char *s) { char c; int i = 0; if(flag==1){ linha++; flag=0; } while ((c = fgetc(fp)) != EOF) { if (isalpha(c)) break; if (c == '\n') { linha++; } } if (c == EOF) { return 0; } else { s[i++] = c; } while (i < MAXT - 1 && (c = fgetc(fp)) != EOF && (isalpha(c))) { s[i++] = c; } s[i] = '\0'; if(c != '\n') return 1; if (c == '\n') { flag=1; } return 1; } static void inicializa(hash tab) { int i; for (i = 0; i < MAXT; i++) tab[i] = NULL; } static int f_hash(char *s) { int i; int total = 0; for (i = 0; s[i] != '\0'; i++) total += s[i]; return total % MAXT; } static palavra_t *acessa(hash tab, char *s) { palavra_t *p; int h = f_hash(s); if (tab[h] == NULL) { p = (palavra_t *) malloc(sizeof (palavra_t)); strcpy(p->palavra, s); p->qtd = 0; p->prox = NULL; tab[h] = p; return p; } for (p = tab[h]; p != NULL; p = p->prox) { if (strcmp(p->palavra, s) == 0) return p; } p = (palavra_t *) malloc(sizeof (palavra_t)); strcpy(p->palavra, s); p->qtd = 0; p->prox = tab[h]; tab[h] = p; return p; } static int cont_elems(hash tab) { int i; int total = 0; palavra_t *p; for (i = 0; i < MAXT; i++) { for (p = tab[i]; p != NULL; p = p->prox) total++; } return total; } static palavra_t ** cria_vet(int n, hash tab) { int i, j = 0; palavra_t *p; palavra_t **vet = (palavra_t **) malloc(sizeof (palavra_t *) * n); for (i = 0; i < MAXT; i++) { for (p = tab[i]; p != NULL; p = p->prox) vet[j++] = p; } return vet; } static int compara(const void *v1, const void *v2) { palavra_t ** p1 = (palavra_t **) v1; palavra_t ** p2 = (palavra_t **) v2; //if ((*p1)->qtd > (*p2)->qtd) return -1; if (strcmp((*p1)->palavra, (*p2)->palavra) < 0) return -1; //else if ((*p1)->qtd < (*p2)->qtd) return 1; else if (strcmp((*p1)->palavra, (*p2)->palavra) > 0) return 1; else if (strcmp((*p2)->palavra, (*p2)->palavra) == 0) return 0; } static void imprime_ordenado(hash tab) { int i, j; int qtd; palavra_t **vet; qtd = cont_elems(tab); vet = cria_vet(qtd, tab); qsort(vet, qtd, sizeof (palavra_t **), compara); for (i = 0; i < qtd; i++) { printf("%15s ", vet[i]->palavra); for (j = 0; j < (vet[i]->qtd); j++) { printf("%d ", vet[i]->ocorrencias[j]); } printf("\n"); } } static void inicializaHash(FILE*fp,char*palavra,hash tabela){ inicializa(tabela); while (le_palavra(fp, palavra)) { palavra_t *p = acessa(tabela, palavra); if(p->ocorrencias[p->qtd-1]!=linha){ p->ocorrencias[p->qtd] = linha; p->qtd++; } } } static void busca(FILE*fp,hash tabela,char* palavra){ rewind(fp); char buffer[20480]; //linha inteira palavra_t *p = acessa(tabela, palavra); int j=0; for (int i = 0; i < p->qtd; i++) { for (j = 0; j < (p->ocorrencias[i]); j++) { fgets (buffer, 20480, fp); } printf("%d - ",j); puts(buffer); rewind(fp); } } static void buscaLinha(FILE*fp,int linha){ rewind(fp); char buffer[20480]; //linha inteira int i; for (i = 0; i < linha; i++) { fgets (buffer, 20480, fp); //printf("%d - ",j); //puts(buffer); } //rewind(fp); printf("%d - ",i); puts(buffer); } int contains(int* vector,int size,int number){ for (int i = 0; i < size; i++) { if(number==vector[i]){ return 1; } } return 0; } #ifdef __cplusplus } #endif #endif /* HASH_H */
C
#include<stdio.h> #include <stdlib.h> struct node { int data; struct node *next; }; struct node *head1 = NULL; struct node *head2 = NULL; void merge() { struct node *temp1 = head1; struct node *temp2 = head2; struct node *holder1 = NULL; struct node *holder2 = NULL; while(temp1!=NULL && temp2!=NULL) { holder1=temp1->next; temp1->next=temp2; if(holder1!=NULL) { holder2=temp2->next; temp2->next=holder1; } temp1=holder1; temp2=holder2; } } void print(struct node *temp) { while(temp!=NULL) { printf("%d ",temp->data); temp=temp->next; } } int main() { struct node *one = (struct node*)malloc(sizeof(struct node)); struct node *two = (struct node*)malloc(sizeof(struct node)); struct node *three = (struct node*)malloc(sizeof(struct node)); struct node *four = (struct node*)malloc(sizeof(struct node)); struct node *five = (struct node*)malloc(sizeof(struct node)); struct node *six = (struct node*)malloc(sizeof(struct node)); struct node *seven = (struct node*)malloc(sizeof(struct node)); head1=one; head2=two; //head1 points to first node of first linked list //head2 points to first node of second linked list one->data=1; one->next=three; two->data=2; two->next=four; three->data=3; three->next=five; four->data=4; four->next=six; five->data=5; five->next=NULL; six->data=6; six->next=NULL; //Last node of second input linked list seven->data=7; seven->next=NULL; printf("\nBefore Merging\n"); printf("\nInput: Linked List A: "); print(head1); printf("\nInput: Linked List B: "); print(head2); merge(); printf("\n\nAfter Merging\n"); printf("\nOutput\n: Linked List in ascending order: "); print(head1); return 0; }
C
#include<stdio.h> main() { int i,a=0,d=0,h; char res[100000]; scanf("%d%s",&h,&res); for(i=0;i<h;i++) { if(res[i]=='A') a++; else d++; } if(a>d) printf("Anton"); else if(d>a) printf("Danik"); else printf("Friendship"); }
C
/* ============================================================================ Name : GPuzzle.c Author : Tiangang Liu Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> void remove_a_double_b(char *s) { int read_ptr=0; int length=strlen(s); int b_cnt=0; int write_ptr=0; printf("Input:%s\n", s); while (read_ptr<length) { while (s[read_ptr]=='A') read_ptr++; if (write_ptr!=read_ptr) s[write_ptr]=s[read_ptr]; if (s[write_ptr]=='B') b_cnt++; read_ptr++; write_ptr++; } s[write_ptr]='\0'; printf("phase 1: %s\, b counter:%d \n", s,b_cnt); if (b_cnt==0) return; read_ptr=write_ptr; write_ptr+=b_cnt; while (read_ptr>=0 && b_cnt>0) { s[write_ptr]=s[read_ptr]; if (s[write_ptr]=='B') { write_ptr--; s[write_ptr]='B'; b_cnt--; } write_ptr--; read_ptr--; } printf("phase 2: %s\n", s); } int main(void) { char buf[1024]; int i; char *str[]={"AABBCCCDDD","AAAA","CCDD","BBCAA","ABABAA","BBB","CCCCBBB","AACCCCBBB"}; for (i=0;i<8;i++) { strcpy(buf,str[i]); remove_a_double_b(buf); //printf("Input: %s, Output %s\n",str[i],buf); memset(buf,0,1024); } return EXIT_SUCCESS; }
C
#include <stdio.h> #include <stdlib.h> int main() { int i,quantH,QuantM; char genero; QuantM = quantH = 0; float altura,media; float maiorAl = 0,menorAL = 1000; float somaAL = 0; for(i=1;i<=4;i++){ printf("Qual seu genero: H/M\nDigite aqui: "); scanf(" %c",&genero); printf("Digite sua Altura: "); scanf("%f",&altura); if(genero == 'H'){ quantH = quantH + 1; }else if(genero == 'M'){ QuantM = QuantM + 1; somaAL = somaAL + altura; } if(altura>maiorAl){ maiorAl = altura; }else if(altura < menorAL){ menorAL = altura; } } system("CLS"); media = somaAL/QuantM; printf("A media das alturas das mulheres e igual a %.2f\n",media); printf("A quantidade de homens e %d\n",quantH); printf("A menor altura e %.2f\n",maiorAl); printf("A menor altura e %.2f",menorAL); return 0; }
C
#include "magnetometer.h" #define MAGNETOMETER_ADDRESS 0x1E static int16_t offsets[3]; void magnetometer_init(){ twi_init(); uint8_t message[2]; message[0] = 0x00; //Register 0 message[1] = 0x78; //8 sample average, 75 Hz, normal mode twi_write_to(MAGNETOMETER_ADDRESS, message, 2, TWI_BLOCK, TWI_STOP); message[0] = 0x01; //Register 1 message[1] = 0x20; //Gain 1 (± 1.3 Ga) twi_write_to(MAGNETOMETER_ADDRESS, message, 2, TWI_BLOCK, TWI_STOP); message[0] = 0x02; //Register 2 message[1] = 0x00; //Comtinuous measurement mode twi_write_to(MAGNETOMETER_ADDRESS, message, 2, TWI_BLOCK, TWI_STOP); int16_t data[3]; magnetometer_read_raw(data); //Disregard first reading after changing mode } void magnetometer_set_offsets(int16_t x, int16_t y, int16_t z){ offsets[0] = x; offsets[1] = y; offsets[2] = z; } void magnetometer_read_raw(int16_t* data){ uint8_t message[6]; message[0] = 0x06; twi_read_from(MAGNETOMETER_ADDRESS, message, 6, TWI_STOP); data[0] = (((uint16_t) message[0]) << 8 | message[1]) + offsets[0]; data[1] = (((uint16_t) message[4]) << 8 | message[5]) + offsets[1]; data[2] = (((uint16_t) message[2]) << 8 | message[3]) + offsets[2]; message[0] = 0x03; twi_write_to(MAGNETOMETER_ADDRESS, message, 1, TWI_BLOCK, TWI_STOP); } double magnetometer_read_heading(){ int16_t data[3]; magnetometer_read_raw(data); return atan2(data[1], data[0]); }
C
#include <stdio.h> void func(); int sum; int main() { int var1; int *var2 = &var1; var1 = 1; sum = var1 + *var2; func(); printf("sum = %d\n", sum); return 0; }
C
#include <osal.h> #include <httpd.h> /* A simple example that demonstrates how to create GET and POST handlers for * the web server. */ #define HELLO_WORLD "Hello World!" /* An HTTP GET handler */ int hello_get_handler(httpd_req_t *req) { /* Send a simple response */ httpd_resp_send(req, HELLO_WORLD, strlen(HELLO_WORLD)); return OS_SUCCESS; } struct httpd_uri get_handler = { .uri = "/hello", .get = hello_get_handler }; /* An HTTP POST handler */ int echo_post_handler(httpd_req_t *req) { char buf[100]; int ret; /* Read the data for the request */ ret = httpd_req_recv(req, buf, sizeof(buf)); if (ret < 0) return -OS_FAIL; buf[ret] = '\0'; /* Send back the same data */ httpd_resp_send(req, buf, strlen(buf)); return OS_SUCCESS; } struct httpd_uri post_handler = { .uri = "/echo", .post = echo_post_handler }; int main() { /* Start the web server */ httpd_start(); httpd_register_uri_handler(&get_handler); httpd_register_uri_handler(&post_handler); /* The httpd_start(), starts a new thread. Make sure the process doesn't * terminate killing that thread */ othread_delete(); return 0; }
C
#include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node *next; } node; void getLength(node **head) { if (*head == NULL) printf("list is empty"); else { int count = 0; node *cur = *head; do { count++; cur = cur->next; } while (cur != *head); printf("\ntotal : %d",count); } } void traverse(node **head) { if (*head == NULL) printf("list is empty"); else { node *cur = *head; do { printf("element : %d\n", cur->data); cur = cur->next; } while (cur != *head); } } void insertAtEnd(node **head) { node *newnode = (struct node *)malloc(sizeof(struct node)); printf("enter the data : "); scanf("%d", &newnode->data); if (*head == NULL) { *head = newnode; newnode->next = *head; } else { node *cur = *head; while (cur->next != *head) cur = cur->next; cur->next = newnode; newnode->next = *head; } } void insertAtBeginning(node **head) { node *newnode = (struct node *)malloc(sizeof(struct node)); printf("enter the data : "); scanf("%d", &newnode->data); newnode->next = *head; node *cur = *head; while (cur->next != *head) { printf("element : %d\n", cur->data); cur = cur->next; } cur->next = newnode; *head = newnode; } void deleteAtEnd(node **head) { if (*head == NULL) printf("list is empty"); else { node *cur = *head; while (cur->next->next != *head) { cur = cur->next; } node *temp = cur->next; cur->next = cur->next == cur ? *head = NULL : *head; free(temp); } } void deleteAtBeginning(node **head) { if (*head == NULL) printf("list is empty"); else { node *cur = *head; while (cur->next != *head) { cur = cur->next; } node *temp = cur->next; cur->next = (*head)->next; *head = (*head)->next == *head ? NULL : (*head)->next; free(temp); } } int main() { struct node *head = NULL; int choice; while (1) { printf("\n\n---->MENU<----\n"); printf("1.Insert at end\n"); printf("2.Insert at beginning\n"); printf("3.Delete from end\n"); printf("4.Delete from beginnig\n"); printf("5.Traverse\n"); printf("6.Get Length\n"); printf("7.Exit\n"); printf("\n"); printf("Enter the choice\n"); scanf("%d", &choice); switch (choice) { case 1: insertAtEnd(&head); break; case 2: insertAtBeginning(&head); break; case 3: deleteAtEnd(&head); break; case 4: deleteAtBeginning(&head); break; case 5: traverse(&head); break; case 6: getLength(&head); break; case 7: exit(1); break; default: printf("invalid input..."); } } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include "dico.h" int piocherMot(char *motPioche) { FILE* dico = NULL; /*Le ponteur de fichier qui va contenir notre fichier*/ int nombreMots = 0, numMotChoisi = 0, i = 0; int caractereLu = 0; dico = fopen("dico.txt", "r"); /*On ouvre en lecture seule*/ /*On vérifie si on a reussi à ouvrir le dictionnaire*/ if(dico == NULL) /*Si on n'a pas reussi à ouvrir le dictionnaire*/ { printf("\nImpossible de charger le dictionnaire de mots"); return 0; /*On retourne 0 pour indiquer que la fonction a échoué*/ /*A la lecture du return, la fonction s'arrête immédiatement*/ } /*On compte le nombre de mots dans le fichier (il suffit de compter les entrées \n*/ do { caractereLu = fgetc(dico); if(caractereLu == '\n') nombreMots++; } while(caractereLu != EOF); numMotChoisi = nombreAleatoire(nombreMots); /*On pioche un mot au hasard*/ /*On recommence à lire le fichier depuis le début. On arrête lorsqu'on est arrivé au bon mot*/ rewind(dico); while(numMotChoisi > 0) { caractereLu = fgetc(dico); if(caractereLu == '\n') numMotChoisi--; } }
C
// Copyright (c) 2018, Tobechukwu Osakwe. // // All rights reserved. // // Use of this source code is governed by an // MIT-style license that can be found in the LICENSE file. #include <stdlib.h> #include <string.h> #include "stack.h" #include "vm.h" bonobo_stack_entry_t *bonobo_stack_top(bonobo_vm_t *vm) { bonobo_stack_t *stack = &vm->stack; return &stack->entries[stack->index]; } bonobo_stack_entry_t *bonobo_stack_pop(bonobo_vm_t *vm) { bonobo_stack_t *stack = &vm->stack; bonobo_stack_entry_t *entry = bonobo_stack_top(vm); if (stack->index > 0) stack->index--; return entry; } int bonobo_stack_push(bonobo_vm_t *vm, bonobo_object_t *data) { bonobo_stack_t *stack = &vm->stack; if (stack->index >= stack->size) return EXIT_FAILURE; bonobo_object_t *object = (bonobo_object_t *) bonobo_vm_allocate(vm, sizeof(bonobo_object_t)); memcpy(object, data, sizeof(bonobo_object_t)); size_t index = stack->index++; bonobo_vm_deallocate(vm, stack->entries[index].data); stack->entries[index].data = object; return EXIT_SUCCESS; }
C
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include "./sound_medium.h" #include "./lt.h" #include "./error.h" struct sound_medium_t { lt_t *lt; }; sound_medium_t *create_sound_medium_from_folder(const char *folder_path) { assert(folder_path); lt_t *lt = create_lt(); if (lt == NULL) { return NULL; } sound_medium_t *sound_medium = PUSH_LT(lt, malloc(sizeof(sound_medium_t)), free); if (sound_medium == NULL) { throw_error(ERROR_TYPE_LIBC); RETURN_LT(lt, NULL); } sound_medium->lt = lt; return sound_medium; } void destroy_sound_medium(sound_medium_t *sound_medium) { assert(sound_medium); RETURN_LT0(sound_medium->lt); } int sound_medium_play_sound(sound_medium_t *sound_medium, const char *sound_name, point_t position) { assert(sound_medium); assert(sound_name); (void) position; return 0; } int sound_medium_listen_sounds(sound_medium_t *sound_medium, point_t position) { assert(sound_medium); (void) position; return 0; }
C
#ifndef SRAM_H #define SRAM_H #include <stdint.h> /** * @brief Write to SRAM address * * @param address Address in SRAM * @param data Data to be sent * @return 0 if successful, 1 if errors occured */ int sram_write(uint16_t address, char data); /** * @brief Read from SRAM address * * @param address Address in SRAM * @return char */ char sram_read(uint16_t address); /** * @brief Initialize SRAM * */ void sram_init(void); #endif
C
#include <sys/types.h> #include <sys/uio.h> #include <unistd.h> #include <stdio.h> #include <math.h> /** * Read a positive number (excluding 0) from STDIN. * Stops at the first position which is not a digit * between 1..9 * * @return the number or 0 if nothing to read from STDIN. */ int read_num() { char buf; int num = 0; while (read(STDIN_FILENO, &buf, sizeof(buf))) { /* skip all leading white spaces / new lines */ if ((buf == ' ' | buf == '\n') && num == 0) continue; if (!('0' <= buf && buf <= '9')) return num; num *= 10; num += buf - '0'; } return num; } int calc_cycle_length(int cycle, int num) { if (num == 1) return cycle; if (num%2 == 0) { return calc_cycle_length(++cycle, num/2); } else { return calc_cycle_length(++cycle, 3*num+1); } } int main() { char buf; int a = read_num(); int b = read_num(); int longest_cycle = 0; int cycle; while (a > 0) { int i; int start = a < b ? a : b; int end = a > b ? a : b; for (i = start; i <= end; i++) { cycle = calc_cycle_length(1, i); if (cycle > longest_cycle) longest_cycle = cycle; } printf("%d %d %d\n", a, b, longest_cycle); longest_cycle = 0; a = read_num(); b = read_num(); } return 0; }
C
#include <stdio.h> #include <stdlib.h> struct node { int key; struct node *left, *right; }; struct node* newnode(int value) { struct node* temp = (struct node*)malloc(sizeof(struct node)); node->key = value; node->right= NULL; node->left = NULL; return temp; } void traverse_func(struct node* root) { if(root!=NULL) { traverse_func(root->left); printf("%d \n", root->key); traverse_func(root->right); } } struct node* insert_func(struct node* node, int key) { if(node==NULL) { return newnode(key); } if(key > node->key) { node->right = insert_func(node->right, key); } else if(key< node->key) { node->left = insert_func(node->left, key); } return node; } void main() { struct mode* root = NULL; root = insert_func(root, 45); insert(root, 70); insert(root,65); insert(root, 80); insert(root, 95); insert(root, 12); insert (root, 25); traverse_func(root); }
C
/*------------------------------------------------------------------------------ TEST.C: ISD51 Demo for TI MSC 1210 Copyright 2003 Keil Software, Inc. ------------------------------------------------------------------------------*/ #include <REG1200.H> #include <intrins.h> #include <stdio.h> #include "ISD51.h" #ifndef XTAL // if no XTAL defined use: #define XTAL 22118400 // XTAL frequency 22.1184 MHz #endif unsigned char xdata testarray[0x100]; // can be used to test access breakpoints (see below) unsigned char j; // On-board LEDs sbit RedLed = P3^4; sbit YellowLed = P3^5; #if 0 // uncomment this function to verify serial communication /* * Test Function: verify serial communication with HyperTerminal */ void TestSerial (void) { // for UART0 char c = 'A'; TI = 1; while (1) { if (RI) { c = SBUF; RI = 0; } while (!TI); TI = 0; SBUF = c; } } void TestSerial (void) { // for UART1 char c = 'A'; TI_1 = 1; while (1) { if (RI_1) { c = SBUF1; RI_1 = 0; } while (!TI_1); TI_1 = 0; SBUF1 = c; } } #endif // Other interrupt sources such as A/D Converter SPI, PFI // and (milli)second timer which are sharing the interrupt vector at // address 33H (interrupt 6) must be relocated to address 6BH (interrupt 13)! void AuxInterrupt (void) interrupt 6 { unsigned char x; if (AISTAT & 0x80) { // Seconds Interrupt YellowLed = !YellowLed;// toggle yellow LED x = SECINT; // dummy read to clear SECINT interrupt request flag } AI = 0; // clear auxiliary interrupt request flag } void delay(void) { long i; i = 0x1000; while(i--); } void main (void) { unsigned int i; CKCON = 0x10; // 0 MOVX cycle stretch TCON = 0; // Setup Serial Interface PCON = 0x80; SCON = 0x52; TMOD = 0x20; TH1 = 0xEE; TR1 = 1; TI = 1; //RedLed = ON; P3DDRL = 0xC0; // set port pins of UART to input/strong drive output P3DDRH = 0x00; // set port pins of UART to input/strong drive output #ifdef ISD51 // The following settings are important for ISD51 (enable flash programming, disable watchdog) USEC = ((XTAL+500000)/1000000)-1; // USEC timer factor MSEC = (XTAL/1000)-1; // (MSECH+MSCL) MS Timer counting at 1.0ms HMSEC = 100-1; // Hundred MS Timer to 100.0ms SECINT = (10-1) | 0x80; // SECINT= 10 * HMS Timer Rate = 1 sec // '0x80' will set the MSB for write immediate MSINT = (10-1) | 0x80; // MSINT = 10ms for Tone period time base FTCON = 0xA5; // setup flash programming times #endif // Setup Auxiliary Interrupts AIE = 0x81; // set EDLVB bit to enable hardware breakpoint interrupt // and ESEC bit to enable seconds interrupt //AIE = 0x01; // set EDLVB bit to enable hardware breakpoint interrupt //AIE |= 0x80; // read-modify-write instructions do not work on AIE!!! EICON |= 0x20; // enable all auxiliary interrupts EA = 1; // Enable global interrupt flag // TestSerial (); // uncomment this function to verify serial communication #if 0 // init ISD51 and start user program until the uVision2 Debugger connects ISDinit (); // initialize uVision2 Debugger and continue program run #endif #if 0 // init ISD51 and wait until the uVision2 Debugger connects ISDwait (); // wait for connection to uVision2 Debugger #endif // The lines below demonstrate in-application flash programming with boot-ROM functions. // Function entries are defined in module ROM.A51, declarations are inROM.h. See also: MWS register above. // MWS = 0x01; // enable flash programming (and disable internal RAM) // page_erase (0x3000, 0x00, 0x00); // erase a 128 byte program flash page at address 0x3000 // write_flash_byte (0x3003, 0x55, 0x00); // write 0x55 to address 0x3003 into program flash // MWS = 0x00; // disable flash programming (and disable internal RAM) // Following loop can be used to test access breakpoints: With 'BS read &testarray[10]' and hardware // breakpoints enabled, the debugger will stop in this for-loop. By default, flash breakpoints are // enabled for (i = 0; i < sizeof (testarray); i++) { j = testarray[i]; } while (1) { #if 1 // init ISD51 only when the uVision2 Debugger tries to connect ISDcheck(); // initialize uVision2 Debugger and continue program run #endif _nop_(); // these NOP's allocate space for test breakpoints. _nop_(); _nop_(); _nop_(); _nop_(); printf("Hello World\n"); _nop_(); _nop_(); _nop_(); RedLed = !RedLed; // toggle red LED _nop_(); _nop_(); _nop_(); delay(); #if 0 // you may use ISDbreak when ISD51 is started with ISDcheck or ISDwait ISDbreak (); // hard coded stop (breakpoint) #endif _nop_(); _nop_(); _nop_(); } }
C
#include "cus-common.h" int CusFileSetlock(int fd){ struct flock lk; memset(&lk,0,sizeof(lk)); lk.l_type = F_WRLCK; lk.l_whence = SEEK_SET; lk.l_start = 0; lk.l_len = 0; lk.l_pid = getpid(); int r = fcntl(fd,F_SETLK,&lk); if(r < 0){ printf("pidfile,unable to set lock.\n"); return 0; } return 1; } void CusFileUnlock(int fd){ struct flock lk; memset(&lk,0,sizeof(lk)); lk.l_type = F_UNLCK; lk.l_whence = SEEK_SET; lk.l_start = 0; lk.l_len = 0; lk.l_pid = getpid(); int r = fcntl(fd,F_SETLK,&lk); if(-1 == r){ printf("fail to unlock pidfile.\n"); } }
C
#include <stdio.h> int main(int argc, char* argv[]) { FILE* f = fopen("/tmp/out.txt", "wb"); if( f != NULL ) { fprintf(stderr, "File creation should have failed\n"); return 1; } if( mkdir("/tmp/foobar") == 0 ) { fprintf(stderr, "Directory creation should have failed\n"); return 1; } return 0; }
C
#include <detpic32.h> void configTimer(void); void configInterrupts(void); unsigned char flag = 0; int main(void){ configTimer(); configInterrupts(); while(1); return 0; } void configTimer(void){ // Configuration of Timer T1 - 2Hz T1CONbits.TCKPS = 3; PR1 = 39062; TMR1 = 0; // Reset timer 1 T1CONbits.TON = 1; // Enable timer 1 // Configuration of Timer T3 - 10 Hz T3CONbits.TCKPS = 5; PR3 = 62499; TMR3 = 0; T3CONbits.TON = 1; } void configInterrupts(void){ // Interruptions of Timer T1 IPC1bits.T1IP = 2; // Interrupt priority IEC0bits.T1IE = 1; // Enable timer T3 IFS0bits.T1IF = 0; // Reset Timer T3 // Interruptions of Timer T3 IPC3bits.T3IP = 2; // Interrupt priority IEC0bits.T3IE = 1; // Enable timer T3 IFS0bits.T3IF = 0; // Reset Timer T3 EnableInterrupts(); } void _int_(_TIMER_1_VECTOR) isr_T1(void){ putChar('1'); IFS0bits.T1IF = 0; } void _int_(_TIMER_3_VECTOR) isr_T3(void){ putChar('3'); IFS0bits.T3IF = 0; }
C
#include<stdio.h> #include<conio.h> int t,size,element[100],head; void cscan() { int i,j,temp,index,sum=0,d; for(i=0;i<size;i++) { for(j=i+1;j<size;j++) { if(element[i]>element[j]) { temp=element[i]; element[i]=element[j]; element[j]=temp; } } } for(i=0;i<size;i++) { if(element[i] >head) { index=i-1; break; } } printf("CSCAN\n"); printf("%d->",head); for(i=index;i>=0;i--) { if(head>element[i]) { d=head-element[i]; head=element[i]; sum+=d; } else { d=element[i]-head; head=element[i]; sum+=d; } printf("%d->",head); } sum+=head; head=0; printf("%d->",head); head=t-1; sum+=head; printf(%d) printf("%d->",head); for(i=head;i>=(index+1);i--) { if(head>element[i]) { d=head-element[i]; head=element[i]; sum+=d; } else { d=element[i]-head; head=element[i]; sum+=d; } printf("%d->",head); } printf("\nseek time=%d",sum); } int main() { int i; printf("enter number of tracks:"); scanf("%d",&t); printf("enter work queue size:"); scanf("%d",&size); printf("enter elements:"); for(i=0;i<size;i++) { scanf("%d",&element[i]); } printf("enter head start pos:"); scanf("%d",&head); cscan(); getch(); return 0; }
C
// // Created by edmon on 18/4/2020. // #ifndef GRUPO_4_CORREDOR_H #define GRUPO_4_CORREDOR_H #include <stdio.h> #include <string.h> #include <stdlib.h> #include "funciones_Basicas.h" /** * La estrucutra Corredor contiene los atributos particulares de cada piloto. La estructura Corredores va a almacenar * un array dinàmico de 7 pilotos. */ typedef struct{ char nombre[MAX_STRING]; int dorsal; char escuderia[MAX_STRING]; int velocidad; int aceleracion; int consumo; int fiabilidad; int reflejos; int cond_fisica; int temperamento; int gestion_neumaticos; }Corredor; typedef struct { int num_corredors; Corredor *corredores; }Corredores; /** * Función para leer el fichero con la información de corredores que se pasa por parámetro en el main * @param path la ruta podriamos decir para encontrar el fichero y poderlo abrir * @param pilotos Estructura donde vamos a guardar la información de todos los pilotos * @return Devuelve un entero que nos permitira saber si ha habido algún error a la hora de abrir el fichero */ int leerCorredores(char* path, Corredores *Pilotos); #endif //GRUPO_4_CORREDOR_H
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gtorvald <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/09/23 14:58:53 by gtorvald #+# #+# */ /* Updated: 2019/09/23 14:58:54 by gtorvald ### ########.fr */ /* */ /* ************************************************************************** */ #include "includes/checker.h" int check_nums(t_stack *a, t_stack *b, int count) { int i; if (a->size != count || b->size != 0) return (1); i = 1; while (i < a->size) { if (a->nums[i] < a->nums[i - 1]) return (1); i++; } return (0); } void read_comands_write_result(t_stack *a, t_stack *b, int count) { char *cmd; int i; i = 0; while (get_next_line(0, &cmd)) { if (ft_strcmp(cmd, "sa") && ft_strcmp(cmd, "sb") && ft_strcmp(cmd, "ss") && ft_strcmp(cmd, "pa") && ft_strcmp(cmd, "pb") && ft_strcmp(cmd, "ra") && ft_strcmp(cmd, "rb") && ft_strcmp(cmd, "rr") && ft_strcmp(cmd, "rra") && ft_strcmp(cmd, "rrb") && ft_strcmp(cmd, "rrr")) { write(2, "Error\n", 6); free(cmd); return ; } else do_comand(a, b, cmd, 0); free(cmd); } free(cmd); if (check_nums(a, b, count)) ft_putstr("KO\n"); else ft_putstr("OK\n"); } int main(int argc, char **argv) { t_stack *a; t_stack *b; char **tab; int count; count = argc - 1; tab = argv + 1; if (argc == 2) { count = count_str(argv[1], ' '); tab = ft_strsplit(argv[1], ' '); } if (argc == 1 || (argc != 2 && count == 0) || !(a = check_and_make_stack(count, tab))) { free_stacks(0, 0, &tab, argc); return (1); } b = make_stack(count, 0); if ((argc != 2 || count != 0) && !check_nums_in_stack(a)) read_comands_write_result(a, b, count); if (argc == 2 && count == 0) write(2, "Error\n", 6); free_stacks(&a, &b, &tab, argc); return (0); }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <limits.h> #define TEMP_TROPOPAUSE -56 /** * This method is a linear equation (temp = temp0 + (deltaT / deltaH) (height - height0)) * @param height0 - initial height of the layer * @param height - the input height * @param temp0 - the initial temperature in the layer * @param lapseRate * @return calculation of linear equation */ int getTemperature(double height0, double height, double temp0, double lapseRate){ return round(temp0 + lapseRate * (height - height0)); } int calculateTemperature(int height){ if (height < 0 || height > 25000){ return INT_MAX; } double heightKm = (double) height / 1000; if (heightKm >= 0 && heightKm <= 11){ return getTemperature(0, heightKm, 15, -6.5); } if (heightKm >= 11 && heightKm <= 20){ return TEMP_TROPOPAUSE; } else{ return getTemperature(20, heightKm, -56, 1); } } int main() { FILE *fptr; fptr = fopen("C:\\Users\\Tamar.LAPTOP-55EK84EJ\\Desktop\\test\\program.txt","w"); if(fptr == NULL) { printf("Error!"); exit(1); } int i = 0; while (i < 20000) { fprintf(fptr, "%d", calculateTemperature(i)); fprintf(fptr, "%c", ','); fprintf(fptr, "%d\n", i); i += 10; } fclose(fptr); return 0; }
C
#include <stdio.h> int main(int argc, char *argv[]) { /* Write your code after this line */ while (1) {int x,n; scanf ("%d",&x); while (x<0) { printf("Input number not in range, please enter again\n"); scanf ("%d",&x); } scanf("%d",&n); while ((n>=17)||(n<=1)) { printf("Input base not in range, please enter again\n"); scanf("%d",&n); } if ((n>1)&&(n<17)&&(x>0)) { while (x>0) { if ((x%n)<10) printf ("%d",(x%n)); if((x%n)==10) printf("A"); if((x%n)==11) printf("B"); if((x%n)==12) printf("C"); if((x%n)==13) printf("D"); if((x%n)==14) printf("E"); if((x%n)==15) printf("F"); x=x/n; }}} return 0; }
C
/* ȡABʾϷĿʼʱͽʱ䣬СʱΪλ ȻϷijʱ䣬֪Ϸһ쿪ʼһʱΪ24Сʱ ABȣΪ24Сʱ ʽ һУAB ʽ ʽΪO JOGO DUROU X HORA(S)XΪϷʱ䡣 ݷΧ 0A,B23 1 16 2 1 O JOGO DUROU 10 HORA(S) 2 0 0 2 O JOGO DUROU 24 HORA(S) 3 2 16 3 O JOGO DUROU 14 HORA(S) */ #include <iostream> using namespace std; int main() { int a, b; cin >> a >> b; int time; if(a == b) time = 24; else if(a > b) time = 24 - a + b; else time = b - a; cout << "O JOGO DUROU " << time << " HORA(S)"; return 0; }
C
#include<stdio.h> #include<conio.h> main() { char a,b,c,product=1; clrscr(); printf("entern the any number "); scanf("%c",&a); for (b='a';b>='a'&&b<'z';b++ ) { c=b; printf("%d",c); } getch(); }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_7__ TYPE_2__ ; typedef struct TYPE_6__ TYPE_1__ ; /* Type definitions */ struct TYPE_7__ {scalar_t__ rc; } ; struct TYPE_6__ {int /*<<< orphan*/ iSegid; } ; typedef TYPE_1__ Fts5StructureSegment ; typedef TYPE_2__ Fts5Index ; typedef int /*<<< orphan*/ Fts5Data ; /* Variables and functions */ void* FTS5_CORRUPT ; int /*<<< orphan*/ FTS5_SEGMENT_ROWID (int /*<<< orphan*/ ,int) ; scalar_t__ SQLITE_OK ; int /*<<< orphan*/ * fts5DataRead (TYPE_2__*,int /*<<< orphan*/ ) ; int /*<<< orphan*/ fts5DataRelease (int /*<<< orphan*/ *) ; scalar_t__ fts5LeafFirstRowidOff (int /*<<< orphan*/ *) ; int /*<<< orphan*/ fts5LeafIsTermless (int /*<<< orphan*/ *) ; __attribute__((used)) static void fts5IndexIntegrityCheckEmpty( Fts5Index *p, Fts5StructureSegment *pSeg, /* Segment to check internal consistency */ int iFirst, int iNoRowid, int iLast ){ int i; /* Now check that the iter.nEmpty leaves following the current leaf ** (a) exist and (b) contain no terms. */ for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){ Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i)); if( pLeaf ){ if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT; if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT; } fts5DataRelease(pLeaf); } }
C
/*************************************************************************************************** * * @author Preshit Harlikar, Shivam Khandelwal * @file project3_1.c * @brief This file includes logging functions for host and beaglebone black * @date November 23, 2017 * * long description - The logger.c file includes functions to - * 1) project3_1() * 2) data() * 3) profiling() * ***************************************************************************************************/ #include "project3_1.h" /*----- Global Variables --------------------------------------------------*/ uint8_t character_count[4]={0,0,0,0}; uint8_t char_str[4][10]; char value; uint32_t t = 1000000; time_t t0; /********************************** project3_1()********************************************************** * * @name - project3_1() * @brief - function to initialize log and other logging functions * * long description - This function executes logging for host and beaglebone black * * @return - void * ******************************************************************************************************/ /*********************************** project3_1() function definition ***********************************/ void project3_1(){ uint8_t i; uint8_t j; while(1) { printf("\n %s \t",ctime(&t0)); printf("Initialize logger (1/0): "); scanf("%d",&i); //read value from user if(i==1){ //if input is 1 then initialize log printf("\n %s \t",ctime(&t0)); printf(" Log Initialized %d\n\n",LOG_INITIALIZED); //print log initialized printf(" %s \t",ctime(&t0)); printf(" System Initialized %d\n\n",SYSTEM_INITIALIZED); //print system initialized while(1){ scanf("%d",&j); if(j==1){ //if j==1 enable data input j=0; printf(" %s \t",ctime(&t0)); printf(" Data Input Enabled %d\n\n",DATA_INPUT_ENABLED); //print data input enabled data(); } if(j==2){ //if j==2 enable profiling j=0; printf(" %s \t",ctime(&t0)); printf(" Profiling Started %d\n\n",PROFILING_STARTED); //print profiling started profiling(); printf(" %s \t",ctime(&t0)); printf(" Profiling Completed %d\n\n",PROFILING_COMPLETED); //print profiling completed } if(j==3){ //if j==3 exit loop j=0; break; } } printf(" %s \t",ctime(&t0)); printf(" System Halted %d\n\n",SYSTEM_HALTED); //print system halted } if(i==0){ break; } } } /********************************** data()********************************************************** * * @name - data() * @brief - function to take data input and display data analysis * * long description - This function takes data input from user and performs data analysis * * @return - void * ******************************************************************************************************/ /*********************************** data() function definition ***********************************/ void data(){ while(1){ scanf("\n%c",&value); //----- Check for Numeric characters -------------------------------------------- ------ if((value>47) && (value<58)){ //check ascii value for numeric character value=atoi(&value); printf(" %s \t",ctime(&t0)); printf(" Data Received %d %d\n\n",DATA_RECEIVED,value); //print the received character character_count[0]++; value=0; } //----- Check for Alphabetic characters ----------------------------------------- ------ else if(((value>64) && (value<91)) || ((value>96) && (value<123))){ //check ascii value for alphabetic character printf(" %s \t",ctime(&t0)); printf(" Data Received %d %c\n\n",DATA_RECEIVED,value); //print the received character character_count[1]++; value=0; } //----- Check for Punctuation characters ----------------------------------------- ---- else if(((value>32) && (value<46))||((value>57) && (value<61))||((value>90) && (value<97))||((value>122) && (value<127))){ //check ascii value for punctuation character printf(" %s \t",ctime(&t0)); printf(" Data Received %d %c\n\n",DATA_RECEIVED,value); //print the received character character_count[2]++; value=0; } //----- Check for Miscellaneous characters --------------------------------------------- else if(((value>90)&&(value<97))||(value==127)||(value==27)){ //check ascii value for miscellaneous characters printf(" %s \t",ctime(&t0)); printf(" Data Received %d %c\n\n",DATA_RECEIVED,value); //print the received character character_count[3]++; value=0; } //----- Check for . character - ------------------------------------------------ ------ else if(value==46){ //if '.' is pressed print analysis printf(" %s \t",ctime(&t0)); printf(" Data Analysis Started %d\n\n",DATA_ANALYSIS_STARTED); //print analysis started printf(" %s \t",ctime(&t0)); printf(" Data Alpha Count %d %d\n\n",DATA_ALPHA_COUNT,character_count[1]); //print alpha count printf(" %s \t",ctime(&t0)); printf(" Data Numeric Count %d %d\n\n",DATA_NUMERIC_COUNT,character_count[0]); //print numeric count printf(" %s \t",ctime(&t0)); printf(" Data Punc Count %d %d\n\n",DATA_PUNCTUATION_COUNT,character_count[2]); //print punctuation count printf(" %s \t",ctime(&t0)); printf(" Data Misc Count %d %d\n\n",DATA_MISC_COUNT,character_count[3]); //print miscellaneous count printf(" %s \t",ctime(&t0)); printf(" Data Analysis Completed %d\n\n",DATA_ANALYSIS_COMPLETED); //print analysis completed value=0; } if(value==47){ //if '/' is pressed disable input value=0; printf(" %s \t",ctime(&t0)); printf(" Data Input Disabled %d\n\n",DATA_INPUT_DISABLED); //print input disabled break; } } } /********************************** profiling()********************************************************** * * @name - data() * @brief - function to take data input and display data analysis * * long description - This function takes data input from user and performs data analysis * * @return - void * ******************************************************************************************************/ /*********************************** profiling() function definition ***********************************/ void profiling(){ lib_memmove_test(10); printf(" %s \t",ctime(&t0)); printf(" Info %d lib-memmove for 10 bytes\n\n",INFO); //print info lib_memmove_test(100); printf(" %s \t",ctime(&t0)); printf(" Info %d lib-memmove for 100 bytes\n\n",INFO); //print info lib_memmove_test(1000); printf(" %s \t",ctime(&t0)); printf(" Info %d lib-memmove for 1000 bytes\n\n",INFO); //print info lib_memmove_test(5000); printf(" %s \t",ctime(&t0)); printf(" Info %d lib-memmove for 5000 bytes\n\n",INFO); //print info lib_memset_test(10); printf(" %s \t",ctime(&t0)); printf(" Info %d lib-memset for 10 bytes\n\n",INFO); //print info lib_memset_test(100); printf(" %s \t",ctime(&t0)); printf(" Info %d lib-memset for 100 bytes\n\n",INFO); //print info lib_memset_test(1000); printf(" %s \t",ctime(&t0)); printf(" Info %d lib-memset for 1000 bytes\n\n",INFO); //print info lib_memset_test(5000); printf(" %s \t",ctime(&t0)); printf(" Info %d lib-memset for 5000 bytes\n\n",INFO); //print info my_memmove_test(10); printf(" %s \t",ctime(&t0)); printf(" Info %d my-memmove for 10 bytes\n\n",INFO); //print info my_memmove_test(100); printf(" %s \t",ctime(&t0)); printf(" Info %d my-memmove for 100 bytes\n\n",INFO); //print info my_memmove_test(1000); printf(" %s \t",ctime(&t0)); printf(" Info %d my-memmove for 1000 bytes\n\n",INFO); //print info my_memmove_test(5000); printf(" %s \t",ctime(&t0)); printf(" Info %d my-memmove for 5000 bytes\n\n",INFO); //print info my_memset_test(10); printf(" %s \t",ctime(&t0)); printf(" Info %d my-memset for 10 bytes\n\n",INFO); //print info my_memset_test(100); printf(" %s \t",ctime(&t0)); printf(" Info %d my-memset for 100 bytes\n\n",INFO); //print info my_memset_test(1000); printf(" %s \t",ctime(&t0)); printf(" Info %d my-memset for 1000 bytes\n\n",INFO); //print info my_memset_test(5000); printf(" %s \t",ctime(&t0)); printf(" Info %d my-memset for 5000 bytes\n\n",INFO); //print info } /********************************** lib_memmove_test()********************************************************** * * @name - lib_memmove_test() * @brief - function to perform profiling on library memmove function * * * @return - void * ******************************************************************************************************/ /*********************************** lib_memmove_test() function definition ***********************************/ void lib_memmove_test(uint32_t len){ uint32_t i=0; uint8_t source[len]; //initialize source array while(i<(len)) { source[i]=i; i++; } uint8_t destination[len]; //initialize destination array clock_t begin = clock(); memmove(source,destination,len); //library memmove function clock_t end = clock(); double time1 = (double)((end - begin)*t) / CLOCKS_PER_SEC; //calculate time printf(" %s \t",ctime(&t0)); printf(" Profiling Result %d %f\n\n",PROFILING_RESULT,time1); //print profiling result } /********************************** lib_memset_test()********************************************************** * * @name - lib_memset_test() * @brief - function to perform profiling on library memset function * * * @return - void * ******************************************************************************************************/ /*********************************** lib_memset_test() function definition ***********************************/ void lib_memset_test(uint32_t len){ uint8_t val = 10; uint8_t destination[len]; //initialize destination array clock_t begin = clock(); memset(destination,val,len); //library memset function clock_t end = clock(); double time1 = (double)((end - begin)*t) / CLOCKS_PER_SEC; //calculate time printf(" %s \t",ctime(&t0)); printf(" Profiling Result %d %f\n\n",PROFILING_RESULT,time1); //print profiling result } /********************************** my_memmove_test()********************************************************** * * @name - my_memmove_test() * @brief - function to perform profiling on my_memmove function * * * @return - void * ******************************************************************************************************/ /*********************************** my_memmove_test() function definition ***********************************/ void my_memmove_test(uint32_t len){ uint32_t i=0; uint8_t source[len]; //initialize source array while(i<(len)) { source[i]=i; i++; } uint8_t destination[len]; //initialize destination array clock_t begin = clock(); my_memmove(source,destination,len); //my_memmove fuction clock_t end = clock(); double time1 = (double)((end - begin)*t) / CLOCKS_PER_SEC; //calculate time printf(" %s \t",ctime(&t0)); printf(" Profiling Result %d %f\n\n",PROFILING_RESULT,time1); //print profiling result } /********************************** my_memset_test()********************************************************** * * @name - my_memset_test() * @brief - function to perform profiling on my_memset function * * * @return - void * ******************************************************************************************************/ /*********************************** my_memset_test() function definition ***********************************/ void my_memset_test(uint32_t len){ uint32_t val =10; uint8_t destination[len]; //initialize destination array clock_t begin = clock(); my_memset(val,destination,len); //my_memset fuction clock_t end = clock(); double time1 = (double)((end - begin)*t) / CLOCKS_PER_SEC; //calculate time printf(" %s \t",ctime(&t0)); printf(" Profiling Result %d %f\n\n",PROFILING_RESULT,time1); //print profiling result }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lherbelo <lherbelo@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/02/05 01:10:18 by lherbelo #+# #+# */ /* Updated: 2016/06/14 16:25:58 by lherbelo ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static int ft_lire(t_gnl *gnl, int fd) { int i; i = 0; while (gnl->line[fd][i] != '\n' && gnl->line[fd][i] != '\0') i++; return (i); } static void ft_saveline(t_gnl *gnl, int fd) { if (gnl->line[fd] == NULL) gnl->line[fd] = ft_strnew(1); while (!(ft_strchr(gnl->line[fd], '\n')) && (gnl->nb = read(fd, gnl->buff, BUFF_SIZE)) > 0) { gnl->buff[gnl->nb] = '\0'; gnl->tmp = gnl->line[fd]; gnl->line[fd] = ft_strjoin(gnl->line[fd], gnl->buff); ft_strdel(&gnl->tmp); } ft_strdel(&gnl->buff); } int get_next_line(int const fd, char **line) { static t_gnl gnl; if (fd < 0 || line == NULL || fd > MAX_FD || !(gnl.buff = (char *)ft_memalloc(sizeof(char) * BUFF_SIZE + 1))) return (-1); ft_saveline(&gnl, fd); if (gnl.nb == -1) return (-1); *line = ft_strsub(gnl.line[fd], 0, ft_lire(&gnl, fd)); if (ft_strchr(gnl.line[fd], '\n')) { gnl.tmp = gnl.line[fd]; gnl.line[fd] = ft_strdup(ft_strchr(gnl.line[fd], '\n') + 1); ft_strdel(&gnl.tmp); return (1); } if (ft_lire(&gnl, fd) > 0) { gnl.line[fd] = gnl.line[fd] + ft_lire(&gnl, fd); return (1); } return (0); }
C
#include <stdio.h> #include "myLib.h" #include "DataLoader.h" static dldrMethods dldr_vtable={ DataLoader_dtor, NULL, NULL, loadFrom, build }; dldr* DataLoader_ctor(){ dldr* d = (dldr *)malloc(sizeof(dldr)); if(d==NULL) mallocError("DataLoader"); d->input = NULL; d->vptr = &dldr_vtable; return d; } void DataLoader_dtor(dldr *this){ if (this != NULL) free(this); } arrayItem* loadFrom(dldr* this, arrayItem* arr, String filename){ FILE* xpto = fopen(filename, "r"); if (!xpto){ printf("Erro a ler o ficheiro: %s.\n\n",filename); exit(1); } this->input = xpto; this->vptr->build(this,arr,0); fclose(this->input); return arr; } arrayItem* build(dldr* this, arrayItem* arr, int n){ int idx=0, i=0; ItemType* item=NULL; String line ; String* elems; line = (String) malloc(sizeof(char)*MAX_LINE_SZ+1); if (line==NULL) mallocError("DataLoader"); if ((fgets(line, MAX_LINE_SZ,this->input))==NULL){ if (!feof(this->input)){ free(line); return NULL; /*THROW(IO_ERROR_EXCEPTION);*/ } else{ arr->size = n; arr->array=this->vptr->newArray(n); free(line); return arr; } } elems = (String*) malloc(sizeof(String)*MAX_ITEMS); if (elems==NULL) mallocError("DataLoader"); /*contar o num de tokens e alocar espaco do elems*/ /*assumimos que existem um maximo de MAX_ITEMS por linha*/ while((elems[idx]=strtok(line,"\\|"))!=NULL){ ++idx; line=NULL; } free(line); if(idx>0 && strlen(elems[0])>0){ for (i=0; i<idx; ++i){ elems[i]=xstrtrim(elems[i]); } item = this->vptr->newInstance(elems, idx); free(elems); } if(item != NULL){ arr = build(this,arr, n+1); /*printf("n: %i\n", n); DEBUG*/ arr->array[n] = item; return arr; } return this->vptr->build(this,arr, n); }
C
/** *@file main.c *@Author Dirk Dubois *@version 1.0 *@date Feb 12, 2011 * *@brief A C program that displays a voltage measured on RB7 using the onboard ADC *and displays it to a standard LCD display on PORTA running in 4bit mode. *The voltage at RB7 is divide by a voltage divider of (1/4) requiring a scaling of 4. *The voltage across the PIC of +5V is used to operate the ADC *For details on the hookup of the LCD see lcd.c for more information. */ /*Includes*/ #include <htc.h> #include <stdlib.h> #include "lcd.h" #include "delay.h" /*Defines*/ #define _XTAL_FREQ 4000000 /**<A define for the clock frequency*/ /*Function Prototypes*/ char *ftoa(float f, int *status); /** *@brief An initialization function that sets the Tristate registers and oscillator *The oscillator is set to a value of four mega hertz, and RB7 is set as an input *@retval None */ void init(void) { OSCCON = 0b01100000; //set internal oscillator frequency to 4 MHz TRISA = 0b00000000; //set PORTA as output for LCD TRISB = 0b10000000; //set PORTB outputs except RB7 as input ANSEL = 0x00; } /** *@brief An initalization function for the ADC on port RB7 *@retval */ void adcInit(void) { ANSEL = 0b01000000; //Sets the analogue select ports to RB7 ADCON0 = 0b11110000; //Sets ADCON0 ADCON1 = 0b10000000; //Sets ADCON1 ADON = 1; //Turn on the ADC } /** *@brief A function that starts the adc sampling *@retval None */ void adcGo(void) { GODONE = 1; while(GODONE); return; } /** *@brief A display function that takes a float and displays it to the 2nd line of the LCD. *@param[in] value The value you wish to print to the display *@retval None *@note This functions uses the lcd library */ void lcd_Display(float value) { lcd_goto(0x40); //Goto the 2nd line char *buffer; //Create a buffer for ftoa function int status; buffer = ftoa(value, &status); //Ftoa function that converts the float to a string lcd_puts(buffer); //Displays the buffer return; } /** *@brief The main function that initalizes the peripherals and displays the value returned by the adc in volts. *@retval None */ void main(void) { //Intialization function calls init(); //Intialize the PIC lcd_init(); //Initialize the lcd lcd_write(0x0C); //Turn off cursor lcd_goto(0x00); //Goto begining of the screen lcd_puts("Output Voltage"); //Display header adcInit(); //ADC setup //Values for the Voltage Meter int i; /**<Width of the Average*/ int low = 0; /**<Low end of the ADC value */ int high = 0; /**<High end of the ADC value*/ float Vin = 0; /**<To Calculate Vin*/ float Avg; /**<To Calculate the average*/ //For the duration of the program while(1) { Avg = 0; // Clear the average //Take 128 samples for the average for(i=0; i<128; i++) { adcGo(); //Start the ADC low = ADRESL; //Retrieve the ADC values high = ADRESH; high = high << 8; //Combine the high and low values of the ADC Vin = high + low; Vin = (Vin / 1024) * 5; //Scale the ADC Values w.r.t +5V Avg = Avg + Vin ; } Avg = Avg / 128; //Divide the average by its width i Avg = Avg * 4; //Convert Vin due to voltage divider circuit //Displays the voltage on the 2nd line and truncates decimal places lcd_Display(Avg); lcd_goto(0x46); lcd_puts(" Volts"); } }
C
/* * Copyright (C) 2017, Saul Lawliet <october dot sunbathe at gmail dot com> * All rights reserved. * * 两个指针, 往中间查找 */ #include <stdlib.h> /* malloc() */ #include <string.h> /* strlen(), strchr() */ #include "c/test.h" void swap(char *a, char *b) { char tmp = *a; *a = *b; *b = tmp; } char *reverseVowels(char *s) { const char *vowels = "aeiouAEIOU"; char *p1 = s, *p2 = s+strlen(s)- 1; while (p1 < p2) { if (!strchr(vowels, *p1)) { p1++; continue; } if (!strchr(vowels, *p2)) { p2--; continue; } swap(p1++, p2--); } return s; } void test(const char *expect, char *str) { int sz = strlen(str); char *s = malloc(sz + 1); strncpy(s, str, sz + 1); s = reverseVowels(s); EXPECT_EQ_STRING_AND_FREE_ACTUAL(expect, s); } int main(void) { test("holle", "hello"); test("leotcede", "leetcode"); test(".", "."); test("Aa", "aA"); return testOutput(); }
C
#define _CRT_SECURE_NO_DEPRECATE #include <stdio.h> int main() { FILE *f; char s[100],c,d; int k=0; printf("Plese, enter full way to file: "); //getchar(); gets(s); f = fopen(s, "r+t"); if (f != NULL) { while ((c = fgetc(f)) != EOF) { d = tolower(c); fseek(f, -1, SEEK_CUR); fputc(d, f); //k++; fseek(f, 0, SEEK_CUR); } fclose(f); } else { printf("Such File doesn't exists\n"); } system("pause"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> typedef unsigned int uint; /* 九九乘法表 小时候学过的九九乘法表也许将会扎根于我们一生的记忆, 现在让我们重温那些温暖的记忆,请编程输出九九乘法表. 现在要求你输出它的格式与平常的 不同啊! 是那种反过来的三角形啦,具体如下图: 每两个式子之前用一个空格 隔开。。。 输入 第一有一个整数N,表示有N组数据(N<10)接下来由N行, 每行只有一个整数M(1<=M<=9); 输出 对应每个整数M,根据要求输出乘法表的前N行, 具体格式参见输入输出样例和上图.每两组测试数据结果之间有一个空行隔开, 样例输入 3 2 1 5 样例输出 1*1=1 1*2=2 1*3=3 1*4=4 1*5=5 1*6=6 1*7=7 1*8=8 1*9=9 2*2=4 2*3=6 2*4=8 2*5=10 2*6=12 2*7=14 2*8=16 2*9=18 1*1=1 1*2=2 1*3=3 1*4=4 1*5=5 1*6=6 1*7=7 1*8=8 1*9=9 1*1=1 1*2=2 1*3=3 1*4=4 1*5=5 1*6=6 1*7=7 1*8=8 1*9=9 2*2=4 2*3=6 2*4=8 2*5=10 2*6=12 2*7=14 2*8=16 2*9=18 3*3=9 3*4=12 3*5=15 3*6=18 3*7=21 3*8=24 3*9=27 4*4=16 4*5=20 4*6=24 4*7=28 4*8=32 4*9=36 5*5=25 5*6=30 5*7=35 5*8=40 5*9=45 */ /* Note: */ void jiujiuchengfabiao() { int N, M; scanf("%d", &N); while(N-- && scanf("%d", &M) != EOF){ for(int i=1; i<=M; ++i){ for(int j=i; j<10; ++j){ printf("%dx%d=%d ", i, j, i*j); } printf("\n"); } } } int main() { jiujiuchengfabiao(); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<limits.h> struct array { int free; int *arr; int *top; int *next; int n,k; }; struct array *createStack(int n,int k) { struct array *s=(struct array*)malloc(sizeof(s)); s->free=0; s->arr=(int*)malloc(n*sizeof(int)); s->top=(int*)malloc(k*sizeof(int)); s->next=(int*)malloc(n*sizeof(int)); s->n=n; s->k=k; int i; for(i=0;i<n-1;i++) s->next[i]=i+1; s->next[n-1]=-1; for(i=0;i<k;i++) s->top[i]=-1; return s; }; void push(int key,int stk,struct array *s) { if(s->free==-1){ printf("stack overflow"); return;} int i=s->free; s->free=s->next[i]; s->next[i]=s->top[stk]; s->top[stk]=i; s->arr[i]=key; } int pop(struct array *s,int stk) { if(s->top[stk]==-1){ printf("stack underflow\n"); return INT_MIN; } int i=s->top[stk]; s->top[stk]=s->next[i]; s->next[i]=s->free; s->free=i; return s->arr[i]; } int main() { int n=5,k=3; struct array *s=createStack(n,k); push(15,2,s); push(45,2,s); push(9,2,s); push(11,1,s); push(19,1,s); int x=pop(s,1); if(x!=INT_MIN) printf("popped element from stack-%d :%d",1,x); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <GL/glx.h> #include "shaderprogramset.h" struct ShaderProgramSet { GLuint vertShaderId; GLuint fragShaderId; GLuint programId; }; static int32_t printShaderCompileInfo(GLuint shaderId) { GLint status = 0; glGetShaderiv(shaderId, GL_COMPILE_STATUS, &status); if(status == GL_FALSE){ GLint count; glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &count); if(count > 0){ GLchar *pErrorStr = malloc(sizeof(GLchar)*(count+1)); if(pErrorStr != NULL){ glGetShaderInfoLog(shaderId, count, NULL, pErrorStr); printf("Shader Compile Status\n"); printf("%s\n", pErrorStr); free(pErrorStr); } } return -1; } else { printf("compiled shader source.\n"); } return 0; } static int32_t createShader(GLenum shaderType, const char *pShaderSrc, GLuint *pShaderId) { int32_t ret; GLuint shaderId; GLenum glErr; shaderId = glCreateShader(shaderType); if(shaderId == 0){ return -1; } glShaderSource(shaderId, 1, &pShaderSrc, NULL); glErr = glGetError(); if(glErr != GL_NO_ERROR){ printf("load shader code to shader. %s\n", gluErrorString(glErr)); ret = -1; goto error_exit; } glCompileShader(shaderId); ret = printShaderCompileInfo(shaderId); if(ret < 0){ goto error_exit; } *pShaderId = shaderId; return 0; error_exit: glDeleteShader(shaderId); return ret; } static int32_t deleteShader(GLuint shaderId){ glDeleteShader(shaderId); return 0; } static int32_t printShaderLinkInfo(GLuint programId){ GLint status = 0; glGetProgramiv(programId, GL_LINK_STATUS, &status); if(status == GL_FALSE){ GLint count; glGetProgramiv(programId, GL_INFO_LOG_LENGTH, &count); if(count > 0){ GLchar *pErrorStr = (GLchar *)malloc(sizeof(GLchar)*(count+1)); if(pErrorStr != NULL){ glGetProgramInfoLog(programId, count, NULL, pErrorStr); fprintf(stderr, "Program Link Status\n"); fprintf(stderr, "%s\n", pErrorStr); free(pErrorStr); } } return -1; } else { printf("program linked\n"); } return 0; } static int32_t createProgramObject(struct ShaderProgramSet *pSet){ int32_t ret; GLuint programId = 0; programId = glCreateProgram(); if(programId == 0){ printf("Failed to create program. %s\n", gluErrorString(glGetError())); goto error_exit; } if(pSet->vertShaderId != 0){ glAttachShader(programId, pSet->vertShaderId); } if(pSet->fragShaderId != 0){ glAttachShader(programId, pSet->fragShaderId); } glLinkProgram(programId); ret = printShaderLinkInfo(programId); if(ret < 0){ goto error_exit; } pSet->programId = programId; return 0; error_exit: if (programId != 0){ glDeleteProgram(programId); } return -1; } static int32_t deleteProgramObject(struct ShaderProgramSet *pSet){ if(pSet->programId != 0){ glDeleteProgram(pSet->programId); pSet->programId = 0; } return 0; } int32_t shaderProgramSetCreate(ShaderProgramSetHandler *pHandler, const char *pVertShaderSrc, const char *pFragShaderSrc){ int32_t ret; struct ShaderProgramSet *pNewSet = NULL; pNewSet = (struct ShaderProgramSet *)malloc(sizeof(struct ShaderProgramSet)); if(pNewSet == NULL){ return -1; } memset(pNewSet, 0x00, sizeof(*pNewSet)); // vertex shaderを作成 if(pVertShaderSrc != NULL){ ret = createShader(GL_VERTEX_SHADER, pVertShaderSrc, &pNewSet->vertShaderId); if(ret < 0){ goto error_exit; } } // fragment shaderを作成 if(pFragShaderSrc != NULL){ ret = createShader(GL_FRAGMENT_SHADER, pFragShaderSrc, &pNewSet->fragShaderId); } // shader programを作成 ret = createProgramObject(pNewSet); if(ret < 0){ goto error_exit; } *pHandler = (ShaderProgramSetHandler*)pNewSet; return 0; error_exit: if(pNewSet->vertShaderId != 0){ deleteShader(pNewSet->vertShaderId); } if(pNewSet->fragShaderId != 0){ deleteShader(pNewSet->fragShaderId); } free(pNewSet); return -1; } int32_t shaderProgramSetDestroy(ShaderProgramSetHandler handler){ int32_t ret; struct ShaderProgramSet *pSet = (struct ShaderProgramSet *)handler; deleteProgramObject(pSet); if(pSet->fragShaderId != 0){ deleteShader(pSet->fragShaderId); pSet->fragShaderId = 0; } if(pSet->vertShaderId != 0){ deleteShader(pSet->vertShaderId); pSet->vertShaderId = 0; } free(pSet); return -1; } GLuint shaderProgramGetProgram(ShaderProgramSetHandler handler){ struct ShaderProgramSet *pSet = (struct ShaderProgramSet *)handler; if(handler == NULL){ return 0; } return pSet->programId; }
C
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <getopt.h> #include <string.h> #include "websocket.h" #include "WebsocketBridge.h" #include "version.h" const char* progname = NULL; extern settings_t settings; //allocated in websocket.c void usage(int exit_code) { printf( "version: " APP_VERSION "\n" "Usage: virtualizm-wsproxy [-h] [-i listen_ip] [-p port]\n" "\n" "Options:\n" " -i listen_ip : IP adddress for WS socket\n" " -p port : port for WS socket\n" " -v : enable verbose mode. -v to print WS handshake data. -vv to print traffic events in addition\n" " -h : this help\n" "\n" " -s, --src-whitelist list_def : restrict allowed source IP addresses for incoming WebSocket connections\n" " comma-separated networks list in CIDR notation\n" "\n" " -d, --dst-whitelist list_def : restrict allowed destination IP addresses for outgoing TCP connections\n" " comma-separated networks list in CIDR notation\n" "\n"); exit(exit_code); } int main(int argc, char **argv) { int opt, opt_index; progname = strrchr(argv[0], '/'); progname = (progname == NULL ? argv[0] : progname + 1); static const char* opts = "hvi:p:s:d:"; static struct option long_options[] = { {"src-whitelist", required_argument, NULL, 's'}, {"dst-whitelist", required_argument, NULL, 'd'}, {NULL, 0, NULL, 0} }; settings.verbose = 0; settings.src_whitelist = NULL; settings.dst_whitelist = NULL; settings.listen_host[0] = '\0'; settings.listen_port = 52525; while (-1!=(opt = getopt_long(argc, argv, opts, long_options, &opt_index))) { switch (opt) { case '?': fprintf(stderr, "%s: unknown option '-%c'\n", progname, optopt); usage(EXIT_FAILURE); case ':': fprintf(stderr, "%s: missing argument for option '-%c'\n", progname, optopt); usage(EXIT_FAILURE); case 'h': usage(EXIT_SUCCESS); case 'v': settings.verbose++; break; case 'i': strcpy(settings.listen_host, optarg); break; case 'p': settings.listen_port = atoi(optarg); if(!settings.listen_port || settings.listen_port <= 0 || settings.listen_port > 0xffff) { fprintf(stderr, "%s: wrong port value: %s\n", progname, optarg); usage(EXIT_FAILURE); } break; case 's': //source whitelist if(acl_parse(&settings.src_whitelist, optarg)) { fprintf(stderr, "%s: failed to parse src_whitelist: '%s'\n", progname, optarg); usage(EXIT_FAILURE); } break; case 'd': //destination whitelist if(acl_parse(&settings.dst_whitelist, optarg)) { fprintf(stderr, "%s: failed to parse dst_whitelist: '%s'\n", progname, optarg); usage(EXIT_FAILURE); } break; default: break; } } if(!strlen(settings.listen_host)) { strcpy(settings.listen_host, "127.0.0.1"); } if(settings.verbose) { printf("verbosity level: %d\n", settings.verbose); } if(settings.src_whitelist) acl_print(settings.src_whitelist, "src_whitelist"); if(settings.dst_whitelist) acl_print(settings.dst_whitelist, "dst_whitelist"); start(); return EXIT_SUCCESS; }
C
#include <stdio.h> int Maximun(int Array[],int array_size) { int max=0,i; max=Array[0]; for(i=0;i<array_size;i++) { if(Array[i]>max) { max=Array[i]; } } return max; } int Minimum(int Array[],int array_size) { int min=0,i; min=Array[0]; for(i=0;i<array_size;i++) { if(Array[i]<min) { min=Array[i]; } } return min; } int *Sort_Increasing(int Array[], int array_size) { int i,j,a; for (i=0;i<array_size;++i) { for(j=i+1;j<array_size;++j) { if(Array[i]>Array[j]) { a=Array[j]; Array[j]=Array[i]; Array[i]=a; } } } return Array; } int *Sort_Decreasing(int Array[], int array_size) { int i,j,a; for (i=0;i<array_size;++i) { for(j=i+1;j<array_size;++j) { if(Array[i]<Array[j]) { a=Array[j]; Array[j]=Array[i]; Array[i]=a; } } } return Array; } int *Insert(int Array[],int array_size,int index,int Element) { int i; for(i=array_size;i>index;i--) { Array[i]=Array[i-1]; } Array[index]=Element; return Array; } int *Delete(int Array[],int array_size,int index) { int i; for(i=index;i<=array_size;i++) { Array[i]=Array[i+1]; } return Array; } int main() { int array_size,i,max,min,index,Element; printf("Enter the Size of Array:\n"); scanf("%d",&array_size); int Array[array_size]; printf("Enter the elements of array: \n"); for(i=0;i<array_size;i++) { scanf("%d",&Array[i]); } while(1) { printf("Enter the Option Number\n"); printf("(1) Find Maximun\n(2) Find Minimum\n(3)Sort Increasing\n(4)Sort Decreasing\n(5) Insert Element\n(6) Delete Element\n(7) Exit\n"); int option; scanf("%d",&option); switch(option) { case 1: printf("you have selected option 1\n"); max=Maximun(Array,array_size); printf("Maximun from Array is: \n"); printf("%d\n",max); break; case 2 : printf("you have selected option 2\n"); min=Minimum(Array,array_size); printf("Minimum from Array is: \n"); printf("%d\n",min); break; case 3: printf("you have selected option 3\n"); Sort_Increasing(Array,array_size); printf("Sorted Array is: \n"); for (i=0;i<array_size;i++) { printf("%d\n",Array[i] ); } break; case 4: printf("you have selected option 4\n"); Sort_Decreasing(Array,array_size); printf("Sorted Array is: \n"); for (i=0;i<array_size;i++) { printf("%d\n",Array[i] ); } break; case 5: printf("you have selected option 5\n"); printf("At which index you want to insert? \n"); scanf("%d",&index); printf("Enter the Element: \n"); scanf("%d",&Element); Insert( Array,array_size,index, Element); for(i=0;i<=array_size;i++) { printf("%d\n",Array[i]); } break; case 6: printf("you have selected option 6\n"); printf("Enter the index you want to delete: \n"); scanf("%d",&index); Delete(Array,array_size,index); for (i = 0; i <array_size-1;i++) { printf("%d\n",Array[i] ); } break; case 7: return 0; default : printf("Invalid grade\n" ); } } }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> typedef struct s_drawing { char *m; int w; int h; char c; } drawing; typedef struct s_rectangle { char type; float x; float y; float w; float h; char c; } rectangle; FILE *f; drawing d; rectangle r; int get_info(void) { if (fscanf(f, "%d %d %c\n", &d.w, &d.h, &d.c) != 3) return (0); if ((d.w < 1) || (d.w > 300) || (d.h < 1) || (d.h > 300)) return (0); if (!(d.m = malloc(d.w * d.h))) return (0); memset(d.m, d.c, d.w * d.h); return (1); } int in_rectangle(float x, float y) { if (x < r.x || r.x + r.w < x || y < r.y || r.y + r.h < y) return (0); if (x - r.x < 1. || (r.x + r.w) - x < 1. || y - r.y < 1. || (r.y + r.h) - y < 1.) return (2); return (1); } int apply(void) { int x; int y; int is; if ((r.w <= 0. || r.h <= 0.) || (r.type != 'R' && r.type != 'r')) return (0); x = -1; while (++x < d.w && (y = -1)) while (++y < d.h) if ((is = in_rectangle(x, y)) == 2 || (is == 1 && r.type == 'R')) d.m[x + y * d.w] = r.c; return (1); } int execute(void) { int x; int scan; x = -1; if (!get_info()) return (0); while ((scan = fscanf(f, "%c %f %f %f %f %c\n", &r.type, &r.x, &r.y, &r.w, &r.h, &r.c)) == 6) if (!apply()) return (0); if (scan != -1) return (0); while (++x < d.h) write(1, d.m + (x * d.w), d.w) && write(1, "\n", 1); return (1); } int main (int argc, char **argv) { if (argc == 2) { f = fopen(argv[1], "r"); if (f && execute()) return (0); write (1, "Error: Operation file corrupted\n", 32); } else write(1, "Error: argument\n", 16); return (1); }
C
#include <stdio.h> #include <malloc.h> #include <string.h> char* adfgxPlain; int * adfgxNormPlain; int * adfgxTransposed; int * adfgxNormCipher; int * adfgxKey; int * adfgxKeyOrder; int * adfgxKeyIndex; int * adfgxRowsPerCol; int * adfgxCumRowsPerCol; char adfgxMatrix[5][5]= { {'A', 'B', 'C', 'D', 'E'}, {'F', 'G', 'H', 'I', 'K'}, {'L', 'M', 'N', 'O', 'P'}, {'Q', 'R', 'S', 'T', 'U'}, {'V', 'W', 'X', 'Y', 'Z'}, }; int adfgxNormCipherLength; int adfgxMaxCipherLength; void quicksort(int* source, int* target, int first, int last) { int i, j; int pivot, temp; if(first<last) { pivot=first; i=first; j=last; while(i<j) { while(source[i]<=source[pivot]&&i<last) i++; while(source[j]>source[pivot]) j--; if(i<j) { temp=source[i]; source[i]=source[j]; source[j]=temp; temp=target[i]; target[i]=target[j]; target[j]=temp; } } temp=source[pivot]; source[pivot]=source[j]; source[j]=temp; temp=target[pivot]; target[pivot]=target[j]; target[j]=temp; quicksort(source, target, first,j-1 ); quicksort(source, target, j+1 ,last); } } void adfgxAlloc(int keySize, int cipherSize) { int rows; rows=cipherSize/keySize; if (cipherSize/keySize!=0) { rows++; } adfgxMaxCipherLength=rows*keySize; adfgxPlain =malloc(adfgxMaxCipherLength)+1; adfgxPlain[cipherSize/2]=0; adfgxNormPlain =malloc(adfgxMaxCipherLength/2*sizeof(int)); adfgxTransposed =malloc(adfgxMaxCipherLength*sizeof(int)); adfgxNormCipher =malloc(adfgxMaxCipherLength*sizeof(int)); adfgxKey =malloc(keySize*sizeof(int)); adfgxKeyIndex =malloc(keySize*sizeof(int)); adfgxKeyOrder =malloc(keySize*sizeof(int)); adfgxRowsPerCol =malloc(keySize*sizeof(int)); adfgxCumRowsPerCol =malloc(keySize*sizeof(int)); } void adfgxFree() { /* free(adfgxPlain); free(adfgxNormPlain); free(adfgxTransposed); free(adfgxNormCipher); free(adfgxKeyIndex); free(adfgxKeyOrder); free(adfgxRowsPerCol); free(adfgxCumRowsPerCol); */ } char* adfgxDecrypt(char* key, int keyLength) { int rows, row, col; int i; // The column order e.g. T,A,G -> 2,0,1 i=0; while (i<keyLength) { adfgxKey [i]=key[i]; adfgxKeyIndex[i]=i; i++; } quicksort(adfgxKey, adfgxKeyIndex, 0, keyLength-1); i=0; while (i<keyLength) { adfgxKeyOrder[adfgxKeyIndex[i]]=i; i++; } // The number of rows per column i=0; while (i<keyLength) { adfgxRowsPerCol[i]=adfgxNormCipherLength/keyLength; if (adfgxKeyIndex[i]<adfgxNormCipherLength%keyLength) { adfgxRowsPerCol[i]++; } if (i==0) { adfgxCumRowsPerCol[i]=0; } else { adfgxCumRowsPerCol[i]=adfgxCumRowsPerCol[i-1]+adfgxRowsPerCol[i-1]; } i++; } rows=adfgxNormCipherLength/keyLength; if (adfgxNormCipherLength%keyLength!=0) { rows++; } row=0; while (row<rows) { col=0; while (col<keyLength) { adfgxTransposed[row*keyLength+col]=adfgxNormCipher[adfgxCumRowsPerCol[adfgxKeyOrder[col]]+row]; col++; } row++; } i=0; while (i<adfgxNormCipherLength) { row=adfgxTransposed[i]; col=adfgxTransposed[i+1]; adfgxNormPlain[i/2]=row*5+col; adfgxPlain[i/2]=adfgxMatrix[row][col]; i+=2; } adfgxPlain[i/2]='\0'; return adfgxPlain; } void adfgxNormalizeCipher(char* cipher, int cipherLength) { int i; i=0; while (i<cipherLength) { switch(cipher[i]) { case 'A': adfgxNormCipher[i]=0; break; case 'D': adfgxNormCipher[i]=1; break; case 'F': adfgxNormCipher[i]=2; break; case 'G': adfgxNormCipher[i]=3; break; case 'X': adfgxNormCipher[i]=4; break; } i++; } adfgxNormCipherLength=cipherLength; } void adfgxDenormalizeCipher(int* cipher) { int i; i=0; while (i<adfgxNormCipherLength) { switch(cipher[i]) { case 0: adfgxPlain[i]='A'; break; case 1: adfgxPlain[i]='D'; break; case 2: adfgxPlain[i]='F'; break; case 3: adfgxPlain[i]='G'; break; case 4: adfgxPlain[i]='X'; break; } i++; } } /**************************************************************************************************\ * * Calculates the index of coincidence * TODO: transform to int calculation for speed * \**************************************************************************************************/ float adfgxIndexOfCoincidence() { int c; int i; float ioc; int iocCharCount[25]; int plainTextSize; plainTextSize=adfgxNormCipherLength/2; c=0; while (c<25) { iocCharCount[c]=0; c++; } i=0; while (i<plainTextSize) { iocCharCount[adfgxNormPlain[i]]++; i++; } ioc=0.0; c=0; while (c<25) { ioc+=iocCharCount[c]*(iocCharCount[c]-1); c++; } ioc/=plainTextSize*(plainTextSize-1); ioc*=25.0; return ioc; } void adfgxDump() { int i; i=0; while (i<adfgxNormCipherLength) { printf("%d %d - ", adfgxNormCipher[i], adfgxNormCipher[i+1]); i+=2; } printf("\n"); } void adfgxDumpPlain() { int i; i=0; while (i<adfgxNormCipherLength/2) { printf("%d ", adfgxNormPlain[i]); i++; } printf("\n"); }
C
listnode* reverseList(listnode* A, int B) { if (B == 1) return A ; listnode *tmp, *prev, *nex, *rprev, *rhead, *ret ; int cnt = 1 ; printf ("Starting rev %d, ", A->val) ; rprev = NULL ; rhead = A ; while (rhead) { cnt = 1 ; prev = rprev ; tmp = rhead ; while (cnt != B) { nex = tmp->next ; tmp->next = prev ; prev = tmp ; tmp = nex ; cnt++ ; } printf ("Ending rev %d\n", tmp->val) ; nex = tmp->next ; tmp->next = prev ; if (rprev == NULL) ret = tmp ; else rprev->next = tmp ; rprev = rhead ; if (nex == NULL) rhead->next = NULL ; rhead = nex ; if (rhead) printf ("Starting rev %d, ", rhead->val) ; else printf ("No more rev\n") ; } return ret ; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> struct vet { int vert; struct vet *prox; }; void grafo(struct vet **vetOrig, int nroArest); void digrafo(struct vet **vetOrig, int nroArest); void showMatAdj(struct vet **vetOrig, int nroArestas, int nroVertices); void insertGrafo(struct vet **vetOrig, int dest); void insertDigrafo(struct vet **vetOrig, int dest); void getDest(char *dest, int *iDest); void getOrig(char *orig, int *iOrig); struct vet * getVert(struct vet *vetOrig, int *vert); void freeMemory(struct vet**data, int datSize); int main(void) { struct vet **vetOrig; char nv[4], na[4], grafo_digrafo[2]; int i, iNv, iNa, iGrDgr; memset(nv, 0, sizeof(nv)); memset(na, 0, sizeof(na)); memset(grafo_digrafo,0,sizeof(grafo_digrafo)); printf("Numero de vertices: "); fgets(nv, sizeof(nv), stdin); // sscanf(nv,"%d",&iNv); iNv = atoi(nv); // numero de vertices printf("Numero de Arestas: "); fgets(na, sizeof(na), stdin); // sscanf(na,"%d",&iNa); iNa = atoi(na); // numero de arestas vetOrig = (struct vet**) malloc(sizeof(struct vet) * iNv); for (i = 0; i < iNv; i++) vetOrig[i] = NULL; printf("Grafo ou Digrafo?\nDigite 1 para Grafo e 2 para Digrafo: "); fflush(stdin); fgets(grafo_digrafo, sizeof(grafo_digrafo), stdin); iGrDgr = atoi(grafo_digrafo); // grafo if (iGrDgr == 1) { grafo(vetOrig,iNa); showMatAdj(vetOrig,iNa,iNv); // printf("vertice 1: %d, %d\n",vetOrig[0]->vert, vetOrig[0]->prox->vert); // printf("vertice 2: %d, %d\n",vetOrig[1]->vert, vetOrig[1]->prox->vert); // printf("vertice 3: %d, %d\n",vetOrig[2]->vert, vetOrig[2]->prox->vert); // printf("vertice 4: %d, %d\n",vetOrig[3]->vert, vetOrig[3]->prox->vert); // printf("vertice 5: %d, %d\n",vetOrig[4]->vert, vetOrig[4]->prox->vert); freeMemory(vetOrig,iNv); } // Digrafo else { digrafo(vetOrig,iNa); showMatAdj(vetOrig,iNa,iNv); // printf("vertice 1: %d\n",vetOrig[0]->vert); // printf("vertice 2: %d\n",vetOrig[1]->vert); // printf("vertice 3: %d\n",vetOrig[2]->vert); // printf("vertice 4: %d\n",vetOrig[3]->vert); // printf("vertice 5: %d\n",vetOrig[4]->vert); freeMemory(vetOrig,iNv); } return 0; } void digrafo(struct vet **vetOrig, int nroArest) { int i, iOrig, iDest; char orig[4], dest[4]; for (i = 1; i <= nroArest; i++) { printf("(Aresta %d)\n",i); fflush(stdin); memset(orig, 0, sizeof(orig)); memset(dest, 0, sizeof(dest)); getOrig(orig,&iOrig); // fix bug if(iOrig == 0) iOrig = 1; getDest(dest,&iDest); insertDigrafo(&vetOrig[iOrig - 1],iDest); } } void grafo(struct vet **vetOrig, int nroArest) { int i, iOrig, iDest; //converter para int char orig[4], dest[4]; //pega entrada do usuario for (i = 1; i <= nroArest; i++) { printf("(Aresta %d)\n",i); fflush(stdin); memset(orig, 0, sizeof(orig)); memset(dest, 0, sizeof(dest)); getOrig(orig,&iOrig); // fix bug if(iOrig == 0) iOrig = 1; getDest(dest,&iDest); insertGrafo(&vetOrig[iOrig - 1],iDest); if (iOrig != iDest) insertGrafo(&vetOrig[iDest - 1], iOrig); } } void getOrig(char *orig, int *iOrig) { printf("Origem: \n"); fgets(orig, sizeof(orig), stdin); *iOrig = atoi(orig); } void getDest(char *dest, int *iDest) { printf("Destino: \n"); fgets(dest, sizeof(dest), stdin); *iDest = atoi(dest); } void insertDigrafo(struct vet **vetOrig, int dest) { struct vet *aux; aux = (struct vet*) malloc(sizeof(struct vet)); aux->vert = dest; aux->prox = NULL; if (*vetOrig == NULL) *vetOrig = aux; } void insertGrafo(struct vet **vetOrig, int dest) { struct vet *ult, *aux; aux = (struct vet*) malloc(sizeof(struct vet)); aux->vert = dest; aux->prox = NULL; if (*vetOrig == NULL) *vetOrig = aux; else { ult = *vetOrig; while (ult->prox != NULL) ult = ult->prox; ult->prox = aux; } } void showMatAdj(struct vet **vetOrig, int nroArestas, int nroVertices) { int i, j, vertMat; int matAdj[nroVertices+1][nroArestas+1]; struct vet *aux; memset(matAdj, 0, sizeof(matAdj[0][0]) * (nroVertices+1) * (nroArestas+1)); for (i = 1; i <= nroVertices; i++) { aux = vetOrig[i-1]; while (aux != NULL) { aux = getVert(aux,&vertMat); matAdj[i][vertMat] = 1; } } printf("\n\n"); for (i = 1; i <= nroVertices; i++) { printf("vertice: %d| ",i); for (j = 1; j <= nroArestas; j++) { printf("%d ",matAdj[i][j]); } printf("\n"); } } struct vet * getVert(struct vet *vetOrig, int *vertMat) { *vertMat = vetOrig->vert; return vetOrig->prox; } void freeMemory(struct vet **data, int datSize) { int i; for (i = 0; i < datSize; i++) { free(data[i]); } free(data); }
C
/* ID: wangbn11 LANG: C TASK: fact4 */ #include <stdio.h> /* * 对10取余数,则数有几个5的因子,就有多少2 * */ int main() { int number; FILE *fin = fopen("fact4.in", "r"); FILE *fout = fopen("fact4.out", "w"); fscanf(fin, "%d", &number); int digit[5000], time, i; time = 0; for (i = 1; i <= number; i++) { digit[i] = i; while (digit[i] % 5 == 0) { time++; digit[i] /= 5; } } for (i = 1; i <= number; i++) { while (digit[i] % 2 == 0 && time > 0) { time--; digit[i] /=2; } } int tail = 1; for (i = 1; i <= number; i++) { tail = tail * digit[i] % 10; } fprintf(fout, "%d\n", tail); fclose(fin); fclose(fout); }
C
#include<errno.h> #include<fcntl.h> #include<stdio.h> #include<unistd.h> #include<stdlib.h> #include<string.h> #include<mosquitto.h> // Server connection parameters #define MQTT_HOSTNAME "broker.mqttdashboard.com" #define MQTT_PORT 1883 #define MQTT_USERNAME "NULL" #define MQTT_PASSWORD "NULL" #define MQTT_TOPIC "test" /* * Start here */ int main (int argc, char **argv) { struct mosquitto *mosq = NULL; // Initialize the Mosquitto library mosquitto_lib_init(); // Create a new Mosquitto runtime instance with a random client ID, // and no application-specific callback data. mosq = mosquitto_new (NULL, true, NULL); if (!mosq) { fprintf (stderr, "Can't initialize Mosquitto library\n"); exit (-1); } mosquitto_username_pw_set (mosq, MQTT_USERNAME, MQTT_PASSWORD); // Establish a connection to the MQTT server. Do not use a keep-alive ping int ret = mosquitto_connect (mosq, MQTT_HOSTNAME, MQTT_PORT, 0); if (ret) { fprintf (stderr, "Can't connect to Mosquitto server\n"); exit (-1); } void my_message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message) { // Note: nothing in the Mosquitto docs or examples suggests that we // must free this message structure after processing it, // (nor that we can assume that it is null-terminated.) printf ("Got message: %s\n", (char *)message->payload); } //... mosquitto_subscribe (mosq, NULL, MQTT_TOPIC, 0); // Specify the function to call when a new message is received mosquitto_message_callback_set (mosq, my_message_callback); // Wait for new messages mosquitto_loop_forever (mosq, -1, 1); // We need a short delay here, to prevent the Mosquitto library being // torn down by the operating system before all the network operations // are finished. // sleep (1); // Tidy up // mosquitto_disconnect (mosq); // mosquitto_destroy (mosq); // mosquitto_lib_cleanup(); return 0; }
C
#include <stdio.h> int main() { int n1,i,a[1000],b[1000],c[1000],d=0,k=0; scanf("%d",&n1); for(i=0;i<n1;i++) scanf("%d",&a[i]); for(i=0;i<n1;i++) { if(a[i]==0) { b[k]=a[i]; k++; a[i]='#'; } } for(i=0;i<n1;i++) { if(a[i]!='#') { c[d]=a[i]; d++; } } printf("\n"); for(i=0;i<n1;i++) { c[d]=b[i]; d++;; } for(i=0;i<n1;i++) { printf("%d",c[i]); } return 0; }
C
#ifndef QUEUE_T_H #define QUEUE_T_H #include <stdlib.h> #include <pthread.h> typedef struct queue_element_t { void *next; int value; } queue_element_t; typedef struct queue_t { queue_element_t *head; queue_element_t *tail; pthread_mutex_t *mutex; unsigned int size; } queue_t; extern queue_t* create(); extern void destroy(queue_t *q); extern void push(queue_t *q, int elem); extern int pop(queue_t *q); #endif
C
#include <stdio.h> int main() { int scores = 3; int garry[scores], sharry[scores]; for (int name = 0; name < 2; name++) { for (int score = 0; score < scores; score++) { if (name) { scanf("%d", &sharry[score]); } else { scanf("%d", &garry[score]); } } } int garry_get = 0; int sharry_get = 0; for (int i = 0; i < scores; i++) { garry_get += garry[i]; sharry_get += sharry[i]; } if (garry_get == sharry_get) { printf("None 0"); } else { garry_get > sharry_get ? printf("Garry %d", garry_get - sharry_get) : printf("Sharry %d", sharry_get - garry_get); } return 0; }
C
#include <stdio.h> #include <string.h> int main() { char a[1000]; long long int t,n,i,sum=0; scanf("%lld",&t); for(i=1;i<=t;i++) { scanf("%s",a); if(a[0]=='d') { scanf("%lld",&n); sum=sum+n; } else if(a[0]=='r') printf("%lld\n",sum); } return 0; }
C
/* * AMIT_Program.c * * Created on: Oct 13, 2021 * Author: Lenovo */ #include "STD_TYPES.h" #include "DIO_Interface.h" #include "SEG_interface.h" #include "AMIT_Interface.h" #include "util/delay.h" u16 Counter5000=0; u8 Counter10=0,Counter100=0; u8 Button_State_On_Off=OFF_STATE; u8 ModeFlag=DEFAULT_MODE; u8 GLO_u8EEPROMValue; //this function controls the onn and off states void AMIT_Project_voidON_OFF(void) { if(Button_State_On_Off==OFF_STATE) { Button_State_On_Off=ON_STATE; } else if(Button_State_On_Off==ON_STATE) { Button_State_On_Off=OFF_STATE; } else { /* NOTHING */ } } //this functions is used to increment the set temperature void AMIT_Project_voidUP(void) { //enters the SET_TEMPERATURE_MODE if(ModeFlag==DEFAULT_MODE) { ModeFlag=SET_TEMPERATURE_MODE; } else if(ModeFlag==SET_TEMPERATURE_MODE && GLO_u8EEPROMValue<75)//Min TEMP { //increment the set temperature GLO_u8EEPROMValue+=5; } else { /* NOTHING */ } Counter5000=0; } void AMIT_Project_voidDOWN(void) { if(ModeFlag==DEFAULT_MODE) { //enters the SET_TEMPERATURE_MODE ModeFlag=SET_TEMPERATURE_MODE; } else if(ModeFlag==SET_TEMPERATURE_MODE && GLO_u8EEPROMValue>35)//Min TEMP { //decrement the set temperature GLO_u8EEPROMValue-=5; } else { /* NOTHING */ } Counter5000=0; } void AMIT_Project_Timers(void) { //the timers starts counting Counter10++; Counter100++; } void AMIT_Projectvoid_Cooling_HeatingLeds(u8 Copy_u8Flag) { //if we need to cool the water if (Copy_u8Flag == COOLING) //Cooling { //Set the LED DIO_u8SetPinValue(DIO_PIN7, DIO_PORTC, PIN_HIGH); } //if we need to heat the water else if (Copy_u8Flag == HEATING) //Heating { //toggle the LED DIO_u8TogglePinValue(DIO_PIN7, DIO_PORTC); } else { /*Nothing*/ } } u8 AMIT_Projectu8_TempreatureCompare(u8 Copy_u8SensorTempreature,u8 Copy_u8SetTempreature) { u8 flag; // if the water is hotter than the needed temperature if(Copy_u8SensorTempreature>=(Copy_u8SetTempreature+5)) { flag=COOLING;//Cooling } // if the water is colder than the needed temperature else if (Copy_u8SensorTempreature<=(Copy_u8SetTempreature-5)) { flag=HEATING;//Heating } else { flag=0;//the water temp is close to the set temp +-5 } return flag; }
C
/* \file file_utils.c * * \brief Implementacao de funcoes relativas ao tratamento de arquivos * necessarios ao servidor * * "$Id: $" */ #include "file_utils.h" #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <sys/stat.h> const char * const IndexStr = "/index.html"; const char * const PutMark = ".~put"; #define PutMarkSize 5 void init_file_components(FileComponents *file) { file->file_path[0] = '\0'; file->file_ptr = NULL; file->is_new_file = 0; memset(&(file->stats), 0, sizeof(file->stats)); file->should_delete = 1; } int32_t set_file_components(FileComponents *file, char *file_path, const int8_t flags) { if (file == NULL) { printf("Trying to initialize a null FileComponent\n"); return FileComponentNull; } file->file_ptr = NULL; if (file_path == NULL || file_path[0] == '\0') { printf("Wrong file path\n"); return FilePathNull; } get_file_stats(file_path, &(file->stats)); if (flags & ReadFile) { if (!is_regular_file(file)) { return NotARegularFile; } read_treatment(file, file_path); } else if (flags & WriteFile) { if (is_directory(file)) { return NotARegularFile; } int8_t ret = write_treatment(file, file_path); if (ret == ExistentFile) { return ret; } } else { printf("Unknown flags"); return UnknownFlag; } if (file->file_ptr == NULL) { return CouldntOpen; } return Success; } void read_treatment(FileComponents *file, char *file_path) { size_t file_path_size = strlen(file_path); strncpy(file->file_path, file_path, file_path_size); file->file_path[file_path_size] = '\0'; file->file_ptr = fopen(file->file_path, "rb"); } int8_t write_treatment(FileComponents *file, char *file_path) { snprintf(file->file_path, PATH_MAX, "%s%s", file_path, PutMark); if (get_file_stats(file->file_path, &(file->stats))) { return ExistentFile; } if (get_file_stats(file_path, &(file->stats))) { file->is_new_file = 0; } else { file->is_new_file = 1; } file->file_ptr = fopen(file->file_path, "wb"); return Success; } int32_t destroy_file_components(FileComponents *file) { if (file->file_ptr != NULL) { fclose(file->file_ptr); } file->file_path[0] = '\0'; file->should_delete = 1; memset(&(file->stats), 0, sizeof(file->stats)); return 0; } void setup_file_path(char *base_path, char *resource, char *full_path) { int32_t resource_size = strlen(resource); if ((strncmp(resource, "/", resource_size) == 0) || (strncmp(resource, ".", resource_size) == 0) ) { strncpy(resource, IndexStr, strlen(IndexStr)); } resource_size = strlen(resource); const int32_t path_size = strlen(base_path); const int32_t file_name_size = path_size + resource_size + 1; snprintf(full_path, file_name_size, "%s%s", base_path, resource); } int8_t is_symbolic_link_and_valid(char *base_path, const int32_t base_path_len, char *full_path) { struct stat buf; if (lstat(full_path, &buf) == -1) { perror("stat"); return 0; } if (!S_ISLNK(buf.st_mode)) { return 0; } if (strncmp(base_path, full_path, base_path_len) != 0) { return 0; } return 1; } int8_t is_realpath_inside_base_path(char *base_path, const int32_t base_path_len, char *real_path) { if (strncmp(base_path, real_path, base_path_len) == 0) { return 1; } return 0; } int8_t verify_file_path(char *base_path, char *full_path) { const int32_t path_size = strlen(base_path); char real_path[PATH_MAX]; memset(real_path, '\0', PATH_MAX); realpath(full_path, real_path); /**/ /*if (strncmp(full_path, real_path, strlen(full_path)) == 0) { return 0; }*/ if (is_realpath_inside_base_path(base_path, path_size, real_path) || is_symbolic_link_and_valid(base_path, path_size, full_path)) { memset(full_path, '\0', PATH_MAX); strncpy(full_path, real_path, strlen(real_path) + 1); return 0; } memset(full_path, '\0', PATH_MAX); return 1; } int32_t get_file_mime(uint32_t full_path_size, char *full_path, char *mime) { char *cmd_mask = "file -i %s"; int32_t total_size = strlen(cmd_mask) + full_path_size; FILE* pipe = NULL; char *cmd = malloc(sizeof(char)*(total_size)); { snprintf(cmd, total_size, cmd_mask, full_path); pipe = popen(cmd, "r"); } free(cmd); if (pipe == NULL) { return -1; } fscanf(pipe, "%*s %128[^\n]s\n", mime); /*MAX_MIME_SIZE*/ pclose(pipe); return 0; } int32_t erase_put_mark(FileComponents *file) { uint32_t name_size = strlen(file->file_path); if (name_size < PutMarkSize) { printf("Invalid Name\n"); return -1; } uint32_t name_size_without_put_mark = name_size - PutMarkSize; if (strncmp(file->file_path + name_size_without_put_mark, PutMark, PutMarkSize) != 0) { printf("Invalid file name %s\n", file->file_path); return -1; } char old_file_name[PATH_MAX]; strncpy(old_file_name,file->file_path, name_size); strncpy(file->file_path, old_file_name, name_size_without_put_mark); old_file_name[name_size] = '\0'; file->file_path[name_size_without_put_mark] = '\0'; if (rename(old_file_name, file->file_path) < 0) { printf("old_name: %s\n", old_file_name); printf("new name: %s\n", file->file_path); perror("rename"); return -1; } return 0; } int32_t remove_file(FileComponents *file) { if (file->file_ptr != NULL) { if (remove(file->file_path) < 0) { printf("remove file:"); return -1; } } return 0; } int32_t treat_file_after_put(FileComponents *file, uint8_t error) { if (file == NULL) { printf("Null file component received\n"); return -1; } if (error) { return remove_file(file); } else { if (file->file_ptr != NULL) { fclose(file->file_ptr); file->file_ptr = NULL; } return erase_put_mark(file); } } uint8_t get_file_stats(char *file_path, struct stat *file_stats) { return (stat(file_path, file_stats) == 0); } uint8_t is_valid_file(FileComponents *file) { uint8_t ret = (file->file_ptr == NULL) ? 0 : 1; return ret; } uint8_t is_regular_file(FileComponents *file) { if (!S_ISREG(file->stats.st_mode)) { return 0; } return 1; } uint8_t is_directory(FileComponents *file) { if (file == NULL) { printf("file is null"); } if (!S_ISDIR(file->stats.st_mode)) { return 0; } return 1; }
C
#include<stdio.h> #include<math.h> int main() { int valor, qnt; scanf("%d", &valor); printf("%d\n", valor); qnt=floorf(valor/100); printf("%d nota(s) de R$ 100,00\n", qnt); valor = (valor -(qnt*100)); qnt=floorf(valor/50); printf("%d nota(s) de R$ 50,00\n", qnt); valor = (valor -(qnt*50)); qnt=floorf(valor/20); printf("%d nota(s) de R$ 20,00\n", qnt); valor = (valor -(qnt*20)); qnt=floorf(valor/10); printf("%d nota(s) de R$ 10,00\n", qnt); valor = (valor -(qnt*10)); qnt=floorf(valor/5); printf("%d nota(s) de R$ 5,00\n", qnt); valor = (valor -(qnt*5)); qnt=floorf(valor/2); printf("%d nota(s) de R$ 2,00\n", qnt); valor = (valor -(qnt*2)); qnt=floorf(valor/1); printf("%d nota(s) de R$ 1,00\n", qnt); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strsplit.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: egiles <egiles@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/09/20 15:26:08 by egiles #+# #+# */ /* Updated: 2019/09/25 16:23:00 by egiles ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static size_t ft_wlen(char const *s, char c) { size_t i; i = 0; while (s[i] && s[i] != c) i++; return (i); } static void *ft_free_arr(char **arr, size_t i) { size_t j; j = -1; while (++j < i - 1) { free(arr[j]); arr[j] = NULL; } free(arr); arr = NULL; return (NULL); } char **ft_strsplit(char const *s, char c) { size_t i; size_t j; size_t k; char **str; if (s == NULL || !(str = (char **)malloc(sizeof(char*) * (ft_count_words(s, c) + 1)))) return (NULL); j = -1; i = ft_skip_ws(s, c); while (++j < ft_count_words(s, c) && s[i]) { i = i + ft_skip_ws(s + i, c); if (!(str[j] = (char *)malloc(sizeof(char) * (ft_wlen(s + i, c) + 1)))) return (ft_free_arr(str, j)); k = -1; while (s[i] != c && s[i]) str[j][++k] = s[i++]; str[j][++k] = '\0'; } str[j] = NULL; return (str); }
C
/* hw2_20a.c */ #include <stdio.h> #include <stdlib.h> int main(void) { int i=5; printf("%d+%d=%d\n",i,i,i+i); system("pause"); return 0; } /* output---- 5+5=10 -----------*/
C
#include <unistd.h> #include <fcntl.h> #include <stdio.h> #define TAM 100 int readln(int fd, char* buff, int tam){ int r, i; r = read(fd, buff, tam); for(i=0; i<r && buff[i] != '\n'; i++); if(buff[i] == '\n') i++; return i; } void main(int argc, char* argv[]){ char buff[TAM]; char aux[10]; int n, i=0; while(n = readln(0, buff, TAM-1)){ if(buff[0] != '\n'){ sprintf(aux, "\t%d: ", i++); write(1, aux, 10); write(1, buff, n); } } }
C
#include <stdio.h> #include <stdlib.h> int main() { int a,b; scanf("%d\n%d",&a,&b); int result=1; float value; if(a>0 && b>0) { for(int i=0;i<b;i++) { result*=a; } printf("%d",result); } else if(a>0 && b<0) { for(int i=0;i<(b*-1);i++) { result*=a; } value=1/(float)result; printf("%.2f",value); } return 0; }
C
#include "holberton.h" /** *_strdup - returns a pointer to a new string which is a duplicate of * the string. *@str: * string *Return: NULL or String */ char *_strdup(char *str) { char *s; unsigned int a; if (str == NULL) { return (NULL); } for (a = 0; str[a] != '\0'; a++) { } s = malloc(sizeof(char) * (a + 1)); if (s == NULL) { return (NULL); } for (a = 0; str[a] != '\0'; a++) { s[a] = str[a]; } s[a] = '\0'; return (s); }
C
#include <math.h> #include <DHT.h> #include <SigFox.h> // Definimos el pin digital donde se conecta el sensor #define DHTPIN 2 // Dependiendo del tipo de sensor /* Offset encoding */ #define OFFSET_ENCODING 27 #define DHTTYPE DHT11 /* 12 Bytes per message as a requirement of SigFox */ #define BYTES_PER_MSG 12 /* One read takes 3 bytes */ #define BYTES_PER_LOG 3 /* ReaDs per Packet as ratio */ #define READS_PER_PACKET (BYTES_PER_MSG / BYTES_PER_LOG) /* Send packet every 10 minutes */ #define WAIT_READ_GROUP_MS (1000 * 60 * 3) /* Read Sensor every 2 seconds */ #define READ_EVERY_MS (1000 * 2) /* Number Readings per log is the ratio of number of Total Wait time by * Reads per packet and reads per second */ #define NUMBER_READS ((WAIT_READ_GROUP_MS / READS_PER_PACKET) / READ_EVERY_MS) /* Ignore percent algorithm */ #define IGNORE_PERCENT (5/100) /* Ignore percent for double side algorithm */ #define IGNORE_PERCENT_SIDE (IGNORE_PERCENT / 2) /* Lower index of reading after adjusting */ #define LOWER_BOUND_INFO (((int)(IGNORE_PERCENT_SIDE * NUMBER_READS)) + 1) /* Higher index of reading after adjusting */ #define UPPER_BOUND_INFO ((int)((1 - IGNORE_PERCENT_SIDE) * NUMBER_READS)) /* Number of reads taken into account */ #define NUMBER_BOUND (UPPER_BOUND_INFO - LOWER_BOUND_INFO) // Inicializamos el sensor DHT11 DHT dht(DHTPIN, DHTTYPE); /* * Print Basic Info about SigFox and * start serial 9600 */ void setup() { Serial.begin(9600); if (!SigFox.begin()) { //ensures SigFox is connected Serial.println("Shield error or not present!"); return; } String version = SigFox.SigVersion(); String ID = SigFox.ID(); String PAC = SigFox.PAC(); Serial.println("ID = " + ID); Serial.println("PAC = " + PAC); SigFox.end(); SigFox.debug(); dht.begin(); } /* * Adjust int to byte format */ byte adjust_format(int input) { return (byte)(input + OFFSET_ENCODING); } /* * Send Message with SigFox */ void send_message(byte message[12]) { SigFox.begin(); delay(100); // Wait 100ms for the begin SigFox.status(); delay(1); // Start packet SigFox.beginPacket(); // Write buffer SigFox.write(message, 12); // Send data int result = SigFox.endPacket(); // Check result if(result == 0){ Serial.println("Message sent."); }else{ Serial.println("Error sending message."); } // Shutdown module SigFox.end(); } /* * Comparator for sort */ int compare( const void* a, const void* b) { float f_a = * ( (float*) a ); float f_b = * ( (float*) b ); if (f_a == f_b) { return 0; } else if (f_a < f_b) { return -1; } else { return 1; } } /* * Gets the mean from a percent adjusted algorithm */ float mean_array_adjusted(float to_calculate[NUMBER_READS]){ qsort(to_calculate, NUMBER_READS, sizeof(float), compare); float medium = to_calculate[LOWER_BOUND_INFO]; for(int i = LOWER_BOUND_INFO + 1; i < UPPER_BOUND_INFO; i++){ medium += to_calculate[i]; } return medium / NUMBER_BOUND; } void loop() { byte packet[BYTES_PER_MSG]; /* * For every packet that has to be read */ for(int index_packet = 0; index_packet < READS_PER_PACKET; index_packet++){ /* * For every log that has to be made for the log of the packet */ float temperatures[NUMBER_READS]; float moistures[NUMBER_READS]; for(int index_read = 0; index_read < NUMBER_READS; index_read++){ /* * Read Value and log */ float h = dht.readHumidity(); float t = dht.readTemperature(); if (isnan(h) || isnan(t)) { Serial.println("Error getting data from DHT11, restart cycle"); return; } float hic = dht.computeHeatIndex(t, h, false); temperatures[index_read] = hic; moistures[index_read] = h; Serial.print("Temp: "); Serial.println(hic); Serial.print("Hum: "); Serial.println(h); delay(READ_EVERY_MS); } /* * Get Means Adjusted */ float mean_temp = mean_array_adjusted(temperatures); float mean_hum = mean_array_adjusted(moistures); Serial.print("Mean Temp: "); Serial.println(mean_temp); Serial.print("Mean Hum: "); Serial.println(mean_hum); /* * Format the bytes as the algorithm specifies */ char str_repr_temp[5]; sprintf(str_repr_temp, "%4.2f", mean_temp); int pre_i = atoi(strtok (str_repr_temp,".")); int post_i = atoi(strtok (NULL, ".")); byte pre = adjust_format(pre_i); byte post = adjust_format(post_i); byte hum = adjust_format(round(mean_hum)); int offset = index_packet * 3; /* Save bytes in the packet */ packet[offset + 0] = pre; packet[offset + 1] = post; packet[offset + 2] = hum; /* Print for logging */ char log_packet_buffer[100]; sprintf(log_packet_buffer, "%02X%02X%02X", pre, post, hum); Serial.print("Packet: "); Serial.println(log_packet_buffer); } /* Send message */ send_message(packet); }
C
#include <stdio.h> #include <stdlib.h> #include <wchar.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> char buf[256][256]; int read_buf(char *filename) { FILE *fp; int line = 0; fp = fopen(filename, "r"); if (fp == NULL) { fprintf(stderr, "No such file %s\n", filename); exit(0); } while(!feof(fp)) { //fgetws(buf[line], sizeof(buf[line]), fp); fgets(buf[line], sizeof(buf[line]), fp); line++; } return line; } int main (int argc, char *argv[]) { int sock; struct sockaddr_in addr; in_addr_t ipaddr; size_t len; size_t text_len, str_len; int cnt; text_len = read_buf("test.txt"); sock = socket(AF_INET, SOCK_DGRAM, 0); addr.sin_family = AF_INET; addr.sin_port = htons(12345); addr.sin_addr.s_addr = inet_addr("239.1.1.2"); //ipaddr = inet_addr("127.0.0.1"); ipaddr = inet_addr("192.168.123.254"); if (setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF, (char *)&ipaddr, sizeof(ipaddr)) != 0) { perror("setsockopt"); return EXIT_FAILURE; } while (1) { for (cnt = 0; cnt < text_len - 1; cnt++) { str_len = strlen(buf[cnt]); buf[cnt][str_len-1] = '\0'; /* str_len = wcsnlen(buf[cnt], 256); */ len = sendto(sock, buf[cnt], str_len, 0, (struct sockaddr *)&addr, sizeof(addr)); sleep(1); printf("%s / idx:%d / %d sent\n", buf[cnt], cnt, len); } } //len = sendto(sock, "HELLO", 5, 0, (struct sockaddr *)&addr, sizeof(addr)); close(sock); return EXIT_SUCCESS; }
C
#include "sort.h" #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #include "sort.h" int i_pow(int v, int p) { if(p<0) return 0; int i, rez=1; for(i=0; i<p; ++i) rez*=v; return rez; } void sortVstavkaInt(int size, int* array, int loops) { int i, j, temp; for (i = 1; i < size; i++) { temp = array[i]; for (j = i - 1; j >= 0; j--) { if (array[j] < temp) break; array[j+1] = array[j]; array[j]= temp; } } } void sortVstavkaChar(int size, char* array, int loops) { int i, j, temp; for (i = 1; i < size; i++) { temp = array[i]; for (j = i - 1; j >= 0; j--) { if (array[j] < temp) break; array[j+1] = array[j]; array[j]= temp; } } } void print_arrInt(int N, int* array) { int i; for(i=0; i<N; i++) printf(" %i ",array[i]); printf("\n"); } void print_arrChar(int N,char *array) { int i; for(i=0; i<N; i++) printf(" %c ",array[i]); printf("\n"); } void initArrInt(int N,int *array) { int i; for(i=0; i<N; ++i) array[i]=rand()%39; } void initArrChar(int N,char *array) { int i; for(i=0; i<N; ++i) array[i]=rand()%39+61; } void mergeInt( int *a, int *b, int *c, int m, int n ) { int i = 0, j = 0, k = 0; while (i < m && j < n) { if( a[i] < b[j] ) c[k++] = a[i++]; else c[k++] = b[j++]; } while ( i < m ) c[k++] = a[i++]; while ( j < n ) c[k++] = b[j++]; } void mergeSortInt(int size, int* array, int loops) { int i,j; int *w =calloc(size,sizeof(int)); //Указатель на промежуточный массив. int *b1=array; //Промежуточный массив из которого берутся данные. int *b2=w; //Промежуточный массив в который вставляются данные. i=1; int num=0; //Количество шагов сортировки. while(i<size) i=i*2, ++num; //printf("num=%d\n",num); for(i=0; i<num; ++i) { int numElem=i_pow(2,i); //Количество элементов в группах сравнений int numDel=size/i_pow(2,i+1);//количество групп сравнений //printf("numDel=%d\n",numDel); j=0; while(2*j*numElem<size) { int startArr1=2*j*numElem; //Смещение первой части от начала массива b1 int sizeArr1=0; //Количество элементов в первой части. sizeArr1=(size-startArr1<numElem)?size-startArr1:numElem; int startArr2=(2*j+1)*numElem; //Смещение второй части от начала массива b1 int sizeArr2=0; //Количество элементов во второй части. sizeArr2=(size-startArr2<numElem)?size-startArr2:numElem; int startArr3=2*j*numElem; //Смещение отсортированных данных от начала массива b2 mergeInt(b1+startArr1,b1+startArr2,b2+startArr3,sizeArr1,sizeArr2); ++j; } int *b3=b2; b2=b1; b1=b3;//Перестановка виртуальных буферов местами для выполнения следующего шага сортировки. } if(array==b2) for(i=0; i<size; ++i) array[i]=b1[i]; free(w); } void mergeChar(char *a, char *b, char *c, int m, int n ) { int i = 0, j = 0, k = 0; while (i < m && j < n) { if( a[i] < b[j] ) c[k++] = a[i++]; else c[k++] = b[j++]; } while ( i < m ) c[k++] = a[i++]; while ( j < n ) c[k++] = b[j++]; } void mergeSortChar(int size, char* array, int loops) { int i,j; char *w =calloc(size,sizeof(char)); //Указатель на промежуточный массив. char *b1=array; //Промежуточный массив из которого берутся данные. char *b2=w; //Промежуточный массив в который вставляются данные. i=1; int num=0; //Количество шагов сортировки. while(i<size) i=i*2, ++num; //printf("num=%d\n",num); for(i=0; i<num; ++i) { int numElem=i_pow(2,i); //Количество элементов в группах сравнений int numDel=size/i_pow(2,i+1);//количество групп сравнений //printf("numDel=%d\n",numDel); j=0; while(2*j*numElem<size) { int startArr1=2*j*numElem; //Смещение первой части от начала массива b1 int sizeArr1=0; //Количество элементов в первой части. sizeArr1=(size-startArr1<numElem)?size-startArr1:numElem; int startArr2=(2*j+1)*numElem; //Смещение второй части от начала массива b1 int sizeArr2=0; //Количество элементов во второй части. sizeArr2=(size-startArr2<numElem)?size-startArr2:numElem; int startArr3=2*j*numElem; //Смещение отсортированных данных от начала массива b2 mergeChar(b1+startArr1,b1+startArr2,b2+startArr3,sizeArr1,sizeArr2); ++j; } char *b3=b2; b2=b1; b1=b3;//Перестановка виртуальных буферов местами для выполнения следующего шага сортировки. } if(array==b2) for(i=0; i<size; ++i) array[i]=b1[i]; free(w); } void detectTimeInt(void (*foo) (int, int*, int) , int size, int* array, int n) { int i; clock_t start,end; double t; int stime; long ltime; ltime=time(NULL); stime=(unsigned)ltime/2; srand(stime); start=clock(); for(i=0; i<n; ++i) { foo(size,array,n); } end=clock(); t=(end-start)*1.0/CLOCKS_PER_SEC; // print_arrInt(size,array); printf("Time=%f\n",t); } void detectTimeChar(void (*foo) (int, char*, int) , int size, char* array, int n) { int i; clock_t start,end; double t; int stime; long ltime; ltime=time(NULL); stime=(unsigned)ltime/2; srand(stime); start=clock(); for(i=0; i<n; ++i) { foo(size,array,n); } end=clock(); t=(end-start)*1.0/CLOCKS_PER_SEC; // print_arrChar(size,array); printf("Time=%f\n",t); } void callFreeInt(int size, int *array, int loops) { int *w =calloc(size,sizeof(int)); free(w); } void callFreeChar(int size, char *array, int loops) { char *w =calloc(size,sizeof(char)); free(w); }