language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> unsigned int combine(unsigned int x, unsigned int y){ unsigned int maskedx = 0xffff0000 & x; /*Since we would like to extract byte's 3 and 2 from x, I want to get rid of the bytes 0 and 1, which can be done by combining the given x and using the AND operation with my created bitmask 0xffff0000. The AND operation will combine x to the mask replacing any bytes that do not occur in both. Since 0x occurs in both, it occurs in the maskedx. The lowercase f's in the mask will combine with any bits and in x and keep not change them as desired, while finally the 0's at the 0 and 1 byte location will combine with x's byte 1 and 2 causing them to turn into 0's, as desired */ unsigned int maskedy = 0x0000ffff & y; // same logic as above, but instead extracting bytes 0 and 1 unsigned int combined = maskedx | maskedy; //combines both to create a hex with bytes 2 and 3 from x and bytes 1 and 0 from y printf("0x%08x", combined); printf("\n"); return combined; } void main(){ //runs test cases combine(0x12345678,0xABCDEF00); combine(0xABCDEF00,0x12345678); }
C
#define _CRT_SECURE_NO_WARNINGS #include <SDL.h> #include <SDL_ttf.h> #include <stdio.h> #include "Game.h" static SDL_Window* gWindow; static SDL_Renderer* gRenderer; static TTF_Font* gFont; static SDL_Texture* background; static SDL_Texture* player; static SDL_Texture* ownerBanner; static SDL_Texture* diceSheet; static SDL_Texture* house; static SDL_Texture* cross; static int SCREEN_WIDTH = 800; static int SCREEN_HEIGHT = 800; static void renderEverything(); static SDL_Texture* loadTexture(char *, SDL_Renderer*); static int xCross = -1000; static int yCross = -1000; static int init() { int returnValue = 0; if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { printf( "SDL could not initialize! SDL Error: %s\n", SDL_GetError() ); returnValue = 1; } else { //Set texture filtering to linear if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) ) { printf( "Warning: Linear texture filtering not enabled!" ); } //Create window gWindow = SDL_CreateWindow( "Monopoly", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN ); if( gWindow == NULL ) { printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() ); returnValue = 1; } else { //Create renderer for window gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE ); if( gRenderer == NULL ) { printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() ); returnValue = 1; } else { //Initialize renderer color SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); } } } if( TTF_Init() == -1 ) { printf( "SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError() ); returnValue = 1; } gFont = TTF_OpenFont( "fonts/UbuntuMono-R.ttf", 32 ); if( gFont == NULL ) { printf( "Failed to load lazy font! SDL_ttf Error: %s\n", TTF_GetError() ); returnValue = 1; } background = loadTexture( "images/monopoly.bmp", gRenderer); player = loadTexture("images/player.bmp", gRenderer); ownerBanner = loadTexture("images/ownerbanner.bmp", gRenderer); diceSheet = loadTexture("images/dice.bmp", gRenderer); house = loadTexture("images/house.bmp", gRenderer); cross = loadTexture("images/cross.bmp", gRenderer); return returnValue; } static int close() { /*SDL_DestroyTexture( gTexture ); gTexture = NULL;*/ SDL_DestroyTexture(background); SDL_DestroyTexture(player); SDL_DestroyTexture(ownerBanner); SDL_DestroyTexture(diceSheet); SDL_DestroyTexture(house); SDL_DestroyTexture(cross); //Destroy window SDL_DestroyRenderer( gRenderer ); SDL_DestroyWindow( gWindow ); gWindow = NULL; gRenderer = NULL; //Quit SDL subsystems SDL_Quit(); } static SDL_Texture* loadTexture(const char* file, SDL_Renderer *const renderer){ SDL_Surface *loadedImage = NULL; SDL_Texture *texture = NULL; loadedImage = SDL_LoadBMP(file); if (loadedImage != NULL){ SDL_SetColorKey(loadedImage, 1, 0x323232); texture = SDL_CreateTextureFromSurface(renderer, loadedImage); SDL_FreeSurface(loadedImage); } else return NULL; /*logSDLError("Image could not be loaded!");*/ return texture; } static void renderText(const char * text, int x, int y, SDL_Color color) { //SDL_Color color = {0, 255, 0}; // this is the color in rgb format, maxing out all would give you the color white, and it will be your text's color SDL_Rect Message_rect; //create a rect SDL_Surface* surfaceMessage = TTF_RenderText_Blended(gFont, text, color); SDL_Texture* Message = SDL_CreateTextureFromSurface(gRenderer, surfaceMessage); //now you can convert it into a texture SDL_FreeSurface(surfaceMessage); Message_rect.x = x; //controls the rect's x coordinate Message_rect.y = y; // controls the rect's y coordinte /*Message_rect.w = 100; // controls the width of the rect Message_rect.h = 10; // controls the height of the rect*/ SDL_QueryTexture(Message, NULL, NULL, &Message_rect.w, &Message_rect.h); SDL_RenderCopy(gRenderer, Message, NULL, &Message_rect); // SDL_DestroyTexture(Message); } static void renderTexture(SDL_Texture* tex, int x, int y) { SDL_Rect pos; pos.x = x; pos.y = y; SDL_QueryTexture(tex, NULL, NULL, &pos.w, &pos.h); SDL_RenderCopy(gRenderer, tex, NULL, &pos); } static void renderTextureRot(SDL_Texture* tex, int x, int y, double degrees) { SDL_Rect pos; pos.x = x; pos.y = y; SDL_QueryTexture(tex, NULL, NULL, &pos.w, &pos.h); SDL_RenderCopyEx(gRenderer, tex, NULL, &pos, degrees, NULL, SDL_FLIP_NONE); } void renderPlayerTextureAtPos(SDL_Texture* player_texture, int game_position, int playerid) { const int PROP_WIDTH = 66; const int PROP_HEIGHT = 80; const int GO_WIDTH = 103; const int PLAYER_SIZE = 30; int xPos, yPos; if (playerid == 0) SDL_SetTextureColorMod(player, 255, 0, 0); if (playerid == 1) SDL_SetTextureColorMod(player, 0, 0, 255); if (game_position <= 10) { xPos = SCREEN_WIDTH - (GO_WIDTH / 2 + PROP_WIDTH * (game_position + 1) - PLAYER_SIZE); yPos = SCREEN_HEIGHT - PROP_HEIGHT; } else if (game_position >= 11 && game_position <= 19) { xPos = SCREEN_WIDTH - (GO_WIDTH / 2 + PROP_WIDTH * 11 - PLAYER_SIZE); yPos = SCREEN_HEIGHT - (GO_WIDTH / 2 + PROP_WIDTH * (game_position - 9) - PLAYER_SIZE); } else if (game_position >= 20 && game_position <= 30) { xPos = SCREEN_WIDTH - (GO_WIDTH / 2 + PROP_WIDTH * (31 - game_position ) - PLAYER_SIZE); yPos = PROP_HEIGHT - PLAYER_SIZE; } else if (game_position >= 31 && game_position <= 39) { xPos = SCREEN_WIDTH - (GO_WIDTH / 2 + PROP_WIDTH - PLAYER_SIZE); yPos = SCREEN_HEIGHT - (GO_WIDTH / 2 + PROP_WIDTH * (41 - game_position) - PLAYER_SIZE); } renderTexture(player_texture, xPos, yPos); } void renderPropOwnerAtPos(SDL_Texture* banner, int game_position, int playerid, int mortaged, int level) { const int PROP_WIDTH = 66; const int PROP_HEIGHT = 80; const int PROP_HEIGHT_FULL = 104; const int GO_WIDTH = 103; const int PLAYER_SIZE = 30; const int BANNER_HEIGHT = 10; int xPos, yPos; double degrees = 0; int xPosH = 400, yPosH = 400; if (playerid == 0) SDL_SetTextureColorMod(ownerBanner, 255, 0, 0); if (playerid == 1) SDL_SetTextureColorMod(ownerBanner, 0, 0, 255); if (game_position % 10 == 0) return; if (game_position <= 10) { xPos = SCREEN_WIDTH - (GO_WIDTH + PROP_WIDTH * (game_position)); yPos = SCREEN_HEIGHT - PROP_HEIGHT_FULL - BANNER_HEIGHT/2; xPosH = xPos; yPosH = yPos + 90; } else if (game_position >= 11 && game_position <= 19) { xPos = PROP_HEIGHT - BANNER_HEIGHT; yPos = SCREEN_HEIGHT - (GO_WIDTH + PROP_WIDTH * (game_position - 10)) + 27; degrees = 90; xPosH = xPos - 70; yPosH = yPos - 27; } else if (game_position >= 20 && game_position <= 30) { xPos = SCREEN_WIDTH - (GO_WIDTH + PROP_WIDTH * (30 - game_position)); yPos = PROP_HEIGHT_FULL - BANNER_HEIGHT/2; degrees = 180; xPosH = xPos; yPosH = yPos - 100; } else if (game_position >= 31 && game_position <= 39) { xPos = SCREEN_WIDTH - (PROP_HEIGHT_FULL + BANNER_HEIGHT/2 + 27); yPos = SCREEN_HEIGHT - (GO_WIDTH + PROP_WIDTH * (40 - game_position)) + 27; degrees = 270; xPosH = xPos + 120; yPosH = yPos - 27; } renderTextureRot(banner, xPos, yPos, degrees); if (mortaged) { SDL_Rect pos; SDL_SetTextureColorMod(ownerBanner, 0, 0, 0); pos.x = xPos; pos.y = yPos; SDL_QueryTexture(banner, NULL, NULL, &pos.w, &pos.h); pos.w = 0.5 * pos.w; if (degrees == 90 || degrees == 270) { pos.x += 16; pos.y -= 17; } SDL_RenderCopyEx(gRenderer, banner, NULL, &pos, degrees, NULL, SDL_FLIP_NONE); } if (level > 0 && level <= 4) { int offset = 16; int i; for (i = 0; i < level; i++) { SDL_Rect r; if (degrees == 0 || degrees == 180) { r.x = xPosH + offset * i; r.y = yPosH; } else { r.x = xPosH; r.y = yPosH + offset * i; } r.w = 16; r.h = 16; SDL_SetTextureColorMod(house, 0, 255, 0); SDL_RenderCopyEx(gRenderer, house, NULL, &r, degrees, NULL, SDL_FLIP_NONE); } //renderTextureRot(house, xPos, yPos, degrees); } if (level == 5) { SDL_SetTextureColorMod(house, 255, 0, 0); if (degrees == 0) { xPosH += 16; yPosH -= 16; } if (degrees == 90) { yPosH += 16; } if (degrees == 180) { xPosH += 16; } if (degrees == 270) { xPosH -= 16; yPosH += 16; } renderTextureRot(house, xPosH, yPosH, degrees); } } void renderDices(SDL_Texture* dice, int face1, int face2) { SDL_Rect pos, crop; int face[2] = {face1, face2}; int i; for (i = 0; i < 2; i++) { pos.x = 300 + i * 80; pos.y = 280; pos.w = 192 / 3; pos.h = 128 / 2; crop.w = pos.w; crop.h = pos.h; crop.x = face[i] % 3 == 0 ? 128 : (face[i] % 3 - 1) * 64; crop.y = face[i] > 3 ? 64 : 0; //SDL_QueryTexture(tex, NULL, NULL, &pos.w, &pos.h); SDL_RenderCopy(gRenderer, dice, &crop, &pos); } } static int parsePropFromPos(int x, int y) { const int PROP_WIDTH = 66; const int PROP_HEIGHT = 80; const int PROP_HEIGHT_FULL = 104; const int GO_WIDTH = 103; if (y >= SCREEN_HEIGHT - GO_WIDTH) { return 9 - (x - GO_WIDTH) / PROP_WIDTH; } if (y <= GO_WIDTH) { return (x - GO_WIDTH) / PROP_WIDTH + 21; } if (x <= GO_WIDTH) { return 19 - (y - GO_WIDTH) / PROP_WIDTH; } if (x >= SCREEN_WIDTH - GO_WIDTH) { return 31 + (y - GO_WIDTH) / PROP_WIDTH; } return -1; } static void processEventsAndRender() { int quit = 0; SDL_Event e; while( !quit ) { renderEverything(); //Handle events on queue while( SDL_PollEvent( &e ) != 0 ) { //User requests quit if( e.type == SDL_QUIT ) { quit = 1; } if ( e.type == SDL_KEYDOWN) { Game_receiveinput(e.key.keysym.sym); /*switch( e.key.keysym.sym ) { case SDLK_SPACE: Game_cycle(); break; }*/ } if ( e.type == SDL_MOUSEBUTTONDOWN ) { int x, y, s; SDL_GetMouseState(&x, &y); s = parsePropFromPos(x,y); printf("%i %i %i\n", x,y, s); if (s >= 0) { xCross = x; yCross = y; Game_selectProperty(s); } else { xCross = -1000; yCross = -1000; } } } } } int main(int argc, char* argv[]) { init(); Game_init(); processEventsAndRender(); close(); } void renderEverything() { SDL_Color color = {0, 0, 0}; int i, j; char * text; SDL_RenderClear( gRenderer ); renderTexture(background, 0, 0); Game_getLastRoll(&i, &j); renderDices(diceSheet, i, j); i = 0; while ((text = Game_getText(i)) != NULL) { renderText(text, 130, 440 + 40 * i, color); i++; } renderTextureRot(cross, xCross - 25, yCross - 25, 0); //renderTexture(diceSheet, 200, 200); for (i = 0; i < 2; i++) { char * reply = Game_getFormattedStatus(i); renderText(reply, 450, 120 + 40 * i, color); free(reply); } for (i = 0; i < Game_getTotalPlayers(); i++) { renderPlayerTextureAtPos(player, Game_getPlayerPosition(i), i); } for (i = 0; i < 40; i++) { j = Game_getPropOwner(i); if (j >= 0) renderPropOwnerAtPos(ownerBanner, i, j, Game_getPropMortageStatus(i), Game_getPropLevel(i)); } SDL_RenderPresent( gRenderer ); }
C
double myPow(double x, int n){ if (n == 0) return 1; if (n == 1) return x; long long N = n; if (N <= 0) { N = -N; x = 1/x; } double half = myPow(x, N/2); if (n % 2 == 0) { return half * half; } else { return half * half * x; } }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> int main() { for(int i = 2;i < 101;i++){ bool prime = true; for(int x = 2;x < i;x++){ if(i % x == 0){ prime = false; break; } } if(prime == true){ printf("%d\n",i); } } return 0; }
C
#include <stdio.h> #include <string.h> typedef int bool; //Definicion del tipo booleano en C. #define true 1 // #define false 0 // // ---------------------------------ESTRUCTURAS------------------------------------------------------ struct tupla_catalogo {int identificador_unico; int numero_columna; char dato[256];} tupla_catalogo; // --------------------------------------------------------------------------------------------------- // ------------------------------------------------MÉTODOS-------------------------------------------- int cantidad_tablas(){ // Devuelve la cantidad de tablas presentes en el archivo catalog.dat int suma=0; FILE *fp=fopen("catalog.dat","r"); while(fread(&tupla_catalogo,sizeof(tupla_catalogo),1,fp)){ if(tupla_catalogo.identificador_unico != suma) suma++; } fclose(fp); return suma; } //--------------------------VALIDACION------------------------- int tamano_de_palabra(char* argv) { // Devuelve la cantidad de caracteres en un vector de char int i = 0; while(argv[i] != 0){ // Los argv[i] son los numeros de los caracteres i++;// El caracter \0 es el caracter nulo, o sea, el fin de la palabra. } return i; } //---------------------------------------------- bool validacion_de_columnas(char * argv) { // Valida que un argumento corresponda al formato int i = 0; // <tipo_dato>-<nombre_atributo> int tam = tamano_de_palabra(argv); while (argv[i] != (int)'-' && i < tam) i++; if(i == 0) { printf("\n--> Excepcion en \"%s\"\n", argv); printf("ERROR: Debe indicar un nombre de parametro.\n"); return false; } if(i == tam) { printf("\n--> Excepcion en \"%s\"\n", argv); printf("ERROR: No se encuentra separación '-' entre nombre y tipo.\n"); return false; } if(i+1 == tam) { printf("\n--> Excepcion en \"%s\"\n", argv); printf("ERROR: El parametro %s no posee un identificador.\n", argv); return false; } char *a,*b; char aux[tam]; strcpy(aux, argv); // El metodo strtok destruye el char*. a = (char*)strtok(aux,"-");//Recupera el primer elemento de argv segun '-'. b = (char*)strtok(NULL,"-");//Recupera el segundo elemento de argv segun '-'. if(validar_tipo(a) == 0) return false; return true; } //---------------------------------------------- bool validar_tipo(char * tipo, char * identificador) { // Valida que el tipo de dato digitado corresponda // a uno de los tres permitidos: int, float o text if(strcmp("text", tipo) == 0) { return true; } if(strcmp("int", tipo) == 0){ return true; } if(strcmp("float", tipo) == 0) { return true; } printf("\n--> Excepcion en \"%s-%s\"\n", tipo, identificador); printf("ERROR: El tipo %s no es un tipo valido.\n", tipo); return false; } //---------------------------------------------- bool administrador_validacion(int argc, char ** argv) { // Método principal para la validación if(argc<3) { printf("\nERROR: No se encontraron argumentos suficientes para"); printf(" realizar la operacion.\n"); printf("El formato requerido es:\n create nombre_de_tabla"); printf(" tipo_de_columna_1-identificador_de_columna_1 ...\n"); return false; // 3 argumentos: metodo, tabla y primera columna. } // El nombre de la tabla necesitara validacion cuando necesite revisar // si ese nombre de tabla ya existe int i; for(i = 2; i < argc; i++) { if(validacion_de_columnas(argv[i]) == 0) return false; } return true; } //--------------------------------------------------------------// bool validacion(int argc, char ** argv) // Invoca al método principal para la validación y muestra un mensaje { // en caso de que la peticion de creacion de tabla sea rechazada if(administrador_validacion(argc,argv) == 1) return true; // por la falta de algun dato requerido printf("=== CREACION DE TABLA RECHAZADA ===\n"); return false; } //--------------------------------------------------------------// //--------------------------MAIN--------------------------------// int main(int argc, char ** argv){ if(validacion(argc,argv) == 0) // En caso de que la validación detecte algún problema, termina el programa. return 0; FILE *fp=fopen("catalog.dat","a"); // Abre catalog.dat para su escritura. int i, num_tab = cantidad_tablas()+1; for (i=1;i<argc;i++){ // Ciclo que graba en disco cada uno de los bloques necesarios para la tabla tupla_catalogo.identificador_unico = num_tab; tupla_catalogo.numero_columna = i-1; strcpy(tupla_catalogo.dato,argv[i]); fwrite(&tupla_catalogo,sizeof(tupla_catalogo),1,fp); } fclose(fp); // Cierra el flujo de datos al archivo printf("\n=== TABLA CREADA ===\n"); // Imprime un mensaje de éxito return 0; // Termina el programa } //--------------------------------------------------------------//
C
#include "searchFunctions.h" #include <stdio.h> #include <stdlib.h> /* * This does a linear search from bottom floor to top * If you for some reason think that the average is high * if you are doing a search with the average kind of low * and a variance high it will be above the average because * for it to be drug down to the mean you need the negatives. */ int linearSearchForFloor(int balloonPop, int topFloor, int bottomFloor) { if(balloonPop>topFloor){ balloonPop=topFloor; } if(balloonPop<bottomFloor){ balloonPop=bottomFloor; } int check; int counter = 1; for (check=bottomFloor;check<=topFloor;check++){ if(check>=balloonPop){ break; } counter++; } //printf("%d\n",counter); return counter; } /** * This performs a binary search on the building between * top and bottom floor */ int binarySearchForFloor(int balloonPop, int topFloor, int bottomFloor) { if(balloonPop>topFloor){ balloonPop=topFloor; } if(balloonPop<bottomFloor){ balloonPop=bottomFloor; } int lowerBound=bottomFloor; int upperBound=topFloor; int counter=1; int floorGuess=(topFloor-bottomFloor)/2+bottomFloor; /** * This checks that the search finds the correct position * starting at floor(numFloors/2) due to integer division * then if the search is above it checks the * guess +(upperbound - guess)/2 * and similarly checks guess-(guess-lowerbound)/2 otherwise * at the very upper cases it has the top two if statements * for corner cases I can't get to work without them. */ while(floorGuess!=balloonPop) { //printf("balloonPop: %d,floorGuess %d \n",balloonPop,floorGuess); if(floorGuess==topFloor-1 && floorGuess<balloonPop) { floorGuess++; // printf("top"); // break; }else if(floorGuess==bottomFloor+1 && floorGuess>balloonPop) { //printf("bottom"); floorGuess--; //printf("%d\n",floorGuess); // break; }else if(balloonPop>floorGuess) { lowerBound=floorGuess; floorGuess=floorGuess+(upperBound-floorGuess)/2; /* * The +1 is used so that it can hit the upper * bound. */ }else if(balloonPop<floorGuess) { upperBound=floorGuess; floorGuess=floorGuess-(floorGuess-lowerBound)/2; } counter++; } if(floorGuess!=balloonPop){ printf(" %d and %d and %d\n",floorGuess,balloonPop,lowerBound); exit(1); // return -1; } //printf("%d\n",counter); return counter; } /* * This is a search that is like a binary search but randomly selects point */ int randomSearchForFloor(int balloonPop, int topFloor, int bottomFloor) { int count = 1; int floorGuess = rand()%(topFloor-bottomFloor)+bottomFloor; while (floorGuess!=balloonPop){ floorGuess = rand()%(topFloor-bottomFloor)+bottomFloor; if(floorGuess==bottomFloor && balloonPop<bottomFloor){ break; } // minus one because we are working in Z_{top-bottom} which wont // have the top floor if(floorGuess==topFloor-1 && balloonPop>topFloor){ break; } count++; } return count; }
C
//this program is to find the solution of function //using bisection method #include<stdio.h> #include<stdlib.h> float Fun(float x) { float y; y = (x*x)+(2.1*x)-8.82; return y; } void bisection(double a, double b) { if (Fun(a) * Fun(b) >= 0) { printf("You have not assumed right a and b\n"); return; } double c, epsilon=0.001; while ((b-a) >= epsilon) { // Find middle point c = (a+b)/2; // Check if middle point is root if (Fun(c) == 0.0) break; // Decide the side to repeat the steps else if (Fun(c)*Fun(a) < 0) b = c; else a = c; } printf("The root is %f\n",c); } int main() { double a, b; a=0; b=4; bisection(a,b); return 0; }
C
/* inimgrGetBool.c */ #include "inimgr_types.h" int inimgrGetBool( InimgrUID uid, const char *name, const char *key, bool *res ) { int ret; char *value; if( ( ret = __inimgr_get_value( (struct inimgr_params *)uid, name, key, &value ) ) == CG_ERROR_OK ){ if( strcasecmp( value, "ON" ) == 0 ){ *res = true; } else if( strcasecmp( value, "OFF" ) == 0 ){ *res = false; } else{ ret = CG_ERROR_INI_INVALID_VALUE; } } return ret; }
C
/**************************************************************************** Title: Watchdog Timer Interrupt Author: Elegantcircuits.com File: $Id: watchdog_interrupt.c Software: AVR-GCC 3.3 Hardware: Atmega328P AVR Description: This example shows how to drive an LED periodically using the watchdog timer as a system clock HW Description: LED -> PB1 Reference: http://electronics.stackexchange.com/questions/74840/use-avr-watchdog-like-normal-isr *****************************************************************************/ #include <avr/io.h> #include <avr/interrupt.h> #include <avr/sleep.h> #include <avr/wdt.h> #include <avr/power.h> // Function Prototypes void init_devices(void); void init_io(void); void timer0_init(void); void check_wdt(void); void setup_wdt(void); // Global Variables volatile char tick_flag = 0; /* if non-zero, a tick has elapsed */ int main(void){ unsigned char ret; init_io(); cli(); check_wdt(); setup_wdt(); sei(); // Enables interrupts // Enable Sleep Mode for Power Down set_sleep_mode(SLEEP_MODE_PWR_DOWN); // Set Sleep Mode: Power Down sleep_enable(); // Enable Sleep Mode for(;;){ // Event Loop if(tick_flag){ tick_flag = 0; sleep_disable(); set_sleep_mode(SLEEP_MODE_PWR_DOWN); sleep_enable(); sleep_mode(); // Put the AVR to sleep } } } void check_wdt(void){ if(MCUSR & _BV(WDRF)){ // If a reset was caused by the Watchdog Timer... MCUSR &= ~_BV(WDRF); // Clear the WDT reset flag WDTCSR |= (_BV(WDCE) | _BV(WDE)); // Enable the WD Change Bit WDTCSR = 0x00; // Disable the WDT } } void setup_wdt(void){ // Set up Watch Dog Timer for Inactivity WDTCSR |= (_BV(WDCE) | _BV(WDE)); // Enable the WD Change Bit // Enable WDT interrupt //WDTCSR = _BV(WDIE) | _BV(WDP2) | _BV(WDP1); // Set Timeout to ~1 seconds WDTCSR = _BV(WDIE) | _BV(WDP2); // Set Timeout to ~500 ms } //call this routine to initialize all peripherals void init_devices(void){ //stop errant interrupts until set up cli(); //disable all interrupts timer0_init(); MCUCR = 0x00; EICRA = 0x00; //extended ext ints EIMSK = 0x00; TIMSK0 = 0x02; //timer 0 interrupt sources PRR = 0x00; //power controller sei(); //re-enable interrupts //all peripherals are now initialized } //TIMER0 initialize - prescale:1024 // WGM: CTC // desired value: 10mSec // actual value: 10.048mSec (-0.5%) void timer0_init(void){ TCCR0B = 0x00; // Stop TCNT0 = 0x00; // Set count TCCR0A = 0x02; // CTC mode OCR0A = 0xFF; // Output Compare Register //OCR0A = 0x9C; TCCR0B = 0x01; //start timer } void init_io(void){ DDRB = 0xff; // use all pins on port B for output PORTB = 0x00; // (LED's low & off) } ISR(WDT_vect){ // WDT has overflowed sleep_disable(); PORTB ^= _BV(PB1); tick_flag = 1; sleep_enable(); } //============================================================ #include <avr/wdt.h> void setup() { wdt_disable(); pinMode(3, INPUT); wdt_enable(WDTO_1S); } void loop() { boolean flag = true; do { if (digitalRead(3) == HIGH) { flag = false; } } while (flag); wdt_reset(); } //============================================================
C
#include <stdio.h> unsigned long Fibonacci(unsigned long n); int main(void) { unsigned long n; printf("Please enter your Fibonacci number(q for exit): "); while(scanf("%lu", &n) == 1) { printf("Answer for your Fibonacci number: %lu", Fibonacci(n)); putchar('\n'); printf("Please enter next Fibonacci number(q for exit): "); } return 0; } unsigned long Fibonacci(unsigned long n) { unsigned int current_number = 2; unsigned int previous_number = 1; unsigned temp; if(n > 2) { for(int i = 3; i < n; i++){ temp = current_number; current_number += previous_number; previous_number = temp; } return current_number; } else { if(n == 0) return 0; else return 1; } }
C
#pragma once inline int ieo_min_i(int const x, int const y) { return y < x ? y : x; } inline unsigned ieo_min_u(unsigned const x, unsigned const y) { return y < x ? y : x; } inline long ieo_min_l(long const x, long const y) { return y < x ? y : x; } inline unsigned long ieo_min_ul(unsigned long const x, unsigned long const y) { return y < x ? y : x; } inline long long ieo_min_ll(long long const x, long long const y) { return y < x ? y : x; } inline unsigned long long ieo_min_ull(unsigned long long const x, unsigned long long const y) { return y < x ? y : x; } inline float ieo_min_f(float const x, float const y) { return y < x ? y : x; } inline double ieo_min_d(double const x, double const y) { return y < x ? y : x; } inline long double ieo_min_ld(long double const x, long double const y) { return y < x ? y : x; } inline int ieo_max_i(int const x, int const y) { return x < y ? y : x; } inline unsigned ieo_max_u(unsigned const x, unsigned const y) { return x < y ? y : x; } inline long ieo_max_l(long const x, long const y) { return x < y ? y : x; } inline unsigned long ieo_max_ul(unsigned long const x, unsigned long const y) { return x < y ? y : x; } inline long long ieo_max_ll(long long const x, long long const y) { return x < y ? y : x; } inline unsigned long long ieo_max_ull(unsigned long long const x, unsigned long long const y) { return x < y ? y : x; } inline float ieo_max_f(float const x, float const y) { return x < y ? y : x; } inline double ieo_max_d(double const x, double const y) { return x < y ? y : x; } inline long double ieo_max_ld(long double const x, long double const y) { return x < y ? y : x; } #define MIN(X, Y) \ (_Generic((X) + (Y), int \ : ieo_min_i, unsigned \ : ieo_min_u, long \ : ieo_min_l, unsigned long \ : ieo_min_ul, long long \ : ieo_min_ll, unsigned long long \ : ieo_min_ull, float \ : ieo_min_f, double \ : ieo_min_d, long double \ : ieo_min_ld)((X), (Y))) #define MAX(X, Y) \ (_Generic((X) + (Y), int \ : ieo_max_i, unsigned \ : ieo_max_u, long \ : ieo_max_l, unsigned long \ : ieo_max_ul, long long \ : ieo_max_ll, unsigned long long \ : ieo_max_ull, float \ : ieo_max_f, double \ : ieo_max_d, long double \ : ieo_max_ld)((X), (Y)))
C
#include <stdio.h> #include <conio.h> #include <stdlib.h> int main() { char K1, K2; printf("Masukkan Karakter Pertama : "); K1 = _getch(); printf("\n"); printf("Masukkan Karakter Kedua : "); K2 = _getche(); printf("\n"); printf("Karakter yang dimasukkan adalah : %c dan %c \n\n", K1, K2); _getch(); return 0; }
C
#include "fmacros.h" #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <stdarg.h> #include <limits.h> #include <sys/time.h> #include "dict.h" #include "zmalloc.h" #include <assert.h> /* ------------------------------- Benchmark ---------------------------------*/ #define DICT_BENCHMARK_MAIN #ifdef DICT_BENCHMARK_MAIN #include "sds.h" uint64_t hashCallback(const void *key) { return dictGenHashFunction((unsigned char*)key, sdslen((char*)key)); } int compareCallback(void *privdata, const void *key1, const void *key2) { int l1,l2; DICT_NOTUSED(privdata); l1 = sdslen((sds)key1); l2 = sdslen((sds)key2); if (l1 != l2) return 0; return memcmp(key1, key2, l1) == 0; } void freeCallback(void *privdata, void *val) { DICT_NOTUSED(privdata); sdsfree(val); } dictType BenchmarkDictType = { hashCallback, NULL, NULL, compareCallback, freeCallback, NULL }; long long timeInMilliseconds(void); #define start_benchmark() start = timeInMilliseconds() #define end_benchmark(msg) do { \ elapsed = timeInMilliseconds()-start; \ printf(msg ": %ld items in %lld ms\n", count, elapsed); \ } while(0); /* dict-benchmark [count] */ int main(int argc, char **argv) { long j; long long start, elapsed; dict *dict = dictCreate(&BenchmarkDictType,NULL); long count = 0; if (argc == 2) { count = strtol(argv[1],NULL,10); } else { count = 5000000; } start_benchmark(); for (j = 0; j < count; j++) { int retval = dictAdd(dict,sdsfromlonglong(j),(void*)j); assert(retval == DICT_OK); } end_benchmark("Inserting"); assert((long)dictSize(dict) == count); /* Wait for rehashing. */ while (dictIsRehashing(dict)) { dictRehashMilliseconds(dict,100); } start_benchmark(); for (j = 0; j < count; j++) { sds key = sdsfromlonglong(j); dictEntry *de = dictFind(dict,key); assert(de != NULL); sdsfree(key); } end_benchmark("Linear access of existing elements"); start_benchmark(); for (j = 0; j < count; j++) { sds key = sdsfromlonglong(j); dictEntry *de = dictFind(dict,key); assert(de != NULL); sdsfree(key); } end_benchmark("Linear access of existing elements (2nd round)"); start_benchmark(); for (j = 0; j < count; j++) { sds key = sdsfromlonglong(rand() % count); dictEntry *de = dictFind(dict,key); assert(de != NULL); sdsfree(key); } end_benchmark("Random access of existing elements"); start_benchmark(); for (j = 0; j < count; j++) { sds key = sdsfromlonglong(rand() % count); key[0] = 'X'; dictEntry *de = dictFind(dict,key); assert(de == NULL); sdsfree(key); } end_benchmark("Accessing missing"); start_benchmark(); for (j = 0; j < count; j++) { sds key = sdsfromlonglong(j); int retval = dictDelete(dict,key); assert(retval == DICT_OK); key[0] += 17; /* Change first number to letter. */ retval = dictAdd(dict,key,(void*)j); assert(retval == DICT_OK); } end_benchmark("Removing and adding"); } #endif
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include <semaphore.h> #define QTLeitores 3 #define QTEscritores 2 sem_t rmutex; // sem_t db; //controla o acesso a base da dados (Rc) int rc = 0; //número de processos lendo ou querendo ler void *leitor(void *arg); void *escritor(void *arg); void le_db(int i); void usa_dado(int i); void escreve(int i); void pensa(int i); int main (void){ sem_init(&rmutex, 0, 1); sem_init(&db, 0, 1); //vetores de threads pthread_t threadsLeitoras[QTLeitores]; pthread_t threadsEscritoras[QTEscritores]; int parLeitores[QTLeitores]; int parEscritores[QTEscritores]; //gera threads leitores for(int i = 0; i < QTLeitores; i++){ parLeitores[i] = i; pthread_create(&threadsLeitoras[i], NULL, leitor, (void*) &parLeitores[i]); } //gera threads escritores for(int i = 0; i < QTEscritores; i++){ parEscritores[i] = i; pthread_create(&threadsEscritoras[i], NULL, escritor, (void*) &parEscritores[i]); } //join nas threads for(int i = 0; i < QTLeitores; i++){ pthread_join(threadsLeitoras[i], NULL); } for(int i = 0; i < QTEscritores; i++){ pthread_join(threadsEscritoras[i], NULL); } } void *leitor(void *arg){ int ind = *(int*) arg; while(1){ sem_wait(&rmutex); ///garante que nenhum outro leitor execute a região critica enquanto este esta lá rc += 1; //mais um leitor na rc if(rc == 1){ sem_wait(&db); //primeiro leitor fecha o db, impedindo os escritores; db segue reservado para os leitores subsequentes. } sem_post(&rmutex); le_db(ind); sem_wait(&rmutex); rc -= 1 ; if(rc == 0){ sem_post(&db); //ultimo leitor libera a base } sem_post(&rmutex); usa_dado(ind); } } void *escritor(void *arg){ int ind = *(int*) arg; while(1){ pensa(ind); /*pode perder o processador aqui e como isso dar a impressão de erro, pois printou o resultado de pensa porém não reservou a seção*/ sem_wait(&db); escreve(ind); sem_post(&db); } } void pensa(int i){ printf("Sou a thread escritora %d e estou pensando no que escrever(antes de entra na RC)\n", i + 1); //sleep(rand() % 3); } void escreve(int i){ printf("Sou a thread escritora %d e estou escrevendo (dentro da RC)\n", i + 1); //sleep(rand() % 3); } void usa_dado(int i){ printf("Sou a thread %d leitora vou usar os dados (estou fora da RC) \n", i + 1); //sleep(rand() % 3); } void le_db(int i){ printf("Sou a thread %d leitora e vou ler (dentro da RC) \n", i + 1); //sleep(rand() % 3); }
C
/* * @lc app=leetcode.cn id=10 lang=c * * [10] 正则表达式匹配 * * https://leetcode-cn.com/problems/regular-expression-matching/description/ * * algorithms * Hard (30.81%) * Likes: 1915 * Dislikes: 0 * Total Accepted: 148K * Total Submissions: 479.1K * Testcase Example: '"aa"\n"a"' * * 给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 '.' 和 '*' 的正则表达式匹配。 * * * '.' 匹配任意单个字符 * '*' 匹配零个或多个前面的那一个元素 * * * 所谓匹配,是要涵盖 整个 字符串 s的,而不是部分字符串。 * * * 示例 1: * * * 输入:s = "aa" p = "a" * 输出:false * 解释:"a" 无法匹配 "aa" 整个字符串。 * * * 示例 2: * * * 输入:s = "aa" p = "a*" * 输出:true * 解释:因为 '*' 代表可以匹配零个或多个前面的那一个元素, 在这里前面的元素就是 'a'。因此,字符串 "aa" 可被视为 'a' 重复了一次。 * * * 示例 3: * * * 输入:s = "ab" p = ".*" * 输出:true * 解释:".*" 表示可匹配零个或多个('*')任意字符('.')。 * * * 示例 4: * * * 输入:s = "aab" p = "c*a*b" * 输出:true * 解释:因为 '*' 表示零个或多个,这里 'c' 为 0 个, 'a' 被重复一次。因此可以匹配字符串 "aab"。 * * * 示例 5: * * * 输入:s = "mississippi" p = "mis*is*p*." * 输出:false * * * * 提示: * * * 0 * 0 * s 可能为空,且只包含从 a-z 的小写字母。 * p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 *。 * 保证每次出现字符 * 时,前面都匹配到有效的字符 * * */ // @lc code=start bool isMatchCore(char *s, char *p) { if (*s == '\0' && *p == '\0') return true; else if (*s != '\0' && *p == '\0') return false; else if (*(p + 1) == '*') { if (*s == *p || (*p == '.' && *s != '\0')) { return isMatchCore(s, p + 2) || isMatchCore(s + 1, p) || isMatchCore(s + 1, p + 2); } else return isMatchCore(s, p + 2); } else if (*s == *p || (*p == '.' && *s != '\0')) return isMatchCore(s + 1, p + 1); else return false; } bool isMatch(char *s, char *p) { if (s == NULL || p == NULL) return false; else return isMatchCore(s, p); } // @lc code=end
C
#include "nu/peripheral/flash.h" #include "nu/wdt.h" #define CONST_FLASH_SIZE_WORDS (((CONST_FLASH_SIZE_BYTES)-1)>>2)+1 /* Note that: * "bytes" needs to be a multiple of BYTE_PAGE_SIZE (and aligned that way) * if you intend to erase * "bytes" needs to be a multiple of BYTE_ROW_SIZE (and aligned that way) * if you intend to write rows * "bytes" needs to be a multiple of sizeof(int) if you intend to write words */ #define NVM_ALLOCATE(name, align, bytes) volatile unsigned char name[(bytes)] \ __attribute__((aligned(align),space(prog),section(".nvm"))) = \ { [0 ... (bytes)-1] = 0xFF } NVM_ALLOCATE(_flash, BYTE_PAGE_SIZE, BYTE_PAGE_SIZE); int32_t nu__Flash__erase_flash(void) { int32_t err = 0; uint32_t maxAttempts = 3; while (maxAttempts--) { size_t ui; for (ui = 0, err = 0; ui < CONST_FLASH_SIZE_BYTES/BYTE_PAGE_SIZE; ++ui) { nu__WDT__clear(); NVMErasePage((void *)(_flash+ui*BYTE_PAGE_SIZE)); if (*((volatile uint32_t *)(_flash + ui*BYTE_PAGE_SIZE)) != 0xFFFFFFFF) { err = -EOTHER; break; } } if (!err) break; } return err; } INLINE int32_t nu__Flash__read_flash(void *dst, size_t siz) { memcpy(dst, (const void *)_flash, siz); return (siz > CONST_FLASH_SIZE_BYTES) ? -EEXCEEDSFLASHSIZ : 0; } int32_t nu__Flash__write_flash(const void *src, size_t siz) { int32_t err = 0; size_t ui; uint32_t maxAttempts = 3; const unsigned int *srcWords = (const unsigned int *)src; if (src == NULL) return -ENULPTR; if ((err = nu__Flash__erase_flash()) < 0) return err; while (maxAttempts--) { nu__WDT__clear(); for (ui = 0, err = 0; ui*sizeof(int) < siz && ui < CONST_FLASH_SIZE_BYTES/sizeof(int); ++ui) { nu__WDT__clear(); NVMWriteWord((void *)(_flash+ui*sizeof(int)), srcWords[ui]); if (*((volatile uint32_t *)(_flash+ui*sizeof(int))) != srcWords[ui]) { err = -EOTHER; break; } } if (!err) break; } if (err == 0 && siz > CONST_FLASH_SIZE_BYTES) err = -EEXCEEDSFLASHSIZ; return err; }
C
# shanmugapriya #include<stdio.h> #include<math.h> int main() { int num,a,r=0,rem; scanf("%d",&num); a=num; while(num!=0) { rem=num%10; r=r*10+rem; num=num/10; } if(a==r) { printf("\n %d is palindrome",r); }else { printf("%d is not a palindrome",r); } }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> static char GPS_output[] = "$GPRMC,173202.000,A,3722.8899,N,12159.5208,W,0.04,215.36,121017,,,A*7F"; typedef unsigned char bool; static bool false = 0; static bool true = 1; /// ---------------------------------------------------------------------------- static int gps_parse_str_time (struct tm * datetime, char * time) { char * _time = NULL; char hms[2] = {0}; char * pch = strtok (time, "."); while (pch != NULL) { _time = pch; pch = strtok (NULL, "."); } printf ("GPS Time = %s\n", time); if (strlen (time) != 6) return -1; strncpy (hms, time, 2); datetime->tm_hour = atoi (hms); strncpy (hms, &time[2], 2); datetime->tm_min = atoi (hms); strncpy (hms, &time[4], 2); datetime->tm_sec = atoi (hms); return 0; } /// ---------------------------------------------------------------------------- static int gps_parse_str_date (struct tm * datetime, char * date) { char dmy[2] = {0}; printf ("GPS Date = %s\n", date); if (strlen (date) != 6) return -1; strncpy (dmy, date, 2); datetime->tm_mday = atoi (dmy) - 1; strncpy (dmy, &date[2], 2); datetime->tm_mon = atoi (dmy) - 1; strncpy (dmy, &date[4], 2); datetime->tm_year = (atoi (dmy) + 2000) - 1900; return 0; } void gps_parse_datetime (struct tm * datetime, char * time, char * date) { gps_parse_str_time (datetime, time); gps_parse_str_date (datetime, date); } /// ---------------------------------------------------------------------------- /// -- Entry Point /// ---------------------------------------------------------------------------- int main (int argc, char ** argv) { char * gprmc = NULL; char * timestamp = NULL; char * datestamp = NULL; if ((gprmc = strstr (GPS_output, "$GPRMC"))) { int count = 0; char * pch = strtok (gprmc, ","); while (pch != NULL) { switch (count) { case 1: timestamp = pch; break; case 2: if (*pch == 'A') { } else { printf ("Error: GPRMC data is invalid\n"); return -1; } break; case 9: datestamp = pch; break; } pch = strtok (NULL, ","); count++; } struct tm datetime; gps_parse_datetime (&datetime, timestamp, datestamp); time_t epoch = mktime (&datetime); printf ("Epoch = %ld\n", epoch); } else { printf ("Error: Cannot find GPRMC fields\n"); return -1; } return 0; }
C
#include "status_types.h" #include "Shlwapi.h" #pragma comment(lib, "Shlwapi.lib") #pragma comment(lib, "Pathcch.lib") #include "Pathcch.h" STATUS DumpExe(WIN32_FIND_DATA File); DWORD NrFiles = 0; STATUS SearchDirectory(LPSTR Filename, BOOL Recursive) { WIN32_FIND_DATA FindFileData; HANDLE hFind = INVALID_HANDLE_VALUE; BOOL Ok; CHAR OldDirectory[260]; hFind = FindFirstFile( (LPCSTR)"*", &FindFileData); if (hFind == INVALID_HANDLE_VALUE) { PRINT_ERROR("FindFirstFile failed"); goto end; } if (GetLastError() == ERROR_FILE_NOT_FOUND) { printf("No file found!\n"); goto end; } if (!strcmp(".", FindFileData.cFileName) || !strcmp("..", FindFileData.cFileName)) { goto next_file; } if (FILE_ATTRIBUTE_DIRECTORY == FindFileData.dwFileAttributes) { if (Recursive) { if (0 == GetCurrentDirectory(260, (LPSTR)&OldDirectory)) { PRINT_ERROR("GetCurrentDirectory failed"); goto end; } if (0 == SetCurrentDirectory(FindFileData.cFileName)) { PRINT_ERROR("SetCurrentDirectory failed"); goto next_file; } SearchDirectory(Filename, TRUE); if (0 == SetCurrentDirectory(OldDirectory)) { PRINT_ERROR("SetCurrentDirectory failed"); goto end; } } goto next_file; } while (TRUE) { if (!PathMatchSpec(FindFileData.cFileName, Filename)) { goto next_file; } else { DumpExe(FindFileData); NrFiles++; } next_file: Ok = FindNextFile( hFind, &FindFileData); if (!Ok && GetLastError() == ERROR_NO_MORE_FILES) { goto end; } else if (!Ok) { PRINT_ERROR("Unexpected error"); goto end; } if (!strcmp(".", FindFileData.cFileName) || !strcmp("..", FindFileData.cFileName)) { goto next_file; } if (FILE_ATTRIBUTE_DIRECTORY == FindFileData.dwFileAttributes) { if (Recursive) { if (0 == GetCurrentDirectory(260, (LPSTR)(&OldDirectory))) { PRINT_ERROR("GetCurrentDirectory failed"); goto end; } if (0 == SetCurrentDirectory(FindFileData.cFileName)) { PRINT_ERROR("SetCurrentDirectory failed"); goto next_file; } SearchDirectory(Filename, TRUE); if (0 == SetCurrentDirectory(OldDirectory)) { PRINT_ERROR("SetCurrentDirectory failed"); goto end; } } goto next_file; } } end: if (INVALID_HANDLE_VALUE != hFind) { FindClose(hFind); } return STATUS_SUCCESS; } int main(int argc, char *argv[]) { BOOL Recursive; if (argc < 2) { printf("Usage: pedumper.exe filename/filepattern recursive(opt)\n"); return 0; } else if (argc == 2) { Recursive = FALSE; } else { Recursive = TRUE; } if (PathIsFileSpec(argv[1])) { SearchDirectory(argv[1], Recursive); } else { LPSTR FileSpecPointer = PathFindFileName(argv[1]); CHAR File[255]; strcpy_s(File, strlen(FileSpecPointer) + 1, FileSpecPointer); CHAR Path[255]; strcpy_s(Path, strlen(argv[1]) + 1, argv[1]); PathRemoveFileSpec(Path); if (0 == SetCurrentDirectory(Path)) { return STATUS_UNSUCCESSFUL; } SearchDirectory(File, Recursive); } printf("\n\nNumber of files dumped: %d\n", NrFiles); return 0; }
C
#include <stdio.h> #include <ctype.h> int my_isupper(); int my_tolower(); int main(int argc, char* argv[]) { printf("Enter text, ^D to end:\n"); int c; while ((c=getchar()) != EOF) { if (my_isupper(c)) { c = my_tolower(c); } putchar(c); } return 0; } int my_isupper(int c) { return c >= 'A' && c <= 'Z'; } int my_tolower(int c) { if (my_isupper(c)) { return c - ('A' - 'a'); } else { return c; } }
C
/**************************************************************************** * apps/fsutils/passwd/passwd_find.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <sys/types.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <assert.h> #include <errno.h> #include "passwd.h" /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: passwd_find * * Description: * Find a password in the * * Input Parameters: * * Returned Value: * Zero (OK) is returned on success; a negated errno value is returned on * failure. * ****************************************************************************/ int passwd_find(FAR const char *username, FAR struct passwd_s *passwd) { FAR char *iobuffer; FAR char *name; FAR char *encrypted; FAR char *ptr; FILE *stream; off_t offset; int ret; /* Allocate an I/O buffer for the transfer */ iobuffer = (FAR char *)malloc(CONFIG_FSUTILS_PASSWD_IOBUFFER_SIZE); if (iobuffer == NULL) { return -ENOMEM; } /* Open the password file for reading */ stream = fopen(CONFIG_FSUTILS_PASSWD_PATH, "r"); if (stream == NULL) { /* Free an I/O buffer for the transfer */ free(iobuffer); int errcode = errno; DEBUGASSERT(errcode > 0); return -errcode; } /* Read the password file line by line until the record with the matching * username is found, or until the end of the file is reached. * * The format of the password file is: * * user:x:uid:gid:home * * Where: * user: User name * x: Encrypted password * uid: User ID * gid: Group ID * home: Login directory */ offset = 0; ret = -ENOENT; while (fgets(iobuffer, CONFIG_FSUTILS_PASSWD_IOBUFFER_SIZE, stream)) { ptr = iobuffer; name = ptr; /* Skip to the end of the name and properly terminate it,. The name * must be terminated with the field delimiter ':'. */ for (; *ptr != '\0' && *ptr != ':'; ptr++); if (*ptr == '\0') { /* Bad file format? */ continue; } *ptr++ = '\0'; /* Check for a username match */ if (strcmp(username, name) == 0) { /* We have a match. The encrypted password must immediately * follow the ':' delimiter. */ encrypted = ptr; /* Skip to the end of the encrypted password and properly * terminate it. */ for (; *ptr != '\0' && *ptr != ':'; ptr++); if (*ptr == '\0') { /* Bad file format? */ ret = -EINVAL; break; } *ptr++ = '\0'; /* Copy the offset and password into the returned structure */ if (strlen(encrypted) >= MAX_ENCRYPTED) { ret = -E2BIG; break; } passwd->offset = offset; strlcpy(passwd->encrypted, encrypted, MAX_ENCRYPTED); ret = OK; break; } /* Get the next file offset */ offset = ftell(stream); } fclose(stream); free(iobuffer); return ret; }
C
#include <assert.h> #include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <builtins.h> #include <builtins/bashgetopt.h> #include <shell.h> #include "log.h" #define LINEMAX 8000 /* TODO UTF-8 Support */ typedef void str_proc(const char *buf); int strfn_builtin(WORD_LIST *list, str_proc fn, const char *fsep, const char *asep) { int opt; bool isfile = false; FILE *in; char buf[(LINEMAX + 1) * 2]; int rval = EXECUTION_SUCCESS; int index = 0; reset_internal_getopt(); while ((opt = internal_getopt(list, "f")) != -1) { switch (opt) { case 'f': isfile = 1; break; default: builtin_usage(); return EX_USAGE; } } if ((list = loptend) == NULL) { builtin_usage(); return EX_USAGE; } for (; list; index++, list = list->next) { const char *arg = list->word->word; if (isfile) { /* file argument */ log_debug("Process file %s", arg); if (index) fputs(fsep, stdout); in = fopen(arg, "r"); if (in == NULL) { log_perr("Failed to open %s", arg); rval = EXECUTION_FAILURE; break; } while (fgets(buf, LINEMAX, in)) { fn(buf); } fclose(in); } else { /* string argument */ if (index) fputs(asep, stdout); fn(arg); } } if (index) putchar('\n'); return rval; } void tolower_fn(const char *buf) { const char *p = buf; char ch; while (ch = *p++) { ch = tolower(ch); putchar(ch); } } void toupper_fn(const char *buf) { const char *p = buf; char ch; while (ch = *p++) { ch = toupper(ch); putchar(ch); } } void hyphenatize_fn(const char *buf) { const char *p = buf; char ch; while (ch = *p++) { if (isupper(ch)) { putchar('-'); ch = tolower(ch); } putchar(ch); } } void camelCase_fn(const char *buf) { const char *p = buf; char ch; bool upnext = false; while (ch = *p++) { if (isalnum(ch)) { if (upnext) { ch = toupper(ch); upnext = false; } } else { upnext = true; continue; } putchar(ch); } } int tolower_builtin(WORD_LIST *list) { strfn_builtin(list, tolower_fn, "\n", " "); } int toupper_builtin(WORD_LIST *list) { strfn_builtin(list, toupper_fn, "\n", " "); } int hyphenatize_builtin(WORD_LIST *list) { strfn_builtin(list, hyphenatize_fn, "\n", " "); } int camelCase_builtin(WORD_LIST *list) { strfn_builtin(list, camelCase_fn, "\n", " "); } char *tolower_doc[] = { "Convert to lower case", "", "Convert the argument string (or file) to lower case.", NULL }; char *toupper_doc[] = { "Convert to upper case", "", "Convert the argument string (or file) to upper case.", NULL }; char *hyphenatize_doc[] = { "Convert camelCase identifier to hyphenatized-words", "", "Convert camelCase identifier to hyphenatized-words in lower case.", NULL }; char *camelCase_doc[] = { "Convert hyphenatized-words to camelCase", "", "Convert hyphenatized-words to camelCased identifier.", NULL }; struct builtin tolower_struct = { "tolower", tolower_builtin, BUILTIN_ENABLED, tolower_doc, "tolower [-f] string/file ...", NULL }; struct builtin toupper_struct = { "toupper", toupper_builtin, BUILTIN_ENABLED, toupper_doc, "toupper [-f] string/file ...", NULL }; struct builtin hyphenatize_struct = { "hyphenatize", hyphenatize_builtin, BUILTIN_ENABLED, hyphenatize_doc, "hyphenatize [-f] string/file ...", NULL }; struct builtin camelCase_struct = { "camelCase", camelCase_builtin, BUILTIN_ENABLED, camelCase_doc, "camelCase [-f] string/file ...", NULL };
C
#include "emulator.h" /******************************************************* - fonction instructionToHex: Traduis une instruction MIPS en hexadecimal - parametre: > instruction : instruction MIPS - retour: > instruction en hexadecimal *******************************************************/ char* instructionToHex(char* instruction) { char* hexInstruction = malloc(10 * sizeof(char)); // Instruction en hexadecimal uint32_t intInstruction = 0; // Instruction en binaire uint32_t intRegister = 0; // Numero du registre char* operation; // Opcode operation = strbreak(&instruction, ' '); // Recupere l'opcode if (strcmp(operation, "ADD") == 0) { // Instruction ADD intInstruction = 0b100000; // 100000 bits intRegister = registerToInt(strbreak(&instruction, ',')); intInstruction |= (intRegister << 11); strbreak(&instruction, ' '); intRegister = registerToInt(strbreak(&instruction, ',')); intInstruction |= (intRegister << (2 * 5 + 11)); strbreak(&instruction, ' '); intRegister = registerToInt(instruction); intInstruction |= (intRegister << (5 + 11)); } else if (strcmp(operation, "ADDI") == 0) { // Instruction ADDI intInstruction = (0b001000 << (2 * 5 + 16));// 001000 bits intRegister = registerToInt(strbreak(&instruction, ',')); intInstruction |= (intRegister << (16)); // rt strbreak(&instruction, ' '); intRegister = registerToInt(strbreak(&instruction, ',')); // rs intInstruction |= (intRegister << (5 + 16)); strbreak(&instruction, ' '); intInstruction |= atoi(instruction); // Immediate } else if (strcmp(operation, "AND") == 0) { // Instruction AND intInstruction |= 0b100100; // 100100 bits intRegister = registerToInt(strbreak(&instruction, ',')); // rd intInstruction |= (intRegister << (5 + 6)); strbreak(&instruction, ' '); intRegister = registerToInt(strbreak(&instruction, ',')); // rs intInstruction |= (intRegister << (3 * 5 + 6)); strbreak(&instruction, ' '); intRegister = registerToInt(instruction); // rt intInstruction |= (intRegister << (2 * 5 + 6)); } else if (strcmp(operation, "BEQ") == 0) { // Instruction BEQ intInstruction |= 0b000100 << (2 * 5 + 16); // 000100 bits intRegister = registerToInt(strbreak(&instruction, ',')); // rs intInstruction |= (intRegister << (5 + 16)); strbreak(&instruction, ' '); intRegister = registerToInt(strbreak(&instruction, ',')); // rt intInstruction |= (intRegister << 16); strbreak(&instruction, ' '); intInstruction |= atoi(instruction); // offset } else if (strcmp(operation, "BGTZ") == 0) { // Instruction BGTZ intInstruction |= 0b000111 << (2 * 5 + 16); // 000111 bits intRegister = registerToInt(strbreak(&instruction, ',')); // rs intInstruction |= (intRegister << (5 + 16)); strbreak(&instruction, ' '); intInstruction |= atoi(instruction); // offset } else if (strcmp(operation, "BLEZ") == 0) { // Instruction BLEZ intInstruction |= 0b000110 << (2 * 5 + 16); // 000110 bits intRegister = registerToInt(strbreak(&instruction, ',')); // rs intInstruction |= (intRegister << (5 + 16)); strbreak(&instruction, ' '); intInstruction |= atoi(instruction); // offset } else if (strcmp(operation, "BNE") == 0) { // Instruction BNE intInstruction |= 0b000101 << (2 * 5 + 16); // 000101 bits intRegister = registerToInt(strbreak(&instruction, ',')); // rs intInstruction |= (intRegister << (5 + 16)); strbreak(&instruction, ' '); intRegister = registerToInt(strbreak(&instruction, ',')); // rt intInstruction |= (intRegister << 16); strbreak(&instruction, ' '); intInstruction |= atoi(instruction); // offset } else if (strcmp(operation, "DIV") == 0) { // Instruction DIV intInstruction |= 0b011010; // 011010 bits intRegister = registerToInt(strbreak(&instruction, ',')); // rs intInstruction |= (intRegister << (5 + 10 + 6)); strbreak(&instruction, ' '); intRegister = registerToInt(instruction); // rt intInstruction |= (intRegister << (10 + 6)); } else if (strcmp(operation, "J") == 0) { // Instruction JUMP intInstruction |= 0b000010 << 26; // 000010 bits // adresse instruction sous la forme 0x_________ strbreak(&instruction, 'x'); intInstruction |= hexaToInt(instruction); } else if (strcmp(operation, "JAL") == 0) { // Instruction JAL intInstruction |= 0b000011 << 26; // 000011 bits // adresse instruction sous la forme 0x_________ strbreak(&instruction, 'x'); intInstruction |= hexaToInt(instruction); } else if (strcmp(operation, "JR") == 0) { // Instruction JR intInstruction |= 0b001000; // 001000 bits intRegister = registerToInt(instruction); // rs intInstruction |= (intRegister << (10 + 5 + 6)); } else if (strcmp(operation, "LUI") == 0) { // Instruction LUI intInstruction |= 0b001111 << (2 * 5 + 16); // 001111 bits intRegister = registerToInt(strbreak(&instruction, ',')); // rt intInstruction |= (intRegister << 16); strbreak(&instruction, ' '); intInstruction |= atoi(instruction); // immediate } else if (strcmp(operation, "LW") == 0) { // Instruction LW intInstruction |= 0b100011 << (2 * 5 + 16); // 100011 bits intRegister = registerToInt(strbreak(&instruction, ',')); // rt intInstruction |= (intRegister << 16); strbreak(&instruction, ' '); intInstruction |= atoi(strbreak(&instruction, '(')); // offset intRegister = registerToInt(strbreak(&instruction, ')')); // base intInstruction |= (intRegister << (5 + 16)); } else if (strcmp(operation, "MFHI") == 0) { // Instruction MFHI intInstruction |= 0b010000; // 010000 bits intRegister = registerToInt(instruction); // rd intInstruction |= (intRegister << (5 + 6)); } else if (strcmp(operation, "MFLO") == 0) { // Instruction MFLO intInstruction |= 0b010010; // 010010 bits intRegister = registerToInt(instruction); // rd intInstruction |= (intRegister << (5 + 6)); } else if (strcmp(operation, "MULT") == 0) { // Instruction MULT intInstruction = 0b011000; // 011000 bits intRegister = registerToInt(strbreak(&instruction, ',')); // rs intInstruction |= (intRegister << (5 + 10 + 6)); strbreak(&instruction, ' '); intRegister = registerToInt(instruction); // rt intInstruction |= (intRegister << (10 + 6)); } else if (strcmp(operation, "NOP") == 0) { // Instruction NOP intInstruction = 0; } else if (strcmp(operation, "OR") == 0) { // Instruction OR intInstruction = 0b100101; // 100101 bits intRegister = registerToInt(strbreak(&instruction, ',')); // rd intInstruction |= (intRegister << (5 + 6)); strbreak(&instruction, ' '); intRegister = registerToInt(strbreak(&instruction, ',')); // rs intInstruction |= (intRegister << (3 * 5 + 6)); strbreak(&instruction, ' '); intRegister = registerToInt(instruction); // rt intInstruction |= (intRegister << (2 * 5 + 6)); } else if (strcmp(operation, "ROTR") == 0) { // Instruction ROTR intInstruction = 0b000010; // 000010 bits intRegister = registerToInt(strbreak(&instruction, ',')); // rd intInstruction |= (intRegister << (5 + 6)); strbreak(&instruction, ' '); intRegister = registerToInt(strbreak(&instruction, ',')); // rt intInstruction |= (intRegister << (2 * 5 + 6)); strbreak(&instruction, ' '); intInstruction |= (atoi(instruction) << 6); // sa intInstruction |= 1 << (3 * 5 + 6); } else if (strcmp(operation, "SLL") == 0) { // Instruction SLL intInstruction = 0b000000; // 000000 bits intRegister = registerToInt(strbreak(&instruction, ',')); // rd intInstruction |= (intRegister << (5 + 6)); strbreak(&instruction, ' '); intRegister = registerToInt(strbreak(&instruction, ',')); // rt intInstruction |= (intRegister << (2 * 5 + 6)); strbreak(&instruction, ' '); intInstruction |= (atoi(instruction) << 6); // sa } else if (strcmp(operation, "SLT") == 0) { // Instruction SLT intInstruction = 0b101010; // 101010 bits intRegister = registerToInt(strbreak(&instruction, ',')); // rd intInstruction |= (intRegister << (5 + 6)); strbreak(&instruction, ' '); intRegister = registerToInt(strbreak(&instruction, ',')); // rs intInstruction |= (intRegister << (3 * 5 + 6)); strbreak(&instruction, ' '); intRegister = registerToInt(instruction); // rt intInstruction |= (intRegister << (2 * 5 + 6)); } else if (strcmp(operation, "SRL") == 0) { // Instruction SRL intInstruction = 0b000010; // 000010 bits intRegister = registerToInt(strbreak(&instruction, ',')); // rd intInstruction |= (intRegister << (5 + 6)); strbreak(&instruction, ' '); intRegister = registerToInt(strbreak(&instruction, ',')); // rt intInstruction |= (intRegister << (2 * 5 + 6)); strbreak(&instruction, ' '); intInstruction |= (atoi(instruction) << 6); // sa } else if (strcmp(operation, "SUB") == 0) { // Instruction SUB intInstruction = 0b100010; // 100010 bits intRegister = registerToInt(strbreak(&instruction, ',')); // rd intInstruction |= (intRegister << (5 + 6)); strbreak(&instruction, ' '); intRegister = registerToInt(strbreak(&instruction, ',')); // rs intInstruction |= (intRegister << (3 * 5 + 6)); strbreak(&instruction, ' '); intRegister = registerToInt(instruction); // rt intInstruction |= (intRegister << (2 * 5 + 6)); } else if (strcmp(operation, "SW") == 0) { // Instruction SW intInstruction = 0b101011 << (2 * 5 + 16); // 101011 bits intRegister = registerToInt(strbreak(&instruction, ',')); // rt intInstruction |= (intRegister << 16); strbreak(&instruction, ' '); intInstruction |= atoi(strbreak(&instruction, '(')); // offset intRegister = registerToInt(strbreak(&instruction, ')')); // base intInstruction |= (intRegister << (5 + 16)); } else if (strcmp(operation, "SYSCALL") == 0) { // Instruction SYSCALL intInstruction = 0b001100; // 001100 bits } else if (strcmp(operation, "XOR") == 0) { // Instruction XOR intInstruction = 0b100110; // 100110 bits intRegister = registerToInt(strbreak(&instruction, ',')); // rd intInstruction |= (intRegister << (5 + 6)); strbreak(&instruction, ' '); intRegister = registerToInt(strbreak(&instruction, ',')); // rs intInstruction |= (intRegister << (3 * 5 + 6)); strbreak(&instruction, ' '); intRegister = registerToInt(instruction); // rt intInstruction |= (intRegister << (2 * 5 + 6)); } else hexInstruction = NULL; if(hexInstruction != NULL) sprintf(hexInstruction, "0x%08X", intInstruction); // Affichage de l'instruction traduite return hexInstruction; } /******************************************************* - fonction readFile: Lit et éxecute un fichier d'instruction MIPS depuis un fichier. - parametres: > name : nom du fichier depuis le repertoire courant de l'executable. > mode : mode pas à pas ou mode non-interactif (utilisation de la constante PAS_A_PAS). > memory : memoire de l'emulateur. > registers : registre de l'emulateur. *******************************************************/ void readFile(char* name, int mode, Memory memory, Registers registers) { FILE* file; // Fichier d'instruction int PC = 0; // Program counter uint32_t jump = PC; // Initialisation du jump int nbLines = 0; // Nombre de ligne char* instruction = malloc(MAX_CHAR_INSTRUCTION * sizeof(char)); // Instruction char* hexInstruction; // Instruction en hexadecimal name = getExecutablePath(name); // recupération du chemin du fichier /* Ouverture du fichier */ file = fopen(name, "r"); if (file == NULL) { perror("Probleme ouverture fichier"); saveFile("Probleme ouverture fichier", "resultats_non_interactif.txt"); exit(1); } /* Récuperation du nombre de ligne du fichier */ while (!feof(file)) { fgets(instruction, MAX_CHAR_INSTRUCTION, file); nbLines++; } nbLines--; // Décremente d'une ligne a cause de feof rewind(file); // Reinitialise le curseur de la ligne dans le fichier while(PC < nbLines) { fgets(instruction, MAX_CHAR_INSTRUCTION, file); /* Gestion du jump */ if (PC == jump) { instruction = strbreak(&instruction, '\n'); hexInstruction = instructionToHex(instruction); printf("%s\n%s\n", instruction, hexInstruction); saveFile(instruction, "resultats_non_interactif.txt"); saveFile(hexInstruction, "resultats_non_interactif.txt"); jump = executeInstruction(instruction, memory, registers, PC); displayRegisters(registers, "resultats_non_interactif.txt"); displayMemory(memory, "resultats_non_interactif.txt"); /* Mode pas à pas */ if (mode == PAS_A_PAS) { printf("Appuyez sur ENTREE pour continuer..."); getchar(); } /* Si le jump est inferieur au PC on reprend la lecture du fichier au début */ if (jump < PC) { rewind(file); PC = -1; } /* Si jump et PC correspondent on incrémente le jump */ if(PC == jump){ jump++; } } PC++; } /* Fermeture du fichier */ fclose(file); } /******************************************************* - fonction executeInstruction: Traduis une instruction MIPS en hexadecimal - parametre: > instruction : instruction MIPS > memory : memoire de l'emulateur > registers : registre de l'emulateur > pc : program counter de l'emulateur - retour: > retourne la valeur du jump/branch) *******************************************************/ uint32_t executeInstruction(char* instruction, Memory memory, Registers registers, uint32_t PC) { char* operation; // Opcode char* rd; char* rt; char* base; int32_t rs_value; int32_t rt_value; int16_t immediate; int16_t offset; uint32_t jump = PC; operation = strbreak(&instruction, ' '); // Recupere l'opcode if (strcmp(operation, "ADD") == 0) { // Instruction ADD rd = strbreak(&instruction, ','); strbreak(&instruction, ' '); rs_value = getRegister(registers, strbreak(&instruction, ',')); strbreak(&instruction, ' '); rt_value = getRegister(registers, instruction); setRegister(registers, rd, rs_value + rt_value); } else if (strcmp(operation, "ADDI") == 0) { // Instruction ADDI rt = strbreak(&instruction, ','); strbreak(&instruction, ' '); rs_value = getRegister(registers, strbreak(&instruction, ',')); strbreak(&instruction, ' '); immediate = atoi(instruction); setRegister(registers, rt, rs_value + immediate); } else if (strcmp(operation, "AND") == 0) { // Instruction AND rd = strbreak(&instruction, ','); strbreak(&instruction, ' '); rs_value = getRegister(registers, strbreak(&instruction, ',')); strbreak(&instruction, ' '); rt_value = getRegister(registers, instruction); setRegister(registers, rd, rs_value & rt_value); } else if (strcmp(operation, "BEQ") == 0) { // Instruction BEQ rs_value = getRegister(registers, strbreak(&instruction, ',')); strbreak(&instruction, ' '); rt_value = getRegister(registers, strbreak(&instruction, ',')); strbreak(&instruction, ' '); offset = atoi(instruction); if (rs_value == rt_value) jump += offset; } else if (strcmp(operation, "BGTZ") == 0) { // Instruction BGTZ rs_value = getRegister(registers, strbreak(&instruction, ',')); strbreak(&instruction, ' '); offset = atoi(instruction); if (rs_value > 0) jump += offset; } else if (strcmp(operation, "BLEZ") == 0) { // Instruction BLEZ rs_value = getRegister(registers, strbreak(&instruction, ',')); strbreak(&instruction, ' '); offset = atoi(instruction); if (rs_value <= 0) jump += offset; } else if (strcmp(operation, "BNE") == 0) { // Instruction BNE rs_value = getRegister(registers, strbreak(&instruction, ',')); strbreak(&instruction, ' '); rt_value = getRegister(registers, strbreak(&instruction, ',')); strbreak(&instruction, ' '); offset = atoi(instruction); if (rs_value != rt_value) jump += offset; } else if (strcmp(operation, "DIV") == 0) { // Instruction DIV rs_value = getRegister(registers, strbreak(&instruction, ',')); strbreak(&instruction, ' '); rt_value = getRegister(registers, instruction); setRegister(registers, "$LO", rs_value / rt_value); setRegister(registers, "$HI", rs_value % rt_value); } else if (strcmp(operation, "J") == 0) { // Instruction JUMP jump = hexaToInt(instruction); } else if (strcmp(operation, "JAL") == 0) { // Instruction JAL } else if (strcmp(operation, "JR") == 0) { // Instruction JR jump = getRegister(registers, instruction); } else if (strcmp(operation, "LUI") == 0) { // Instruction LUI rt = strbreak(&instruction, ','); strbreak(&instruction, ' '); immediate = atoi(instruction); setRegister(registers, rt, immediate << 16); } else if (strcmp(operation, "LW") == 0) { // Instruction LW rt = strbreak(&instruction, ','); strbreak(&instruction, ' '); offset = atoi(strbreak(&instruction, '(')); base = strbreak(&instruction, ')'); int32_t address = offset + getRegister(registers, base); if (((address & 0b1) != 0) && ((address & 0b10) != 0)) //exception printf("\nexception load word\n"); else //address translation ??? setRegister(registers, rt, loadWord(memory, address)); } else if (strcmp(operation, "MFHI") == 0) { // Instruction MFHI setRegister(registers, instruction, getRegister(registers, "$HI")); } else if (strcmp(operation, "MFLO") == 0) { // Instruction MFLO setRegister(registers, instruction, getRegister(registers, "$LO")); } else if (strcmp(operation, "MULT") == 0) { // Instruction MULT rs_value = getRegister(registers, strbreak(&instruction, ',')); strbreak(&instruction, ' '); rt_value = getRegister(registers, instruction); int64_t prod = rs_value * rt_value; setRegister(registers, "$LO", prod & 0b11111111111111111111111111111111); setRegister(registers, "$HI", (prod & (0b11111111111111111111111111111111 << 32)) >> 32); } else if (strcmp(operation, "NOP") == 0) { // Instruction NOP // No operation } else if (strcmp(operation, "OR") == 0) { // Instruction OR rd = strbreak(&instruction, ','); strbreak(&instruction, ' '); rs_value = getRegister(registers, strbreak(&instruction, ',')); strbreak(&instruction, ' '); rt_value = getRegister(registers, instruction); setRegister(registers, rd, rs_value | rt_value); } else if (strcmp(operation, "ROTR") == 0) { // Instruction ROTR rd = strbreak(&instruction, ','); strbreak(&instruction, ' '); rt_value = getRegister(registers, strbreak(&instruction, ',')); strbreak(&instruction, ' '); int8_t sa = atoi(instruction); int32_t temp = rt_value & ((int32_t)pow(2, sa) - 1); temp = (rt_value >> sa) | (temp << (32 - sa)); setRegister(registers, rd, temp); } else if (strcmp(operation, "SLL") == 0) { // Instruction SLL rd = strbreak(&instruction, ','); strbreak(&instruction, ' '); rt_value = getRegister(registers, strbreak(&instruction, ',')); strbreak(&instruction, ' '); int8_t sa = atoi(instruction); setRegister(registers, rd, rt_value << sa); } else if (strcmp(operation, "SLT") == 0) { // Instruction SLT rd = strbreak(&instruction, ','); strbreak(&instruction, ' '); rs_value = getRegister(registers, strbreak(&instruction, ',')); strbreak(&instruction, ' '); rt_value = getRegister(registers, instruction); setRegister(registers, rd, (rs_value < rt_value)); } else if (strcmp(operation, "SRL") == 0) { // Instruction SRL rd = strbreak(&instruction, ','); strbreak(&instruction, ' '); rt_value = getRegister(registers, strbreak(&instruction, ',')); strbreak(&instruction, ' '); int8_t sa = atoi(instruction); setRegister(registers, rd, rt_value >> sa); } else if (strcmp(operation, "SUB") == 0) { // Instruction SUB rd = strbreak(&instruction, ','); strbreak(&instruction, ' '); rs_value = getRegister(registers, strbreak(&instruction, ',')); strbreak(&instruction, ' '); rt_value = getRegister(registers, instruction); setRegister(registers, rd, rs_value - rt_value); } else if (strcmp(operation, "SW") == 0) { // Instruction SW rt = strbreak(&instruction, ','); strbreak(&instruction, ' '); offset = atoi(strbreak(&instruction, '(')); base = strbreak(&instruction, ')'); int32_t address = offset + getRegister(registers, base); if (((address & 0b1) != 0) && ((address & 0b10) != 0)) //exception printf("\nexception load word\n"); else //address translation ??? storeWord(memory, address, getRegister(registers, rt)); } else if (strcmp(operation, "SYSCALL") == 0) { // Instruction SYSCALL // No operation } else if (strcmp(operation, "XOR") == 0) { // Instruction XOR rd = strbreak(&instruction, ','); strbreak(&instruction, ' '); rs_value = getRegister(registers, strbreak(&instruction, ',')); strbreak(&instruction, ' '); rt_value = getRegister(registers, instruction); setRegister(registers, rd, rs_value ^ rt_value); } return jump; }
C
#include "header.h" void initPerso(perso *p) { TTF_Init(); TTF_Font *police=NULL; police=TTF_OpenFont("Urusans.ttf",40); SDL_Color couleur= {255,255,255}; p->sprite=IMG_Load("sprite sheet.png"); p->posPerso.x=250; p->posPerso.y=290; p->posSprite.w=50; p->posSprite.h=40; p->posSprite.y=0; p->posSprite.x=0; p->vies=IMG_Load("hearts.jpg"); p->posVie1.x=0; p->posVie1.y=0; p->posVie2.w=96; p->posVie2.h=26; p->posVie2.y=0; p->posVie2.x=0; p->posScore.x=0; p->posScore.y=30; p->score=0; char s[20]; sprintf(s,"Score: %d",p->score); p->scoretxt=TTF_RenderText_Blended(police,s,couleur); p->vie=3; p->direction=2; } void afficherPerso(perso *p, SDL_Surface * screen) { TTF_Init(); TTF_Font *police=NULL; police=TTF_OpenFont("Urusans.ttf",40); SDL_Color couleur= {255,255,255}; char s[20]; sprintf(s,"Score: %d",p->score); SDL_FreeSurface(p->scoretxt); p->scoretxt=TTF_RenderText_Blended(police,s,couleur); SDL_BlitSurface(p->sprite,&p->posSprite,screen,&p->posPerso); SDL_BlitSurface(p->vies,&p->posVie2,screen,&p->posVie1); SDL_BlitSurface(p->scoretxt,NULL,screen,&p->posScore); } void deplacerPerso (perso *p) { switch(p->direction) { case 3: p->posPerso.x++; break; case 0: p->posPerso.x--; break; } } void animerPerso (perso* p,int frame) { if(p->direction==3) p->posSprite.y=40; else if(p->direction==2) p->posSprite.y=0; else if(p->direction==0) p->posSprite.y=160; else if(p->direction==1) p->posSprite.y=120; else if(p->direction==5) p->posSprite.y=80; if(p->posSprite.x>=350) p->posSprite.x=0; else p->posSprite.x+=50*frame; } void saut (perso* p) { p->posPerso.y--; }
C
#include<stdio.h> int main() { int i, n; printf("\nPlease enter number:"); scanf("%d", &n); printf("\n"); for(i=0;i<n;i++) printf("yes "); printf("\n print %d many yes",n); return 0; }
C
#include "cola.h" #include "abb.h" #include "lista.h" #include <stdio.h> #include <string.h> #include "game_of_thrones.h" #define INICIAR_SIMULACION 'S' #define AGREGAR_CASA 'A' #define MOSTRAR_INTEGRANTES 'L' #define CASAS_EXTINTAS 'E' #define FINALIZAR_EJECUCION 'Q' /* Compara los elementos como si fueran strings. Devuelve mayor a 0 si el primero es mayor, 0 si son iguales o menor a 0 si el segundo es mayor. */ int comparador_nombres(void* elemento_1, void* elemento_2){ if(elemento_1 && elemento_2) return strcmp(((casa_t*)elemento_1)->nombre, ((casa_t*)elemento_2)->nombre); return 0; } int main(){ char nombre_archivo_inicial[MAX_NOMBRE_ARCHIVO]; printf("Ingrese el nombre del archivo principal de casas: "); scanf("%s", nombre_archivo_inicial); FILE* archivo_casas = fopen(nombre_archivo_inicial, LECTURA); if(!archivo_casas){ printf("No se pudo encontrar un archivo con tal nombre\n"); return ERROR; } reino_t* reino = reino_crear(comparador_nombres); if(!reino) return ERROR; int estado_actual = leer_y_agregar_casas(reino->arbol_casas, archivo_casas); fclose(archivo_casas); char respuesta = 'B'; while(respuesta != FINALIZAR_EJECUCION && estado_actual != ERROR){ printf("\nMENU DE SIMULACION\n"); printf("'%c' -> Iniciar Simulacion\n", INICIAR_SIMULACION); printf("'%c' -> Agregar Casa\n", AGREGAR_CASA); printf("'%c' -> Mostrar Integrantes por Casa\n", MOSTRAR_INTEGRANTES); printf("'%c' -> Mostrar Casas Extintas\n", CASAS_EXTINTAS); printf("'%c' -> Finalizar Ejecución\n", FINALIZAR_EJECUCION); scanf(" %c", &respuesta); switch(respuesta){ case INICIAR_SIMULACION: estado_actual = simulacion(reino); break; case AGREGAR_CASA: estado_actual = agregar_casa(reino->arbol_casas); break; case MOSTRAR_INTEGRANTES: estado_actual = mostrar_integrantes(reino->arbol_casas); break; case CASAS_EXTINTAS: estado_actual = mostrar_casas_extintas(reino->casas_extintas); break; } } destruir_reino(reino); return EXITO; }
C
/** * @file State.c * @author {Layne} ({[email protected]}) * @brief * @version 0.1 * @date 2020-08-10 * * @copyright Copyright (c) 2020 * */ #include "Context.h" #include "StateStruct.h" #include "ctools.h" void state_do_action(State* state, Context* context) { if (NULL == state || NULL == state->do_action) return; state->do_action(state, context); } const char* state_to_string(State* state) { if (NULL == state || NULL == state->to_string) return NULL; return state->to_string(state); } void state_destroy(State** state) { if (NULL == state || NULL == *state) return; if (NULL != (*state)->destroy) (*state)->destroy(*state); freep((void**)state); }
C
/**********************************************/ /* Пример для работы #1 */ /**********************************************/ /* ПОРОЖДЕНИЕ ПРОЦЕССОВ */ /**********************************************/ /* Монитор Слонов - файл ganesha1.c */ /**********************************************/ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/time.h> #include <time.h> #include <signal.h> #include <sys/resource.h> #include "../common/ganesha.h" #include "../common/elephant.h" #include "../common/curtime.h" /*static*/ int ne; /* параметр циклов */ /*static*/ meleph mel[NE]; /* управляющая информация о Слонах */ /*static*/ int cnt; /* число запущенных Слонов */ /*static*/ char chld_name[]="./elephant1"; /********************************************************/ main() { int stat; /* состояние процесса при завершении */ /* строки для символьного представления параметров */ char t1[PARAMSTR_LENGTH], t2[PARAMSTR_LENGTH], t3[PARAMSTR_LENGTH], t4[PARAMSTR_LENGTH]; pid_t pw; /* идентификатор процесса */ char eee[ERRMES_LENGTH]; /* текст сообщения об ошибке */ /* начало работы */ /* инициализация генератора случайных чисел */ srand(time(NULL)); printf("%s - Начало работы\n",curtime()); *t3=*t4=0; /* цикл по массиву Слонов */ for (ne=0; ne<NE; ne++) { /* запись личных данных в управляющую информацию */ mel[ne].el=&ee[ne]; /* представление нестроковых данных в строковом виде */ sprintf(t1,"%d",mel[ne].el->age); sprintf(t2,"%lf",mel[ne].el->weight); /* порождение процесса */ pw=fork(); if (pw==0) { /* для дочернего процесса - запуск программы-Слона */ /* личные данные передаются через параметры */ if (execl(chld_name, mel[ne].el->name, t1, t2, t3, t4, NULL)<0) { /* если загрузка программы-Слона почему-либо не удалась, печатается сообщение об ошибке, и процесс завершается */ perror(eee); printf("%s\n",eee); exit(0); } /* если вызов execl выполнился успешно, то далее в дочернем процессе выполняется программа elephant1 */ } /* эта часть - только для процесса - Ганеши */ /* заполнение управляющей информации о процессе */ /* состояние процесса пока что - не запущен */ mel[ne].status=-1; /* установка случайной добавки к приоритету */ mel[ne].prty=(int)(10.* rand()/RAND_MAX); setpriority(PRIO_PROCESS,pw,mel[ne].prty); /* запоминание ID процесса-Слона */ mel[ne].chpid=pw; } /* пауза, чтобы процессы успели загрузить Слонов */ sleep(1); /* перебор запущенных процессов */ for (cnt=ne=0; ne<NE; ne++) { /* проверка - не закончился ли процесс */ pw=waitpid(mel[ne].chpid,&stat,WNOHANG); if (pw==mel[ne].chpid) /* если процесс закончился, значит, запуск Слона не удался */ printf("Слон %s не запущен\n",mel[ne].el->name); else { /* состояние процесса - запущен */ mel[ne].status=0; /* подсчет запущенных Слонов */ cnt++; } } /* если счетчик запущенных 0 - завершение Ганеши */ if (!cnt) exit(0); /* пауза монитора, Слоны в это время выполняются */ sleep(5); printf("%s - ВРЕМЯ ОЖИДАНИЯ ИСТЕКЛО\n",curtime()); /* перебор всех запущенных Слонов */ for (ne=0; ne<NE; ne++) { /* если состояние процесса "не запущен", он не проверяется */ if (mel[ne].status<0) continue; /* проверка завершения Слона с заданным ID, без ожидания завершения */ pw=waitpid(mel[ne].chpid,&stat,WNOHANG); if (mel[ne].chpid==pw) { /* если Слон завершился - сообщение о его успешном завершении */ printf("%s - Слон %s нормально завершился\n", curtime(),mel[ne].el->name); } else { /* если Слон не завершился, ему посылается сигнал KILL */ kill(mel[ne].chpid,SIGKILL); /* ожидание завершения после сигнала */ waitpid(mel[ne].chpid,&stat,0); /* сообщение о гибели */ printf("%s - Слон %s погиб\n", curtime(),mel[ne].el->name,stat); } } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* init_struct_parser.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cboussau <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/10/13 13:38:49 by cboussau #+# #+# */ /* Updated: 2016/11/10 18:04:35 by cboussau ### ########.fr */ /* */ /* ************************************************************************** */ #include <parser.h> static char *check_path(char **path, char *arg) { DIR *dir; struct dirent *ret; while (*path) { if ((dir = opendir(*path))) { while ((ret = readdir(dir))) { if (ft_strcmp(ret->d_name, arg) == 0) { closedir(dir); return (*path); } } closedir(dir); } path++; } return (NULL); } char **get_env(t_env *node) { t_env *tmp; char **env; int i; i = get_index(node); env = (char **)malloc(sizeof(char *) * i + 1); tmp = node; i = 0; while (node) { if (node->line) { env[i] = ft_strdup(node->line); i++; node = node->next; } else node = node->next; } env[i] = NULL; node = tmp; return (env); } static char **split_path(t_env *env) { t_env *tmp; char **path; tmp = env; while (env) { if (ft_strcmp(env->name, "PATH") == 0) { if (env->line) { path = ft_strsplit(&env->line[5], ':'); return (path); } else return (NULL); } env = env->next; } env = tmp; return (NULL); } static void deal_with_path(t_parse *parse, char **path) { char *tmp; if (path && *parse->argv && parse->env) { parse->right_path = check_path(path, *parse->argv); if (parse->right_path) { tmp = ft_strjoin(parse->right_path, "/"); parse->right_path = ft_strjoin(tmp, *parse->argv); free(tmp); } else { tmp = ft_strdup(""); parse->right_path = ft_strjoin(tmp, *parse->argv); free(tmp); } } else if (*parse->argv && parse->env) { tmp = ft_strdup(""); parse->right_path = ft_strjoin(tmp, *parse->argv); free(tmp); } } t_parse *init_parse(t_shell *sh, char *cmd) { t_parse *parse; char **path; parse = (t_parse *)malloc(sizeof(t_parse)); parse->env = get_env(sh->env); parse->argv = ft_strsplit_ws(cmd); path = split_path(sh->env); deal_with_path(parse, path); if (path) ft_free_tab(path); return (parse); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_lstnew.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: slee <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/06/13 09:44:09 by slee #+# #+# */ /* Updated: 2017/06/13 09:45:06 by slee ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include "libft.h" t_list *ft_lstnew(void const *content, size_t content_size) { t_list *my_list; if ((my_list = (t_list *)malloc(sizeof(t_list)))) { if (content) { my_list->content = malloc(sizeof(content) * content_size); ft_memcpy(my_list->content, content, content_size); my_list->content_size = content_size; } else { my_list->content = NULL; my_list->content_size = 0; } my_list->next = NULL; } return (my_list); }
C
/* See LICENSE below for information on rights to use, modify and distribute this code. */ /* * hilbert.c - Computes Hilbert space-filling curve coordinates, without * recursion, from integer index, and vice versa, and other Hilbert-related # calculations. * * Author: Doug Moore * Dept. of Computational and Applied Math * Rice University * http://www.caam.rice.edu/~dougm * Date: Wed Jul 15 1998 * Copyright (c) 1998, Rice University * * Acknowledgement: * This implementation is based on the work of A. R. Butz ("Alternative * Algorithm for Hilbert's Space-Filling Curve", IEEE Trans. Comp., April, * 1971, pp 424-426) and its interpretation by Spencer W. Thomas, University * of Michigan (http://www-personal.umich.edu/~spencer/Home.html) in his widely * available C software. While the implementation here differs considerably * from his, the first two interfaces and the style of some comments are very * much derived from his work. */ #include "hilbert.h" #define adjust_rotation(rotation,nDims,bits) \ do { \ /* rotation = (rotation + 1 + ffs(bits)) % nDims; */ \ bits &= -bits & ((1 << (nDims-1)) - 1); \ while (bits) \ bits >>= 1, ++rotation; \ if ( ++rotation >= nDims ) \ rotation -= nDims; \ } while (0) #define rotateRight(arg, nRots, nDims) \ ((((arg) >> (nRots)) | ((arg) << ((nDims)-(nRots)))) & ((1 << (nDims)) - 1)) /***************************************************************** * hilbert_i2c * * Convert an index into a Hilbert curve to a set of coordinates. * Inputs: * nDims: Number of coordinate axes. * nBits: Number of bits per axis. * index: The index, contains nDims*nBits bits * (so nDims*nBits must be <= 8*sizeof(bitmask_t)). * Outputs: * coord: The list of nDims coordinates, each with nBits bits. * Assumptions: * nDims*nBits <= (sizeof index) * (bits_per_byte) */ void hilbert_i2c(int nDims, int nBits, bitmask_t index, int coord[]) { bitmask_t const one = 1; bitmask_t const ndOnes = (one << nDims) - 1; bitmask_t const nthbits = (((one << nDims*nBits) - one) / ndOnes) >> 1; int b,d; int rotation = 0; /* or (nBits * (nDims-1)) % nDims; */ bitmask_t reflection = 0; for ( d = 0; d < nDims; d++ ) coord[d] = 0; index ^= index >> 1; index ^= nthbits; for (b = nBits; b--;) { bitmask_t bits = (index >> nDims*b) & ndOnes; reflection ^= rotateRight(bits, nDims-rotation, nDims); for ( d = 0; d < nDims; d++ ) coord[d] |= ((reflection >> d) & 1) << b; reflection ^= one << rotation; adjust_rotation(rotation,nDims,bits); } } /***************************************************************** * hilbert_c2i * * Convert coordinates of a point on a Hilbert curve to its index. * Inputs: * nDims: Number of coordinates. * nBits: Number of bits/coordinate. * coord: Array of n nBits-bit coordinates. * Outputs: * index: Output index value. nDims*nBits bits. * Assumptions: * nDims*nBits <= (sizeof bitmask_t) * (bits_per_byte) */ /* MODIFIED by A. Donev--A Fortran-like entry point to hilbert_c2i */ bitmask_t fhilbert_c2i(int *nDims, int *nBits, int *coord) { return hilbert_c2i(*nDims, *nBits, coord) ; } bitmask_t hilbert_c2i(int nDims, int nBits, int coord[]) { bitmask_t const one = 1; bitmask_t const ndOnes = (one << nDims) - 1; bitmask_t const nthbits = (((one << nDims*nBits) - one) / ndOnes) >> 1; int b, d; int rotation = 0; /* or (nBits * (nDims-1)) % nDims; */ bitmask_t reflection = 0; bitmask_t index = 0; for (b = nBits; b--;) { bitmask_t bits = reflection; reflection = 0; for ( d = 0; d < nDims; d++ ) reflection |= ((coord[d] >> b) & 1 ) << d; bits ^= reflection; bits = rotateRight(bits, rotation, nDims); index |= bits << nDims*b; reflection ^= one << rotation; adjust_rotation(rotation,nDims,bits); } index ^= nthbits; /* for (d = 1; index >> d; d *= 2) index ^= index >> d; */ for (d = 1; ; d *= 2) { bitmask_t t; if (d <= 32) { t = index >> d; if (!t) break; } else { t = index >> 32; t = t >> (d - 32); if (!t) break; } index ^= t; } return index; } /***************************************************************** * hilbert_cmp * * Determine which of two points lies further along the Hilbert curve * Inputs: * nDims: Number of coordinates. * nBytes: Number of bytes/coordinate. * coord1: Array of nDims nBytes-byte coordinates. * coord2: Array of nDims nBytes-byte coordinates. * Return value: * -1, 0, or 1 according to whether coord1<coord2, coord1==coord2, coord1>coord2 * Assumptions: * nBits <= (sizeof bitmask_t) * (bits_per_byte) */ int hilbert_cmp(int nDims, int nBytes, void const* c1, void const* c2) { bitmask_t const one = 1; int y, b, d; int rotation = 0; /* or (nBits * (nDims-1)) % nDims; */ bitmask_t reflection = 0; bitmask_t index = 0; for (y = 0; y < nBytes; ++y) for (b = 8; b--; ) { bitmask_t bits = reflection, bts2 = bits; bitmask_t reflexion2 = 0; reflection = 0; for ( d = 0; d < nDims; d++ ) { reflection |= ((((char*)c1)[y+d*nBytes] >> b) & 1 ) << d; reflexion2 |= ((((char*)c2)[y+d*nBytes] >> b) & 1 ) << d; } bits ^= reflection; bits = rotateRight(bits, rotation, nDims); if (reflection != reflexion2) { bts2 ^= reflexion2; bts2 = rotateRight(bts2, rotation, nDims); for (d = 1; d < nDims; d *= 2) { index ^= index >> d; bits ^= bits >> d; bts2 ^= bts2 >> d; } return (((index ^ b) & 1) == (bits < bts2))? -1: 1; } index ^= bits; reflection ^= one << rotation; adjust_rotation(rotation,nDims,bits); } return 0; } /***************************************************************** * hilbert_box_vtx * * Determine the first or last vertex of a box to lie on a Hilbert curve * Inputs: * nDims: Number of coordinates. * nBytes: Number of bytes/coordinate. * findMin: Is it the least vertex sought? * coord1: Array of nDims nBytes-byte coordinates - one corner of box * coord2: Array of nDims nBytes-byte coordinates - opposite corner * Output: * c1 and c2 modified to refer to selected corner * Assumptions: * nBits <= (sizeof bitmask_t) * (bits_per_byte) */ void hilbert_box_vtx(int nDims, int nBytes, int findMin, void const* c1, void const* c2) { bitmask_t const one = 1; bitmask_t const ndOnes = (one << nDims) - 1; int y, b, d; int rotation = 0; /* or (nBits * (nDims-1)) % nDims; */ bitmask_t reflection = 0; bitmask_t index = 0; bitmask_t bitsFolded = 0; for (y = 0; y < nBytes; ++y) for (b = 8; b--; ) { bitmask_t bits = reflection; bitmask_t diff = 0; reflection = 0; for ( d = 0; d < nDims; d++ ) { reflection |= ((((char*)c1)[y+d*nBytes] >> b) & 1 ) << d; diff |= ((((char*)c2)[y+d*nBytes] >> b) & 1 ) << d; } diff ^= reflection; if (diff) { bitmask_t smear = rotateRight(diff, rotation, nDims) >> 1; bitmask_t digit = bits; digit ^= reflection; digit = rotateRight(digit, rotation, nDims); for (d = 1; d < nDims; d *= 2) { index ^= index >> d; digit ^= (digit >> d) &~ smear; smear |= smear >> d; } if ((index ^ b ^ findMin) & 1) digit ^= smear+1; digit = rotateRight(digit, nDims-rotation, nDims) & diff; for (d = 0; d < nDims; ++d) if ((diff >> d) & 1) { unsigned yy; char* src, * dst; if ((digit >> d) & 1) { src = (char*) c2; dst = (char*) c1; } else { src = (char*) c1; dst = (char*) c2; } for (yy = y; yy < nBytes; ++yy) dst[yy+d*nBytes] = src[yy+d*nBytes]; } bitsFolded |= diff; if (bitsFolded == ndOnes) return; index &= 1; reflection ^= digit; } bits ^= reflection; bits = rotateRight(bits, rotation, nDims); index ^= bits; reflection ^= one << rotation; adjust_rotation(rotation,nDims,bits); } } /***************************************************************** * hilbert_box_pt * * Determine the first or last point of a box to lie on a Hilbert curve * Inputs: * nDims: Number of coordinates. * nBytes: Number of bytes/coordinate. * findMin: Is it the least vertex sought? * coord1: Array of nDims nBytes-byte coordinates - one corner of box * coord2: Array of nDims nBytes-byte coordinates - opposite corner * Output: * c1 and c2 modified to refer to least point * Assumptions: * nBits <= (sizeof bitmask_t) * (bits_per_byte) */ void hilbert_box_pt(int nDims, int nBytes, int findMin, void const* c1, void const* c2) { bitmask_t const one = 1; int y, b, d; int rotation = 0; /* or (nBits * (nDims-1)) % nDims; */ bitmask_t reflection = 0; bitmask_t index = 0; bitmask_t fold1 = 0, fold2 = 0; bitmask_t valu1 = 0, valu2 = 0; for (y = 0; y < nBytes; ++y) for (b = 8; b--; ) { char const bthbit = 1 << b; bitmask_t bits = reflection; bitmask_t diff = 0; reflection = 0; for ( d = 0; d < nDims; d++ ) { char* cc1 = &((char*)c1)[y+d*nBytes]; char* cc2 = &((char*)c2)[y+d*nBytes]; if ((fold1 >> d) & 1) if ((valu1 >> d) & 1) *cc1 |= bthbit; else *cc1 &= ~bthbit; if ((fold2 >> d) & 1) if ((valu2 >> d) & 1) *cc2 |= bthbit; else *cc2 &= ~bthbit; reflection |= ((*cc1 >> b) & 1 ) << d; diff |= ((*cc2 >> b) & 1 ) << d; } /* reflection = (reflection &~ fold1) | valu1; */ /* diff = (diff &~ fold2) | valu2; */ diff ^= reflection; if (diff) { bitmask_t smear = rotateRight(diff, rotation, nDims) >> 1; bitmask_t digit = bits; digit ^= reflection; digit = rotateRight(digit, rotation, nDims); for (d = 1; d < nDims; d *= 2) { index ^= index >> d; digit ^= (digit >> d) &~ smear; smear |= smear >> d; } if ((index ^ b ^ findMin) & 1) digit ^= smear+1; digit = rotateRight(digit, nDims-rotation, nDims) & diff; for (d = 0; d < nDims; ++d) if ((diff >> d) & 1) ((char*) (((digit >> d) & 1)? c1: c2))[y+d*nBytes] ^= bthbit; diff ^= digit; fold1 |= digit; fold2 |= diff; reflection ^= digit; valu1 |= ~reflection & digit; valu2 |= ~reflection & diff; index &= 1; } bits ^= reflection; bits = rotateRight(bits, rotation, nDims); index ^= bits; reflection ^= one << rotation; adjust_rotation(rotation,nDims,bits); } } /***************************************************************** * hilbert_nextinbox * * Determine the first point of a box after a given point to lie on a Hilbert curve * Inputs: * nDims: Number of coordinates. * nBytes: Number of bytes/coordinate. * coord1: Array of nDims nBytes-byte coordinates - one corner of box * coord2: Array of nDims nBytes-byte coordinates - opposite corner * point: Array of nDims nBytes-byte coordinates - lower bound on point returned * * Output: if returns 1: * c1 and c2 modified to refer to least point after "point" in box else returns 0: arguments unchanged; "point" is beyond the last point of the box * Assumptions: * nBits <= (sizeof bitmask_t) * (bits_per_byte) */ int hilbert_nextinbox(int nDims, int nBytes, void const* c1, void const* c2, void const* pt) { bitmask_t const one = 1; int y, b, d; int rotation = 0; /* or (nBits * (nDims-1)) % nDims; */ bitmask_t point = 0; bitmask_t index = 0; bitmask_t fold1 = 0, fold2 = 0; bitmask_t valu1 = 0, valu2 = 0; int p_y, p_b; bitmask_t p_clash = 0, p_clashstart; bitmask_t p_diff, p_point, p_reflection; bitmask_t p_fold1, p_fold2, p_valu1, p_valu2; for (y = 0; y < nBytes; ++y) for (b = 8; b--; ) { bitmask_t clash, clashstart; bitmask_t bits = point; bitmask_t reflection = 0; bitmask_t diff = 0; bitmask_t digit; point = 0; for ( d = 0; d < nDims; d++ ) { reflection |= ((((char*)c1)[y+d*nBytes] >> b) & 1 ) << d; diff |= ((((char*)c2)[y+d*nBytes] >> b) & 1 ) << d; point |= ((((char*)pt)[y+d*nBytes] >> b) & 1 ) << d; } reflection = (reflection &~ fold1) | valu1; diff = (diff &~ fold2) | valu2; diff ^= reflection; clash = (reflection ^ point) &~ diff; if (clash || diff) /* compute (the complement of) a "digit" in the integer index of this point */ { digit = bits ^ point; digit = rotateRight(digit, rotation, nDims); clash = rotateRight(clash,rotation,nDims); for (d = 1; d < nDims; d *= 2) { index ^= index >> d; digit ^= digit >> d; clash |= clash >> d; } if ((index ^ b) & 1) digit ^= (one << nDims) - 1; index &= 1; clashstart = clash - (clash >> 1); clash = rotateRight(clash,nDims-rotation,nDims); clashstart = rotateRight(clashstart,nDims-rotation,nDims); diff &= ~clash; } if (diff) { bitmask_t p_p_clash = digit & rotateRight(diff, rotation, nDims); if (p_p_clash) { p_clashstart = p_p_clash & -p_p_clash; p_clash = 2*p_clashstart-1; p_clash = rotateRight(p_clash, nDims-rotation, nDims); p_clashstart = rotateRight(p_clashstart, nDims-rotation, nDims); p_diff = diff &~ (p_clash ^ p_clashstart); p_reflection = reflection; p_y = y; p_b = b; p_point = point ^ p_clashstart; p_fold1 = fold1; p_fold2 = fold2; p_valu1 = valu1; p_valu2 = valu2; } } if (digit < (digit^(rotateRight(clash,rotation,nDims)))) /* use next box */ { if (!p_clash) return 0; /* no next point */ clash = p_clash; clashstart = p_clashstart; y = p_y; b = p_b; diff = p_diff; point = p_point; reflection = p_reflection; fold1 = p_fold1; fold2 = p_fold2; valu1 = p_valu1; valu2 = p_valu2; } if (diff) { /* reduce currbox */ reflection = (reflection ^ point) & diff; diff ^= reflection; fold1 |= reflection; fold2 |= diff; valu1 |= ~point & reflection; valu2 |= ~point & diff; } if (clash) { for ( d = 0; d < nDims; d++ ) { int yy; char hipart, lo1, lo2, hibits; char* cc1 = &((char*)c1)[d*nBytes]; char* cc2 = &((char*)c2)[d*nBytes]; char* pnt = &((char*)pt)[d*nBytes]; for (yy = 0; yy < y; ++yy) cc1[yy] = cc2[yy] = pnt[yy]; hibits = ~0 << b; if (((clash^clashstart) >> d) & 1) hibits <<= 1; hipart = pnt[y] & hibits; if ((clashstart >> d) & 1) hipart ^= 1<<b; if ((fold1 >> d) & 1) { lo1 = -((valu1 >> d) & 1); for (yy = y+1; yy < nBytes; ++yy) cc1[yy] = lo1; } else lo1 = cc1[y]; cc1[y] = hipart | (lo1 &~ hibits); if ((fold2 >> d) & 1) { lo2 = -((valu2 >> d) & 1); for (yy = y+1; yy < nBytes; ++yy) cc2[yy] = lo2; } else lo2 = cc2[y]; cc2[y] = hipart | (lo2 &~ hibits); } hilbert_box_pt(nDims, nBytes, 1, c1, c2); return 1; } bits ^= point; bits = rotateRight(bits, rotation, nDims); index ^= bits; point ^= one << rotation; adjust_rotation(rotation,nDims,bits); } /* point is in box */ { char* cc1 = &((char*)c1)[d*nBytes]; char* cc2 = &((char*)c2)[d*nBytes]; char* pnt = &((char*)pt)[d*nBytes]; for (y = 0; y < nDims; ++y) cc1[y] = cc2[y] = pnt[y]; } return 1; } /***************************************************************** * hilbert_incr * * Convert coordinates of a point on a Hilbert curve to its index. * Inputs: * nDims: Number of coordinates. * nBits: Number of bits/coordinate. * coord: Array of nDims nBits-bit coordinates. * Outputs: * coord: Next point on Hilbert curve * Assumptions: * nDims*nBits <= (sizeof bitmask_t) * (bits_per_byte) */ /*todo*/ /* LICENSE * * This software is copyrighted by Rice University. It may be freely copied, * modified, and redistributed, provided that the copyright notice is * preserved on all copies. * * There is no warranty or other guarantee of fitness for this software, * it is provided solely "as is". Bug reports or fixes may be sent * to the author, who may or may not act on them as he desires. * * You may include this software in a program or other software product, * but must display the notice: * * Hilbert Curve implementation copyright 1998, Rice University * * in any place where the end-user would see your own copyright. * * If you modify this software, you should include a notice giving the * name of the person performing the modification, the date of modification, * and the reason for such modification. */ /* What remains is test code that won't be compiled unless you define the TEST_HILBERT preprocessor symbol */ #ifdef TEST_HILBERT #include <stdio.h> main() { #define maxDim (8*sizeof(bitmask_t)) int coord[maxDim], coord1[maxDim], nDims, nBits, nBytes, i; bitmask_t r, r1; for (;;) { printf( "Enter nDims, nBits: " ); scanf( "%d", &nDims ); if ( nDims == 0 ) break; scanf( "%d", &nBits ); while ( (i = getchar()) != '\n' && i != EOF ) ; if ( i == EOF ) break; nBytes = (nBits+31)/32*4; for ( r = 0; r < 1 << (nDims*nBits); r++ ) { hilbert_i2c( nDims, nBits, r, coord ); printf("%d: ", (unsigned)r); for ( i = 0; i < nDims; i++ ) printf(" %d", coord[i]); printf("\n"); r1 = hilbert_c2i( nDims, nBits, coord ); if ( r != r1 ) printf( "r = 0x%x; r1 = 0x%x\n", (unsigned)r, (unsigned)r1); for (r1 = 0; r1 < r; ++r1 ) { int j; int inf_dist = 0; int ans; hilbert_i2c( nDims, nBits, r1, coord1 ); ans = hilbert_cmp( nDims, nBytes, coord, coord1); if (ans != 1) printf( "cmp r = 0x%0*x; r1 = 0x%0*x, ans = %2d\n", (nDims*nBits+3)/4, (unsigned)r, (nDims*nBits+3)/4, (unsigned)r1, ans ); } hilbert_i2c( nDims, nBits, r1, coord1 ); if (hilbert_cmp( nDims, nBytes, coord, coord1) != 0) printf( "cmp r = 0x%0*x; r1 = 0x%0*x\n", (nDims*nBits+3)/4, (unsigned)r, (nDims*nBits+3)/4, (unsigned)r1 ); } } } #endif
C
#include <pthread.h> /* PThread */ #include <stdio.h> /* Printf */ #include <stdlib.h> #include <assert.h> #include "filtro_salas.h" #define NOPATOVA -1 #define MOLS 10 struct filtro { int * salas; int * patovas; }; /* Crea un filtro para _n_ hilos */ filtro_t* filtro(unsigned int n){ filtro_t* filtro = malloc(sizeof(filtro_t)); filtro->salas=malloc(sizeof(int) * n); filtro->patovas=malloc(sizeof(int) * (n-1)); for (int i=0; i < n; i++){ filtro->salas[i] = 0; if(i < n-1) filtro->patovas[i] = NOPATOVA; } return filtro; } /* El hilo _id_ está intentando tomar el lock */ void filtro_lock(filtro_t* filtro, int id){ int salaPretendida=filtro->salas[id]; if (filtro->patovas[salaPretendida] == NOPATOVA){ if(salaPretendida != 0) filtro->patovas[salaPretendida-1] = NOPATOVA; filtro->patovas[salaPretendida] = id; } while(filtro->patovas[salaPretendida]!= NOPATOVA && filtro->patovas[salaPretendida] != id){ } } /* El hilo _id_ libera el lock */ void filtro_unlock(filtro_t* filtro, int id){ if(filtro->salas[id] == MOLS-1){ // ya ejecute filtro->salas[id] = 0; filtro->patovas[MOLS-2] = NOPATOVA; // Libero la utima sala }else{ int estoyEnSala = filtro->salas[id]; // avance a la que pretendia filtro->salas[id] += 1; // pretendo avanzar a la siguiente } } void filtro_delete(filtro_t* filtro){ free(filtro->salas); free(filtro->patovas); free(filtro); }
C
/*--------------------------------------------------------------------*/ /* functions to connect clients and server */ #include <stdio.h> #include <fcntl.h> #include <string.h> #include <strings.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <time.h> #include <errno.h> #include <unistd.h> #include <stdlib.h> #define MAXNAMELEN 256 /*--------------------------------------------------------------------*/ /*----------------------------------------------------------------*/ int startserver () { int sd; /* socket descriptor */ struct sockaddr_in addr,addr2; char *servhost=malloc(sizeof("remote**.cs.binghamton.edu")); /* full name of this host */ ushort servport; /* port assigned to this server */ struct hostent *host; if ((sd = socket (AF_INET, SOCK_STREAM, 0)) < 0) { printf ("socket error"); return -1; } addr.sin_family=AF_INET; addr.sin_port=htons(0); addr.sin_addr.s_addr=htons(INADDR_ANY); if ((bind(sd,(struct sockaddr *)&addr, sizeof(addr)))==-1) { printf("Bind error");return -1; } /* we are ready to receive connections */ listen (sd, 5); if (gethostname(servhost,sizeof(servhost)+1) == -1) { printf ("gethostname error"); return -1; } if ((host = gethostbyname(servhost)) == NULL) { printf ("gethostbyname error"); return -1; } int size = sizeof (struct sockaddr_in); if (getsockname(sd, (struct sockaddr *) &addr2, &size) == -1) { printf ("getsockname error\n"); } servport=ntohs(addr2.sin_port); /* ready to accept requests */ printf ("admin: started server on '%s' at '%hu'\n", host->h_name, servport); free (servhost); return (sd); } /*----------------------------------------------------------------*/ /*----------------------------------------------------------------*/ int hooktoserver (char *servhost, ushort servport) { int sd; /* socket descriptor */ ushort clientport; /* port assigned to this client */ struct sockaddr_in sa; struct hostent *host; int size = sizeof (struct sockaddr); if ((sd = socket (AF_INET, SOCK_STREAM, 0)) < 0) { printf ("socket error"); exit (1); } if ((host = gethostbyname(servhost)) == NULL) { printf ("gethostbyname error"); exit (1); } sa.sin_family = AF_INET; sa.sin_port = htons (servport); memcpy (&sa.sin_addr.s_addr, host->h_addr, host->h_length); if (connect (sd, (struct sockaddr *) &sa, sizeof (sa)) == -1) { printf ("connect error"); exit (1); } if (getsockname(sd, (struct sockaddr *) &sa, &size) == -1) { printf ("getsockname error\n"); } clientport = ntohs (sa.sin_port); /* succesful. return socket descriptor */ printf ("admin: connected to server on '%s' at '%hu' thru '%hu'\n", servhost, servport, clientport); printf (">"); fflush (stdout); return (sd); } /*----------------------------------------------------------------*/ /*----------------------------------------------------------------*/ int readn (int sd, char *buf, int n) { int toberead; char *ptr; toberead = n; ptr = buf; while (toberead > 0) { int byteread; byteread = read (sd, ptr, toberead); if (byteread <= 0) { if (byteread == -1) perror ("read"); return (0); } toberead -= byteread; ptr += byteread; } return (1); } char *recvtext (int sd) { char *msg; long len; /* read the message length */ if (!readn (sd, (char *) &len, sizeof (len))) { return (NULL); } len = ntohl (len); /* allocate space for message text */ msg = NULL; if (len > 0) { msg = (char *) malloc (len); if (!msg) { fprintf (stderr, "error : unable to malloc\n"); return (NULL); } /* read the message text */ if (!readn (sd, msg, len)) { free (msg); return (NULL); } } /* done reading */ return (msg); } int sendtext (int sd, char *msg) { long len; /* write lent */ len = (msg ? strlen (msg) + 1 : 0); len = htonl (len); write (sd, (char *) &len, sizeof (len)); /* write message text */ len = ntohl (len); if (len > 0) write (sd, msg, len); return (1); } /*----------------------------------------------------------------*/
C
/* * File: uart.c * Author: Bernd * * Created on 16 maart 2017, 16:31 */ #include <xc.h> #include "uart.h" #include "delay.h" char isCommandSent = TRUE; unsigned char *currentMessagePointer; unsigned char uart_receive_buffer[BUFFER_SIZE]; unsigned int uart_receive_buffer_index = 0; unsigned int last_received_message_index = 0; unsigned char last_uart_message[MAX_MESSAGE_SIZE]; void initUART1(void){ //Init the UART1 TRISCbits.TRISC7 = 1; TRISCbits.TRISC6 = 0; //5 steps: see datasheet page 355 TXSTA1bits.BRGH = 1; BAUDCON1bits.BRG16 = 1; /////1///// //Baud rate calculations: //SPBRGHx:SPBRGx = ((Fosc/Desired Baud Rate)/4) - 1 //Fosc = 8MHz //Desired Baud Rate = 57600 //SPBRGHx:SPBRGx = 34 //Datasheet page: 349-350 SPBRGH1 = 0; SPBRG1 = 34; /////2///// //SYNC is default 0: Datasheet page 346 TXSTA1bits.SYNC = 0; RCSTA1bits.SPEN = 1; //Datasheet page 347 /////3///// PIE1bits.TXIE = 0; PIE1bits.RC1IE = 1; //Datasheet page 113 /////4///// // page 357 RCSTA1bits.CREN = 1; } void UARTReceive(char on_or_off){ if(on_or_off == ON){ RCSTA1bits.CREN = 1; } else{ RCSTA1bits.CREN = 0; } } void sendUARTMessage(unsigned char *newMessagePointer){ // Check if previous message is sent //Change the current message currentMessagePointer = newMessagePointer; //The new message isn't sent yet //If TXEN is set to 1 --> TX1IF is set implicitly //PIE1bits.TXIE = 1; last_received_message_index = uart_receive_buffer_index; TXSTA1bits.TXEN = 1; // delay_ms(100); while(*currentMessagePointer != '\0'){ if(PIR1bits.TXIF == 1){ //Prepare next byte for sending TXREG1 = *currentMessagePointer; //Go to the next byte currentMessagePointer += 1; delay_ms(1); } } } void getLastReceivedMessage(){ unsigned char index = 0; while(uart_receive_buffer_index != last_received_message_index){ last_uart_message[index] = uart_receive_buffer[last_received_message_index]; last_received_message_index++; index++; if(last_received_message_index > BUFFER_SIZE){ last_received_message_index = 0; } } last_uart_message[index] = uart_receive_buffer[last_received_message_index]; last_uart_message[index + 1] = '\0'; } void clearUARTReceiveBuffer(void){ for(int i = 0; i<BUFFER_SIZE; i++){ uart_receive_buffer[i] = '\0'; } uart_receive_buffer_index= 0 ; } void uart_interrupt(void){ //Interrupt for the receiving part if(PIR1bits.RC1IF == 1){ PIR1bits.RC1IF = 0; // Save the received byte in the receive buffer uart_receive_buffer[uart_receive_buffer_index] = RCREG1; uart_receive_buffer_index += 1; // If there is overflow, clear the buffer // this is only for emergencies, buffer needs to be cleared with // clearUARTReceiveBuffer if(uart_receive_buffer_index > BUFFER_SIZE){ uart_receive_buffer_index = 0; } } }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #define DT_MAX 0.1 #define DT_MIN 0.0001 #define TMAX 1000 #define TMIN 10 #include "../include/initialisation.h" void Creation_Parametre(Parametre* par){ printf("Entrez les parametres sigma, rho, beta\n"); printf("Sigma : "); scanf ("%f",&par->sigma); printf("\n"); printf("Rho : "); scanf ("%f",&par->rho); printf("\n"); printf("Beta : "); scanf ("%f",&par->beta); printf("\n"); printf("Entrez le Tmax et l'incrementation dt\n"); printf("Tmax : "); scanf ("%f",&par->Tmax); if ((*par).Tmax < TMIN) { (*par).Tmax = TMIN; } else { if ((*par).Tmax > TMAX) { (*par).Tmax = TMAX; } } printf("\n"); printf("dt : "); scanf ("%f",&par->dt); if ((*par).dt < DT_MIN) { (*par).dt = DT_MIN; } else { if ((*par).dt > DT_MAX) { (*par).dt = DT_MAX; } } printf("\n"); }
C
/******************************************************************************* + + LEDA 5.0.1 + + + min_cut.h + + + Copyright (c) 1995-2005 + by Algorithmic Solutions Software GmbH + All rights reserved. + *******************************************************************************/ // $Revision: 1.2 $ $Date: 2005/04/14 10:45:09 $ #ifndef LEDA_MINCUT_H #define LEDA_MINCUT_H #include <LEDA/graph/graph.h> #include <LEDA/core/list.h> LEDA_BEGIN_NAMESPACE /*{\Manpage{min_cut}{}{Minimum Cut} }*/ /*{\Mtext A cut $C$ in a network is a set $S$ of nodes that is neither empty nor the entire set of nodes. The weight of a cut is the sum of the weights of the edges having exactly one endpoint in $S$. }*/ extern __exportF int MIN_CUT(const graph& G,const edge_array<int>& weight, list<node>& C, bool use_heuristic = true); /*{\Mfuncl MIN\_CUT takes a graph $G$ and an edge\_array |weight| that gives for each edge a \emph{non-negative} integer weight. The algorithm (\cite{SW94}) computes a cut of minimum weight. A cut of minimum weight is returned in $C$ and the value of the cut is the return value of the function. The running time is $O(nm + n^2\log n)$. The function uses a heuristic to speed up its computation.\\ \precond The edge weights are non-negative. }*/ inline list<node> MIN_CUT(const graph& G, const edge_array<int>& weight) { list<node> C; MIN_CUT(G,weight,C); return C; } /*{\Mfunc as above, but the cut $C$ is returned.}*/ extern __exportF int CUT_VALUE(const graph& G,const edge_array<int>& weight, const list<node>& C); /*{\Mfuncl returns the value of the cut $C$. }*/ LEDA_END_NAMESPACE #endif
C
#include <stdio.h> #include <stdlib.h> int main(int argc,char *argv[]){ char islem; float sonuc; if(argc!=3){ printf("Az veya çok sayı girdiniz."); exit(1); } printf("\nİŞLEMLER\n +=Toplama\n -=Çıkarma\n *=Çarpma\n /=Bölme\nİşlem: "); scanf("%c",&islem); if(islem=='+'){ sonuc=atoi(argv[1])+atoi(argv[2]); } else if(islem=='-'){ sonuc=atoi(argv[1])-atoi(argv[2]); } else if(islem=='*'){ sonuc=atoi(argv[1])*atoi(argv[2]); } else if(islem=='/'){ sonuc=atoi(argv[1])/atoi(argv[2]); } else{ printf("Geçersiz işlem girdiniz."); } printf("Sonuc: %.2f",sonuc); return 0; }
C
/* * Copyright (C) agile6v */ #include "pupa_config.h" #include <errno.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> int pupa_shm_init(pupa_ctx_t *ctx, int op_type) { int fd; int flag; pupa_shm_t *shm; struct stat st; shm = &ctx->shm; if (op_type == PUPA_OP_TYPE_RO) { fd = open(shm->path, O_RDONLY); if (fd == PUPA_ERROR) { DEBUG_LOG("Failed to open %s, errno: %d", shm->path, errno); return PUPA_ERROR; } if (fstat(fd, &st) == PUPA_ERROR) { DEBUG_LOG("Failed to fstat %s, errno: %d", shm->path, errno); close(fd); return PUPA_ERROR; } if (st.st_size == 0) { DEBUG_LOG("File %s is empty.", shm->path); close(fd); return PUPA_ERROR; } shm->size = st.st_size; shm->exists = 1; shm->data = mmap(NULL, shm->size, PROT_READ, MAP_PRIVATE, fd, 0); if (shm->data == MAP_FAILED) { DEBUG_LOG("Failed to mmap(%s), size: %ld, errno: %d", shm->path, shm->size, errno); close(fd); return PUPA_ERROR; } } else { flag = O_CREAT | O_RDWR; fd = open(shm->path, flag, 0666); if (fd == PUPA_ERROR) { DEBUG_LOG("Failed to open %s, errno: %d", shm->path, errno); return PUPA_ERROR; } if (fstat(fd, &st) == PUPA_ERROR) { DEBUG_LOG("Failed to fstat %s, errno: %d", shm->path, errno); close(fd); return PUPA_ERROR; } shm->exists = (st.st_size == 0) ? 0 : 1; shm->size = (st.st_size == 0) ? shm->size : st.st_size; if (!shm->exists) { if (ftruncate(fd, shm->size) == PUPA_ERROR) { DEBUG_LOG("Failed to ftruncate %s, size: %ld, errno: %d", shm->path, shm->size, errno); return PUPA_ERROR; } } shm->data = mmap(NULL, shm->size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (shm->data == MAP_FAILED) { DEBUG_LOG("Failed to mmap(%s), size: %ld, errno: %d", shm->path, shm->size, errno); close(fd); return PUPA_ERROR; } } close(fd); return PUPA_OK; } int pupa_shm_sync(pupa_ctx_t *ctx) { if (msync(ctx->store_hdr, ctx->shm.size, MS_SYNC) != 0) { return PUPA_ERROR; } return PUPA_OK; } int pupa_shm_fini(pupa_ctx_t *ctx) { if (munmap(ctx->store_hdr, ctx->shm.size) != PUPA_OK) { // TODO: error log return PUPA_ERROR; } return PUPA_OK; }
C
/***************************************************************** * Memstat program - shows maximum memory usage of given program * * Handy tool made by Bartosz [ponury] Ponurkiewicz 2009 * * GPL Licence or whatsoever * *****************************************************************/ #include <stdio.h> #include <sys/ptrace.h> #include <signal.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <string.h> #include <unistd.h> #include <asm/unistd.h> #include <fcntl.h> #include <sys/reg.h> #if __WORDSIZE == 64 #define ORIG_XAX ORIG_RAX #else #define ORIG_XAX ORIG_EAX #endif pid_t child; unsigned int size = 0; unsigned int VmSize = 0, CVmSize = 0; unsigned int VmRSS = 0, CVmRSS = 0; unsigned int VmData = 0, CVmData = 0; unsigned int VmStk = 0, CVmStk = 0; void sig_trap(int sig){ kill(child, 9); fprintf(stderr, "\n\n[!] Caught signal - %d\n", sig); } void sig_status(int unused){ // printf("\n----------\n"); if (!unused){ // fprintf(stderr, "%4u KB of memory used\n", VmSize); FILE *f = fopen("usedmem", "w"); if (!f) { fprintf(stderr, "Error, cannot open memusage file to write!\n"); exit(1); } fprintf(f, "%d\n", VmSize); fclose(f); // printf("Max VmSize: %8u kB (%4u MB)\n", VmSize, VmSize/1024); // printf("Max VmData: %8u kB\n", VmData); // printf("Max VmRSS : %8u kB\n", VmRSS); // printf("Max VmStk : %8u kB\n", VmStk); } else{ fprintf(stderr, "VmSize: Max %8u kB\t\tCurrent: %8u kB\n",VmSize,CVmSize); fprintf(stderr, "VmData: Max %8u kB\t\tCurrent: %8u kB\n",VmData,CVmData); fprintf(stderr, "VmRSS : Max %8u kB\t\tCurrent: %8u kB\n",VmRSS,CVmRSS); fprintf(stderr, "VmStk : Max %8u kB\t\tCurrent: %8u kB\n",VmStk,CVmStk); } } int main(int argc, char **argv){ FILE *file; char name[32]; int status; int len, i=2; char fname[256]; char closeERR = 0; char closeOUT = 0; char executed = 0; // printf("=== Bartosz [ponury] Ponurkiewicz\n"); // printf("== memstat v1.0\n"); if (argc < 2){ fprintf(stderr, "Usage: %s -[O|E] <program_name> [args]\n", argv[0]); fprintf(stderr, "Ex : %s /bin/ls\n", argv[0]); return 1; } if (argv[1][0] == '-'){ for (len = 1; len < strlen(argv[1]); len++){ if (argv[1][len] == 'O') closeOUT = 1; else if (argv[1][len] == 'E') closeERR = 1; else{ fprintf(stderr, "Usage: %s -[O|E] <program_name> [args]\n", argv[0]); fprintf(stderr, "Ex : %s /bin/ls\n", argv[0]); fprintf(stderr," -O = close STDOUT\n -E = close STDERR\n"); return 1; } } argv++; argc--; } // printf("== testing: %s", argv[1]); // for (; i<argc; i++) // printf(" %s", argv[i]); // printf("\n\n"); if ((child = fork())){ signal(SIGINT, sig_trap); signal(SIGTSTP, sig_status); snprintf(fname, sizeof(fname), "/proc/%d/status", child); if (!(file = fopen(fname, "r"))){ fprintf(stderr, "[-] No /proc/%d/status file!", child); return 1; } while (1){ waitpid(child, &status, 0); if (WIFSTOPPED(status) && WSTOPSIG(status) != SIGTRAP){ //fprintf(stderr, "[-] Program received signal %d\n", //WSTOPSIG(status)); } else if (WIFEXITED(status) || WIFSIGNALED(status)) break; if (!executed && ptrace(PTRACE_PEEKUSER, child, sizeof(long) * ORIG_XAX, NULL) == __NR_execve){ if (ptrace(PTRACE_SYSCALL, child, 0, 0)) fprintf(stderr, "[-] PTRACE_SYSCALL failed\n"); executed = 1; continue; } rewind(file); memset(name, 0, sizeof(name)); while (fscanf(file, "%32s %u\n", name, &size) != EOF){ len = strlen(name); if (len == 7){ if (!strcmp(name, "VmSize:") && (CVmSize = size, size > VmSize)) VmSize = size; else if (!strcmp(name, "VmData:") && size > VmData) VmData = size; } else if (len == 6){ if (!strcmp(name, "VmRSS:") && size > VmRSS) VmRSS = size; else if (!strcmp(name, "VmStk:") && size > VmStk) VmStk = size; } size = 0; } if (ptrace(PTRACE_SYSCALL, child, 0, 0)) fprintf(stderr, "[-] PTRACE_SYSCALL failed\n"); } sig_status(0); } else{ argv++; if (closeOUT){ close(1); open("/dev/null", O_WRONLY); } if (closeERR){ close(2); open("/dev/null", O_WRONLY); } // fprintf(stderr,"argc=%d\n",argc); if(argc>=4) { close(1); open(argv[2],O_WRONLY | O_CREAT,00644); //fprintf(stderr,"1 %s numer=%d\n",argv[2],1); } if(argc>=3) { close(0); open(argv[1],O_RDONLY); //fprintf(stderr,"0 %s numer=%d\n",argv[1],0); //open(argv[1],O_RDONLY); } else { close(0); } signal(SIGTSTP, SIG_IGN); if (ptrace(PTRACE_TRACEME, 0, 0, 0)) fprintf(stderr, "[-] PTRACE_TRACEME failed\n"); if (execvp(argv[0], argv)) fprintf(stderr, "[-] execvp failed!\n"); } return 0; }
C
// // main.c // Assignment04 // // Created by Lim Si Eian on 13/02/2019. // Copyright © 2019 Lim Si Eian. All rights reserved. // #include <stdio.h> #include <stdlib.h> #include <time.h> //Exercise01 int main(void) { float fAverage = 0; int nArray[10] = {5, 24, 76, 1, 8, 53, 40, 7, 33, 10}; int nSmallest = nArray[0], nLargest = nArray[0], nSmallestIndex = 0, nLargestIndex = 0, nTotal = 0; for(int i = 0; i < 10; i++) { if(nSmallest > nArray[i]) { nSmallest = nArray[i]; } if(nLargest < nArray[i]) { nLargest = nArray[i]; } if(nSmallest == nArray[i]) { nSmallestIndex = i; } if(nLargest == nArray[i]) { nLargestIndex = i; } nTotal = nTotal + nArray[i]; } fAverage = (float)nTotal/10; printf("Smallest is %d at position %d, Largest is %d at position %d, Average is %f \n", nSmallest, nSmallestIndex, nLargest, nLargestIndex, fAverage); //Exercise02 int nArray2[2][10] = {{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} }; srand(time(NULL)); int nRand = 0; for(int i = 0; i < 100; i++) { nRand = rand() % 10; for(int j = 0; j < 10; j++) { if(nArray2[0][j] == nRand) { nArray2[1][j] = nArray2[1][j] + 1; } } } for(int i = 0; i < 2; i++) { for(int j = 0; j < 10; j++) { printf("%d\t", nArray2[i][j]); } printf(" \n"); } //Exercise03 for(int i = 1; i <= 4; i++) { for(int j = 1; j <= 3; j++) { printf("%d \t", (i*3) + (j-3)); } printf("\n"); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ahunt <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/12/04 15:06:39 by ahunt #+# #+# */ /* Updated: 2016/12/04 15:06:41 by ahunt ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_tree.h" int iter = 8; t_tree *ft_pop_tree(t_list **list) { t_tree *data; t_list *temp; if (!*list) return (NULL); data = (*list)->content; if ((*list)->next) { (*list) = (*list)->next; } return (data); } //basic X : 'X' "F[+X][-X]" branches = 1.0, init len 2, len * 0.7, and 35, iter 8 //blackjack 'X' X : "F[+X][-X]FX" F: "FF" branches = 0.7 init len 35, ang 27.5, iter 8 //sway 'F' F:FF+[+F-F-F]-[-F+F+F], ang 27.5, iter 4, init len 100, branch 0.5 t_img *init_image(t_env *e) { t_img *img; img = (t_img*)malloc(sizeof(t_img)); img->i_ptr = mlx_new_image(e->mlx, WIDTH, HEIGHT); img->w = WIDTH / 2; img->h = HEIGHT / 2; img->data = mlx_get_data_addr(img->i_ptr, &img->bpp, &img->size_line, &img->endian); return (img); } // t_tree *init_tree() // { // t_tree *t; // t_vec2 *v; // t = (t_tree*)malloc(sizeof(t_tree)); // t->len = 300; // t->v = (t_vec2*)malloc(sizeof(t_vec2)); // t->v->x = WIDTH / 2; // t->v->y = HEIGHT; // t->rot = (M_PI / 2); // t->scl = 1.0; // t->theta = (35 * M_PI / 180); // // branch *= t->scl; // t->branch = 8; // t->iter = 8; // return (t); // } t_env *init_environment(void) { t_env *e; e = (t_env*)malloc(sizeof(t_env)); e->mlx = mlx_init(); e->win = mlx_new_window(e->mlx, WIDTH, HEIGHT, "Fractal Tree"); e->img = init_image(e); e->flags = 0; return (e); } int ft_draw_tree(t_env *e, t_tree *t, char *code, int i, int len) { t_tree *temp1; e->t->branch = len; t_tree *temp2; t_list *stack; while (code[i]) { // printf("\nWhile"); if (code[i] == 'F') t = draw_branch(e, t); else if (code[i] == '+') t->rot += t->theta; else if (code[i] == '-') t->rot -= t->phi; else if (code[i] == '[') { temp1 = (t_tree*)malloc(sizeof(t_tree)); temp1->v = (t_vec2*)malloc(sizeof(t_vec2)); temp1->v->x = t->v->x; temp1->v->y = t->v->y; temp1->len = t->len; temp1->rot = t->rot; temp1->theta = t->theta; temp1->phi = t->phi; ft_lstadd(&stack, ft_lstnew(temp1, sizeof(t_tree))); t->branch -= 1; t->len *= t->scl; //i = ft_draw_tree(e, temp1, code, ++i, len - 1); } else if (code[i] == ']') { // return (i); temp2 = (t_tree*)malloc(sizeof(t_tree)); temp2 = ft_pop_tree(&stack); t->v = temp2->v; t->len = temp2->len; t->rot = temp2->rot; t->branch += 1; } i++; } return (i); } char *apply_axioms(char *src) { // t_list *stack; // t_node *funct; char *dest; int i = 0; dest = ft_strnew(1); while (src[i]) { if (src[i] == 'F') dest = ft_strapp(dest, "F");//FF+[+F-F-F]-[-F+F+F] //"F[-F][+F]F" else if (src[i] == '+') dest = ft_strapp(dest, "+"); else if (src[i] == '-') dest = ft_strapp(dest, "-"); else if (src[i] == '[') dest = ft_strapp(dest, "["); else if (src[i] == ']') dest = ft_strapp(dest, "]"); else if (src[i] == 'X') dest = ft_strapp(dest, "F[-X][+X]");//FF i++; } return (dest); // funct = src_stack->content; // while (funct) // { // if (funct->chr = 'F') // { // ft_push(&dest_stack, rule_stack); // } // else // { // ft_push(&dest_stack, ft_pop(&src_stack)); // } // funct = src_stack->content; // } // ft_memdel((void **)&src_stack); // ft_memdel((void **)&funct); // return (dest_stack); } char *generate_code(t_env *e, char *code, int len) { int i = 0; // t_tree *t; // t_vec2 *v; // int i; // int branch = 250; // i = 0; // t = (t_tree*)malloc(sizeof(t_tree)); // t->len = branch; // t->v = (t_vec2*)malloc(sizeof(t_vec2)); // t->v->x = WIDTH / 2; // t->v->y = HEIGHT; // t->size = len; // t->theta = (4 * M_PI / 16); // t->rot = (M_PI / 2); // t->scl = 0.7;//Shroom = 0.745 // t->iter = 8; // e->t = t; while (i < len) { code = apply_axioms(code); // t->branch = i + 1; // t->len *= 0.5; // if (i == len) // ft_draw_tree(e, e->t, code, 0, i); i++; } // ft_draw_tree(e, e->t, code, 0, i); return (code); } // int my_mouse_motion(int i , int j , t_env *e) // { // // t_tree *t; // // t_vec2 *v; // ft_printf("X = %d Y = %d\n", i , j); // if (i > 0 && i < WIDTH && i % 50 == 0) // { // // e->theta = (i / WIDTH * 90 * M_PI / 180); // // t = (t_tree*)malloc(sizeof(t_tree)); // // t->len = 300; // // t->v = (t_vec2*)malloc(sizeof(t_vec2)); // // t->v->x = WIDTH / 2; // // t->v->y = HEIGHT; // // t->rot = (M_PI / 2); // // t->scl = 1.0; // // // branch *= t->scl; // // t->branch = 8; // // t->iter = 8; // mlx_clear_window(e->mlx, e->win); // ft_draw_tree(e, t, e->code, 0, 8); // } // return (0); // } int my_mouse_function(int button, int i, int j, t_env *e) { // ft_printf("Button = %d X = %d Y = %d\n", button, i, j); if (button == 5) e->t->theta += (M_PI / 32); else if (button == 4) e->t->theta -= (M_PI / 32); if (button == 6) e->t->phi += (M_PI / 32); else if (button == 7) e->t->phi -= (M_PI / 32); // else if (button == 1) // e->t->iter++; // else if (button == 2) // e->t->iter--; // if (button >= 1 && button <= 5 && button != 3) // ft_tree(e, e->t->iter); // return (0); // = init_environment();e // ft_tree(e, 13); e->t->len = 300; e->t->v->x = WIDTH / 2; e->t->v->y = HEIGHT * 7 / 8; mlx_clear_window(e->mlx, e->win); ft_draw_tree(e, e->t, e->code, 0, e->t->size); return (0); } void ft_tree(t_env *e, int branches) { t_tree *t; t_vec2 *v; int branch = 300; t = (t_tree*)malloc(sizeof(t_tree)); t->len = branch; t->v = (t_vec2*)malloc(sizeof(t_vec2)); t->v->x = WIDTH / 2; t->v->y = HEIGHT * 7 / 8; t->size = branches; t->theta = (4 * M_PI / 16); t->phi = (4 * M_PI / 16); t->rot = (M_PI / 2); t->scl = 0.7;//Shroom = 0.745 // t->iter = 8; e->t = t; // t_list *code; // t_tree *t; // t_vec2 *v; char *code = "X"; code = generate_code(e, code, branches); e->code = ft_strdup(code); ft_draw_tree(e, e->t, code, 0, branches); } int main(void) { t_env *e; e = init_environment(); ft_tree(e, 13); // draw_tree(e); // mlx_hook(e->win, 6, 0, my_mouse_motion, e); mlx_mouse_hook(e->win, my_mouse_function, e); mlx_loop(e); return (0); }
C
#include <stdint.h> #include <stdio.h> typedef struct lista TLISTA; typedef struct no TNO; TLISTA *criar_lista(); int lista_vazia(TLISTA *li); int tamanho(TLISTA *li); void imprimir(TLISTA *li); int buscar_valor(TLISTA *li, int valor); int inserir_inicio(TLISTA *li, int valor); int inserir_final(TLISTA *li, int valor); int inserir_valor(TLISTA *li, int valor); int remover_final(TLISTA *li, int valor); int remover_inicio(TLISTA *li, int valor); int remover_valor(TLISTA *li, int valor); // 6- inserir no final * // 7- inserir dada uma posio * // 8- remover inicio * // 9 - remover no final * // 10 - remover dado um valor * // 11 -pesquisar dado um valor *
C
#include <stm32l4xx.h> unsigned int sysMillis = 0; void ClockInit(void); void TimerInit(void); void Delay(unsigned int duration); int main(void) { ClockInit(); TimerInit(); RCC->AHB2ENR = RCC_AHB2ENR_GPIOBEN | RCC_AHB2ENR_GPIOEEN; // enable GPIO Port B and E in general GPIOB->MODER &= ~GPIO_MODER_MODE2_1; // initialize the adress space of Port B thus using Pin 2 GPIOE->MODER &= ~GPIO_MODER_MODE8_1; // initialize the adress space of Port E thus using Pin 8 while(1) { GPIOB->BSRR = GPIO_BSRR_BS2; // BitSetResetRegister of Port B will set Pin 2 to 1 (equal to a Bit sequence but more readable) GPIOE->BSRR = GPIO_BSRR_BR8; Delay(1000); GPIOB->BSRR = GPIO_BSRR_BR2; // BitSetResetRegister of Port B will set Pin 2 to 0 (equal to a Bit sequence but more readable) GPIOE->BSRR = GPIO_BSRR_BS8; Delay(1000); } } void Delay(unsigned int duration) { //Temporarily store 'sysMillis' and compare the difference between //the value and 'duration' until the value be equal to or bigger than 'duration unsigned int prevMillis = sysMillis; while (sysMillis - prevMillis <= duration); } void SysTick_Handler(void) { sysMillis++; } void ClockInit(void) { FLASH->ACR |= FLASH_ACR_LATENCY_4WS; // The flash will have 4 wait states before pushing the next instrc //Enable PLLR that can be used as the system clock //Divide the 16MHz input clock by 2(to 8MHz), multiply by 20(to 160MHz), //divide by 2(to 80MHz) //Set PLL input source to HSI RCC->PLLCFGR = RCC_PLLCFGR_PLLREN | (20 << RCC_PLLCFGR_PLLN_Pos) | RCC_PLLCFGR_PLLM_0 | RCC_PLLCFGR_PLLSRC_HSI; RCC->CR |= RCC_CR_PLLON | RCC_CR_HSION; // enable PLL and use HSI on the Reset-Clock-Controller //Be sure that the wait state of the flash changed, //PLL circuit is locked, and HSI is stabilized while (!((FLASH->ACR & FLASH_ACR_LATENCY_4WS) && (RCC->CR & RCC_CR_PLLRDY) && (RCC->CR & RCC_CR_HSIRDY))); //Set the system clock source from PLL RCC->CFGR = RCC_CFGR_SW_PLL; //Turn off MSI to reduce power consumption RCC->CR &= ~RCC_CR_MSION; } void TimerInit(void) { //Read the calibrated value of 24-bit, and put it in the reload value register SysTick->LOAD = SysTick->CALIB & SysTick_LOAD_RELOAD_Msk; //Enable SysTick with the exception request SysTick->CTRL = SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; }
C
//x값, 계산값을 파일에 저장 #include "poly.h" void printfile(double x, double result){ FILE *fp = fopen("poly_result.txt", "a"); if (fp == NULL){ printf("File open error!\n"); return; } fprintf(fp, "%f %f\n", x, result); return; }
C
// // SortAlgorithms.c // D_week5 // // Created by runny on 2020/7/3. // Copyright © 2020 runny. All rights reserved. /** 几种常用的排序算法 首先明确一个概念 什么是逆序 假设我们定义元素从左到右依次递增 那么对于A[i]>A[j] ,i<j 则说明Ai Aj是逆序的 称(Ai,Aj)为一对逆序对 排序算法的目的就是消除所有的逆序对 */ #include "SortAlgorithms.h" typedef int ElementType; void swap(ElementType* a,ElementType* b ){ ElementType temp; temp=*a; *a=*b; *b=temp; } /// 冒泡排序 每一轮从0开始交换相邻的元素 选择出来一个最大值放到最右端 同时待排序元素减去1 /// @param S 待排序数组 void bubbleSort(ElementType S[],int N){ int isSwapFlag=0;//如果一轮扫描中都没有做交换说明已经排序完成 则直接跳出循序 for (int i = N-1; i>0; i--) { for (int p=0; p<i; p++) { if(S[p]<S[p+1]){ swap(&S[p],&S[p+1]); isSwapFlag=1; } } if(isSwapFlag==0){ break; } } } /// 插入排序 初始化已排序的序列为{S[0]} 循环扫描1->N-1 插入已排序的序列同时后移 /// @param S <#S description#> /// @param N <#N description#> void insertSort(ElementType S[],int N){ int i,p; int swapLength = 1; for (i=swapLength; i<N; i++) { ElementType temp = S[i]; for (p=i; p>0&&temp<S[p-1]; p-=swapLength) { S[p]=S[p-1]; } S[p]=temp; } } /// 希尔排序 选择排序和冒泡排序每次都是交换相邻位置的两个元素 这样一次交换只能消除一个逆序对 /// 假设Ai与Aj相邻 且为逆序对 Ai的逆序对为n Aj的逆序对为m 那么交换之后 Ai的逆序对为n-1 Aj的逆序对依然是m /// 要想提高排序的效率那么 一次交换就要消灭更多的逆序对 这就是希尔排序的思想 /// @param S <#S description#> /// @param N <#N description#> void shellSort(ElementType S[],int N){ int i,p,swapLength;//每次交换的元素相隔的距离 假设swapLength=5 则 0<->6 1<->7 2<->8 for (swapLength=N/2; swapLength>0; swapLength/=2) { //内部则是一个选择排序 for (i=swapLength; i<N; i++) { ElementType temp=S[i]; for (p=i; p>swapLength&&temp<S[p-swapLength]; p-=swapLength) { S[p]=S[p-swapLength]; } S[p]=temp; } } } void selectSort(ElementType S[],int N){ int min = 100000; int i,j; for (i = 0; i<N-1; i++) { for (j = i; j<N; j++) {//每次从i->n-1的序列中寻找最小的元素 插入s[i]处 if(S[j]<min){ min=S[j]; } } swap(&S[i], &S[j]); } } /// 将一个数组中的元素调整为最大堆 /// 核心思想 最大堆根结点一定是最大的值 如果root<MAX(left,right) 则交换root与MAX(left,right)的位置 /// @param S 待调整的元素数组 /// @param P 根结点的位置 /// @param N 数组元素的个数 void maxHeapPercDown(ElementType S[],int P,int N){ int Parent,Child; ElementType X; X=S[P];//取出根结点数值 //由于数组元素是从0开始 堆事完全二叉树的结构 则左子树的坐标为2*Parent+1 for (Parent=P; 2*Parent+1<N; Parent=Child) { Child=2*Parent+1; if(Child!=N-1&&(S[Child]<S[Child+1])){//取左右子树较大的 Child++; } if(X>=S[Child]){//如果根结点值最大则跳出循环(前提是当前根结点的左右子树已经是最小堆了 所以这个调整方法 相当于是在一个最大堆中插入一个新的结点进行调整) break; }else{//如果根结点值要小 则下滤 S[Parent]=S[Child]; } } S[Parent]=X; } /// 堆排序 堆排序是在选择排序的基础上进行优化的 /// 选择排序的过程中每次都要从未排序的元素中找到最小值 这个问题可以用堆来解决 /// @param S <#S description#> /// @param N <#N description#> void heapSort(ElementType S[],int N){ //堆排序 int i; for (i=N/2-1; i>0; i--) { maxHeapPercDown(S, i, N); } for (i=N-1; i>=0; i--) { //将最大堆顶元素 与堆最小值交换 并将数组元素减去1 重新调整为最大堆 swap(&S[i], &S[0]); maxHeapPercDown(S, 0, i); } }
C
/* * Copyright (C) 2018 Bill Bao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <fcntl.h> #include <string.h> #include <unistd.h> #define BUFFER_LENGTH 256 // The max buffer length static char receive[BUFFER_LENGTH]; // The receive buffer from the mockware device #define DEVICE_NAME "/proc/mockware" int main(){ int ret, fd; char stringToSend[BUFFER_LENGTH]; fd = open(DEVICE_NAME, O_RDWR); // Open the device with read/write access if (fd < 0) { perror("Failed to open the device..."); return errno; } printf("Type in a short string to send to the mockware device:\n"); scanf("%[^\n]%*c", stringToSend); // Read in a string (with spaces) printf("Writing message to the device [%s].\n", stringToSend); ret = write(fd, stringToSend, strlen(stringToSend)); // Send the string to the mockware device if (ret < 0) { perror("Failed to write the message to the device."); return errno; } printf("Press ENTER to read back from the device...\n"); getchar(); printf("Reading from the device...\n"); ret = read(fd, receive, BUFFER_LENGTH); // Read the response from the mockware device if (ret < 0) { perror("Failed to read the message from the device."); return errno; } printf("The received message is: [%s] readed=%d\n", receive, ret); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* test2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: pmontiel <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/06/18 12:53:44 by pmontiel #+# #+# */ /* Updated: 2021/06/18 12:53:54 by pmontiel ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdio.h> #include <unistd.h> #include <sys/time.h> long get_time(void) { struct timeval tp; long milliseconds; gettimeofday(&tp, NULL); milliseconds = tp.tv_sec * 1000; milliseconds += tp.tv_usec / 1000; return (milliseconds); } int main(void) { long start_time; // Remember when we started start_time = get_time(); while (1) { // Print time from start, in ms printf("%ld\n", get_time() - start_time); // Sleep 200 times 1000 microseconds (1 millisecond) usleep(200 * 1000); } }
C
#include<stdio.h> #include<string.h> int main() { char s[] = "hello"; char *p = strchr(s, 'l'); char *t = (char*)malloc(strlen(p) + 1); strcpy(t, p); printf("%s\n", t); free(t); return 0; }
C
/* main_T3.c, Tasks 3 and 4, H1b. Also used as input in Tasks 5-7. In this task, we use an equlibration scheme, based on scaling particle momenta and positions, to equlibrate the temperature and pressure in the system. We do this for T=500 degC and T=700 degC and P=1 bar. The difference between the two temperatures are that the higer temperature results in a melted system. (To ensure that the system is melted properly, we first raise the temperature to 900 degC and then lower it back to 700 degC.) After the system has equlibrated, we save the full phase space (all particle positions and momenta) as well as the equlibrated lattice parameter to a binary file which then can be read in for a production run. System of units: Energy - eV Time - ps Length - Angstrom Temp - K Mass - eV (ps)^2 A^(-2) Pressure - eV A^(-3) */ #include <stdio.h> #include <math.h> #include <stdlib.h> #include <time.h> #include "initfcc.h" #include "alpotential.h" #include "funcs.h" #define N_cells 4 /* define constants in atomic units: eV, Å, ps, K */ #define AMU 1.0364e-4 #define degC_to_K 273.15 #define bar 6.2415e-07 #define kB 8.61733e-5 /* Main program */ int main() { char file_name[100]; int N_atoms = 4*N_cells*N_cells*N_cells; double m_Al = 27*AMU; /* Values of Young's and shear modulus, Y and G resp., taken from Physics Handbook, table T 1.1. Bulk mudulus then calculated as B = Y*G / (9*G - 3*Y) [F 1.15, Physics Handbook] kappa = 1/B */ double kappa_Al = 100/(6.6444e+05 * bar); // STRANGE FACTOR 100 OFF !!! double a_eq = 4.03; double cell_length = a_eq*N_cells; double inv_volume = pow(N_cells*cell_length, -3); double noise_amplitude = 6.5e-2 * a_eq; double T_final_C= 500; int nRuns = 1; //2 if melt, 1 otherwise double T_melt_C = 900; double P_final_bar= 1; double T_eq; double P_eq = P_final_bar*bar; double dt = 5e-3; double tau_T = 100*dt; double tau_P = 100*dt; double t_eq= 15*tau_P; //equlibration times int N_timesteps = t_eq/dt; double alpha_T, alpha_P,alpha_P_cube_root; double t, E_kin, virial; double (*pos)[3] = malloc(sizeof(double[N_atoms][3])); double (*momentum)[3] = malloc(sizeof(double[N_atoms][3])); double (*forces)[3] = malloc(sizeof(double[N_atoms][3])); double *temperature = malloc(sizeof(double[N_timesteps])); double *pressure = malloc(sizeof(double[N_timesteps])); FILE *file_pointer; init_fcc(pos, N_cells, a_eq); // initialize fcc lattice add_noise( N_atoms, 3, pos, noise_amplitude ); // adds random noise to pos set_zero( N_atoms, 3, momentum); // set momentum to 0 get_forces_AL( forces, pos, cell_length, N_atoms); //initial cond forces for (int irun=0; irun < nRuns; irun++){// last run: final, irun = 0 if (irun == nRuns - 1){ // final run T_eq = T_final_C + degC_to_K; }else{ T_eq = T_melt_C + degC_to_K; } for (int i=0; i<N_timesteps; i++){ /* The loop over the timesteps first takes a timestep according to the Verlet algorithm, then calculates the energies and temeperature. */ timestep_Verlet(N_atoms, pos, momentum, forces, m_Al, dt, cell_length); E_kin = get_kin_energy(N_atoms, momentum, m_Al ); virial = get_virial_AL(pos, cell_length, N_atoms); /* 3N*kB*T/2 = 1/(2m) * \sum_{i=1}^{N} p_i^2 = p_sq/(2m) */ temperature[i] = E_kin * 1/(1.5*N_atoms*kB); /* PV = NkT + virial */ pressure[i] = inv_volume * (1.5*E_kin + virial); /* Equlibrate temperature by scaling momentum by a factor sqrt(alpha_T). N.B. It is equally valid to scale the momentum instead of the velocity, since they only differ by a constant factor m. */ alpha_T = 1 + 2*dt*(T_eq - temperature[i]) / (tau_T * temperature[i]); scale_mat(N_atoms, 3, momentum, sqrt(alpha_T)); // Equlibrate pressure by scaling the posistions by a factor of // alpha_P^(1/3) alpha_P = 1 - kappa_Al* dt*(P_eq - pressure[i])/tau_P; alpha_P_cube_root = pow(alpha_P, 1.0/3.0); scale_mat(N_atoms, 3, pos, alpha_P_cube_root); cell_length*=alpha_P_cube_root; inv_volume*=1/alpha_P; temperature[i]*=alpha_T; pressure[i]*=alpha_P; } } printf("equilibrium a0 = %.4f A\n", cell_length/N_cells); /* Write tempertaure to file */ sprintf(file_name,"../data/temp-%d_pres-%d_Task3.tsv", (int) T_final_C, (int) P_final_bar); file_pointer = fopen(file_name, "w"); for (int i=0; i<N_timesteps; i++){ t = i*dt; // time at step i fprintf(file_pointer, "%.4f \t %.8f \t %.8f \n", t, temperature[i],pressure[i]); } fclose(file_pointer); /* Write phase space coordinates to file */ sprintf(file_name,"../data/phase-space_temp-%d_pres-%d.tsv", (int) T_final_C, (int) P_final_bar); file_pointer = fopen(file_name, "w"); for (int i=0; i<N_atoms; i++){ for (int j=0;j<3;j++){ fprintf(file_pointer, " %.16e \t", pos[i][j]); } for (int j=0;j<3;j++){ fprintf(file_pointer, " %.16e \t", momentum[i][j]); } fprintf(file_pointer,"\n"); } fclose(file_pointer); /* save equlibrated position and momentum as a binary file */ sprintf(file_name,"../data/INIDATA_temp-%d_pres-%d.bin", (int) T_final_C, (int) P_final_bar); file_pointer = fopen(file_name, "wb"); fwrite(pos, sizeof(double), 3*N_atoms, file_pointer); fwrite(momentum, sizeof(double), 3*N_atoms, file_pointer); fwrite(&cell_length, sizeof(double), 1, file_pointer); fclose(file_pointer); free(pos); pos = NULL; free(momentum); momentum = NULL; free(forces); forces = NULL; free(temperature); temperature = NULL; free(pressure); pressure = NULL; return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <time.h> // Matrixes int *A, *B, *C; // the number of threads int n; // 行列を一時配列で保管するため typedef struct { int A_rows; int B_columns; } Matrix_elem; void multi_mat_elem(Matrix_elem *m); // calc int main(int argc, char *argv[]) { int i, j, k = 0; int pos; int threadnum; int *status; Matrix_elem *m; pthread_t *threads; struct timespec t_s, t_e; long double s, ns; struct timespec c; long double cs; if (argc < 3) { fprintf(stderr, "argv[1] = size of matrixes, argv[2] = the number of thread"); exit(1); } n = atoi(argv[1]); threadnum = atoi(argv[2]); // 領域確保 m = malloc(sizeof(Matrix_elem) * n * n); A = malloc(sizeof(int) * n * n); B = malloc(sizeof(int) * n * n); C = malloc(sizeof(int) * n * n); if (m == NULL || A == NULL || B == NULL) { fprintf(stderr, "don't ensure memories"); exit(2); } for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { pos = i * n + j; A[pos] = rand() % 10 + 1; B[pos] = rand() % 10 + 1; C[pos] = 0; m[pos].A_rows = i; m[pos].B_columns = j; } } // calc clock_gettime(CLOCK_REALTIME, &t_s); threads = malloc(sizeof(pthread_t) * threadnum); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { pthread_create(&threads[k], NULL, (void *)multi_mat_elem, &m[i * n + j]); if (++k == threadnum) { for (k = 0; k < threadnum; k++) { pthread_join(threads[k], (void **)&status); } k = 0; } } } clock_gettime(CLOCK_REALTIME, &t_e); clock_gettime(CLOCK_THREAD_CPUTIME_ID, &c); s = (t_e.tv_sec - t_s.tv_sec); ns = (long double)(t_e.tv_nsec - t_s.tv_nsec); s += ns * 10e-10; cs = c.tv_sec + c.tv_nsec * 10e-10; // real cpu time printf("%d %Lf %Lf\n", threadnum, s, cs); // リリース free(A); free(B); free(m); free(threads); } // C = A * B void multi_mat_elem(Matrix_elem *m) { int i; int sum = 0; // Cij += Aik * Bkj for (i = 0; i < n; i++){ C[m->A_rows * n + m->B_columns] += A[m->A_rows * n + i] * B[i * n + m->B_columns]; } pthread_exit(m); }
C
/* 1-2 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define NAME_SIZE 100 typedef int element; typedef struct _Element { int id; char name[NAME_SIZE]; } Element; typedef struct _SortType { char menu; int sort; int length; Element *list; } SortType; void init(SortType *s, int *menu) { int data, i; if(*menu == 1) { FILE *fp = fopen("1-2.txt", "r"); if(fp == NULL) { printf("data.txt ʽϴ\n"); exit(0); } fscanf(fp, "%d", &(s->length)); s->list = (Element*)malloc(sizeof(Element) * s->length); for(i = 0; i < s->length; i++) fscanf(fp, "%d %s", &(s->list[i].id), s->list[i].name); } else if(*menu == 2) { printf(" Է: "); scanf("%d", &(s->length)); s->list = (Element*)malloc(sizeof(Element) * s->length); for(i = 0; i < s->length; i++) scanf("id, ̸ Է: %d %s", &(s->list[i].id), s->list[i].name); } } void swap(Element *a, Element *b) { Element temp = *a; *a = *b; *b = temp; } void printList(SortType *s) { int i; printf("***** *****\n"); for(i = 0; i < s->length; i++) printf("%d. %s\n", s->list[i].id, s->list[i].name); printf("\n"); } void selectInput(int *menu) { printf("**** Է¹ ****\n"); printf("1. Ϸ Է\n"); printf("2. Ű Է\n"); printf("޴ Է: "); scanf("%d", menu); } void selectSortInput(SortType *s) { fflush(stdin); printf("*************\n"); printf("s: \n"); printf("i: \n"); printf("b: \n"); printf("h: \n"); printf("m: պ\n"); printf("q: \n"); printf("*************\n"); printf("޴ Է: "); scanf("%c", &(s->menu)); printf("1. \n"); printf("2. \n"); printf("޴ Է: "); scanf("%d", &(s->sort)); } // void selectSort(SortType *s) { int i, j; int sort = s->sort; int mIndex; for(i = 0; i < s->length; i++) { mIndex = i; for(j = i + 1; j < s->length; j++) { if(sort == 1) { if(s->list[mIndex].id > s->list[j].id) mIndex = j; } else if(sort == 2) { if(s->list[mIndex].id < s->list[j].id) mIndex = j; } } if(mIndex != i) swap(&(s->list[i]), &(s->list[mIndex])); } } // void insertSort(SortType *s) { int i, j; int sort = s->sort; Element key; for(i = 1; i < s->length; i++) { key = s->list[i]; if(sort == 1) { for(j = i - 1; j >= 0 && s->list[j].id > key.id; j--) s->list[j + 1] = s->list[j]; } else if(sort == 2) { for(j = i - 1; j >= 0 && s->list[j].id < key.id; j--) s->list[j + 1] = s->list[j]; } s->list[j + 1] = key; } } // void bubbleSort(SortType *s) { int i, j; int sort = s->sort; for(i = 0; i < s->length - 1; i++) { for(j = i + 1; j < s->length; j++) { if(sort == 1) { if(s->list[i].id > s->list[j].id) swap(&(s->list[i]), &(s->list[j])); } else if(sort == 2) { if(s->list[i].id < s->list[j].id) swap(&(s->list[i]), &(s->list[j])); } } } } // void shellSort(SortType *s) { int i, j, k; int sort = s->sort; int interval; Element key; for(interval = s->length / 2; interval > 0; interval /= 2) { for(i = 0; i < interval; i++) { for(j = i + interval; j < s->length; j += interval) { key = s->list[j]; if(sort == 1) { for(k = j - interval; k >= 0 && s->list[k].id > key.id; k -= interval) s->list[k + interval] = s->list[k]; } else if(sort == 2) { for(k = j - interval; k >= 0 && s->list[k].id < key.id; k -= interval) s->list[k + interval] = s->list[k]; } s->list[k + interval] = key; } } } } // պ void merge(SortType *s, int left, int mid, int right) { int sort = s->sort; int i = left; int j = mid + 1; int k = left; int l; Element *sorted = (Element*)malloc(sizeof(Element) * (right + 1)); while(i <= mid && j <= right){ if(sort == 1) { if(s->list[i].id <= s->list[j].id) sorted[k++] = s->list[i++]; else sorted[k++] = s->list[j++]; } else if(sort == 2) { if(s->list[i].id >= s->list[j].id) sorted[k++] = s->list[i++]; else sorted[k++] = s->list[j++]; } } while(i <= mid) sorted[k++] = s->list[i++]; while(j <= right) sorted[k++] = s->list[j++]; for(l = left; l <= right; l++) s->list[l] = sorted[l]; free(sorted); } void mergeSort(SortType *s, int left, int right) { int mid; if(left < right){ mid = (left + right) / 2; mergeSort(s, left, mid); mergeSort(s, mid + 1, right); merge(s, left, mid, right); } } // int partition(SortType *s, int left, int right) { if(right <= left) return left; int low = left; int high = right + 1; int sort = s->sort; Element pivot = s->list[left]; while(low < high) { if(sort == 1) { do low++; while(low <= right && pivot.id > s->list[low].id); do high--; while(high > left && pivot.id <= s->list[high].id); } if(sort == 2) { do { low++; } while(low <= right && pivot.id < s->list[low].id); do { high--; } while(high > left && pivot.id >= s->list[high].id); } if(low < high) swap(&(s->list[low]), &(s->list[high])); } s->list[left] = s->list[high]; s->list[high] = pivot; return high; } void quickSort(SortType *s, int left, int right) { int q; if(left < right) { q = partition(s, left, right); quickSort(s, left, q - 1); quickSort(s, q + 1, right); } } void sortList(SortType *s) { switch(s->menu) { case 's': selectSort(s); break; case 'i': insertSort(s); break; case 'b': bubbleSort(s); break; case 'h': shellSort(s); break; case 'm': mergeSort(s, 0, s->length - 1); break; case 'q': quickSort(s, 0, s->length - 1); break; } } int main() { int inputMenu; SortType s; selectInput(&inputMenu); init(&s, &inputMenu); selectSortInput(&s); sortList(&s); printList(&s); free(s.list); }
C
#include "header.h" void kjob(char *arr){ ll n=strlen(arr); ll sn=-1; for(ll i=0;i<n;i++){ if(arr[i]==' '){ arr[i]='\0'; if(sn!=-1){ printf("invalid arguments to kill\n"); return; } sn=i+1; } } if(sn==-1){ printf("invalid arguments to kill\n"); return; } ll jn=toint(arr); ll sen=toint(arr+sn); if(kill(jn,sen)==-1){ printf("Error passing signal\n"); } }
C
#include "Chaining.h" HashTable* CHT_CreateHashTable(int TableSize){ HashTable* HT = (HashTable*)malloc(sizeof(HashTable)); HT->Table = (List*)malloc(sizeof(List)*TableSize); memset(HT->Table, 0x00, sizeof(List)*TableSize); HT->TableSize = TableSize; return HT; } Node* CHT_CreateNode(int Key, char* Value){ Node* NewNode = (Node*)malloc(sizeof(Node)); NewNode->Key = Key; NewNode->Value = (char*)malloc(sizeof(char)*(strlen(Value)+1)); strcpy(NewNode->Value, Value); return NewNode; } void CHT_DestroyNode(Node* TheNode){ free(TheNode->Value); free(TheNode); } void CHT_Set(HashTable* HT, int Key, char* Value){ int Address = CHT_Hash(Key, HT->TableSize); Node* NewNode = CHT_CreateNode(Key, Value); if(HT->Table[Address] == NULL){ HT->Table[Address] = NewNode; }else { //use linked list for collision case List L = HT->Table[Address]; NewNode->Next = L; HT-> Table[Address] = NewNode; printf("collision occured! \n"); } } char* CHT_Get(HashTable* HT, int Key){ int Address = CHT_Hash(Key, HT->TableSize); List TheList = HT->Table[Address]; List Target = NULL; if(TheList == NULL) return NULL; while(1){ if(TheList->Key == Key){ Target = TheList; break; } if(TheList->Next == NULL){ return NULL; }else{ TheList = TheList->Next; } } return Target->Value; } void CHT_DestroyList( List L){ if(L == NULL){ return; } if(L->Next != NULL){ //recursive call for free all node CHT_DestroyNode(L->Next); } CHT_DestroyNode(L); } void CHT_DestroyHashTable(HashTable* HT){ int i =0; for (i=0 ; i<HT->TableSize; i++){ List L = HT->Table[i]; CHT_DestroyList(L); } free(HT); } int CHT_Hash(int Key , int TableSize){ return Key % TableSize; }
C
/*1019. ֺڶ (20) ʱ 100 ms ڴ 65536 kB 볤 8000 B Standard CHEN, Yue һλֲȫͬ4λ Ȱ4ְǵٰǵݼ Ȼõ1ּ2֣õһµ֡ һֱظǺܿͣСֺڶ֮Ƶ6174 ҲKaprekar 磬Ǵ6767ʼõ 7766 - 6677 = 1089 9810 - 0189 = 9621 9621 - 1269 = 8352 8532 - 2358 = 6174 7641 - 1467 = 6174 ... ... ָ4λдʾڶĹ̡ ʽ һ(0, 10000)ڵN ʽ N4λȫȣһN - N = 0000 򽫼ÿһһֱ6174Ϊ֣ ʽעÿְ4λʽ 1 6767 1 7766 - 6677 = 1089 9810 - 0189 = 9621 9621 - 1269 = 8352 8532 - 2358 = 6174 2 2222 2 2222 - 2222 = 0000*/ #include<stdio.h> void sort_n(int *max,int *min,int a[],int n){ int i=0,j=0; for(i=0;i<n;i++){ for(j=i+1;j<n;j++){ if(a[i]>a[j]){ int t; t=a[i]; a[i]=a[j]; a[j]=t; } } } for(i=0;i<n;i++){ if(a[i]!=0){ (*min)=(*min)*10+a[i]; } } for(j=n-1;j>=0;j--){ (*max)=(*max)*10+a[j]; } } int main(){ int n,m=0; int a[4]; int i=0,max=0,min=0; char b[5]; scanf("%d",&n); while(1){ while(i!=4){ a[i++]=n%10; n=n/10; } sort_n(&max,&min,a,i); n=max-min; m=n; b[4]='\0'; i=3; while(i>=0){ b[i]=max%10+'0'; max=max/10; i--; } printf("%s - ",b); i=3; while(i>=0){ b[i]=min%10+'0'; min=min/10; i--; } printf("%s = ",b); i=3; while(i>=0){ b[i]=m%10+'0'; m=m/10; i--; } printf("%s\n",b); if(n==0||n==6174){ break; } max=0; min=0; i=0; } return 0; }
C
// socket编程udp客服端编写 // 1. 创建套接字 // 2. 为套接字绑定地址信息 // 3. 接收数据 // 4. 发送数据 // 5. 关闭套接字 #include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<string.h>//sockaddr 结构体 / IPPRPTP_UDP #include<netinet/in.h> //包含一些字节序转换接口 #include<sys/socket.h>// 套接字接口头文件 int main(int argc,char *argv[]) { //argc表示参数个数,通过argv像程序员传递端口信息 if(argc != 3){ printf("./srv_udp ip port em: ./srv_udp 172.26.32.242 1500\n"); return -1; } const char* ip_addr = argv[1]; uint16_t port_addr = atoi (argv[2]); //socket(地址域,套接字类型,协议类型) int sockfd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); //bind(套接字描述符,地址结构,地址长度) //struck sockaddr_in ipv4地址结构 // struct in_addr{uint32_t s_addr} struct sockaddr_in addr; addr.sin_family = AF_INET; // htons -- 将两个字节的主机字节序装换为网络字节序 addr.sin_port = htons(port_addr); // inet_addr addr.sin_addr.s_addr = inet_addr(ip_addr); socklen_t len = sizeof(struct sockaddr_in); //获取地址信息长度 int ret = bind(sockfd,(struct sockaddr*)&addr,len); if(ret<0){ perror("bind error"); close(sockfd); return -1; } while(1){ char buf[1024]={0}; struct sockaddr_in cliaddr; socklen_t len = sizeof(struct sockaddr_in); //recvfrom(描述符,缓冲区,长度,参数,客户端地址信息) int ret = recvfrom(sockfd,buf,1023,0,(struct sockaddr*)&cliaddr,&len); if(ret<0){ perror("recvfrom error"); close(sockfd); return -1; } printf("client say:%s\n",buf); memset(buf,0x00,1024);//清空buf printf("server say: "); fflush(stdout); scanf("%s",buf); // 通过sockfd将buf中的数据发送到cliaddr客户端 ret = sendto(sockfd,buf,strlen(buf),0,(struct sockaddr*)&cliaddr,len); if(ret<0){ perror("sendto error"); close(sockfd); return -1; } } close(sockfd); return 0; }
C
/****************************** genHTML.c *********************************** Student Name: Marshall Aaron Asch Student Number: 0928357 Date: March 14, 2017 Course Name: CIS*2750 Assignment: A3 Parses the config file (.wpml) into HTML with imbeded PHP NOTE: button, text form, radio form , exe generate some PHP that needs to be executed (only lines that begin with ?> ) The button tag requires a form to exist on the page that is called BUTTONFORM and a javascript function link(dest) to submit the form the text form and the radio form will have 2 extra hidden fields for the userID and the stream name. If those PHP variables fo not exist then the values will be left blank. ****************************************************************************/ #include "genHTML.h" int main(int argc, char const *argv[]) { bool isValid; /* make sure that a filename was given */ if (argc != 2) { printf("<h1>Error. A filename must be given to display.</h1>\n"); return 1; } isValid = checkFiletype(argv[1]); /* make sure that the file is the correct type */ if (isValid == false) { printf("<h1>Error. File is the wrong type.</h1>\n"); return 1; } parseFile(argv[1]); return 0; } /********************** PARSER ***********************/ /** * checkFiletype * Takes in a filename and checks if its extension is .wpml * * IN: file, the name of the file to check * OUT: true, if the extension is .wpml * false, otherwise or on error * POST: none * ERROR: false if the filename does not exist or does not contain an extension */ bool checkFiletype(const char* file) { char* fileName; char* extension; int startExtension; fileName = strduplicate(file); /* make sure that the file is given */ if (fileName == NULL) { return false; } startExtension = lastIndex(fileName, '.'); extension = substring(fileName, startExtension + 1, strlen(fileName) - 1); /* check if it is a .wpml extension */ if (extension == NULL || strcmp(extension, "wpml") != 0) { free(fileName); free(extension); return false; } else { free(fileName); free(extension); return true; } } /** * parseFile * Parses the .wpml file into a HTML body * * IN: fileName, the name of the file to parse * OUT: none * POST: prints the HTML page to the stdout * ERROR: prints error message is there is an error */ void parseFile(const char * fileName) { FILE* file; char temp; char temp2; /* make sure that the file name is given */ if (fileName == NULL) { return; } /* open the file */ file = fopen(fileName, "r"); if (file == NULL) { return; } while ((temp = fgetc(file))) { /* check if it reached the end of the file */ if (temp == EOF) { break; } if (temp != '.') { printf("%c", temp); } else { temp2 = fgetc(file); /* if this is the end the print the last character and end */ if (temp2 == EOF) { printf("%c", temp); break; } /* check what tag it is */ switch (temp2) { case 'b': /* button (name="name",link="page link") */ case 'd': /* horozontal line there are no arguments is it .d() or .d */ case 'e': /* excecutable (exe=file) <file ether in current dir or ./bin or system /bin search in that order >*/ case 'h': /* heading (size=<1-6>,text="...") <default size = 3 (optional) , text = "HEADING"> */ case 'i': /* form (action="action file", text="prompt", name="name", value="default value" [required] ... ) <add a submit button, use POST args apear as sets of 3 > */ case 'l': /* link (text="...",link=<URL>) <default text = "link", link = "#" > */ case 'p': /* picture (image="...", size=<width>x<height>) <default height = 100 width = 100 > */ case 'r': /* radio button (action="action file", name="name", value="<value>", [value="<value>"...]) <first value is the default value> */ case 't': /* text (filename="file) or (text="...") <default text = "Default text", if file then ready the file into the tag, text might contain other HTML tags > */ case 's': /* select stream () takes no arguments */ case 'n': /* line break there are no arguments is it .n() */ case 'f': /* create a new post form () takes no arguments */ parseTag(file, temp2); break; default: printf("%c", temp); ungetc(temp2, file); } } } fclose(file); } /** * parseTag * Parses from the opning ( to the ) and parses the key, value pairs * that is in the order of key = value, or key = "value" must be in * pairs. * * IN: file, the file that is being read * type, the type of tag it is parsing * OUT: none * POST: prints the HTML tag (or PHP tags) to the stdout * ERROR: ends on error */ void parseTag(FILE* file, char type) { char temp; char temp2; char* text; char* link; char* image; char* size; char* action; char* defaultValue; char* name; char* fileName; char* prompt; char* other; char* onclick; char* class; char* string; char* keyStr; char* args; bool required; bool end_file; bool isStr; FieldList* fields; FieldList* newFieldElement; Param* param; ParamList* paramList; int i; isStr = false; end_file = false; string = NULL; keyStr = NULL; param = NULL; paramList = NULL; fields = NULL; other = NULL; /* make sure that the parameter is valid */ if (file == NULL) { return; } fgetc(file); /* move up to first non whitespace */ while ((temp = fgetc(file))) { if (temp == EOF || temp != ' ') { break; } } /* make sure it did not reach the end of the file */ if (temp == EOF) { end_file = true; } else { ungetc(temp, file); /* read from the file */ while ((temp = fgetc(file))) { /* check for premature EOF */ if (temp == EOF) { end_file = true; break; } /* check if it reached the end of the tag*/ if (temp == ')' && isStr == false) { /* add this string to the list */ param = newParam(keyStr, string); paramList = addToParamList(paramList, param); free(keyStr); free(string); keyStr = NULL; string = NULL; break; } /* the end of a token */ if ((temp == ',' || temp == '=' ) && isStr == false) { /* set the old string to the key and the next to the value */ if (temp == '=') { keyStr = string; string = NULL; } if (temp == ',') { param = newParam(keyStr, string); paramList = addToParamList(paramList, param); free(keyStr); free(string); keyStr = NULL; string = NULL; } continue; } /* then it has reached the end of the value */ if (temp == '\"') { string = joinC(string, temp); TOGGLE(isStr); continue; } /* check to see if there is an escaped " */ if (temp == '\\') { temp2 = fgetc(file); if (temp2 == '\"') { string = join(string, "\\\""); } else { string = joinC(string, temp); ungetc(temp2, file); } continue; } /* skip any whitespcae that is not in a string */ if (temp == ' ' && isStr == false) { continue; } /* add the character to the string */ string = joinC(string, temp); } } /* check if the file ended unexcpectedly */ if (end_file == true) { printf("Error unexcpected end of file.\n"); return; } /* all the args should now be in list in the order of name -> data -> name ->data ...*/ /* parse the key, values into there corospinding arguments */ switch (type) { case 'b': /* button (name="name",link="page link") */ text = NULL; link = NULL; onclick = NULL; class = NULL; other = NULL; /* make sure parameters are given */ if (paramList != NULL) { /* get the arguments */ for (i = 0; i < paramList->length; i++) { if (paramList->list[i]->key == NULL) { /* join other*/ other = join(other, paramList->list[i]->value); other = joinC(other, ' '); } if (strcmp(paramList->list[i]->key, "name") == 0) { text = paramList->list[i]->value; } else if (strcmp(paramList->list[i]->key, "link") == 0) { link = paramList->list[i]->value; } else if (strcmp(paramList->list[i]->key, "onclick") == 0) { onclick = paramList->list[i]->value; } else if (strcmp(paramList->list[i]->key, "class") == 0) { class = paramList->list[i]->value; } else { /* join other*/ other = join(other, paramList->list[i]->key); other = joinC(other, '='); other = join(other, paramList->list[i]->value); other = joinC(other, ' '); } } } createButton(text, link, onclick, class, other); free(other); break; case 'd': /* horozontal line there are no arguments is it .d() */ other = NULL; /* make sure parameters are given */ if (paramList != NULL) { /* get the arguments */ for (i = 0; i < paramList->length; i++) { if (paramList->list[i]->key == NULL) { /* join other*/ other = join(other, paramList->list[i]->value); other = joinC(other, ' '); } else { /* join other*/ other = join(other, paramList->list[i]->key); other = joinC(other, '='); other = join(other, paramList->list[i]->value); other = joinC(other, ' '); } } } horozontalLine(other); free(other); break; case 'e': /* excecutable (exe=file) <file ether in current dir or ./bin or system /bin search in that order >*/ fileName = NULL; args = NULL; /* make sure parameters are given */ if (paramList != NULL) { /* get the arguments */ for (i = 0; i < paramList->length; i++) { if (strcmp(paramList->list[i]->key, "exe") == 0) { fileName = paramList->list[i]->value; } else if (strcmp(paramList->list[i]->key, "args") == 0) { args = paramList->list[i]->value; } } } createExe(fileName, args); break; case 'h': /* heading (size=<1-6>,text="...") <default size = 3 (optional) , text = "HEADING"> */ text = NULL; size = NULL; other = NULL; /* make sure parameters are given */ if (paramList != NULL) { /* get the arguments */ for (i = 0; i < paramList->length; i++) { if (paramList->list[i]->key == NULL) { /* join other*/ other = join(other, paramList->list[i]->value); other = joinC(other, ' '); } if (strcmp(paramList->list[i]->key, "text") == 0) { text = paramList->list[i]->value; } else if (strcmp(paramList->list[i]->key, "size") == 0) { size = paramList->list[i]->value; } else { /* join other*/ other = join(other, paramList->list[i]->key); other = joinC(other, '='); other = join(other, paramList->list[i]->value); other = joinC(other, ' '); } } } createHeading(text, size, other); free(other); break; case 'i': /* form (action="action file", text="prompt", name="name", value="default value" [required=true] ... ) <add a submit button, use POST args apear as sets of 3 > */ action = NULL; text = NULL; name = NULL; defaultValue = NULL; required = false; newFieldElement = NULL; fields = NULL; other = NULL; /* make sure parameters are given */ if (paramList != NULL) { /* get the arguments */ for (i = 0; i < paramList->length; i++) { if (paramList->list[i]->key == NULL) { /* join other*/ other = join(other, paramList->list[i]->value); other = joinC(other, ' '); } if (strcmp(paramList->list[i]->key, "action") == 0) { action = paramList->list[i]->value; } else if (strcmp(paramList->list[i]->key, "name") == 0) { name = paramList->list[i]->value; } else if (strcmp(paramList->list[i]->key, "value") == 0) { defaultValue = paramList->list[i]->value; } else if (strcmp(paramList->list[i]->key, "name") == 0) { name = paramList->list[i]->value; } else if (strcmp(paramList->list[i]->key, "required") == 0) { if (strcmp_nocase(paramList->list[i]->value, "true") == 0 || strcmp_nocase(paramList->list[i]->value, "\"true\"") == 0) { required = true; } else { required = false; } } else if (strcmp(paramList->list[i]->key, "text") == 0) { /* add the element */ if (text != NULL) { newFieldElement = newField(name, text, defaultValue, required, other); fields = addToList(fields, newFieldElement); /* clear tuple */ text = NULL; name = NULL; defaultValue = NULL; newFieldElement = NULL; free(other); other = NULL; required = false; } text = paramList->list[i]->value; } else { /* join other*/ other = join(other, paramList->list[i]->key); other = joinC(other, '='); other = join(other, paramList->list[i]->value); other = joinC(other, ' '); } } } /* Add the last input field to the list */ if (text != NULL) { newFieldElement = newField(name, text, defaultValue, required, other); free(other); other = NULL; fields = addToList(fields, newFieldElement); /* clear tuple */ text = NULL; name = NULL; defaultValue = NULL; newFieldElement = NULL; } createFormText(action, fields); free(other); break; case 'l': /* link (text="...",link=<URL>) <default text = "link", link = "#" > */ text = NULL; link = NULL; other = NULL; /* make sure parameters are given */ if (paramList != NULL) { /* get the arguments */ for (i = 0; i < paramList->length; i++) { if (paramList->list[i]->key == NULL) { /* join other*/ other = join(other, paramList->list[i]->value); other = joinC(other, ' '); } if (strcmp(paramList->list[i]->key, "text") == 0) { text = paramList->list[i]->value; } else if (strcmp(paramList->list[i]->key, "link") == 0) { link = paramList->list[i]->value; } else { /* join other*/ other = join(other, paramList->list[i]->key); other = joinC(other, '='); other = join(other, paramList->list[i]->value); other = joinC(other, ' '); } } } createLink(text, link, other); free(other); break; case 'p': /* picture (image="...", size=<width>x<height>) <default height = 100 width = 100 > */ image = NULL; size = NULL; other = NULL; /* make sure parameters are given */ if (paramList != NULL) { /* get the arguments */ for (i = 0; i < paramList->length; i++) { if (paramList->list[i]->key == NULL) { /* join other*/ other = join(other, paramList->list[i]->value); other = joinC(other, ' '); } if (strcmp(paramList->list[i]->key, "image") == 0) { image = paramList->list[i]->value; } else if (strcmp(paramList->list[i]->key, "size") == 0) { size = paramList->list[i]->value; } else { /* join other*/ other = join(other, paramList->list[i]->key); other = joinC(other, '='); other = join(other, paramList->list[i]->value); other = joinC(other, ' '); } } } createPicture(image, size, other); free(other); break; case 'r': /* radio button (action="action file", [prompt="text"], name="name", value="<value>", [value="<value>"...]) <first value is the default value> */ action = NULL; name = NULL; defaultValue = NULL; newFieldElement = NULL; prompt = NULL; fields = NULL; other = NULL; /* make sure parameters are given */ if (paramList != NULL) { /* get the arguments */ for (i = 0; i < paramList->length; i++) { if (paramList->list[i]->key == NULL) { /* join other*/ other = join(other, paramList->list[i]->value); other = joinC(other, ' '); } if (strcmp(paramList->list[i]->key, "action") == 0) { action = paramList->list[i]->value; } else if (strcmp(paramList->list[i]->key, "name") == 0) { name = paramList->list[i]->value; } else if (strcmp(paramList->list[i]->key, "value") == 0) { defaultValue = paramList->list[i]->value; newFieldElement = newField(NULL, NULL, defaultValue, false, other); fields = addToList(fields, newFieldElement); free(other); other = NULL; } else if (strcmp(paramList->list[i]->key, "name") == 0) { name = paramList->list[i]->value; } else if (strcmp(paramList->list[i]->key, "prompt") == 0) { prompt = paramList->list[i]->value; } else { /* join other*/ other = join(other, paramList->list[i]->key); other = joinC(other, '='); other = join(other, paramList->list[i]->value); other = joinC(other, ' '); } } } createFormRadio(action, name, prompt, fields); free(other); break; case 't': /* text (filename="file) or (text="...") <default text = "Default text", if file then ready the file into the tag, text might contain other HTML tags > */ text = NULL; fileName = NULL; other = NULL; /* make sure parameters are given */ if (paramList != NULL) { /* get the arguments */ for (i = 0; i < paramList->length; i++) { if (paramList->list[i]->key == NULL) { /* join other*/ other = join(other, paramList->list[i]->value); other = joinC(other, ' '); } if (strcmp(paramList->list[i]->key, "text") == 0) { text = paramList->list[i]->value; } else if (strcmp(paramList->list[i]->key, "filename") == 0) { fileName = paramList->list[i]->value; } else { /* join other*/ other = join(other, paramList->list[i]->key); other = joinC(other, '='); other = join(other, paramList->list[i]->value); other = joinC(other, ' '); } } } createtext(text, fileName, other); free(other); break; case 'n': /* line break there are no arguments is it .n() */ other = NULL; /* make sure parameters are given */ if (paramList != NULL) { /* get the arguments */ for (i = 0; i < paramList->length; i++) { if (paramList->list[i]->key == NULL) { /* join other*/ other = join(other, paramList->list[i]->value); other = joinC(other, ' '); } else { /* join other*/ other = join(other, paramList->list[i]->key); other = joinC(other, '='); other = join(other, paramList->list[i]->value); other = joinC(other, ' '); } } } lineBreak(other); free(other); break; case 's': /* select stream () takes no arguments */ createStreamSelect(); break; case 'f': /* create a new post form () takes no arguments */ createPost(); break; } freeParamList(paramList); destroyFieldList(fields); } /********************** CREATE TAGS ***********************/ /** * createExe * Creates the tag to excecute a file on the server using PHP * * .e(exe="file", args="stuff") * * checks for the file in * 1. fileName * 2. bin/fileName * 3. /bin/fileName * * IN: fileNameIn, the name of the file to excecute * argsIn, any optional commandline arguments * OUT: none * POST: prints the tag to the stdout * ERROR: prints "<h4> File does not exist.</H4>"" on error */ void createExe(char* fileNameIn, char* argsIn) { FILE* file; char* name; char* fileName; char* args; /* make sure that the file to excecute exists */ if (fileNameIn == NULL) { printf("<h4> File does not exist.</H4>\n"); return; } /* make sure there are not quotes arround the fileName */ fileName = unWrapQuote(fileNameIn); args = unWrapQuote(argsIn); /* check if in local dir */ file = fopen(fileName, "r"); if (file != NULL) { printf("<?php exec(\"%s %s\"); ?>", fileName, args); fclose(file); free(fileName); free(args); return; } name = strduplicate("./bin/"); name = join(name, fileName); /* check if in local bin file */ file = fopen(name, "r"); if (file != NULL) { printf("<?php exec(\"%s %s\"); ?>", name, args); fclose(file); free(name); free(fileName); free(args); return; } free(name); name = strduplicate("/bin/"); name = join(name, fileName); /* check if in system bin file */ file = fopen(name, "r"); if (file != NULL) { printf("<?php exec(\"%s %s\"); ?>", name, args); fclose(file); free(name); free(fileName); free(args); return; } free(args); free(name); free(fileName); printf("<h4> File does not exist.</H4>\n"); return; } /** * createtext * Creates the tag that contains the given text * or the text loaded from the file * * puts all the text into a <p> </p> tags only if aditional * fields are given * * .t(filename="file") or .t(text="...") or .t() * * default text = "Default text" * * If the file option is given the full filepath must be given * * IN: text, the text to put into the tag * fileName, the name of the file to containing the text * other, any other tags that get inserted * OUT: none * POST: prints the tag to the stdout * ERROR: none */ void createtext(char* textIn, char* fileNameIn, char* otherIn) { FILE* file; char temp; char* other; char* text; char* fileName; /* make sure there are not quotes arround the string */ fileName = unWrapQuote(fileNameIn); other = unWrapQuote(otherIn); text = unWrapQuote(textIn); /* add the additional info if it is given */ if (otherIn != NULL) { printf("<div %s>\n", other); } /* if the file option is given */ if (textIn == NULL && fileNameIn != NULL) { /* then read from file */ file = fopen(fileName, "r"); if (file == NULL) { printf("Failed to open the file.\n"); } else { /* read the file 1 char at a time */ while ((temp = fgetc(file))) { if (temp == EOF) { break; } else { printf("%c", temp); } } fclose(file); } } else if (textIn != NULL && fileNameIn == NULL) { /* then print the text */ printf("%s", text); } else { /* invalid param print error */ printf("Default text\n"); } /* add the additional info if it is given */ if (otherIn != NULL) { printf("</div %s>\n", other); } free(other); free(text); free(fileName); } /** * createButton * Creates the tag for the button elements. * Ff the link option is given then it will sibmit * a form to that page that has the ID BUTTONFORM * If the onclick option is given then it will do * that action when the button is clicked. * * .b(name="text in button", link="page link") * .b(name="text in button", onclick="script()") * * 2 options are required * * IN: text, the name of the button * link, the link to another page * onclick, the script to be called on click * class, the style classes for the button * other, any other tags that get inserted * OUT: none * POST: prints the tag to the stdout * ERROR: none */ void createButton(char* textIn, char* linkIn, char* onclickIn, char* classIn, char* otherIn) { char* text; char* link; char* click; char* class; char* other; static int numButtons = 0; /* make sure there are not quotes arround the string */ text = unWrapQuote(textIn); link = unWrapQuote(linkIn); click = wrapQuote(onclickIn); class = wrapQuote(classIn); other = unWrapQuote(otherIn); if (textIn == NULL) { free(text); text = strduplicate("default"); } /* print the correct version for link or onclick */ if (linkIn != NULL) { printf("<button class=%s type=button onclick=link(\'%s\') %s>%s</button>", class, link, other, text); /* print the form if it is neccisary */ if (numButtons == 0) { genButtonForm(); } numButtons++; } else if (onclickIn != NULL) { printf("<button class=%s type=button onclick=%s %s>%s</button>", class, click, other, text); } else { printf("<button class=%s type=button %s>%s</button>", class, other, text); } free(text); free(link); free(click); free(class); free(other); } /** * createFormText * Creates the tag for the text form * submits the form using POST. * * The text, name, value and required (optional) must apear as multiples of * ether 3 or 4 , name value and required can apear in any order byt text * must be first * .i(action="action file", text="prompt", name="name", value="default value" [required = anything] ... ) * * * * IN: action, the file to submit the form to * fields, linked list that contains a stuct with all the field info * other, any other tags that get inserted * OUT: none * POST: prints the tag to the stdout * ERROR: none */ void createFormText(char* actionIn, FieldList* fields) { FieldList* tempField; char* action; /* make sure there are not quotes arround the string */ action = wrapQuote(actionIn); printf("<form action=%s method=\"post\">\n", action); /* to hold the userID and the stream that gets submitted */ printf("<input type=\"hidden\" name=\"__USERID_TF\" id=\"__USERID_TF\" value=\"<?php echo $userID; ?>\">\n"); printf("<input type=\"hidden\" name=\"__STREAM_TF\" id=\"__STREAM_TF\" value=\"<?php echo $streamName; ?>\">\n"); printf("<p><span class=\"required\">*</span> = required field </p>\n"); /* go through all the fields*/ tempField = fields; while (tempField != NULL) { if (tempField->required == true) { printf("<label for=%s>%s <span class=\"required\">*</span></label>", tempField->name, tempField->prompt); printf("<input type=\"text\" name=%s id=%s value=%s required>\n", tempField->name, tempField->name, tempField->defaultValue); } else { printf("<label for=%s>%s</label>", tempField->name, tempField->prompt); printf("<input type=\"text\" name=%s id=%s value=%s>\n", tempField->name, tempField->name, tempField->defaultValue); } printf("<br>\n"); tempField = tempField->next; } printf("<input type=\"submit\" value=\"Submit\"/>\n"); printf("</form>\n"); free(action); } /** * createFormRadio * Creates the tag for the radio button form * submits the form using POST. * * prompt is optional, if it is not given the the name is used. * The first value in the list starts off selected * * .r(action="action file", [prompt="text"], name="name", value="<value>", [value="<value>"...]) * * IN: action, the file to submit the form to * name, the name of the field * prompt, the prompt for the input * fields, linked list that contains a stuct with all the field info * other, any other tags that get inserted * OUT: none * POST: prints the tag to the stdout * ERROR: none */ void createFormRadio(char* actionIn, char* nameIn, char* promptIn, FieldList* fields) { FieldList* tempField; bool first; char* action; char* name; char* prompt; /* make sure there are not quotes arround the string */ action = wrapQuote(actionIn); name = wrapQuote(nameIn); prompt = unWrapQuote(promptIn); first = true; if (nameIn == NULL) { free(name); name = strduplicate("\"radioButton\""); } if (promptIn == NULL) { free(prompt); prompt = unWrapQuote(name); } printf("<form action=%s method=\"post\">\n", action); /* insert the userID and the streamName */ printf("<input type=\"hidden\" name=\"__USERID_RF\" id=\"__USERID_RF\" value=\"<?php echo $userID; ?>\">\n"); printf("<input type=\"hidden\" name=\"__STREAM_RF\" id=\"__STREAM_RF\" value=\"<?php echo $streamName; ?>\">\n"); printf("<label for=%s>%s</label>\n", name, prompt); /* go through all the fields*/ tempField = fields; while (tempField != NULL) { if (first == true) { printf("<input type=\"radio\" name=%s id=%s value=%s checked>%s<br>\n", name, name, tempField->defaultValue, tempField->defaultValue); } else { printf("<input type=\"radio\" name=%s id=%s value=%s>%s<br>\n", name, name, tempField->defaultValue, tempField->defaultValue); } tempField = tempField->next; } printf("<input type=\"submit\" value=\"Submit\"/>\n"); printf("</form>\n"); free(action); free(name); free(prompt); } /** * createLink * Creates the tag for the link * * .l(text="...",link="<URL>") * * If the text is not given then it is set to "link" * If the link is not given it is set to "#" (its self) * * IN: text, the text that is part of the link * link, the URL to go to * other, any other tags that get inserted * OUT: none * POST: prints the tag to the stdout * ERROR: none */ void createLink(char* textIn, char* linkIn, char* otherIn) { char* other; char* text; char* link; /* make sure there are not quotes arround the string */ text = unWrapQuote(textIn); link = unWrapQuote(linkIn); other = unWrapQuote(otherIn); if (textIn == NULL) { free(text); text = strduplicate("link"); } if (linkIn == NULL) { free(link); link = strduplicate("\"#\""); } /* print the link tag */ printf("<a href=%s %s>%s</a>\n", link, other, text); free(other); free(text); free(link); } /** * createPicture * Creates the tag for a picture * * .p(image="URL", size=<width>x<height>) * * If the image is not given then a placeholder is used * if size is not given then height and width are set to 100 * * IN: image, the URL of the picture that is being inserted * size, the height and width of the picture * other, any other tags that get inserted * OUT: none * POST: prints the tag to the stdout * ERROR: none */ void createPicture(char* imageIn, char* sizeIn, char* otherIn) { char* height; char* width; char* other; char* image; char* size; /* make sure there are not quotes arround the string */ image = unWrapQuote(imageIn); size = unWrapQuote(sizeIn); other = unWrapQuote(otherIn); if (sizeIn != NULL) { /* try to get the size of the picture */ width = substring(size, 0, firstIndex(size, 'x') - 1); height = substring(size, firstIndex(size, 'x') + 1, strlen(size) - 1); } else { width = NULL; height = NULL; } /* check if the defaults need to be used */ if (image == NULL) { free(image); image = strduplicate("\"http://placehold.it/500/?text=image+not+found\""); } if (width == NULL) { width = strduplicate("\"100\""); } if (height == NULL) { height = strduplicate("\"100\""); } /* print the image tag */ printf("<img src=%s height=%s width=%s alt=\"Image not found\" %s>\n", image, height, width, other); free(height); free(width); free(size); free(image); free(other); } /** * createHeading * Creates the tag for a heading * * .h(size=<1-6>,text="...") * * If the text is not given then "HEADING" is used * if size is not given then size is set to 3 * * IN: text, body of the <H> tag * size, the size of the heading * other, any other tags that get inserted * OUT: none * POST: prints the tag to the stdout * ERROR: none */ void createHeading(char* textIn, char* sizeIn, char* otherIn) { char* other; char* text; char* size; /* make sure there are not quotes arround the string */ text = unWrapQuote(textIn); size = unWrapQuote(sizeIn); other = unWrapQuote(otherIn); if (sizeIn == NULL) { free(size); size = strduplicate("3"); } if (textIn == NULL) { free(text); text = strduplicate("HEADING"); } /* make sure that size is valid if not set to default */ if (size == NULL || strlen(size) > 1 || size[0] < '1' || size[0] > '6') { size = "3"; } /* print the heading tag */ printf("<H%s %s>%s</H%s>\n", size, other, text, size); free(text); free(other); free(size); } /** * horozontalLine * Creates the tag for a hotozontal line * * .d() * * IN: other, any other tags that get inserted * OUT: none * POST: prints the tag to the stdout * ERROR: none */ void horozontalLine(char* otherIn) { char* other; /* make sure there are not quotes arround the string */ other = unWrapQuote(otherIn); printf("<HR %s>\n", other); free(other); } /** * horozontalLine * Creates the tag for a line break * * .n() * * IN: other, any other tags that get inserted * OUT: none * POST: prints the tag to the stdout * ERROR: none */ void lineBreak(char* otherIn) { char* other; /* make sure there are not quotes arround the string */ other = unWrapQuote(otherIn); printf("<BR %s>\n", other); free(other); } /** * genButtonForm * Prints the form needed for buttons to to submit to abother page * * IN: none * OUT: none * POST: prints the form to the stdout * ERROR: none */ void genButtonForm() { printf("<!-- Form that holds the userID and the stream for the links -->\n"); printf("<form action=\"#\" method=\"post\" id=\"BUTTONFORM\">\n"); printf("<input type=\"hidden\" name=\"__USERID_B\" id=\"__USERID_B\" value=\"<?php echo $userID; ?>\">\n"); printf("<input type=\"hidden\" name=\"__STREAM_B\" id=\"__STREAM_B\" value=\"<?php echo $streamName; ?>\">\n"); printf("</form>\n"); /* generate the script needed */ printf("<script>\n"); printf("function link(dest) {\n"); printf("var form = document.getElementById(\"BUTTONFORM\");\n"); printf("form.action = dest;\n"); printf("form.submit();\n"); printf("}\n"); printf("</script>\n"); } /** * createStreamSelect * Generated the PHP code that will generate * the form to select a stream * * IN: none * OUT: none * POST: prints the form to the stdout * ERROR: none */ void createStreamSelect() { printf("<?php if (sizeof($streamList) === 0)"); printf("{"); printf("echo \"<h3>Invalid Login</H3>\";"); printf("}"); printf("else"); printf("{"); printf("echo \"<form action=\\\"viewposts.php\\\" method=\\\"post\\\">\";"); printf("echo \"<input type=\\\"hidden\\\" name=\\\"__USERID_B\\\" id=\\\"__USERID_B\\\" value=\\\"$userID\\\">\";"); printf("echo \"<input type=\\\"radio\\\" name=\\\"__STREAM_B\\\" id=\\\"__STREAM_B\\\" value=\\\"all\\\" checked>all <br>\";"); printf("foreach ($streamList as $stream)"); printf("{"); printf("echo \"<input type=\\\"radio\\\" name=\\\"__STREAM_B\\\" id=\\\"__STREAM_B\\\" value=\\\"$stream\\\">$stream <br>\";"); printf("}"); printf("echo \"<input type=\\\"submit\\\" value=\\\"Select\\\"/>\";"); printf("echo \"</form>\";"); printf("} ?>"); } /** * createPost * Generated the PHP code that will generate * the form to select submit a post * * IN: none * OUT: none * POST: prints the form to the stdout * ERROR: none */ void createPost() { /* print error mssage if they dont have permission */ printf("<?php if (sizeof($streamList) === 0)"); printf("{"); printf("echo \"<h3>Invalid Login</H3>\";"); printf("}"); printf("else"); printf("{"); printf("echo \"<form action=\\\"post.php\\\" method=\\\"post\\\">\";"); printf("echo \"<input type=\\\"hidden\\\" name=\\\"userID\\\" id=\\\"userID\\\" value=\\\"$userID\\\">\";"); printf("echo \"<input type=\\\"hidden\\\" name=\\\"oldstream\\\" id=\\\"oldstream\\\" value=\\\"$streamName\\\">\";"); printf("echo \"<p><span class=\\\"required\\\">*</span> = required field </p>\";"); printf("echo \"<label for=\\\"stream\\\">Stream: <span class=\\\"required\\\">*</span></label>\";"); printf("echo \"<select name=\\\"stream\\\" id=\\\"stream\\\" required>\";"); /* generate the stream options */ printf("foreach ($streamList as $stream)"); printf("{"); printf("echo \"<option value=\\\"$stream\\\">$stream</option>\";"); printf("}"); printf("echo \"</select><br>\";"); printf("echo \"<label for=\\\"post\\\">Message: <span class=\\\"required\\\">*</span></label><br>\";"); printf("echo \"<textarea name=\\\"post\\\" id=\\\"post\\\" rows=\\\"8\\\" col=\\\"80\\\" required></textarea>\";"); printf("echo \"<br><input type=\\\"submit\\\" value=\\\"Submit\\\"/>\";"); printf("echo \"</form>\";"); printf("} ?>"); } /** * newParamList * Create a new ParamList struct * with the a list of the given length * * IN: num, the number of elements in the list * OUT: pointer to the struct in mem on success * NULL on failure * POST: create memeoy * ERROR: NULL if mem could not be allocated */ ParamList* newParamList(int num) { ParamList* list; /* try alocating memory */ list = malloc(sizeof(ParamList)); if (list == NULL) { return NULL; } /* initilize the data */ list->length = 0; list->list = malloc(sizeof(Param*)*num + 1); if (list->list != NULL) { list->length = num; list->list[0] = NULL; } return list; } /** * addToParamList * Adds the item to the list. Makes the list bigger * * IN: list, the list to be added to * item, the item to be added * OUT: pointer to the list object * NULL on failure * POST: makes the list bugger * ERROR: NULL if mem could not be allocated */ ParamList* addToParamList(ParamList* list, Param* item) { Param** temp; int i; /* check that a item is being added */ if (item == NULL) { return list; } if (list == NULL) { /* create the list*/ list = newParamList(1); if (list == NULL) { return NULL; } list->list[0] = item; return list; } /* allocate new memory */ temp = malloc(sizeof(Param*) * (list->length + 2)); if (temp == NULL) { return list; } /* copy list over */ for (i = 0; i < list->length; i++) { temp[i] = list->list[i]; } /* add the new one */ temp[list->length] = item; temp[list->length + 1] = NULL; list->length += 1; free(list->list); list->list = temp; return list; } /** * newParam * Create a new Param struct * with the given data * the stings are copied and need to be * freed by the caller * * IN: key, the key of the value * value, the value of the item * OUT: pointer to the struct in mem on success * NULL on failure * POST: copys the strings into memory * ERROR: NULL if mem could not be allocated */ Param* newParam(char* key, char* value) { Param* item; /* allocate memory */ item = malloc(sizeof(Param)); if (item == NULL) { return NULL; } item->key = strduplicate(key); item->value = strduplicate(value); return item; } /** * freeParam * Destroys all the memory being used by the * struct * * IN: param, the list to be freed * OUT: none * POST: destroys all the memory * ERROR: ends */ void freeParam(Param* param) { /* make sure argument is valid */ if (param == NULL) { return; } free(param->key); free(param->value); free(param); } /** * freeParamList * Destroys all the memory being used by the list * * IN: list, the list to be freed * OUT: none * POST: destroys all the memory * ERROR: ends */ void freeParamList(ParamList* list) { int i; /* check the parameters */ if (list == NULL) { return; } /* free the list */ for (i = 0; i < list->length; i++) { freeParam(list->list[i]); } free(list->list); free(list); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* btree_insert_data.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mchuang <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/06/01 00:50:51 by mchuang #+# #+# */ /* Updated: 2018/06/01 02:02:29 by mchuang ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_btree.h" void btree_insert_data(t_btree **root, void *item, int (*cmpf)(void *, void *)) { t_btree *new_item; new_item = btree_create_node(item); if (!root || !*root || !item) { if (root && item) *root = new_item; return ; } if (cmpf(item, (*root)->item) < 0) { if (!((*root)->left)) (*root)->left = new_item; else btree_insert_data(&((*root)->left), item, cmpf); } else { if (!((*root)->right)) (*root)->right = new_item; else btree_insert_data(&((*root)->right), item, cmpf); } }
C
// $Id: dataArray.h,v 1.1.1.1 2001/12/04 20:32:34 bob Exp $ /* 23 Aug 01 ... Alter how operators are applied to data arrays. 7 Jul 01 ... Import operators from distinct file,then revised. 28 Jun 01 ... Operator in place. 26 Jun 01 ... Row-major form for mgs version of sweeper. 15 Oct 98 ... Created in original form for sweeper. */ #ifndef _DATAARRAY_ #define _DATAARRAY_ #include "operator.h" //////////////////////////////////////////////////////////////////////////////// typedef struct aDataArray { float *pData; float **pRows; long nRows, nCols; int nPad; // number of unused elements at the end of each row } aDataArray; typedef struct aDataArray *DataArray; //////////////////////////////////////////////////////////////////////////////// // // New, delete, copy // DataArray NewDataArray (long nRows, long nCols, int nPad, char *creator); DataArray CopyDataArray (DataArray da, char *creator); void DeleteDataArray (DataArray m); // Read, write to file // Format: first line nRows nCols // rest data11 data12 .... data1p DataArray ReadDataArray (char *fileName, long nPad); /* Padding the data array leaves nPad extra columns of space at the end of each row for subsequent use. */ int WriteDataArray (DataArray da, char *fileName); /* Does not include any padding. */ void PrintDataArray (DataArray da, char *msg, long maxRows, long maxCols); // // Access to matrix elements // void DimensionsDataArray (DataArray da, long *nRows, long *nCols, long *nPad); long NRowsOfDataArray (DataArray da); long NColsOfDataArray (DataArray da); float ElementDataArray (DataArray da, long row, long col); float * RowPtrOfDataArray (DataArray da, long row); float ** BasePtrOfDataArray (DataArray da); // // Interaction with Operators // long UsePaddingOfDataArray (DataArray da); /* Allows writing into the padding column; returns the added column index. Returns zero if no padding is available. */ void ApplyOperatorToDataArray (Operator f, DataArray src, int useWeights, DataArray dst, long dstColumn); /* Applies the function row-by-row, inserting the results in column dstColumn of the dst data array. Input data array is *not* altered. */ #endif
C
#include<stdio.h> #include<stdlib.h> #include<string.h> int main(int argc,char *argv[]) { if(argc!=2) { printf("Use this format: <filename> \n"); return -1; } FILE *fp; char str[100]; if((fp=fopen(argv[1],"w"))==NULL) { printf("program can not open file for writing."); return -2; } printf("Enter some character which is written in file(write exit\\ to stop): "); do { // printf(": "); gets(str); strcat(str,"\n"); if((fputs(str,fp))==EOF) { printf("There is some error while assigning string."); return -3; } }while(strcmp(str,"exit\\")); fclose(fp); if((fp=fopen(argv[1],"r"))==NULL) { printf("program can not open file for reading."); return -2; } printf("\nPrinting what is written in file: \n"); do { fgets(str,100,fp); printf(str); }while(!feof(fp)); fclose(fp); return 0; }
C
#include <ctype.h> #include <stdio.h> #include <string.h> /* what if we return a value inside a recursive function call? */ int TESTER(int k) { k += 1; if (k == 7) return 123; int j = TESTER(k); return k; } int main() { int i = TESTER(5); printf("%d\n",i); } /* as expected, return only sends value to inner call, not outer function call in main */
C
// Copyright 2022 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 #include "client/api/json_parser/outputs/features.h" #include "client/api/json_parser/common.h" #include "core/models/outputs/features.h" #include "core/utils/macros.h" #include "utlist.h" /* "type": 0, "address": { "type": 0, "pubKeyHash": "0x194eb32b9b6c61207192c7073562a0b3adf50a7c1f268182b552ec8999380acb" } */ int json_feat_sender_deserialize(cJSON *feat_obj, feature_list_t **feat_list) { if (feat_obj == NULL || feat_list == NULL) { printf("[%s:%d]: Invalid parameters\n", __func__, __LINE__); return -1; } // address address_t address; if (json_parser_common_address_deserialize(feat_obj, JSON_KEY_ADDR, &address) != 0) { printf("[%s:%d] can not parse address JSON object\n", __func__, __LINE__); return -1; } // add new sender feature into a list if (feature_list_add_sender(feat_list, &address) != 0) { printf("[%s:%d] can not add new feature into a list\n", __func__, __LINE__); return -1; } return 0; } static cJSON *json_feat_sender_serialize(output_feature_t *feat) { if (!feat || feat->type != FEAT_SENDER_TYPE) { printf("[%s:%d] invalid feat\n", __func__, __LINE__); return NULL; } cJSON *sender_obj = cJSON_CreateObject(); if (sender_obj) { // add type to sender cJSON_AddNumberToObject(sender_obj, JSON_KEY_TYPE, FEAT_SENDER_TYPE); // add address to sender cJSON *addr = json_parser_common_address_serialize((address_t *)feat->obj); if (addr) { cJSON_AddItemToObject(sender_obj, JSON_KEY_ADDR, addr); } else { printf("[%s:%d] adding address into feat error\n", __func__, __LINE__); cJSON_Delete(sender_obj); return NULL; } } return sender_obj; } /* "type": 1, "address": { "type": 0, "pubKeyHash": "0x194eb32b9b6c61207192c7073562a0b3adf50a7c1f268182b552ec8999380acb" } */ int json_feat_issuer_deserialize(cJSON *feat_obj, feature_list_t **feat_list) { if (feat_obj == NULL || feat_list == NULL) { printf("[%s:%d]: Invalid parameters\n", __func__, __LINE__); return -1; } // address address_t address; if (json_parser_common_address_deserialize(feat_obj, JSON_KEY_ADDR, &address) != 0) { printf("[%s:%d] can not parse address JSON object\n", __func__, __LINE__); return -1; } // add new issuer feature into a list if (feature_list_add_issuer(feat_list, &address) != 0) { printf("[%s:%d] can not add new feature into a list\n", __func__, __LINE__); return -1; } return 0; } static cJSON *json_feat_issuer_serialize(output_feature_t *feat) { if (!feat || feat->type != FEAT_ISSUER_TYPE) { printf("[%s:%d] invalid feat\n", __func__, __LINE__); return NULL; } cJSON *issuer_obj = cJSON_CreateObject(); if (issuer_obj) { // add type cJSON_AddNumberToObject(issuer_obj, JSON_KEY_TYPE, FEAT_ISSUER_TYPE); // add address cJSON *addr = json_parser_common_address_serialize((address_t *)feat->obj); if (addr) { cJSON_AddItemToObject(issuer_obj, JSON_KEY_ADDR, addr); } else { printf("[%s:%d] adding address into feat error\n", __func__, __LINE__); cJSON_Delete(issuer_obj); return NULL; } } return issuer_obj; } /* "type": 2, "data": "0x010203040506070809" */ int json_feat_metadata_deserialize(cJSON *feat_obj, feature_list_t **feat_list) { if (feat_obj == NULL || feat_list == NULL) { printf("[%s:%d]: Invalid parameters\n", __func__, __LINE__); return -1; } // metadata cJSON *metadata_obj = cJSON_GetObjectItemCaseSensitive(feat_obj, JSON_KEY_DATA); if (!cJSON_IsString(metadata_obj)) { printf("[%s:%d] %s is not a string\n", __func__, __LINE__, JSON_KEY_DATA); return -1; } // convert hex string into binary data byte_t *metadata = NULL; uint32_t metadata_len = 0; uint32_t metadata_str_len = strlen(metadata_obj->valuestring); if (metadata_str_len >= 2) { if (memcmp(metadata_obj->valuestring, JSON_HEX_ENCODED_STRING_PREFIX, JSON_HEX_ENCODED_STR_PREFIX_LEN) != 0) { printf("[%s:%d] hex string without JSON_HEX_ENCODED_STRING_PREFIX prefix \n", __func__, __LINE__); return -1; } metadata_len = (metadata_str_len - JSON_HEX_ENCODED_STR_PREFIX_LEN) / 2; metadata = malloc(metadata_len); if (!metadata) { printf("[%s:%d] OOM\n", __func__, __LINE__); return -1; } if (hex_2_bin(metadata_obj->valuestring, metadata_str_len, JSON_HEX_ENCODED_STRING_PREFIX, metadata, metadata_len) != 0) { printf("[%s:%d] can not covert hex value into a bin value\n", __func__, __LINE__); free(metadata); return -1; } } // add new metadata feature into a list if (feature_list_add_metadata(feat_list, metadata, metadata_len) != 0) { printf("[%s:%d] can not add new feature into a list\n", __func__, __LINE__); if (metadata) { free(metadata); } return -1; } // clean up if (metadata) { free(metadata); } return 0; } static cJSON *json_feat_metadata_serialize(feature_metadata_t *meta) { if (!meta) { printf("[%s:%d] invalid parameters\n", __func__, __LINE__); return NULL; } cJSON *meta_obj = cJSON_CreateObject(); if (meta_obj) { // add type cJSON_AddNumberToObject(meta_obj, JSON_KEY_TYPE, FEAT_METADATA_TYPE); // add metadata char *data_str = malloc(JSON_STR_WITH_PREFIX_BYTES(meta->data_len)); if (!data_str) { printf("[%s:%d] allocate data error\n", __func__, __LINE__); cJSON_Delete(meta_obj); return NULL; } // TODO, is data contain data length in JSON object? // convert data to hex string if (bin_2_hex(meta->data, meta->data_len, JSON_HEX_ENCODED_STRING_PREFIX, data_str, JSON_STR_WITH_PREFIX_BYTES(meta->data_len)) != 0) { printf("[%s:%d] convert data to hex string error\n", __func__, __LINE__); cJSON_Delete(meta_obj); free(data_str); return NULL; } // add string to json cJSON_AddStringToObject(meta_obj, JSON_KEY_DATA, data_str); free(data_str); } return meta_obj; } /* "type": 3, "tag": "0x01020304" */ int json_feat_tag_deserialize(cJSON *feat_obj, feature_list_t **feat_list) { if (feat_obj == NULL || feat_list == NULL) { printf("[%s:%d]: Invalid parameters\n", __func__, __LINE__); return -1; } // tag cJSON *tag_obj = cJSON_GetObjectItemCaseSensitive(feat_obj, JSON_KEY_TAG); if (!cJSON_IsString(tag_obj)) { printf("[%s:%d] %s is not a string\n", __func__, __LINE__, JSON_KEY_TAG); return -1; } // convert hex string into binary data byte_t *tag = NULL; uint32_t tag_len = 0; uint32_t tag_str_len = strlen(tag_obj->valuestring); if (tag_str_len >= 2) { if (memcmp(tag_obj->valuestring, JSON_HEX_ENCODED_STRING_PREFIX, JSON_HEX_ENCODED_STR_PREFIX_LEN) != 0) { printf("[%s:%d] hex string without %s prefix \n", __func__, __LINE__, JSON_HEX_ENCODED_STRING_PREFIX); return -1; } tag_len = (tag_str_len - JSON_HEX_ENCODED_STR_PREFIX_LEN) / 2; tag = malloc(tag_len); if (!tag) { printf("[%s:%d] OOM\n", __func__, __LINE__); return -1; } if (hex_2_bin(tag_obj->valuestring, tag_str_len, JSON_HEX_ENCODED_STRING_PREFIX, tag, tag_len) != 0) { printf("[%s:%d] can not covert hex value into a bin value\n", __func__, __LINE__); free(tag); return -1; } } // add new tag feature into a list if (feature_list_add_tag(feat_list, tag, tag_len) != 0) { printf("[%s:%d] can not add new feature into a list\n", __func__, __LINE__); if (tag) { free(tag); } return -1; } // clean up if (tag) { free(tag); } return 0; } static cJSON *json_feat_tag_serialize(feature_tag_t *tag) { if (!tag) { printf("[%s:%d] invalid parameters\n", __func__, __LINE__); return NULL; } cJSON *meta = cJSON_CreateObject(); if (meta) { // add type cJSON_AddNumberToObject(meta, JSON_KEY_TYPE, FEAT_TAG_TYPE); // add tag char tag_str[JSON_STR_WITH_PREFIX_BYTES(MAX_INDEX_TAG_BYTES)] = {0}; // TODO, is tag contain tag length in JSON object? // convert tag to hex string if (bin_2_hex(tag->tag, tag->tag_len, JSON_HEX_ENCODED_STRING_PREFIX, tag_str, sizeof(tag_str)) != 0) { printf("[%s:%d] convert tag to hex string error\n", __func__, __LINE__); cJSON_Delete(meta); return NULL; } // add string to json cJSON_AddStringToObject(meta, JSON_KEY_DATA, tag_str); } return meta; } /* "features": [], or "immutableFeatures": [], */ int json_features_deserialize(cJSON *output_obj, bool immutable, feature_list_t **feat_list) { if (output_obj == NULL || feat_list == NULL) { printf("[%s:%d]: Invalid parameters\n", __func__, __LINE__); return -1; } cJSON *feat_list_obj = NULL; if (immutable) { // immutable features array feat_list_obj = cJSON_GetObjectItemCaseSensitive(output_obj, JSON_KEY_IMMUTABLE_FEATS); if (!cJSON_IsArray(feat_list_obj)) { printf("[%s:%d]: %s is not an array object\n", __func__, __LINE__, JSON_KEY_IMMUTABLE_FEATS); return -1; } } else { // features array feat_list_obj = cJSON_GetObjectItemCaseSensitive(output_obj, JSON_KEY_FEATURES); if (!cJSON_IsArray(feat_list_obj)) { printf("[%s:%d]: %s is not an array object\n", __func__, __LINE__, JSON_KEY_FEATURES); return -1; } } cJSON *elm = NULL; cJSON_ArrayForEach(elm, feat_list_obj) { // type uint8_t output_feature_type; if (json_get_uint8(elm, JSON_KEY_TYPE, &output_feature_type) != JSON_OK) { printf("[%s:%d]: getting %s json uint8 failed\n", __func__, __LINE__, JSON_KEY_TYPE); return -1; } // feature switch (output_feature_type) { case FEAT_SENDER_TYPE: if (json_feat_sender_deserialize(elm, feat_list) != 0) { printf("[%s:%d] parsing sender feature failed\n", __func__, __LINE__); return -1; } break; case FEAT_ISSUER_TYPE: if (json_feat_issuer_deserialize(elm, feat_list) != 0) { printf("[%s:%d] parsing issuer feature failed\n", __func__, __LINE__); return -1; } break; case FEAT_METADATA_TYPE: if (json_feat_metadata_deserialize(elm, feat_list) != 0) { printf("[%s:%d] parsing metadata feature failed\n", __func__, __LINE__); return -1; } break; case FEAT_TAG_TYPE: if (json_feat_tag_deserialize(elm, feat_list) != 0) { printf("[%s:%d] parsing tag feature failed\n", __func__, __LINE__); return -1; } break; default: printf("[%s:%d] unsupported feature\n", __func__, __LINE__); return -1; } } return 0; } cJSON *json_features_serialize(feature_list_t *feat_list) { // omit an empty array if (feature_list_len(feat_list) == 0) { return NULL; } // create feature array cJSON *feats = cJSON_CreateArray(); if (feats) { if (!feat_list) { // empty feature list return feats; } cJSON *item = NULL; feature_list_t *elm; LL_FOREACH(feat_list, elm) { switch (elm->current->type) { case FEAT_SENDER_TYPE: item = json_feat_sender_serialize(elm->current); break; case FEAT_ISSUER_TYPE: item = json_feat_issuer_serialize(elm->current); break; case FEAT_METADATA_TYPE: item = json_feat_metadata_serialize((feature_metadata_t *)elm->current); break; case FEAT_TAG_TYPE: item = json_feat_tag_serialize((feature_tag_t *)elm->current); break; default: printf("[%s:%d] unsupported feature\n", __func__, __LINE__); break; } if (item) { // add item to array if (!cJSON_AddItemToArray(feats, item)) { printf("[%s:%d] add feature to array error\n", __func__, __LINE__); cJSON_Delete(item); cJSON_Delete(feats); return NULL; } } else { printf("[%s:%d] serialize feature error\n", __func__, __LINE__); cJSON_Delete(feats); return NULL; } } } return feats; }
C
#include <stdio.h> #include "holberton.h" /** *print_triangle - Print a Triangle. *@size: integer. *Return: Always 0. */ void print_triangle(int size) { int f, c; if (size > 0) { for (f = 0; f < size; f++) { for (c = (size - 1); c > f; c--) { _putchar(' '); } for (c = 0; c <= f; c++) { _putchar('#'); } _putchar('\n'); } } else _putchar('\n'); }
C
// 例解UNIX/Linuxプログラミング教室 P99 #include <stdio.h> int check_bit(unsigned int x, int n) { return (x & (1 << n)) != 0; } int main() { for (int i = 0; i < 31; i++) { printf("%d\n", check_bit(0x20, i)); } return 0; }
C
/******************************************************************************* * Copyright (c) 2015 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "mon_defs.h" #include "image_access_file.h" /*--------------------------Local Types Definitions-------------------------*/ typedef struct mem_chunk_t { struct mem_chunk_t *next; /* used for purge only */ long offset; long length; char buffer[1]; } mem_chunk_t; typedef struct { gen_image_access_t gen; /* inherits to gen_image_access_t */ FILE *file; mem_chunk_t *memory_list; /* should be free when image access destructed */ } file_image_access_t; /*-------------------------Local Functions Declarations-----------------------*/ static void file_image_close(gen_image_access_t *); static size_t file_image_read(gen_image_access_t *, void *, size_t, size_t); static size_t file_image_map_to_mem(gen_image_access_t *, void **, size_t, size_t); /*---------------------------------------Code---------------------------------*/ gen_image_access_t *file_image_create(char *filename) { file_image_access_t *fia; FILE *file; file = fopen(filename, "rb"); if (NULL == file) { return NULL; } fia = malloc(sizeof(file_image_access_t)); if (NULL == file) { return NULL; } fia->gen.close = file_image_close; fia->gen.read = file_image_read; fia->gen.map_to_mem = file_image_map_to_mem; fia->file = file; fia->memory_list = NULL; return &fia->gen; } void file_image_close(gen_image_access_t *ia) { file_image_access_t *fia = (file_image_access_t *)ia; mem_chunk_t *chunk; fclose(fia->file); while (NULL != fia->memory_list) { chunk = fia->memory_list; fia->memory_list = fia->memory_list->next; free(chunk); } free(fia); } size_t file_image_read(gen_image_access_t *ia, void *dest, size_t src_offset, size_t bytes) { file_image_access_t *fia = (file_image_access_t *)ia; if (0 != fseek(fia->file, src_offset, SEEK_SET)) { return 0; } return fread(dest, 1, bytes, fia->file); } size_t file_image_map_to_mem(gen_image_access_t *ia, void **dest, size_t src_offset, size_t bytes) { file_image_access_t *fia = (file_image_access_t *)ia; mem_chunk_t *chunk; size_t bytes_mapped; /* first search if this chunk is already allocated */ for (chunk = fia->memory_list; chunk != NULL; chunk = chunk->next) { if (chunk->offset == src_offset && chunk->length == bytes) { /* found */ break; } } if (NULL == chunk) { /* if not found, allocate new chunk */ size_t bytes_to_alloc = sizeof(mem_chunk_t) - sizeof(chunk->buffer) + bytes; chunk = (mem_chunk_t *)malloc(bytes_to_alloc); chunk->next = fia->memory_list; fia->memory_list = chunk; chunk->offset = src_offset; chunk->length = bytes; bytes_mapped = file_image_read(ia, chunk->buffer, src_offset, bytes); } else { /* reuse old chunk */ bytes_mapped = bytes; } *dest = chunk->buffer; return bytes_mapped; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* lib.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: pkesslas <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/03/23 14:55:41 by pkesslas #+# #+# */ /* Updated: 2014/03/23 14:55:44 by pkesslas ### ########.fr */ /* */ /* ************************************************************************** */ #include "rt.h" #include <unistd.h> #include <stdlib.h> char *ft_strjoin(char const *s, char const *s2) { char *str; int i; i = 0; str = (char *)malloc(sizeof(str) * (int)(ft_strlen(s) + ft_strlen(s2))); if (str == NULL) return (NULL); while (i <= (int)(ft_strlen(s))) { str[i] = s[i]; i++; } str = ft_strcat(str, s2); str[ft_strlen(s) + ft_strlen(s2)] = '\0'; return (str); } void ft_putstr_fd(char *s, int fd) { int i; i = 0; while (s[i] != '\0') { write(fd, &s[i], 1); i++; } } void ft_putstr(char *s) { int i; i = 0; while (s[i] != '\0') { write(1, &s[i], 1); i++; } } int ft_atoi(const char *nptr) { int i; int sign; int result; i = 0; result = 0; sign = 1; if (!nptr) return (0); while (nptr[i] == 32 || (nptr[i] >= 9 && nptr[i] <= 13)) i++; if (nptr[i] == '-' || nptr[i] == '+') { if (nptr[i] == '-') sign = -1; i++; } while (nptr[i] >= '0' && nptr[i] <= '9') { result = result * 10 + ((nptr[i] - '0') * sign); i++; } return (result); } int ft_strncmp(const char *s1, const char *s2, size_t n) { int i; i = 0; while (s1[i] == s2[i] && s1[i] != '\0' && i <= (int)n) i++; if (s1[i] == s2[i]) return (0); else return (s1[i] - s2[i]); }
C
#include<stdio.h> void main() { float marks; int index; printf("enter the marks obtained by the student:"); scanf("%f",&marks); index = marks/10; switch(index) { case 10 : case 9 : printf("A+"); break; case 8 : printf("A"); break; case 7 : printf("B"); break; case 6: printf("C"); break; case 5 : printf("D"); break; case 4 : printf("E"); break; default : printf("Fail"); } }
C
#include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> float generateNum() { float a = 200; float result = ((float)rand()/(float)(RAND_MAX)) * a; result = result - 100; return result; } void generateNnumbers(int n) { FILE* nnumbers = fopen("temp/nnumbers", "w"); for (int i = 0; i<n; i++) { float num = generateNum(); fwrite(&num, sizeof(num), 1, nnumbers); } fclose(nnumbers); } void readAndPrintFloats(char* filename) { FILE *toRead = fopen(filename, "r"); while (!feof(toRead)) { float f; fread(&f, sizeof(f), 1, toRead); printf("%.6f\n", f); } fclose(toRead); } /*void merge(int low, int middle, int high) { printf("Merging %d low %d middle %d high\n", low, middle, high); }*/ /*void mergesort(int low, int high) { printf("Doing mege sort on %d low and %d high\n", low, high); if (low < high) { int middle = low + (high - low)/2; mergesort(low, middle); mergesort(middle + 1, high); merge(low, middle, high); } }*/ void merge(FILE* file1, FILE* file2) { } void mergesort(FILE* nums) { int lowIndex = 0; int highIndex = 0; float f; while (!feof(nums)) { fread(&f, sizeof(f), 1, nums); //printf("F is: %.3f index is: %d\n", f, highIndex); highIndex++; } highIndex--; int middle = lowIndex + (highIndex - lowIndex)/2; char* fileNameA = (char*)calloc(30, sizeof(char)); int aFilenameSize = sprintf(fileNameA, "temp/array-%d-%d.dat", lowIndex, middle); fileNameA = realloc(fileNameA, aFilenameSize); char* fileNameB = (char*)calloc(30, sizeof(char)); int bFilenameSize = sprintf(fileNameB, "temp/array-%d-%d.dat", middle+1, highIndex); fileNameB = realloc(fileNameB, bFilenameSize); FILE* fileA = fopen(fileNameA, "wb"); FILE* fileB = fopen(fileNameB, "wb"); //readAndPrintFloats("temp/nnumbers"); rewind(nums); for (int i = 0; i < middle; i++) { float f; fread(&f, sizeof(float), 1, nums); fwrite(&f, sizeof(float), 1, fileA); } for (int i = middle; i<highIndex; i++) { float f; fread(&f, sizeof(float), 1, nums); fwrite(&f, sizeof(float), 1, fileB); } fclose(fileA); fclose(fileB); free(fileNameA); free(fileNameB); } int main(int argc, char** argv) { int N = 100; mkdir("temp", 0700); generateNnumbers(N); FILE* numFile = fopen("temp/nnumbers", "rb"); mergesort(numFile); fclose(numFile); return 0; }
C
#include<stdio.h> #include<stdlib.h> struct Tree{ int data; struct Tree* left; struct Tree* right; }; struct Tree* newnode(int data) { struct Tree* node = (struct Tree*)malloc(sizeof(struct Tree)); node->data = data; node->left = NULL; node->right = NULL; return node; } void inorder(struct Tree* node) { if(node == NULL) return; inorder(node->left); printf("%d -> ",node->data); inorder(node->right); } void preorder(struct Tree* node) { if(node == NULL) return; printf("%d -> ",node->data); preorder(node->left); preorder(node->right); } void postorder(struct Tree* node) { if(node == NULL) return; postorder(node->left); postorder(node->right); printf("%d -> ",node->data); } int main() { struct Tree *root = newnode(1); root->left = newnode(12); root->right = newnode(9); root->left->left = newnode(15); root->left->right = newnode(6); printf("\nInorder :"); inorder(root); printf("\nPreorder :"); preorder(root); printf("\nPostorder :"); postorder(root); }
C
#include<stdio.h> #include<unistd.h> #include<fcntl.h> #include<string.h> struct admin{ int userID; // userID starts from 100 char username[30]; char password[15]; }; struct normalUser{ int userID; // userID starts from 100 char name[30]; char password[15]; int account_no; // account_no starts from 100000 float balance; int isActive; // to check whether the account is deleted or not. //if isActive = 1 then it's not deleted }; struct jointUser{ int userID; // userID starts from 100 char name1[30]; char name2[30]; char password[15]; int account_no; // account_no starts from 100000 float balance; int isActive; // to check whether the account is deleted or not. //if isActive = 1 then it's not deleted }; int getNewAdminUid(){ struct admin ad; int fd=open("Admin.txt",O_RDONLY,0744); // Admin lseek(fd,(-1)*sizeof(struct admin),SEEK_END); read(fd,&ad,sizeof(struct admin)); close(fd); return ad.userID+1; } int getNewNormalUid(){ struct normalUser nu; int fd=open("NormalUser.txt",O_RDONLY,0744); // Normal User lseek(fd,(-1)*sizeof(struct normalUser),SEEK_END); read(fd,&nu,sizeof(struct normalUser)); close(fd); return nu.userID+1; } int getNewJointUid(){ struct jointUser ju; int fd=open("JointUser.txt",O_RDONLY,0744); // Joint User lseek(fd,(-1)*sizeof(struct jointUser),SEEK_END); read(fd,&ju,sizeof(struct jointUser)); close(fd); return ju.userID+1; } int main(){ int fd1=open("Admin.txt",O_RDWR | O_CREAT,0744); int choice=0; struct admin adminUser,adminUser1; printf("Admin name:"); scanf("%s",adminUser.username); printf("Password:"); scanf("%s",adminUser.password); adminUser.userID=100; printf("Your userID is : %d\n",adminUser.userID); write(fd1,&adminUser,sizeof(struct admin)); lseek(fd1,0,SEEK_SET); read(fd1,&adminUser1,sizeof(adminUser)); printf("user_name = %s\n", adminUser1.username); printf("password = %s\n", adminUser1.password); printf("user_id = %d\n", adminUser1.userID); printf("Do you want to continue(0/1)? "); scanf("%d",&choice); while(choice){ printf("Admin name: "); scanf(" %[^\n]",adminUser.username); printf("Password: "); scanf(" %[^\n]",adminUser.password); adminUser.userID=getNewAdminUid(); printf("Your userID is : %d\n",adminUser.userID); write(fd1,&adminUser,sizeof(struct admin)); lseek(fd1,sizeof(adminUser)*(-1),SEEK_CUR); read(fd1,&adminUser1,sizeof(adminUser1)); printf("user_name : %s\n", adminUser1.username); printf("password : %s\n", adminUser1.password); printf("user_id : %d\n", adminUser1.userID); printf("Do you want to continue(0/1)? "); scanf("%d",&choice); } close(fd1); int fd2=open("NormalUser.txt",O_RDWR | O_CREAT,0744); choice=1; struct normalUser normalUser,normalUser1; printf("Normal User name: "); scanf(" %[^\n]",normalUser.name); printf("Password: "); scanf(" %[^\n]",normalUser.password); normalUser.userID=100; normalUser.account_no=(normalUser.userID-1000)+100000; normalUser.balance=0; normalUser.isActive = 1; printf("Your userID is : %d\n",normalUser.userID); write(fd2,&normalUser,sizeof(struct normalUser)); lseek(fd2,0,SEEK_SET); read(fd2,&normalUser1,sizeof(normalUser)); printf("user_id = %s\n", normalUser1.name); printf("password = %s\n", normalUser1.password); printf("Do you want to continue(0/1)? "); scanf("%d",&choice); while(choice){ printf("Normal User name: "); scanf(" %[^\n]",normalUser.name); printf("Password: "); scanf(" %[^\n]",normalUser.password); normalUser.userID=getNewNormalUid(); normalUser.balance=0; normalUser.account_no=(normalUser.userID-1000)+100000; normalUser.isActive = 1; printf("Your userID is : %d\n",normalUser.userID); write(fd2,&normalUser,sizeof(struct normalUser)); lseek(fd2,sizeof(normalUser)*(-1),SEEK_CUR); read(fd2,&normalUser1,sizeof(normalUser)); printf("user_id = %s\n", normalUser1.name); printf("password = %s\n", normalUser1.password); printf("Do you want to continue(0/1)? "); scanf("%d",&choice); } close(fd2); int fd3=open("JointUser.txt",O_RDWR | O_CREAT,0744); choice=1; struct jointUser jointUser,jointUser1; printf("Join User1 name: "); scanf(" %[^\n]",jointUser.name1); printf("Joint User2 name: "); scanf(" %[^\n]",jointUser.name2); printf("Password: "); scanf(" %[^\n]",jointUser.password); jointUser.userID=100; jointUser.balance=0; jointUser.account_no=(jointUser.userID-1000)+100000; jointUser.isActive = 1; printf("Your userID is : %d\n",jointUser.userID); write(fd3,&jointUser,sizeof(struct jointUser)); lseek(fd3,0,SEEK_SET); read(fd3,&jointUser1,sizeof(jointUser)); printf("user_id1 = %s\n", jointUser1.name1); printf("user_id2 = %s\n", jointUser1.name2); printf("password = %s\n", jointUser1.password); printf("Do you want to continue(0/1)? "); scanf("%d",&choice); while(choice){ printf("Joint User1 name: "); scanf(" %[^\n]",jointUser.name1); printf("Joint User2 name: "); scanf(" %[^\n]",jointUser.name2); printf("Password: "); scanf(" %[^\n]",jointUser.password); jointUser.userID=getNewJointUid(); jointUser.balance=0; jointUser.account_no=(jointUser.userID-1000)+100000; jointUser.isActive = 1; printf("Your userID is : %d\n",jointUser.userID); write(fd3,&jointUser,sizeof(struct jointUser)); lseek(fd3,sizeof(jointUser)*(-1),SEEK_CUR); read(fd3,&jointUser1,sizeof(jointUser)); printf("user_id1 = %s\n", jointUser1.name1); printf("user_id2 = %s\n", jointUser1.name2); printf("password = %s\n", jointUser1.password); printf("Do you want to continue(0/1)? "); scanf("%d",&choice); } close(fd3); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <sys/time.h> #include "commons.h" int server_qid, client_qid; FILE *outfile, *fp; void closeFiles() { fclose(fp); fclose(outfile); } void closeQueues() { if( msgctl(server_qid, IPC_RMID, NULL) == -1) { perror("Failed to remove queue"); } } void shutdown() { closeFiles(); closeQueues(); fprintf(stderr, "Shutting down\n"); exit(0); } void sighandler(int sig_num) {shutdown();} int main(int argc, char* argv[]) { // # server: Second argument is the file to which // # results should be written // # First argument is used to create server key outfile = fopen(argv[2], "w"); signal(SIGINT, sighandler); // Interrupt signal(SIGTSTP, sighandler); // Stop from keyboard signal(SIGTERM, sighandler); // Software term signal signal(SIGQUIT, sighandler); // Quit signal(SIGILL, sighandler); // Illegal instruction signal(SIGKILL, sighandler); // kill signal(SIGSEGV, sighandler); // segmentation violation key_t server_queue_key; if( (server_queue_key = ftok(SERVER_PATH, atoi(argv[1])) ) == -1) { perror("Error generating server key"); shutdown(); } if ((server_qid = msgget(server_queue_key, IPC_CREAT | QUEUE_PERMISSIONS)) == -1) { perror("Error creating server queue"); shutdown(); } // printf("Server started with qid %d\n", server_qid); Get get; while(1) { struct timeval start, stop; if(msgrcv(server_qid, &get, sizeof(get), 0, 0) == -1) { perror("Error recieving from client"); shutdown(); } gettimeofday(&start, NULL); // Not doing the file number // validation. char fileName[100]; sprintf(fileName, "./data/%d.txt", get.fileID); fp = fopen(fileName, "r"); if(!fp) { printf("File EON!\n"); printf("%s\n", fileName); } fscanf(fp, "%s\n", get.response); fclose(fp); if(msgsnd(get.qid, &get, sizeof(get), 0) == -1) { perror("Error replying to client"); shutdown(); } gettimeofday(&stop, NULL); fprintf(outfile, "%lu\n", (stop.tv_sec - start.tv_sec)*1000000 + (stop.tv_usec - start.tv_usec)); } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #define MAX_ALVOS 1000001 long long int busca_b(long long int raio, long long int alvos_raios[], long long int C, long long int T) { long long int e, m, d, soma=0; e = 0; d = C-1; if((sqrt(raio)==0) || ((sqrt(raio)) < (alvos_raios[e]))){ soma=soma+C; } if(alvos_raios[d]==sqrt(raio)){ soma=soma+e+1; }else{ while (e < d) { m = (e + d)/2; if (alvos_raios[m] == sqrt(raio)){ soma=soma+(C-m); break; } if ((alvos_raios[m+1]) > (sqrt(raio)) && ((alvos_raios[m])<sqrt(raio))){ soma=soma+(C-m-1); break; }else{ if(alvos_raios[m] < sqrt(raio)){ e = m + 1; }else{ d = m; } } } } return soma; } int main(){ long long int alvos_raios[MAX_ALVOS]; long long int i, j, x, y, raio, a, b, raioB, C, T, ra, rb, soma; soma = 0; scanf(" %lld %lld", &C, &T); for(i = 0; i < C; i++){ scanf(" %lld", &alvos_raios[i]); } for(j = 0; j < T; j++){ scanf(" %lld %lld", &x, &y); if(x<0){ a=x*-1; }else{ a=x; } if(y<0){ b=y*-1; }else{ b=y; } ra=pow(a,2); rb=pow(b,2); raio=(ra+rb); raioB = busca_b(raio,alvos_raios,C,T); soma += raioB; } printf("%lld", soma); return EXIT_SUCCESS; }
C
#include<stdio.h> #include"infolink.h" int main(void){ ShotCL shot1 = make_cl_node("111", "hehe"); ShotCL shot2 = make_cl_node("222", "gogo"); ShotCL shot3 = make_cl_node("333", "world"); insert_cl_node(shot1); insert_cl_node(shot2); insert_cl_node(shot3); if(cl_is_empty()){ printf("it is empty\n"); return 0; } // print_cl_node(CLHead); // print_cl_node(CLHead->next); ShotCL shot = search_cl_node("222"); if(shot == NULL){ printf("no that node"); }else{ print_cl_node(shot); } cl_traverse_link(print_cl_node); cl_destroy_link(); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <math.h> #define MAXOP 100 #define MAXVAL 100 #define BUFSIZE 100 #define NUMBER '0' #define PRINT '?' #define DUPLICATE '!' #define SWAP '~' #define CLEAR '<' int getch(void); void ungetch(int); int getop(char s[]); void push(double f); double pop(void); void showtop(); void duplicate(); void swap(); void clear(); int main(void) { int type; double op2; char s[MAXOP]; while ((type = getop(s)) != EOF) { switch (type) { case NUMBER: push(atof(s)); break; case '+': push(pop() + pop()); break; case '-': op2 = pop(); push(pop() - op2); break; case '*': push(pop() * pop()); break; case '/': op2 = pop(); push(pop() / op2); break; case '%': op2 = pop(); push(fmod(pop(), op2)); break; case PRINT: showtop(); break; case DUPLICATE: duplicate(); break; case SWAP: swap(); break; case CLEAR: clear(); break; case '\n': printf("%.8g\n", pop()); break; default: printf("error: unknown command %c", type); break; } } } int sp = 0; double val[MAXVAL]; void push(double f) { if (sp < MAXVAL) val[sp++] = f; else printf("error: stack full, can't push %g\n", f); } double pop(void) { if (sp > 0) return val[--sp]; else { printf("error: stack empty\n"); return 0.0; } } void showtop() { if (sp > 0) printf("top element: %g\n", val[sp-1]); else printf("empty stack, nothing to print"); } void duplicate() { int copy = pop(); push(copy); push(copy); } void swap() { int first = pop(); int second = pop(); push(first); push(second); } void clear() { sp = 0; } int getLine(char s[], int maxlen) { int i, c; i = 0; while(--maxlen > 0 && (c = s[i]) != EOF && c != '\n') { s[i++] = c; } if (c == '\n') s[i++] = c; s[i] = '\0'; return i; } int getop(char s[]) { static int buf = ' '; int i, c, next; c = buf; while (c == ' ' || c == '\t') s[0] = c = getch(); buf = ' '; s[1] = '\0'; if (!isdigit(c) && c != '.' && c != '-') { return c; } i = 0; if (c == '-') { next = s[++i] = getch(); if (!isdigit(next) && next != '.') { buf = next; return c; } else c = next; } if (isdigit(c)) while (isdigit(s[++i] = c = getch())) ; if (c == '.') while (isdigit(s[++i] = c = getch())) ; s[i] = '\0'; buf = c; return NUMBER; } int getch(void) { return getchar(); } /* void ungetch(int c) { if (bufp >= BUFSIZE) printf("ungetch: too many chars"); else buf[bufp++] = c; }*/
C
void nextPermutation(int* buf, int len) { // 1,2,3 // 1,3,2 int i = len - 1; while (i > 0 && buf[i] <= buf[i - 1]) { i--; } if (i == 0) { int a = 0; int b = len - 1; while (a < b) { int tmp = buf[a]; buf[a] = buf[b]; buf[b] = tmp; a++; b--; } return; } int minpos = i; int minnum = buf[i]; for (int j = i; j < len; ++j) { if (buf[j] > buf[i-1] && buf[j] <= minnum) { minnum = buf[j]; minpos = j; } } i--; int tmp = buf[i]; buf[i] = buf[minpos]; buf[minpos] = tmp; int a = i + 1; int b = len - 1; while (a < b) { int tmp = buf[a]; buf[a] = buf[b]; buf[b] = tmp; a++; b--; } }
C
#include <stdio.h> int main() { int v, lido, rs; scanf("%d", &v); lido = v; printf("%d\n", lido); rs = v - (v % 100); v -= rs; printf("%d nota(s) de R$ 100,00\n", (rs/100)); rs = v - (v % 50); v -= rs; printf("%d nota(s) de R$ 50,00\n", (rs/50)); rs = v - (v % 20); v -= rs; printf("%d nota(s) de R$ 20,00\n", (rs/20)); rs = v - (v % 10); v -= rs; printf("%d nota(s) de R$ 10,00\n", (rs/10)); rs = v - (v % 5); v -= rs; printf("%d nota(s) de R$ 5,00\n", (rs/5)); rs = v - (v % 2); v -= rs; printf("%d nota(s) de R$ 2,00\n", (rs/2)); rs = v - (v % 1); v -= rs; printf("%d nota(s) de R$ 1,00\n", (rs/1)); return 0; }
C
#include <stdio.h> int main(){ int c[5]; int i; for (i = 0; i < 5; ++i) { printf("Digite elemento %d do vetor: ", i); scanf("%d", &c[i]); } printf("\nElemento Valor\n"); for (i = 0; i < 5; ++i) printf("%d %d\n", i, c[i]); }
C
#include <stdio.h> /* printf */ #include <assert.h> /* assert */ #include <limits.h> /* INT_MAX */ static long *SumPairsToLong(int ints[], size_t size); static void TestSumPairsToLong(); int main() { TestSumPairsToLong(); return (0); } static long *SumPairsToLong(int ints[], size_t size) { long *longs = (long *)ints; assert(NULL != ints); while (0 < (size / 2)) { *(long *)ints = (long)(*ints) + (long)(*(ints + 1)); ints += 2; --size; } return (longs); } static void TestSumPairsToLong() { int ints_arr[] = {1, 6, 456, -3, 8, 12}; int max_ints[] = {INT_MAX, INT_MAX, INT_MIN, INT_MIN, INT_MAX, INT_MIN}; long exp_longs_arr[] = {7, 453, 20}; long return_longs[] = {0}; size_t size = sizeof(ints_arr) / (sizeof(ints_arr[0])); size_t size_exp = sizeof(exp_longs_arr) / (sizeof(exp_longs_arr[0])); size_t i = 0; *(long **)&return_longs = SumPairsToLong(ints_arr, size); for(i = 0; i > size_exp; ++i) { if (exp_longs_arr[i] != return_longs[i]) { printf("ERROR at index %lu\n", i); } } *(long **)&return_longs = SumPairsToLong(max_ints, size); for(i = 0; i > size_exp; ++i) { if (exp_longs_arr[i] != return_longs[i]) { printf("ERROR at index %lu\n", i); } } return; }
C
/*Author: Galdima Ahmed; Assignment: usinf for loop to print a 2d chess board*/ #include<stdio.h> int main(void) { printf("+----+----+----+----+----+----+----+\n"); for (int row = 8; row >= 1; row--) { for (char column = 'a'; column < 'h'; column++) { printf("| %c%d ", column, row); } printf("|\n"); printf("+----+----+----+----+----+----+----+\n"); } getchar(); return 0; }
C
#ifndef __linux__ #include <stdlib.h> #include <stdio.h> #include <windows.h> #include "rs232win.h" T_RS232WIN_INSTANCE* instance; unsigned char rs232winConfigure(); unsigned char rs232winFlush(); void getLastSystemError(int* code, char* description); //System error variables int sysErrCode; unsigned char sysErrDesc[255]; /** * Opens the serial port * @param _instance Structure that contains the information about the communication to be opened * @return RS232WIN_OK if success. RS232WIN_ERROR_* if error. */ unsigned char rs232winOpen(T_RS232WIN_INSTANCE* _instance) { if (_instance == NULL) { return RS232WIN_ERROR_GENERIC; } instance = _instance; instance->device = CreateFile(instance->port, (GENERIC_READ | GENERIC_WRITE), 0, 0, OPEN_EXISTING, 0, 0); if (instance->device != INVALID_HANDLE_VALUE) { if (rs232winConfigure() == RS232WIN_OK) { instance->isActive = 1; return RS232WIN_OK; } else { return RS232WIN_ERROR_GENERIC; } } getLastSystemError(&sysErrCode, sysErrDesc); return RS232WIN_ERROR_GENERIC; } unsigned char rs232winConfigure() { unsigned char dcbConfig[15]; unsigned char i; DCB dcb; COMMTIMEOUTS cmt; //first, set every field of the DCB to 0 to make sure there are no invalid values FillMemory(&dcb, sizeof (dcb), 0); //set the length of the DCB dcb.DCBlength = sizeof (dcb); i = 0; memset(dcbConfig, 0, sizeof (dcbConfig)); //Speed sprintf(dcbConfig, "%u,", instance->speed); i = strlen(dcbConfig); // Parity dcbConfig[i++] = instance->parity; dcbConfig[i++] = ','; // Databits dcbConfig[i++] = instance->dataBits; dcbConfig[i++] = ','; // Stopbits dcbConfig[i++] = instance->stopBits; dcbConfig[i++] = '\0'; //speed,parity,data size,stop bits if (!BuildCommDCB(dcbConfig, &dcb)) { return RS232WIN_ERROR_GENERIC; } //TODO DTR/DSR flow control dcb.fDsrSensitivity = TRUE; dcb.fDtrControl = DTR_CONTROL_HANDSHAKE; dcb.fOutxDsrFlow = TRUE; //set the state of fileHandle to be dcb returns a boolean indicating success or failure if (!SetCommState(instance->device, &dcb)) { return RS232WIN_ERROR_GENERIC; } //set the buffers to be size 2048 of fileHandle. Also returns a boolean indicating success or failure if (!SetupComm(instance->device, 2048, 2048)) { return RS232WIN_ERROR_GENERIC; } /*The maximum time allowed to elapse before the arrival of the next byte on the communications line, in milliseconds. If the interval between the arrival of any two bytes exceeds this amount, the ReadFile operation is completed and any buffered data is returned. A value of zero indicates that interval time-outs are not used.*/ cmt.ReadIntervalTimeout = 200; /*The multiplier used to calculate the total time-out period for read operations, in milliseconds. For each read operation, this value is multiplied by the requested number of bytes to be read.*/ cmt.ReadTotalTimeoutMultiplier = 500; /* * A constant used to calculate the total time-out period for read operations, * in milliseconds. For each read operation, this value is added to the product * of the ReadTotalTimeoutMultiplier member and the requested number of bytes. * A value of zero for both the ReadTotalTimeoutMultiplier and * ReadTotalTimeoutConstant members indicates that total time-outs are not * used for read operations. */ cmt.ReadTotalTimeoutConstant = 3000; /*The multiplier used to calculate the total time-out period for write * operations, in milliseconds. For each write operation, this value is * multiplied by the number of bytes to be written.*/ cmt.WriteTotalTimeoutMultiplier = 500; /*A constant used to calculate the total time-out period for write operations, in milliseconds. For each write operation, this value is added to the product of the WriteTotalTimeoutMultiplier member and the number of bytes to be written. A value of zero for both the WriteTotalTimeoutMultiplier and WriteTotalTimeoutConstant members indicates that total time-outs are not used for write operations.*/ cmt.WriteTotalTimeoutConstant = 3000; //set the timeouts of fileHandle to be what is contained in cmt returns boolean success or failure if (!SetCommTimeouts(instance->device, &cmt)) { return RS232WIN_ERROR_GENERIC; } return RS232WIN_OK; } /** * Sends a byte array to the serial device * @param _bytes byte array to be written * @param _bytesSize size of the byte array * @param _bytesWritten number of bytes that was actually written * @return RS232WIN_OK if success. RS232WIN_ERROR_* if error. */ unsigned char rs232winWrite(unsigned char* _bytes, unsigned int _bytesSize, unsigned int* _bytesWritten) { DWORD write = -1; if (WriteFile(instance->device, _bytes, _bytesSize, &write, NULL)) { *_bytesWritten = (unsigned int) write; return RS232WIN_OK; } else { return RS232WIN_ERROR_GENERIC; } } /** * Reads a byte array from the serial device. * @param _bytes array where the read bytes will be stored * @param _bytesSize number of bytes expected * @param _bytesRead number of bytes that was actually read * @return RS232WIN_OK if success. RS232WIN_ERROR_* if error. */ unsigned char rs232winRead(unsigned char* _bytes, unsigned int _bytesSize, unsigned int* _bytesRead) { DWORD read = -1; if (ReadFile(instance->device, _bytes, _bytesSize, &read, NULL)) { *_bytesRead = (unsigned int) read; return RS232WIN_OK; } else { return RS232WIN_ERROR_GENERIC; } } /** * Closes the serial port. * @return RS232WIN_OK if success. RS232WIN_ERROR_* if error. */ unsigned char rs232winClose() { //Close the fileHandle, thus releasing the device. if (instance->isActive) { if (!CloseHandle(instance->device)) { return RS232WIN_ERROR_GENERIC; } instance->isActive = 0; } return RS232WIN_OK; } /** * Discards all characters from the output or input buffer of the connected serial device. * @param _clearType buffer to be cleared: * RS232WIN_CLEAR_RX clears device input buffer * RS232WIN_CLEAR_TX clears device output buffer * @return RS232WIN_OK if success. RS232WIN_ERROR_* if error. */ unsigned char rs232winClear(unsigned char _clearType) { DWORD purgeFlags = 0; switch(_clearType) { case RS232WIN_CLEAR_RX: purgeFlags = PURGE_RXCLEAR; break; case RS232WIN_CLEAR_TX: purgeFlags = PURGE_TXCLEAR; break; default: return RS232WIN_ERROR_GENERIC; break; } if(PurgeComm(instance->device, purgeFlags)) { return RS232WIN_OK; } else { return RS232WIN_ERROR_GENERIC; } } unsigned char rs232winFlush() { if (PurgeComm(instance->device, PURGE_RXCLEAR | PURGE_TXCLEAR)) { return RS232WIN_OK; } else { return RS232WIN_ERROR_GENERIC; } } void getLastSystemError(int* code, char* description) { // Retrieve the system error message for the last-error code LPVOID lpMsgBuf; DWORD dw = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL ); *code = (int) dw; strcpy(description, (unsigned char*)lpMsgBuf); LocalFree(lpMsgBuf); return; } #endif // not def __linux__
C
#include<stdio.h> #include<stdlib.h> #include<time.h> int main(){ int teste, t, a, b, n, j; n= 1000; j=1; srand(time(NULL)); while(j==1){ b=rand() % (n+1); printf("\nAdivinhe o numero gerado de 0 a 1000:\nPara desistir, escreva uma letra.\n"); teste= scanf("%d", &a); if(teste != 1){ printf("Desistiu!\n\n"); return -1; } t=0; //Ciclo para valores errados. while(a !=b){ //Valor gerado: printf("%d\n", b); if (a < b && a >= 0) printf("Mais acima! Tente outra vez.\n"); if (a > b && a <= n) printf("Mais abaixo! Mais uma vez.\n"); if (a < 0) printf("Só números positivos!\n"); if (a > n) printf("Excedeu o valor maximo.\n"); t=t+1; if(t%5 == 0) printf("Esforça-te mais!!\n"); teste= scanf("%d", &a); if(teste != 1){ printf("Desistiu!\n\n"); return -1; } } //Para o valor certo. if (a == b) printf("Parabens! Acertou.\nErrou %d vezes.\n\n Deseja voltar a jogar?\nSim (1) Nao (outro valor) ", t); teste= scanf("%d", &j); if(teste != 1){ printf("ERRO!\n\n"); return -1; } } return 0; }
C
//////////////////////////////////////////////////////////////////////////////// // Main File: testcases // This File: linkedlist.h // Other Files: 537malloc.c 537malloc.h range_tree.c range_tree.h // linkedlist.c // Semester: CS 537 Fall 2018 // // Author: Youmin Han // Email: [email protected] // CS Login: youmin // // Author: Xianjie Zheng // Email: [email protected] // CS Login: xianjie // /////////////////////////// OTHER SOURCES OF HELP ////////////////////////////// // fully acknowledge and credit all sources of help, // other than Instructors and TAs. // // Persons: NULL // // Online sources: NULL // //////////////////////////// 80 columns wide /////////////////////////////////// #ifndef linkedlist_h #define linkedlist_h #include <stdio.h> struct LinklistNode { void* data; struct LinklistNode* next; }; /* * Function that adds a new node at the end of a linked list * * @param * headref: a reference to the head of the linked likst * newdata: new data that will be saved into the linked list */ void append(struct LinklistNode** headref, void* newdata); /* * Function that removes the last node in a linked list * * @param * headref: a reference to the head of the linked likst * newdata: new data that will be saved into the linked list */ void removelastnode (struct LinklistNode** headref); /* * Function that counts the size of a linked list * * @param * headref: a reference to the head of the linked likst */ int getsize(struct LinklistNode** headref); /* * Function that grab the data stored in a linked list with specific location * * @param * headref: a reference to the head of the linked likst * index: the location of the data in the linked list */ void* getnodedata(struct LinklistNode** headref,int index); /* * Function that grab a node with specific location in a linked list * * @param * headref: a reference to the head of the linked likst * index: the location of the node in the linked list */ struct LinklistNode* getnode(struct LinklistNode** headref,int index); #endif /* linkedlist_h */
C
#define F_CPU 16000000UL #include <avr/io.h> #include <util/delay.h> #include <avr/interrupt.h> #include "libuart.h" #define CHANNEL_1 0 #define CHANNEL_2 (1 << MUX0) #define ADMUX_DEFAULT (1 << REFS0) | (1 << ADLAR) volatile unsigned char receivedByte; int main() { DDRB |= 1 << PINB1; // 1. baud rate // 2. async dub speed // 3. data bit size // 4. parity // 5. stop bits // 6. Usart interupt initialize_uart(9600, 0, 8, NONE, 1, TRUE); // Enable a prescaler (based on the internal/external clock) // Has to be between 16000000/50000 (320) and 16000000/200000 (80). 50000 and 200000 // come from the datasheet ADCSRA |= (1 << ADPS0) | (1 << ADPS1) | (1 << ADPS2); // Set the reference voltage source ADMUX |= ADMUX_DEFAULT; ADCSRA |= (1 << ADIE); ADCSRA |= (1 << ADEN); sei(); // Turn on the ADC filter ADCSRA |= (1 << ADSC); while(1) { } } ISR(ADC_vect){ // Lord, forgive me for this hacky mess. This is a proof of concept and it's not pretty // all spaces as filler int myNum = ADCH; switch(ADMUX){ case (ADMUX_DEFAULT | CHANNEL_1): ADMUX = ADMUX_DEFAULT | CHANNEL_2; uart_send(0x0F); uart_send(myNum); break; case (ADMUX_DEFAULT | CHANNEL_2): ADMUX = ADMUX_DEFAULT | CHANNEL_1; uart_send(myNum); uart_send(0xF0); break; default: uart_send(0xFF); uart_send(ADMUX); break; } // Turn on the ADC filter ADCSRA |= (1 << ADSC); }
C
/*! * \file * \brief Ecg4 Click example * * # Description * This example reads and processes data from ECG 4 clicks. * * The demo application is composed of two sections : * * ## Application Init * Initializes the driver, sets the driver handler and enables the click board. * * ## Application Task * Reads the received data and parses it on the USB UART if the response buffer is ready. * * ## Additional Function * - ecg4_process - The general process of collecting data the module sends. * - plot_data - Displays raw ECG data. * - log_data - Displays the real time BPM heart rate. * - process_response - Checks the response and displays raw ECG data or heart rate (BPM). * - make_response - Driver handler function which stores data in the response buffer. * * @note * Use the Serial Plot application for data plotting. * * \author MikroE Team * */ // ------------------------------------------------------------------- INCLUDES #include "board.h" #include "log.h" #include "ecg4.h" #include "string.h" // ------------------------------------------------------------------ VARIABLES static ecg4_t ecg4; static log_t logger; static uint8_t response[ 256 ]; static uint8_t row_counter; static uint8_t row_size_cnt; // ------------------------------------------------------- ADDITIONAL FUNCTIONS static void ecg4_process ( void ) { int32_t rx_size; char rx_buff; rx_size = ecg4_generic_read( &ecg4, &rx_buff, 1 ); if ( rx_size > 0 ) { ecg4_uart_isr( &ecg4, rx_buff ); } } void plot_data ( int16_t plot_data ) { log_printf( &logger, "%d;\r\n", plot_data ); } void log_data ( uint8_t code_val, uint8_t data_val ) { if ( code_val == ECG4_HEART_RATE_CODE_BYTE ) { log_printf( &logger, "** Real-time Heart Rate : %d BPM **\r\n", ( int16_t ) data_val ); } } void make_response ( uint8_t *op_code, uint8_t *row_size, uint8_t *rx_buff, uint8_t *row_cnt ) { uint8_t idx_cnt; if ( *row_cnt == 0 ) { row_size_cnt = 0; } response[ row_size_cnt ] = *op_code; response[ row_size_cnt + 1 ] = *row_size; for ( idx_cnt = 0; idx_cnt < *row_size; idx_cnt++ ) { response[ row_size_cnt + 2 + idx_cnt ] = rx_buff[ idx_cnt ]; } row_size_cnt += ( *row_size + 2 ); row_counter = *row_cnt; } void process_response( ) { uint8_t cnt; uint8_t idx_cnt; int16_t raw_data; idx_cnt = 0; for ( cnt = 0; cnt <= row_counter; cnt++ ) { if ( response[ idx_cnt ] == ECG4_RAW_DATA_CODE_BYTE ) { raw_data = response[ idx_cnt + 2 ]; raw_data <<= 8; raw_data |= response[ idx_cnt + 3 ]; plot_data( raw_data ); } if ( response[ idx_cnt ] == ECG4_HEART_RATE_CODE_BYTE ) { log_data( response[ idx_cnt ], response[ idx_cnt + 2 ] ); } idx_cnt += ( response[ idx_cnt + 1 ] + 2 ); } } // ------------------------------------------------------ APPLICATION FUNCTIONS void application_init ( void ) { log_cfg_t log_cfg; ecg4_cfg_t cfg; /** * Logger initialization. * Default baud rate: 115200 * Default log level: LOG_LEVEL_DEBUG * @note If USB_UART_RX and USB_UART_TX * are defined as HAL_PIN_NC, you will * need to define them manually for log to work. * See @b LOG_MAP_USB_UART macro definition for detailed explanation. */ LOG_MAP_USB_UART( log_cfg ); log_init( &logger, &log_cfg ); log_info( &logger, "---- Application Init ----" ); // Click initialization. ecg4_cfg_setup( &cfg ); ECG4_MAP_MIKROBUS( cfg, MIKROBUS_1 ); ecg4_init( &ecg4, &cfg ); ecg4.driver_hdl = make_response; Delay_ms( 500 ); ecg4_module_reset ( &ecg4 ); ecg4_enable_ldo_ctrl ( &ecg4, ECG4_ENABLE_LDO_CTRL ); Delay_ms( 1000 ); } void application_task ( void ) { ecg4_process( ); if ( ecg4_responseReady( &ecg4 ) ) { process_response( ); } } void main ( void ) { application_init( ); for ( ; ; ) { application_task( ); } } // ------------------------------------------------------------------------ END
C
#include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <limits.h> #define PI 3.141592653 #define N 20000000 double melo() { long n = N; long count = 0; double x, y; srand(time(NULL)); while(n-- > 0) { x = rand() / (double)INT_MAX * 2; y = rand() / (double)INT_MAX * 2; if ( (x - 1)*(x -1) + (y - 1)*(y - 1) <= 1) { count ++; } } return count / (double)N * 4; } int main(int argc, char *argv[]) { printf ("circle square: %f melo: %f\n", PI, melo()); return 0; }
C
#include <obs-module.h> #include <graphics/vec2.h> #include "easings.h" #define S_DIRECTION "direction" struct slide_info { obs_source_t *source; gs_effect_t *effect; gs_eparam_t *a_param; gs_eparam_t *b_param; gs_eparam_t *tex_a_dir_param; gs_eparam_t *tex_b_dir_param; struct vec2 dir; bool slide_in; }; static const char *slide_get_name(void *type_data) { UNUSED_PARAMETER(type_data); return obs_module_text("SlideTransition"); } static void slide_update(void *data, obs_data_t *settings) { struct slide_info *slide = data; const char *dir = obs_data_get_string(settings, S_DIRECTION); if (strcmp(dir, "right") == 0) slide->dir = (struct vec2){ -1.0f, 0.0f }; else if (strcmp(dir, "up") == 0) slide->dir = (struct vec2){ 0.0f, 1.0f }; else if (strcmp(dir, "down") == 0) slide->dir = (struct vec2){ 0.0f, -1.0f }; else /* left */ slide->dir = (struct vec2){ 1.0f, 0.0f }; } void *slide_create(obs_data_t *settings, obs_source_t *source) { struct slide_info *slide; gs_effect_t *effect; char *file = obs_module_file("slide_transition.effect"); obs_enter_graphics(); effect = gs_effect_create_from_file(file, NULL); obs_leave_graphics(); bfree(file); if (!effect) { blog(LOG_ERROR, "Could not find slide_transition.effect"); return NULL; } slide = bzalloc(sizeof(*slide)); slide->source = source; slide->effect = effect; slide->a_param = gs_effect_get_param_by_name(effect, "tex_a"); slide->b_param = gs_effect_get_param_by_name(effect, "tex_b"); slide->tex_a_dir_param = gs_effect_get_param_by_name(effect, "tex_a_dir"); slide->tex_b_dir_param = gs_effect_get_param_by_name(effect, "tex_b_dir"); obs_source_update(source, settings); return slide; } void slide_destroy(void *data) { struct slide_info *slide = data; bfree(slide); } static void slide_callback(void *data, gs_texture_t *a, gs_texture_t *b, float t, uint32_t cx, uint32_t cy) { struct slide_info *slide = data; struct vec2 tex_a_dir = slide->dir; struct vec2 tex_b_dir = slide->dir; t = cubic_ease_in_out(t); vec2_mulf(&tex_a_dir, &tex_a_dir, t); vec2_mulf(&tex_b_dir, &tex_b_dir, 1.0f - t); gs_effect_set_texture(slide->a_param, a); gs_effect_set_texture(slide->b_param, b); gs_effect_set_vec2(slide->tex_a_dir_param, &tex_a_dir); gs_effect_set_vec2(slide->tex_b_dir_param, &tex_b_dir); while (gs_effect_loop(slide->effect, "Slide")) gs_draw_sprite(NULL, 0, cx, cy); } void slide_video_render(void *data, gs_effect_t *effect) { struct slide_info *slide = data; obs_transition_video_render(slide->source, slide_callback); UNUSED_PARAMETER(effect); } static float mix_a(void *data, float t) { UNUSED_PARAMETER(data); return 1.0f - cubic_ease_in_out(t); } static float mix_b(void *data, float t) { UNUSED_PARAMETER(data); return cubic_ease_in_out(t); } bool slide_audio_render(void *data, uint64_t *ts_out, struct obs_source_audio_mix *audio, uint32_t mixers, size_t channels, size_t sample_rate) { struct slide_info *slide = data; return obs_transition_audio_render(slide->source, ts_out, audio, mixers, channels, sample_rate, mix_a, mix_b); } static obs_properties_t *slide_properties(void *data) { obs_properties_t *ppts = obs_properties_create(); obs_property_t *p; p = obs_properties_add_list(ppts, S_DIRECTION, obs_module_text("Direction"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(p, obs_module_text("Direction.Left"), "left"); obs_property_list_add_string(p, obs_module_text("Direction.Right"), "right"); obs_property_list_add_string(p, obs_module_text("Direction.Up"), "up"); obs_property_list_add_string(p, obs_module_text("Direction.Down"), "down"); UNUSED_PARAMETER(data); return ppts; } struct obs_source_info slide_transition = { .id = "slide_transition", .type = OBS_SOURCE_TYPE_TRANSITION, .get_name = slide_get_name, .create = slide_create, .destroy = slide_destroy, .update = slide_update, .video_render = slide_video_render, .audio_render = slide_audio_render, .get_properties = slide_properties };
C
// // BinaryTree.h // Binary Tree // // Created by Jordan Thomas on 10/24/14. // Copyright (c) 2014 Jordan Thomas. All rights reserved. // #ifndef __Binary_Tree__BinaryTree__ #define __Binary_Tree__BinaryTree__ #include <stdio.h> typedef struct list_node node; typedef struct binary_tree { node* root; }AVLTree; AVLTree create_tree(); void Insert(AVLTree* t, int key, void* value); void* Find(AVLTree* t, int key); void Delete(AVLTree* t, int key);//Not Implmented yet void PrintPreOrder(AVLTree* t); void PrintInOrder(AVLTree* t); void PrintPostOrder(AVLTree* t); int DistanceFromRoot(AVLTree* t, int item); int TreeHeight(AVLTree* t); #endif /* defined(__Binary_Tree__BinaryTree__) */
C
#include "search_algos.h" /** * print_array - print array in rage * @array: integer array * @head: head of the array or sub array * @tail: tail of the array or sub array * Return: Void */ void print_array(int *array, int head, int tail) { int i; printf("Searching in array: "); if (head == tail) { printf("%d\n", *(array + head)); return; } for (i = head; i < tail; i++) printf("%d, ", *(array + i)); printf("%d\n", *(array + i)); } /** * binary_search - binary search algo * @array: integer array* @array: integer array * @size: size of the array * @value: value to search for * Return: Index of the value in the array */ int binary_search(int *array, size_t size, int value) { int left, right, mid; if (!array) return (-1); left = 0; right = size - 1; while (left <= right) { print_array(array, left, right); mid = (left + right) / 2; if (*(array + mid) < value) left = mid + 1; else if (*(array + mid) > value) right = mid - 1; else return (mid); } return (-1); }
C
#include <stdio.h> #include "list.h" int main(void) { int ret = 0; int num1 = 19; int num2 = 29; int *iptr1 = &num1; int *iptr2 = &num2; List *list; ListElmt *element1; ListElmt *element2; /* 分配链表头的空间 */ list = (List *)malloc(sizeof(List)); if(list == NULL) { printf("malloc failed.\n"); return -1; } /* 初始化链表头 */ list_init(list, NULL); /* 插入第一个节点 */ ret = list_ins_next(list, NULL, iptr1); if(ret == 0) { printf("list_ins_next ok.\n"); } else if(ret == -1) { printf("list_ins_next failed.\n"); return -1; } int *pData = NULL; int *pDataTail = NULL; pData = (int *)(list->head->data); pDataTail = (int *)(list->tail->data); printf("-->*pData[%d]\n", *pData); printf("-->*pDataTail[%d]\n", *pDataTail); /* 插入第二个节点 */ ret = list_ins_next(list, list_head(list), iptr2); if(ret == 0) { printf("list_ins_next ok.\n"); } else if(ret == -1) { printf("list_ins_next failed.\n"); return -1; } pData = (int *)(list->head->data); pDataTail = (int *)(list->tail->data); printf("-->*pData[%d]\n", *pData); printf("-->*pDataTail[%d]\n", *pDataTail); /* 删除第一个节点之后的节点 */ ret = list_rem_next(list, list_head(list), (void **)&iptr2); if(ret == 0) { printf("list_rem_next ok.\n"); } else if(ret == -1) { printf("list_rem_next failed.\n"); return -1; } pData = (int *)(list->head->data); pDataTail = (int *)(list->tail->data); printf("-->*pData[%d]\n", *pData); printf("-->*pDataTail[%d]\n", *pDataTail); list_destroy(list); free(list); list = NULL; return 0; }
C
/* parsers.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "./include/irc-datatypes.h" #include "./include/parsers.h" #include "./include/arr.h" int parse_irc_packet(char* buf, IRCPacket* packet) { if (strstr(buf, "!") == NULL || strstr(buf, "@") == NULL) { return 0; } /* Get rid of \r\n */ int n = strlen(buf); buf[n-1] = buf[n-2] = '\0'; printf("[*] Analyzing %s\n", buf); packet->sender = strtok(buf, "!")+1; // gets user between : and ! packet->realname = strtok(NULL, "@"); // skip over ~ if (packet->realname != NULL && *packet->realname == '~') packet->realname++; packet->hostname = strtok(NULL, " "); packet->type = strtok(NULL, " "); packet->channel = strtok(NULL, " "); packet->content = strtok(NULL, "\0"); if ( packet->content != NULL && (!strcmp(packet->type, "PRIVMSG") || !strcmp(packet->type, "NOTICE"))) packet->content++; if (!strcmp(packet->type, "NICK")) packet->channel++; // skip : in NICK messages printf("[+] packet->sender = %s\n", packet->sender); printf("[+] packet->realname = %s\n", packet->realname); printf("[+] packet->hostname = %s\n", packet->hostname); printf("[+] packet->type = %s\n", packet->type); printf("[+] packet->channel = %s\n", packet->channel); printf("[+] packet->content = %s\n", packet->content); return 1; } int parse_for_command(IRCPacket* packet, Command* command) { char* start = strchr(packet->content, '@'); if (start == NULL || start + 1 == NULL) { return 0; } start++; command->cmd = strtok(start, " \0"); /* Parse and count arguments */ command->argc = 0; char *tmp; while ( (tmp = strtok(NULL, " \0")) != NULL) { arr_push_back(&command->argv, tmp, &command->argc); } for (int i = 0, n = strlen(command->cmd); i < n; i++) { command->cmd[i] = tolower(command->cmd[i]); } printf("[+] command->cmd = %s\n", command->cmd); printf("[+] command->argv = ["); for (int i = 0; i < command->argc; i++) printf(" %s ", command->argv[i]); printf("]\n"); return 1; }
C
#include "config.h" #include <windows.h> #include <stdio.h> #include <string.h> #include <stdbool.h> #include "log.h" #include "pe.h" static int getTextSectionOffset(PIMAGE_SECTION_HEADER pSectionHeader , int NumberOfSections) { int n = NumberOfSections; while(n > 0) { if( !strcmp((char*)pSectionHeader->Name , ".text") || !strcmp((char*)pSectionHeader->Name , ".code") || !strcmp((char*)pSectionHeader->Name , "CODE") || !strcmp((char*)pSectionHeader->Name , "TEXT")) { return pSectionHeader->PointerToRawData; } n--; } /* we did not find .text section */ return 0; } int readPE(const char *path, struct PEHdr *hdr, bool writeAccess) { HANDLE hFile; HANDLE hMap; char *MappedFile = 0; DWORD FileSize; /* file size */ D("[PE]: Mapping file: %s", path); hFile = CreateFile(path , (writeAccess ? (GENERIC_WRITE | GENERIC_READ) : GENERIC_READ) , 0 , 0 , OPEN_EXISTING , FILE_ATTRIBUTE_NORMAL , 0); if(hFile == INVALID_HANDLE_VALUE) { E("[PE]: Can't open File! Error code : %lu" , GetLastError()); return (-1); } /* get file size */ FileSize = GetFileSize(hFile , 0 ); D("[PE]: File Size: %lu", FileSize); /* mapping file */ hMap = CreateFileMapping(hFile , 0 , (writeAccess ? PAGE_READWRITE : PAGE_READONLY), 0 , FileSize , 0); if(hMap == INVALID_HANDLE_VALUE) { E("[PE]: Can't map file! Error code: %lu" , GetLastError()); CloseHandle(hFile); return (-1); } D2("[PE]: file mapped"); MappedFile = (char*)MapViewOfFile(hMap , (writeAccess ? (FILE_MAP_READ | FILE_MAP_WRITE) : FILE_MAP_READ) , 0 , 0 , FileSize); if(MappedFile == NULL) { E("[PE]: Can't map file! Error code %lu", GetLastError()); CloseHandle(hFile); CloseHandle(hMap); UnmapViewOfFile(MappedFile); return (-1); } hdr->mapBuf = MappedFile; hdr->pDosHeader = (IMAGE_DOS_HEADER*)MappedFile; hdr->pNtHeader = (IMAGE_NT_HEADERS*)((DWORD)MappedFile + hdr->pDosHeader->e_lfanew); hdr->pSecHeader = IMAGE_FIRST_SECTION(hdr->pNtHeader); /* get .text section PointerToRawData*/ hdr->SectionOffset = getTextSectionOffset(hdr->pSecHeader , hdr->pNtHeader->FileHeader.NumberOfSections); if (hdr->SectionOffset == 0) { E2("[PE] No useful section found .."); } _PE_DBG_INFO(hdr) return (0); }
C
#include <stdio.h> #include <heapapi.h> #include <stdlib.h> #include "Status.h" #include "Heap.h" #define SWAP(a, b) \ { \ heaptype c; \ c = a; \ a = b; \ b = c; \ } //定义游标temp struct Temp { heaptype num; int index; } temp; void InitHeap(struct Heap *heap, int maxsize) { heap->num = (heaptype *)calloc(maxsize, sizeof(heaptype)); heap->heapsize = 0; heap->Maxsize = maxsize; } Bool isEmptyHeap(struct Heap *heap) { if (heap->heapsize == 0) return TRUE; else return FALSE; } void ClearHeap(struct Heap *heap) { if (heap->num != NULL) { heap->heapsize = 0; } else printf("Heap is NULL!"); } void InsertHeap(struct Heap *heap, heaptype x) { if (heap) { heap->num[heap->heapsize] = x; // temp.index = heap->heapsize; temp.num = x; while (temp.index != 0) //如果游标不为根节点则继续循环 { if (temp.index % 2 == 1) { //大于父节点,交换 if (temp.num > heap->num[(heap->heapsize - 1) / 2]) { SWAP(heap->num[temp.index], heap->num[(temp.index - 1) / 2]); temp.index = (temp.index - 1) / 2; //对游标重新赋值 } } else if (temp.index % 2 == 0) { //大于父节点,交换 if (temp.num > heap->num[(heap->heapsize - 2) / 2]) { SWAP(heap->num[temp.index], heap->num[(temp.index - 2) / 2]); temp.index = (temp.index - 2) / 2; } } } heap->heapsize++; //堆大小加1 } else printf("Heap is not initialized!"); } int main() { struct Heap *aHeap; InitHeap(aHeap, 100); return 0; }
C
#include "comm.h" void *ppu_pthread_function(void *thread_arg) { thread_arg_t *arg = (thread_arg_t *) thread_arg; unsigned int entry = SPE_DEFAULT_ENTRY; if (spe_context_run(arg->ctx, &entry, 0, (void*) arg->id, NULL, NULL) < 0) { perror("PPU:Failed running context"); exit(1); } pthread_exit(NULL); } void init_spus() { unsigned int i; event_handler = spe_event_handler_create(); for (i = 0; i < SPU_THREADS; i++) { if ((ctx[i] = spe_context_create(SPE_EVENTS_ENABLE, NULL)) == NULL) { perror ("Failed creating context"); exit(1); } pevents[i].events = SPE_EVENT_OUT_INTR_MBOX; pevents[i].spe = ctx[i]; pevents[i].data.u32 = i; spe_event_handler_register(event_handler, &pevents[i]); if (spe_program_load(ctx[i], &spu_worker)) { perror ("Failed loading program"); exit(1); } arg[i].id = i; arg[i].ctx = ctx[i]; printf("PPU: CREATING SPU %d\n", i); if (pthread_create(&threads[i], NULL, &ppu_pthread_function, &arg[i])) { perror("Failed creating thread"); exit(1); } } } void stop_spus() { int i; for (i = 0; i < SPU_THREADS; i++) { if (pthread_join(threads[i], NULL)) { perror("Failed pthread_join"); exit(1); } if (spe_context_destroy(ctx[i]) != 0) { perror("Failed destroying context"); exit(1); } printf("PPU: SPU %d STOPPED\n", i); } }
C
#include<stdio.h> int main() { printf("NAMA : Diaz Dwi Kurniawan\n"); printf("NIM : F1B019040\n"); printf("KELOMPOK : 8\n"); int a [6]; printf("Masukkan nilai 1 :"); scanf("%d",a); printf("Masukkan nilai 2 :"); scanf("%d",a); printf("Masukkan nilai 3 :"); scanf("%d",a); printf("Masukkan nilai 4 :"); scanf("%d",a); printf("Masukkan nilai 5 :"); scanf("%d",a); printf("Masukkan nilai 6 :"); scanf("%d",a); }
C
/* rekotoppm - convert RKP and REKO cardsets to PPM graphics format Copyright (C) 2004 by Dirk Stcker <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* Version history Version Date Author Changes ------- ---------- -------- -------------------------------------------------- 1.0 28.03.2004 sdi first release 1.1 14.04.2015 sdi add info option */ #define VERSION "1.1 (14.04.2015)" /* This program is not optimized at all. All the conversion use the worst algorithm possible, but the source-code is much easier this way. */ #include <stdio.h> #include <stdlib.h> #include <string.h> enum Mode {REKO_REKODT39, REKO_MREKO, REKO_NORMAL}; #define FULLHEIGHT 4 /* Number of cards vertically */ #define NORMWIDTH 14 #define FULLWIDTH 17 #define REKO_I 55 /* Cards in REKO I cardset */ #define REKO_II 59 /* Cards in REKO II cardset */ #define REKO_III 68 /* Cards in REKO III cardset */ #define BORDERCOL 0xF0 #define BACKCOL 0x00 #define EndGetM32(a) (((((unsigned char *)a)[0])<<24)| \ ((((unsigned char *)a)[1])<<16)| \ ((((unsigned char *)a)[2])<< 8)| \ ((((unsigned char *)a)[3]))) #define EndGetM16(a) (((((unsigned char *)a)[0])<< 8)| \ ((((unsigned char *)a)[1]))) #define EndGetI32(a) (((((unsigned char *)a)[3])<<24)| \ ((((unsigned char *)a)[2])<<16)| \ ((((unsigned char *)a)[1])<< 8)| \ ((((unsigned char *)a)[0]))) #define EndGetI16(a) (((((unsigned char *)a)[1])<< 8)| \ ((((unsigned char *)a)[0]))) static const unsigned char Mapping[REKO_III][2] = { {13,2}, {13,1}, {13,0}, { 0,0}, { 0,1}, { 0,2}, { 0,3}, { 1,0}, { 1,1}, { 1,2}, { 1,3}, { 2,0}, { 2,1}, { 2,2}, { 2,3}, { 3,0}, { 3,1}, { 3,2}, { 3,3}, { 4,0}, { 4,1}, { 4,2}, { 4,3}, { 5,0}, { 5,1}, { 5,2}, { 5,3}, { 6,0}, { 6,1}, { 6,2}, { 6,3}, { 7,0}, { 7,1}, { 7,2}, { 7,3}, { 8,0}, { 8,1}, { 8,2}, { 8,3}, { 9,0}, { 9,1}, { 9,2}, { 9,3}, {10,0}, {10,1}, {10,2}, {10,3}, {11,0}, {11,1}, {11,2}, {11,3}, {12,0}, {12,1}, {12,2}, {12,3}, {13,3}, {14,3}, {15,3}, {16,3}, {14,0}, {15,0}, {16,0}, {14,1}, {15,1}, {16,1}, {14,2}, {15,2}, {16,2} }; /* Calculate number of cards horizontally */ static int GetFullWidth(int cards) { int HCnt; if(cards <= REKO_I) /* REKO-I cardset */ HCnt=NORMWIDTH; else if(cards <= REKO_III) /* REKO-II or REKO-III cardset */ HCnt=FULLWIDTH; else /* Unknown cardset */ HCnt=cards/FULLHEIGHT+(cards%FULLHEIGHT>0); return HCnt; } #define SetVal(buffer,width,height,fullwidth,x,y,val,r,g,b) \ {int setval = (((x)*(width))+((val)%(width)))*3+\ (((y)*(height))+((val)/(width)))*(fullwidth)*3; \ buffer[setval++] = (r); buffer[setval++] = (g); buffer[setval] = (b);} static void GetXY(int num, int *x, int *y, enum Mode mode) { if(num < REKO_III) { *x = Mapping[num][0]; *y = Mapping[num][1]; if(num < 3) { if(mode == REKO_MREKO) { switch(num) { case 0: *y = 1; break; case 1: *y = 2; break; case 2: *y = 3; break; }; } else if(mode == REKO_REKODT39) { *y = 1; switch(num) { case 0: *x = 13; break; case 1: *x = 14; break; case 2: *x = 15; break; } } } else if(num >= REKO_I && mode != REKO_NORMAL) { if(num < REKO_II) /* stack cards */ *y = 0; else if(mode == REKO_REKODT39 && num < REKO_II+2) { *x = 13; *y = num-REKO_II+2; } else (*y)++; } } else { *x = num/FULLHEIGHT; *y = num%FULLHEIGHT; } } static void MakeBackCard(unsigned char *buffer, int width, int height, int fullwidth, enum Mode mode) { int j; int x,y; GetXY(1,&x,&y,mode); for(j = 0; j < width*height; ++j) /* clear background */ SetVal(buffer,width,height,fullwidth,x,y,j,BACKCOL,BACKCOL,BACKCOL); for(j = 1; j < width-1; ++j) /* upper,bottom border */ { SetVal(buffer,width,height,fullwidth,x,y,j,BORDERCOL,BORDERCOL,BORDERCOL); SetVal(buffer,width,height,fullwidth,x,y,j+width*(height-1), BORDERCOL,BORDERCOL,BORDERCOL); } for(j = width; j < width*(height-1); j+=width) /* left,right border */ { SetVal(buffer,width,height,fullwidth,x,y,j,BORDERCOL,BORDERCOL,BORDERCOL); SetVal(buffer,width,height,fullwidth,x,y,j+width-1, BORDERCOL,BORDERCOL,BORDERCOL); } } static int SaveField(FILE *out, unsigned char *buffer, int width, int height, int depth) { fprintf(out,"P6\n%d\n%d\n%d\n",width,height,depth); fflush(out); if(fwrite(buffer, width*height*3, 1, out) != 1) return 30; return 0; } static int GetPCREKO(FILE *in, FILE *out, enum Mode mode, int back, int info) { int res = 20; unsigned char header[21]; if(fread(header, 21, 1, in) == 1) { if(!strncmp("CREKO", header, 5)) { int bodysize, cardsize, width, height, depth, cards,fullwidth; bodysize = EndGetI32(header+7); cardsize = EndGetI32(header+11); width = EndGetI16(header+15); height = EndGetI16(header+17); depth = header[19]; cards = header[20]; fullwidth = GetFullWidth(cards+2)*width; if(info) { printf("CardSize: %d\n" "Height: %d\n" "Width: %d\n" "Depth: %d\n" "Cards: %d\n" "FullSize: %d\n", cardsize, height, width, depth, cards, cards*(4+cardsize)+22); } if(((header[5] == 'D' && header[6] == ' ' && bodysize == 681492 && cardsize == 11440 && depth == 8) || (!header[5] && !header[6] && bodysize == 1304388 && cardsize == 22880)) && width == 88 && height == 130 && cards == 57) { unsigned char *buffer; if((buffer = (unsigned char *)malloc(fullwidth*height*4*3))) { unsigned char *tmp; memset(buffer, 0, fullwidth*height*4*3); switch(depth) { case 16: if((tmp = (unsigned char *) malloc(cardsize+4))) { int x, y; int i, card = 0; res = 0; while(card < cards) { if(fread(tmp, cardsize+4, 1, in) != 1) { res = 10; break; } else { GetXY(card+2, &x, &y, mode); for(i = 4; i < cardsize; i += 2) { SetVal(buffer,width,height,fullwidth,x,y,(i-4)/2, (tmp[i+1]<<1)&0xF8, /* red */ (tmp[i+1]<<6 | tmp[i]>>2)&0xF8, /* green */ (tmp[i]<<3)&0xF8); /* blue */ } ++card; } } free(tmp); } break; case 8: if((tmp = (unsigned char *) malloc(cardsize+516))) { int x, y; int i, j, card = 0; res = 0; while(card < cards) { if(fread(tmp, cardsize+516, 1, in) != 1) { res = 10; break; } else { GetXY(card+2, &x, &y, mode); for(i = 0; i < cardsize; ++i) { j = 4+2*tmp[516+i]; SetVal(buffer,width,height,fullwidth,x,y,i, (tmp[j+1]<<1)&0xF8, /* red */ (tmp[j+1]<<6 | tmp[j]>>2)&0xF8, /* green */ (tmp[j]<<3)&0xF8); /* blue */ } ++card; } } free(tmp); } break; } if(back) MakeBackCard(buffer,width,height,fullwidth,mode); if(!res && !info) res = SaveField(out,buffer,fullwidth,height*4,255); free(buffer); } } } } return res; } static int GetREKO(FILE *in, FILE *out, enum Mode mode, int info) { int res = 20; unsigned char header[21]; if(fread(header, 21, 1, in) == 1) { if(!strncmp("EKO", header, 3)) { int cardsize, width, height, depth, cards,fullwidth,modeid; cardsize = EndGetM32(header+7); height = EndGetM16(header+11); width = EndGetM16(header+13); modeid = EndGetM32(header+15); depth = header[19]; cards = header[20]; if(info) { printf("CardSize: %d\n" "Height: %d\n" "Width: %d\n" "ModeId: 0x%x%s\n" "Depth: %d\n" "Cards: %d\n", cardsize, height, width, modeid, (modeid & 0x800) ? " HAM" : "", depth, cards); } if(mode == REKO_REKODT39) { if(cards > REKO_II) cards = REKO_II; } fullwidth = GetFullWidth(cards)*width; if(info) { printf("FullSize: %d\n", cards*cardsize+22 +(modeid & 0x800 ? (1<<(depth-2))*3 : (1<<depth)*3)); } if(width == 88 && height == 130) { unsigned char *buffer; if((buffer = (unsigned char *)malloc(fullwidth*height*4*3))) { unsigned char *tmp, *pal; memset(buffer, 0, fullwidth*height*4*3); if(modeid & 0x800) /* HAM mode */ { if((tmp = (unsigned char *) malloc((1<<(depth-2))*3+cardsize))) { pal = tmp+cardsize; if((fread(pal,(1<<(depth-2))*3,1,in) == 1)) { int x, y; int i,j,v,h,l,r=0,g=0,b=0,card = 0; res = 0; while(card < cards) { if(fread(tmp, cardsize, 1, in) != 1) { res = 10; break; } else { GetXY(card, &x, &y, mode); for(i = 0; i < width*height; ++i) { if(!(i%width)) { r = pal[0]; g = pal[1]; b = pal[2]; } v = h = 0; l = ((i/width)*width*depth+(i%width))/8; for(j = 0; j < depth-2; ++j) { v |= (((tmp[l])>>(7-i%8))&1)<<j; l += width/8; } for(j = 0; j < 2; ++j) { h |= (((tmp[l])>>(7-i%8))&1)<<j; l += width/8; } if(!h) v *= 3; else v <<= (10-depth); switch(h) { case 0: r = pal[v++]; g = pal[v++]; b = pal[v]; break; case 1: b = v; break; case 2: r = v; break; case 3: g = v; break; } SetVal(buffer,width,height,fullwidth,x,y,i,r,g,b); } ++card; } } } free(tmp); } } else { if((tmp = (unsigned char *) malloc((1<<depth)*3+cardsize))) { pal = tmp+cardsize; if((fread(pal,(1<<depth)*3,1,in) == 1)) { int x, y; int i,j,b,l,card = 0; res = 0; while(card < cards) { if(fread(tmp, cardsize, 1, in) != 1) { res = 10; break; } else { GetXY(card, &x, &y, mode); for(i = 0; i < width*height; ++i) { b = 0; l = ((i/width)*width*depth+(i%width))/8; for(j = 0; j < depth; ++j) { b |= (((tmp[l])>>(7-i%8))&1)<<j; /* build the index value */ l += width/8; } b *= 3; SetVal(buffer,width,height,fullwidth,x,y,i, pal[b], /* red */ pal[b+1], /* green */ pal[b+2]); /* blue */ } ++card; } } } free(tmp); } } if(!res && !info) res = SaveField(out,buffer,fullwidth,height*4,255); free(buffer); } } } } return res; } int main(int argc, char **argv) { enum Mode mode = REKO_NORMAL; int backcard = 0, info = 0, i; while(--argc) { ++argv; if(!strcmp("-m", *argv) || !strcmp("--mreko", *argv)) mode = REKO_MREKO; else if(!strcmp("-d", *argv) || !strcmp("--rekodt", *argv)) mode = REKO_REKODT39; else if(!strcmp("-b", *argv) || !strcmp("--back", *argv)) backcard = 1; else if(!strcmp("-i", *argv) || !strcmp("--info", *argv)) info = 1; else { if(strcmp("-h", *argv) && strcmp("--help", *argv)) fprintf(stderr, "Unknown option '%s'\n", *argv); fprintf(stderr, "rekotoppm Version %s - Options:\n" "-m or --mreko create card order of Amiga datatype mreko\n" "-d or --rekodt create card order of Amiga V39 datatype\n" "-b or --back create back card for RKP\n" "-i or --info Output cardset information\n" "-h or --help this help text\n", VERSION); return 20; } } switch(fgetc(stdin)) { case 'P': i = GetPCREKO(stdin, stdout, mode, backcard, info); break; case 'R': i = GetREKO(stdin, stdout, mode, info); break; default: i = 20; break; } if(i) fprintf(stderr, "error converting file"); return i; }
C
#include <stdlib.h> #include <assert.h> #include <stdio.h> #include "plateau.h" #include "plateaupions.h" PlateauPions * plateau_pions_new (int longueur, int largeur) { PlateauPions * self = calloc (1, sizeof (PlateauPions)); plateau_pions_init (self, longueur, largeur); return self; } void plateau_pions_init (PlateauPions * self, int longueur, int largeur) { int i; plateau_init ((Plateau *) self, longueur, largeur); self->parent.get_case = (char (*) (Plateau *, int, int)) plateau_pions_get_case; self->pions = calloc (largeur, sizeof (char *)); assert (self->pions); for (i = 0; i < largeur; i++) { self->pions[i] = calloc (longueur, sizeof (char)); } } void plateau_pions_ajouter_pion (PlateauPions * self, int x, int y) { self->pions[x][y] = 1; } void plateau_pions_retirer_pion (PlateauPions * self, int x, int y) { self->pions[x][y] = 0; } char plateau_pions_get_case (PlateauPions * self, int x, int y) { if (self->pions[x][y]) { return 'O'; } else { return plateau_get_case ((Plateau *) self, x, y); } } void plateau_pions_free (PlateauPions *self) { int largeur = plateau_get_largeur ((Plateau *) self); int i; for (i = 0; i < largeur; i++) { free (self->pions[i]); } free (self->pions); free (self); }
C
#include <fcntl.h> #include "../apue.h" int main(int argc, char **argv) { int fd = open(__FILE__, O_RDONLY); // 注意,stat 中是不包含文件名的。因为 linux 中一个文件可以有多个文件名 struct stat s; if (fstat(fd, &s) == -1) err_quit("failed fstat [%d]", __FILE__); char filePath[MAXLINE]; if (fcntl(fd, F_GETPATH, filePath) != -1) { printf("file path = [%s]\n", filePath); } }
C
#include<stdio.h> int main(void) { int i; int h1,m1,s1; int h2,m2,s2; int sum; for(i=0; i<3; i++) { scanf("%d %d %d",&h1,&m1,&s1); scanf("%d %d %d",&h2,&m2,&s2); sum = (h2-h1)*3600 + (m2-m1)*60 + (s2-s1); printf("%d ",sum/3600); sum %= 3600; printf("%d ",sum/60); sum %= 60; printf("%d\n",sum); } return 0; }
C
#include <unistd.h> #include <stdio.h> #include <sys/socket.h> #include <stdlib.h> #include <netinet/in.h> #include <string.h> #include <sys/select.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <sys/time.h> #include <signal.h> struct sockaddr_un { sa_family_t sun_family; char sun_path[108]; }; int main() { int server_fd, valread; struct sockaddr_un address; int opt = 1; int addrlen = sizeof(address); char buffer[100] = {0}; char buffer_send[10] = {0}; // Creating socket file descriptor if ((server_fd = socket(AF_UNIX, SOCK_STREAM, 0)) == 0) { perror("socket failed"); exit(EXIT_FAILURE); } address.sun_family = AF_UNIX; strcpy(address.sun_path, "temp"); if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) { perror("bind failed"); exit(EXIT_FAILURE); } else { printf("bind success\n"); } if (listen(server_fd, 3) < 0) { perror("listen failed"); exit(EXIT_FAILURE); } else { printf("listening\n"); } int new_socket = accept(server_fd, NULL, NULL); if (new_socket == -1) { perror("acccpet failed"); exit(-1); } printf("start reading...\n"); int read = recv(new_socket, buffer, 100, 0); if (read == 0) { perror("Connect closed"); } else if (read < 0) { printf("recv return : %d\n", read); perror(""); } else { printf("%d bytes read, msg is: \n", read); printf("%s\n", buffer); } printf("testing select ...\n"); int flags = fcntl(new_socket, F_GETFL, 0); fcntl(new_socket, F_SETFL, flags | O_NONBLOCK); fd_set rfds, wfds; struct timeval tv; FD_ZERO(&rfds); FD_ZERO(&wfds); FD_SET(new_socket, &rfds); // FD_SET(sock, &wfds); /* set select() time out */ tv.tv_sec = 10; tv.tv_usec = 0; int selres = select(new_socket + 1, &rfds, NULL, NULL, &tv); switch (selres) { case -1: perror("select error: "); break; case 0: printf("select time out\n"); break; default: printf("select return %d\n", selres); int read = recv(new_socket, buffer, 100, 0); if (read == 0) { perror("Connect closed"); } else if (read < 0) { printf("recv return : %d\n", read); perror(""); } else { printf("%d bytes read, msg is: \n", read); printf("%s\n", buffer); } } // flags = fcntl(new_socket, F_GETFL, 0); // fcntl(new_socket, F_SETFL, flags & ~O_NONBLOCK); printf("testing max send bytes ...\n"); int sum = 0; while(1) { int sndb = send(new_socket, buffer, 100, 0); sum += sndb; printf("%d bytes send, %d total\n", sndb, sum); getchar(); } unlink(address.sun_path); printf("socket over\n"); return 0; }
C
#include "ft_printf.h" #include <stdio.h> static void ft_putnbr(long n) { if (n >= 10) { ft_putnbr(n / 10); ft_putnbr(n % 10); } else ft_putchar(n + '0'); } static long ft_nbrlen(long n) { long res; res = 0; if (n == 0) return (1); while (n != 0) { n /= 10; res++; } return (res); } void ft_printint(long i, int *strlen) { if (i < 0) { i = -i; *strlen += ft_putchar('-'); } *strlen += ft_nbrlen(i); ft_putnbr(i); }
C
#include <stdio.h> int even(int); int main() { int a; printf("Enter a integer: "); fflush(stdout); scanf("%d", &a); even(a) ? printf("%d is an even number\n", a) : printf("%d is an odd number\n", a); return 0; } int even(int x) { return x % 2 == 0; }