language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdbool.h> #include "game.h" #include "utils/game_utils.h" #include "utils/game_gtk_utils.h" #include "../app/app.h" #include "../connection/connection.h" #include "../modals/modals.h" static gchar *GAMEPLAY_PAGE_STRING = GAMEPLAY_PAGE; static GtkGrid *board; static GtkLabel *stateLabel, *wonLostCountLabel; static Element boardElements[BOARD_SIZE][BOARD_SIZE]; static PlayerType player; static PlayerType whoseFirstTurn = PLAYER_ONE; static PlayerType whoseTurn; static int elementsToWin; static int gamesWon, gamesLost; static bool check_for_game_end(); //Gtk callback functions static gboolean on_hover_enter(GtkWidget *widget); static gboolean on_hover_leave(GtkWidget *widget); static gboolean on_frame_click(GtkWidget *widget); static void play_again(); void game_init(GtkBuilder *builder) { gamesWon = 0; gamesLost = 0; game_clear_winner_sequence_array(); GtkButton *quitButton, *howToPlayButton, *playAgainButton; board = GTK_GRID(gtk_builder_get_object(builder, "gameplay_board")); quitButton = GTK_BUTTON(gtk_builder_get_object(builder, "gameplay_quit_button")); howToPlayButton = GTK_BUTTON(gtk_builder_get_object(builder, "gameplay_how_to_play_button")); playAgainButton = GTK_BUTTON(gtk_builder_get_object(builder, "gameplay-play-again-button")); stateLabel = GTK_LABEL(gtk_builder_get_object(builder, "gameplay_state_label")); wonLostCountLabel = GTK_LABEL(gtk_builder_get_object(builder, "gameplay-won-lost-count-label")); g_signal_connect(quitButton, "clicked", G_CALLBACK(app_quit), NULL); g_signal_connect(howToPlayButton, "clicked", G_CALLBACK(app_how_to_play_show), GAMEPLAY_PAGE_STRING); g_signal_connect(playAgainButton, "clicked", G_CALLBACK(play_again), NULL); for (int x = 0; x < BOARD_SIZE; x++) { for (int y = 0; y < BOARD_SIZE + 1; y++) { GtkEventBox *eventBox = GTK_EVENT_BOX(gtk_event_box_new()); GtkFrame *frame = GTK_FRAME(gtk_frame_new(NULL)); gtk_frame_set_shadow_type(frame, GTK_SHADOW_NONE); GtkLabel *elementLabel = GTK_LABEL(gtk_label_new("")); gtk_widget_set_halign(GTK_WIDGET(elementLabel), GTK_ALIGN_CENTER); gtk_widget_set_valign(GTK_WIDGET(elementLabel), GTK_ALIGN_CENTER); gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(elementLabel)); gtk_container_add(GTK_CONTAINER(eventBox), GTK_WIDGET(frame)); gtk_grid_attach(board, GTK_WIDGET(eventBox), x, y, 1, 1); if (y == 0) { app_add_css_class_to_widget(GTK_WIDGET(frame), CSS_GAMEPLAY_FRAME_FOR_PLACEHOLDER); } else { app_add_css_class_to_widget(GTK_WIDGET(frame), CSS_GAMEPLAY_FRAME); g_signal_connect(GTK_WIDGET(eventBox), "button-press-event", G_CALLBACK(on_frame_click), NULL); g_signal_connect(GTK_WIDGET(eventBox), "enter-notify-event", G_CALLBACK(on_hover_enter), NULL); g_signal_connect(GTK_WIDGET(eventBox), "leave-notify-event", G_CALLBACK(on_hover_leave), NULL); } } } } void game_start(int elementsInSequenceToWin, PlayerType pType) { whoseTurn = whoseFirstTurn; whoseFirstTurn = whoseFirstTurn == PLAYER_ONE ? PLAYER_TWO : PLAYER_ONE; player = pType; elementsToWin = elementsInSequenceToWin; game_set_state_label(stateLabel, whoseTurn, player); game_set_won_lost_count_label(wonLostCountLabel, gamesWon, gamesLost); game_set_winning_elements_background(board, game_winner_sequence, elementsToWin, true); game_clear_winner_sequence_array(); for (int x = 0; x < BOARD_SIZE; x++) { for (int y = 0; y < BOARD_SIZE; y++) { boardElements[x][y] = EMPTY; game_set_element_label(board, x, y, EMPTY, NOT_PLACEHOLDER); } } } void game_move_push(int column, bool wasColumnReplaced) { Element element = get_element(whoseTurn); game_push_element_to_column(boardElements, board, column, element); if (whoseTurn == player && !wasColumnReplaced) { connection_send_move(MOVE_PUSH_PREFIX, column); } if (!check_for_game_end()) { whoseTurn = (whoseTurn == PLAYER_ONE) ? PLAYER_TWO : PLAYER_ONE; game_set_state_label(stateLabel, whoseTurn, player); } } static bool check_for_game_end() { if (!game_are_any_moves_left(boardElements)) { g_debug("A tie!"); whoseTurn = PLAYER_NONE; modal_end_game(&player, PLAYER_NONE); return true; } PlayerType winner = game_check_winner(boardElements, elementsToWin); if (winner != PLAYER_NONE) { g_debug("Player %s wins!", winner == PLAYER_ONE ? "1" : "2"); game_set_winning_elements_background(board, game_winner_sequence, elementsToWin, false); if (winner == player) { gamesWon++; } else { gamesLost++; } whoseTurn = PLAYER_NONE; modal_end_game(&player, winner); return true; } return false; } void game_move_replace(int column) { //If there is only one element in this column if (boardElements[column][BOARD_SIZE - 2] == EMPTY) { game_move_push(column, false); return; } Element bottomElement = boardElements[column][BOARD_SIZE - 1]; for (int y = BOARD_SIZE - 1; y > 0; y--) { boardElements[column][y] = boardElements[column][y - 1]; game_set_element_label(board, column, y, boardElements[column][y], NOT_PLACEHOLDER); } game_push_element_to_column(boardElements, board, column, bottomElement); if (whoseTurn == player) { connection_send_move(MOVE_REPLACE_PREFIX, column); } game_move_push(column, true); } void game_opponent_concede() { gamesWon++; modal_play_again(&player); } static void play_again() { gamesLost++; connection_send_play_again(); if (player == PLAYER_ONE) { app_play_as_1(); } else { app_play_as_2(); } } static gboolean on_hover_enter(GtkWidget *widget) { int x, y; game_get_event_box_coordinates(board, widget, &x, &y); if (game_is_move_possible(boardElements, x) && whoseTurn == player) { Element elem = boardElements[x][y]; int firstEmptyY = game_get_first_empty_y_in_column(boardElements, x); if (elem == EMPTY || firstEmptyY == BOARD_SIZE - 2) { game_set_element_label(board, x, firstEmptyY, get_element(player), PLACEHOLDER_ADD); } else { Element bottomElem = boardElements[x][BOARD_SIZE - 1]; game_set_element_label(board, x, BOARD_SIZE - 1, bottomElem, PLACEHOLDER_REMOVE); game_set_element_label(board, x, firstEmptyY, bottomElem, PLACEHOLDER_ADD); game_set_element_label(board, x, firstEmptyY - 1, get_element(player), PLACEHOLDER_ADD); } } return TRUE; } static gboolean on_hover_leave(GtkWidget *widget) { int x; game_get_event_box_coordinates(board, widget, &x, NULL); game_set_element_label(board, x, -1, EMPTY, NOT_PLACEHOLDER); //Clear row for placeholders for (int currentY = 0; currentY < BOARD_SIZE; currentY++) { game_set_element_label(board, x, currentY, boardElements[x][currentY], NOT_PLACEHOLDER); } return TRUE; } static gboolean on_frame_click(GtkWidget *widget) { int x, y; game_get_event_box_coordinates(board, widget, &x, &y); g_debug("Clicked x:%d y:%d", x, y); if (whoseTurn == player && game_is_move_possible(boardElements, x)) { Element element = boardElements[x][y]; if (element == EMPTY) { game_move_push(x, false); } else { game_move_replace(x); } } return TRUE; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "domino.h" int main() { int deckPieces = 0; int tablePieces = 0; int player1Pieces = 0; int player2Pieces = 0; DominoPiece *deckParts = NULL; DominoPiece *tableParts = NULL; DominoPiece *player1Parts = NULL; DominoPiece *player2Parts = NULL; deckParts = init(&deckPieces, deckParts); while(player1Pieces < 7){ player1Parts = givePiece(&deckPieces, deckParts, &player1Pieces, player1Parts); }; while(player2Pieces < 7){ player2Parts = givePiece(&deckPieces, deckParts, &player2Pieces, player2Parts); }; printf("-------Baralho [Total: %i] -------\n\n", deckPieces); showPieces(deckParts); printf("\n"); printf("-------Mesa [Total: %i] -------\n\n", tablePieces); showPieces(tableParts); printf("\n"); printf("-------Jogador 1 [Total: %i] -------\n\n", player1Pieces); showPieces(player1Parts); printf("\n"); printf("-------Jogador 2 [Total: %i] -------\n\n", player2Pieces); showPieces(player2Parts); printf("\n"); return 0; };
C
/** * @file 17.c * * @brief Number letter counts * * If the numbers 1 to 5 are written out in words: * one, two, three, four, five, * then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. * * If all the numbers from 1 to 1000 (one thousand) inclusive * were written out in words, how many letters would be used? */ #include "stdbool.h" #include "stdint.h" #include "stdlib.h" #include <stdio.h> uint8_t count_ones[10] = { 0, // 3, // one 3, // two 5, // three 4, // four 4, // five 3, // six 5, // seven 5, // eight 4 // nine }; uint8_t count_teens[10] = { 3, // ten 6, // eleven 6, // twelve 8, // thirteen 8, // fourteen 7, // fifteen 7, // sixteen 9, // seventeen 8, // eighteen 8 // nineteen }; uint8_t count_tens[10] = { 0, // 3, // ten 6, // twenty 6, // thirty 5, // forty 5, // fifty 5, // sixty 7, // seventy 6, // eighty 6 // ninety }; uint8_t count_hundred = 7; uint8_t count_and = 3; uint8_t count_thousand = 8; typedef struct Digits { uint16_t num; uint8_t arr[4]; uint8_t len; } Digits; Digits parse_digits(uint16_t num) { Digits digits = { .len = 0, .num = num }; while(0 < num) { digits.arr[digits.len] = num % 10; digits.len++; num /= 10; } return digits; } uint8_t count_letters(Digits *digits) { uint8_t count = 0; for(uint8_t i = 0; i < digits->len; i++) { switch(i) { case 0: if(1 < digits->len && digits->arr[1] == 1) { continue; } else { count += count_ones[digits->arr[0]]; } break; case 1: if(digits->arr[1] == 1) { count += count_teens[digits->arr[0]]; } else { count += count_tens[digits->arr[1]]; } break; case 2: if(digits->arr[2] == 0) { continue; } else { count += count_ones[digits->arr[2]] + count_hundred; } break; case 3: count += count_ones[digits->arr[3]] + count_thousand; break; default: break; } } if(2 < digits->len && !(digits->arr[0] == 0 && digits->arr[1] == 0)) { count += count_and; } return count; } int main(int argc, char *argv[]) { uint16_t num = atoi(argv[1]); uint64_t total = 0; for(uint16_t i = 1; i <= num; i++) { Digits digits = parse_digits(i); total += count_letters(&digits); } printf("Total: %lu\n", total); return 0; }
C
/* Includes ------------------------------------------------------------------*/ #include "AT_UART.h" /******************************************************************* * : void Mcu_UartxSendByte(UART_HandleTypeDef huart,char dat) * : ʹ * : * : * : * ע : ********************************************************************/ void Mcu_UartxSendByte(UART_HandleTypeDef huart,char dat) { /* һֽݵhuart.Instance */ HAL_UART_Transmit(&huart, (uint8_t *)&dat, 1, 0xFFFF); } /******************************************************************* * : Mcu_UartxSendString(UART_HandleTypeDef huart,char * str) * : ַ * : * : * : * ע : ********************************************************************/ void Mcu_UartxSendString(UART_HandleTypeDef huart,char * str) { while(*str)//ַ { Mcu_UartxSendByte(huart,*str++); //͵ǰַ } } /******************************************************************* * : Mcu_UartxSendLR(UART_HandleTypeDef huart) * : ͻس0x0D з0x0A * : * : * : * ע : ********************************************************************/ void Mcu_UartxSendLR(UART_HandleTypeDef huart) { Mcu_UartxSendByte(huart,0x0D); //س Mcu_UartxSendByte(huart,0x0A); //з } /******************************************************************************* * : Mcu_UartxSendAtCommand(UART_HandleTypeDef huart,char * cmd) * : ATָ * : * : * : * ע : *******************************************************************************/ void Mcu_UartxSendAtCommand(UART_HandleTypeDef huart,char * cmd) { Mcu_UartxSendString(huart,cmd); Mcu_UartxSendLR(huart); } /******************************************************************************* * : Mcu_UartxSendDatabyLength(UART_HandleTypeDef huart,char *data, unsigned short len) * : ָݳȷ * : * : * : * ע : *******************************************************************************/ void Mcu_UartxSendDatabyLength(UART_HandleTypeDef huart,char *data, unsigned short len) { unsigned int k = 0; do { Mcu_UartxSendByte(huart,*(data + k)); k++; } while(k < len); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jgainza- <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/10/18 15:16:57 by jgainza- #+# #+# */ /* Updated: 2021/10/18 15:21:12 by jgainza- ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line.h" void test_rd(int rd, char *buff) { if (rd == -1) free(buff); } char *get_next_line(int fd) { char *line; char *buff; static char *cache; int rd; rd = 1; if (fd < 0 || BUFFER_SIZE <= 0) return (NULL); buff = (char *) malloc((BUFFER_SIZE + 1) * sizeof(char)); if (!buff) return (NULL); while (!ft_gnl_strchr(cache, '\n') && rd != 0) { rd = read(fd, buff, BUFFER_SIZE); test_rd(rd, buff); if (rd == -1) return (NULL); buff[rd] = '\0'; cache = ft_gnl_strjoin(cache, buff); } free(buff); line = ft_line(cache); cache = ft_newcache(cache); return (line); }
C
#include <asf.h> /* * Test program for reaction test setup * Author: Philip Ekholm */ #include "console_driver.h" #include "pin_mapper.h" #define LEFT_LED 53 #define MIDDLE_LED 51 #define RIGHT_LED 49 #define BTN1 47 #define BTN2 45 #define VCC 43 void enable_pins(void) { ioport_enable_pin(pin_mapper(LEFT_LED)); ioport_enable_pin(pin_mapper(MIDDLE_LED)); ioport_enable_pin(pin_mapper(RIGHT_LED)); ioport_enable_pin(pin_mapper(BTN1)); ioport_enable_pin(pin_mapper(BTN2)); ioport_enable_pin(pin_mapper(VCC)); ioport_set_pin_dir(pin_mapper(LEFT_LED), IOPORT_DIR_OUTPUT); ioport_set_pin_dir(pin_mapper(MIDDLE_LED), IOPORT_DIR_OUTPUT); ioport_set_pin_dir(pin_mapper(RIGHT_LED), IOPORT_DIR_OUTPUT); ioport_set_pin_dir(pin_mapper(VCC), IOPORT_DIR_OUTPUT); ioport_set_pin_dir(pin_mapper(BTN1), IOPORT_DIR_INPUT); ioport_set_pin_dir(pin_mapper(BTN2), IOPORT_DIR_INPUT); ioport_set_pin_level(pin_mapper(VCC), 1); /* Unfortunately PIO-system doesn't follow ioport convention so we must enter SAM-pins */ PIOC->PIO_PUDR |= PIO_PC18 | PIO_PC16; /* Set pull-up for both buttons */ PIOC->PIO_IFER |= PIO_PC18 | PIO_PC16; /* Enable switch debounce filter for both buttons */ PIOC->PIO_DIFSR |= PIO_PC18 | PIO_PC16; } int main (void) { sysclk_init(); board_init(); console_init(); ioport_init(); enable_pins(); uint8_t button1_pressed = 0, button2_pressed = 0; while(1) { button1_pressed = ~ioport_get_pin_level(pin_mapper(BTN1)) & 1; button2_pressed = ~ioport_get_pin_level(pin_mapper(BTN2)) & 1; if (button1_pressed && button2_pressed) { ioport_set_pin_level(pin_mapper(RIGHT_LED), 1); ioport_set_pin_level(pin_mapper(MIDDLE_LED), 1); ioport_set_pin_level(pin_mapper(LEFT_LED), 1); printf("Both buttons pressed\n"); } else if (button1_pressed) { ioport_set_pin_level(pin_mapper(RIGHT_LED), 0); ioport_set_pin_level(pin_mapper(MIDDLE_LED), 0); ioport_set_pin_level(pin_mapper(LEFT_LED), 1); printf("Button 1 pressed\n"); } else if (button2_pressed) { ioport_set_pin_level(pin_mapper(RIGHT_LED), 1); ioport_set_pin_level(pin_mapper(MIDDLE_LED), 0); ioport_set_pin_level(pin_mapper(LEFT_LED), 0); printf("Button 2 pressed\n"); } else { ioport_set_pin_level(pin_mapper(RIGHT_LED), 0); ioport_set_pin_level(pin_mapper(MIDDLE_LED), 0); ioport_set_pin_level(pin_mapper(LEFT_LED), 0); printf("No button pressed\n"); } } }
C
#include <stdio.h> #include <assert.h> unsigned pwr2k (unsigned k) { return 1U << k; } unsigned div_by_2k (unsigned x, unsigned k) { return x >> k; } unsigned div_by_2k_check (unsigned x, unsigned k) { return x / pwr2k(k); } int sdiv_by_2k (int x, unsigned k) { return (x < 0 ? x + (1 << k) - 1 : x) >> k; } int sdiv_by_2k_check (int x, unsigned k) { return x / (int) pwr2k(k); } int main() { unsigned k; unsigned x; int sx; unsigned step = 11371U; int sstep = (int) step; unsigned N = 0U; for(k = 0; k < 32; ++k) { for(x = 0; x < x + step; x += step) { unsigned u1 = div_by_2k(x,k); unsigned u2 = div_by_2k_check(x,k); N +=1; assert (u1 == u2); } } for(k = 0; k < 31; ++k) { for(sx = -0x80000000; sx < sx + sstep; sx += sstep) { int s1 = sdiv_by_2k(sx,k); int s2 = sdiv_by_2k_check(sx,k); N +=1; assert (s1 == s2); } } printf("Number of checks carried out: %u\n", N); return 0; }
C
#include <stdio.h> #include <string.h> int verificaString (char *str1, char *str2) { int i, j, contagem = 0; for (i = 0; i < strlen(str1) - 1; i++) { if (*(str2+0) == *(str1+i)) { for (j = 0; j < strlen(str2) - 1; j++) { if (*(str2+j) == *(str1+(i++))) { contagem++; } } } if (contagem == strlen(str2) - 1) { break; } } if (contagem == strlen(str2) - 1) { return 1; } else { return -1; } } int main () { char str1[100], str2[100]; printf("String 1: "); setbuf(stdin, NULL); fgets(str1, 100, stdin); printf("String 2: "); setbuf(stdin, NULL); fgets(str2, 100, stdin); int retorno = verificaString(str1, str2); retorno == 1 ? printf("Segunda string ocorre dentro da primeira.\n") : printf("Não ocorre! %i\n", retorno); return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> static void app_do(void); /** * @brief main */ int main(int argc, char *argv[]) { #ifdef __COVERAGESCANNER__ __coveragescanner_install("app"); __coveragescanner_clear(); __coveragescanner_testname("app_coverage"); #endif app_do(); #ifdef __COVERAGESCANNER__ __coveragescanner_teststate("PASSED"); __coveragescanner_save(); #else exit(EXIT_SUCCESS); #endif } /** * @brief my app */ static void app_do(void) { printf("Hello world\n"); } /** * @brief testcase */ void testcase_app() { printf("\r\n"); printf("======================\r\n"); printf("=== UNIT TEST ===\r\n"); printf("======================\r\n"); app_do(); } #ifdef CU_TEST /** * @brief CU_app */ static CU_TestInfo CU_app[] = { {"APP:", testcase_app }, CU_TEST_INFO_NULL }; /** * @brief scenario */ static CU_SuiteInfo scenario[] = { { "APP", NULL, NULL, CU_app }, CU_SUITE_INFO_NULL }; /** * @brief AddTests */ void AddTests(void) { assert(NULL != CU_get_registry()); assert(!CU_is_test_running()); CU_register_suites(scenario); return; } #endif //CU_TEST
C
/* * Company.h * * Created on: May 30, 2017 * Author: Noam */ #ifndef COMPANY_H_ #define COMPANY_H_ #include "mtm_ex3.h" #include "room.h" #include "set.h" #include "list.h" #include <stdlib.h> #include <stdbool.h> typedef struct company *Company; /** * This type defines all errors for the company. */ typedef enum { COMPANY_OUT_OF_MEMORY, // You should exit program after this error COMPANY_NULL_PARAMETER, COMPANY_INVALID_PARAMETER, COMPANY_ROOM_ALREADY_EXIST, COMPANY_ROOM_DOES_NOT_EXIST, COMPANY_ROOM_NOT_AVAILABLE, COMPANY_SUCCESS, COMPANY_DEFAULT } CompanyResult; /** * Company Data Type */ /** * create company in the system with the email and faculty as input. * the identification between companies will be the email. * * @param email the email which the company will have * @param faculty the faculty which the company will be under. * @param CompanyResult* result for output * * @return Company object. NULL if one of the parameters are null, or if there * are problems with memory allocating. */ Company createCompany(char* email, TechnionFaculty faculty, CompanyResult* companyResult); /** * destroy the company, free all its elements memory and free itself. * * @param company object. * @return CompanyResult an Enum result. */ void destroyCompany(Company company); /** * free company for implementing Set. Using the Destroy function of Company. */ void freeCompanySetFunction(SetElement company); /** * free company for implementing List. Using the Destroy function of Company. */ void freeCompanyListFunction(ListElement company); /** * copy company. create a new company with the same values as the company from * the input. this function use the createCompany function to create the * new Company. * * @param company the object to copy the values from * @return company with the same values as the inputed, or NULL if some memory * allocations happened. */ Company companyCopy(Company company); /** * copy function for implementing Set. */ SetElement companyCopySetFunction(SetElement company); /** * copy function for implementing List. */ ListElement companyCopyListFunction(ListElement company); /** * This function use the strcmp from the string library. It uses the function * on the emails of the companies. Means, it compares the emails of the first * companies to the email of the second one. * * @param company_1 first escaper * @param company_2 second escaper * * @return int according to the strcmp function. */ int companyCompareEmails(SetElement company_1, SetElement company_2); /** * This function compares the faculty of the first * companies to the faculty of the second one. * * @param company_1 first escaper * @param company_2 second escaper * * @return int like standard comparing function, according to the the facutly * integer. */ int companyCompareFaculties(SetElement company_1, SetElement company_2); /** * add a room to the current company. this function check if the room is not * already exist in the company, if yes the function will return the right * result, and if not it will add the room into the set of rooms of the company. * * @param company the company to add the room into * @param room the room to add into the company * * @return MtmErrorCode an Enum result, it will return the correct message * depends on the situation. */ CompanyResult addRoomToCompany(Company company, Room room); /** * remove a room from the set of the company, first the function search for the * room according to the id parameter. If the room exist then the * function will remove it from the company. * * @param company the company that the function removes the room from * @param id and id of the room * * @return MtmErrorCode an Enum result, it will return the correct message * depends on the situation. */ CompanyResult removeRoomFromCompany(Company company, int id); /** * get the email of a company from the struct. * * @param company struct * @return NULL if parameter is wrong or problem with memory allocations, * the copy of the company's email if otherwise. */ char* getCompanyEmail(Company company); /** * get The TechnionFaculty Enum of what the company belongs to. * * @param company the Company that belongs to a certain faculty * @return TechnionFaculty Enum, an id of a faculty. */ TechnionFaculty getCompanyFaculty(Company company); /** * This function checks if a certain company has a room with a certain id. * and return true if yes and false otherwise. * * @param company the ADT that contain rooms Set * @param id the id of a room that the function searches; * * @return True if the company has a room with the Id, and false otherwise. */ bool checkCompanyHasRoomWithId(Company company, int id); /** * This function find a room in the company Set of rooms, and return the price * of that room. * * @param company to search the room inside it * @param room_id the room that the function search for * * @return int price, the price of the room with the inputed id. */ int getRoomPriceFromCompany(Company company, int room_id); /** * This function find a room in the company Set of rooms, and return the * difficulty of that room. * * @param company to search the room inside it * @param room_id the room that the function search for * * @return int difficulty, the level of the room with the inputed id. */ int getRoomDifficultyFromCompany(Company company, int room_id); /** * create a new list and insert all the rooms the company has into the list. * each room is a copy. * * @param company the company which the function takes the set of rooms from. * *@return NULL - if one of the parameters is NULL or allocations failed. * A new List in case of success. */ List companyGetListOfRooms(Company company); /** * This function return a copy of all the room of the company that get as * input. * * @param company * * @return Set of companies. NULL if problem with memory allocations. */ Set getCopyOfAllRooms(Company company); /** * This function return the amount of rooms in the a certain company * * @param Company * @return int size of set of rooms in company. */ int companyGetSizeOfRooms(Company company); #endif /* COMPANY_H_ */
C
//Accepted #include<stdio.h> #include<string.h> #include<math.h> #include<stdlib.h> #include<stdbool.h> double b=180000.0,c=300000.0,d=400000.0,e=300000.0; int main() { double a,q; long long sum; int i=1,j,k,T; scanf("%d",&T); while(i<=T) { sum=0; scanf("%lf",&a); if(a<=b) { printf("Case %d: 0\n",i); i++; continue; } q=a-b; if(q<=c) { sum=sum+ceil((q*10.0)/100.0); if(sum>0&&sum<2000) sum=2000; printf("Case %d: %lld\n",i,sum); i++; continue; } else { q=q-c; sum=sum+ceil((c*10.0)/100.0); } if(q<=d) { sum=sum+ceil((q*15.0)/100.0); if(sum>0&&sum<2000) sum=2000; printf("Case %d: %lld\n",i,sum); i++; continue; } else { q=q-d; sum=sum+ceil((d*15.0)/100.0); } if(q<=e) { sum=sum+ceil((q*20.0)/100.0); if(sum>0&&sum<2000) sum=2000; printf("Case %d: %lld\n",i,sum); i++; continue; } else { q=q-e; sum=sum+ceil((e*20.0)/100.0); } if(q>0) { sum=sum+ceil((q*25.0)/100.0); printf("Case %d: %lld\n",i,sum); } i++; } return 0; }
C
#include<stdio.h> int main() { int i,j,n,sum=0,pro; printf("Series: 1+ (1*2)+ (1*2*3)+....+ (1*2*3*...*n)"); printf("Enter number of n\n"); scanf("%d",&n); for(i=1; i<=n; i++) { pro=1; for(j=1; j<=i; j++) pro*=j; sum+=pro; } printf("Sum of Series : %d\n",sum); return 0; }
C
#include "protocol_receiver.c" #include "../app_utils.c" #include <math.h> /** * funcao que verifica se o pacote recebido é o pacote END * @param start pacote START recebida anteriormente * @param sizeStart tamanho da pacote START * @param end mensagem lida a verificar se é END * @param sizeEnd tamanho dessa mesma mensagem * @return TRUE se for END, FALSE caso contrario **/ int isAtEnd(unsigned char *start, int sizeStart, unsigned char *end, int sizeEnd) { int s = 1; int e = 1; if (sizeStart != sizeEnd) // se o tamanho do pacote a analisar e do pacote de START nao for o mesmo return FALSE; else { if (end[0] == 0x03) // se o campo de controlo do pacote atual for 3 (end) { for (; s < sizeStart; s++, e++) // percorre o pacote atual e o pacote START simultaneamente, para os comparar { if (start[s] != end[e]) // se o pacote a analisar nao for igual ao pacote de START em qualquer um dos bytes return FALSE; } return TRUE; } else { return FALSE; } } } int main(int argc, char** argv) { int fd,porta; // descritor da ligacao de dados (fd) e porta serie (porta) unsigned char mensagemPronta[65540]; // variavel onde cada pacote vai ser guardado int sizeMessage = 0; // tamanho do pacote int sizeOfStart = 0; // tamanho do pacote START unsigned char start[100]; // variavel que guarda o pacote START struct timespec before , after; // before vai guardar o tempo de quando começa a receber informação, e after vai guardar o tempo de quando acabar de transferir a informação struct shell_inputs arguments; // struct que vai guardar os argumentos introduzidos u_int64_t before_ns,after_ns; // vai guardar os tempos com grande precisão //verifica se pelo menos tem 2 argumentos, e se o segundo começa com /dev/ttyS if ( (argc < 2) || (strncmp("/dev/ttyS",argv[1],9) != 0) ){ printf("Invalid inputs, the template command is:\n./app /dev/ttySx [-B 38400]\n"); exit(1); } //vai buscar ao array argv os argumentos introduzidos if (readArgvValues(argc,argv,&arguments,RECEIVER) == -1){ exit(-1); } //atribuição dos argumentos lidos BAUDRATE = arguments.baudrate; Delay = arguments.atraso; FER = arguments.FER; porta = atoi(&arguments.port[9]); fd = llopen(porta); // verificar se a porta serie foi aberta com sucesso if (fd == -1) exit(-1); sizeOfStart = llread(fd, start); // lê o pacote de controlo START if (sizeOfStart == -1) //se ocorreu algum erro na leitura do pacote START exit(-1); //recolher a informação do tamanho do ficheiro int num_blocos_tamanho = start[2]; char tamanho_str[num_blocos_tamanho]; for (size_t i = 0; i < num_blocos_tamanho; i++) { tamanho_str[i] = start[3+i]; } int tamanho_int = atoi(tamanho_str); //converter o tamanho de string para inteiro //recolher a informação do nome do ficheiro int num_blocos_nome = start[3+num_blocos_tamanho+1]; char nome_ficheiro[num_blocos_nome+1]; for (size_t i = 0; i < num_blocos_nome; i++) { nome_ficheiro[i] = start[5 + num_blocos_tamanho + i]; } nome_ficheiro[num_blocos_nome]= '\0'; // cria ficheiro com o nome obtido no pacote START FILE *file = fopen(nome_ficheiro, "wb+"); clock_gettime(CLOCK_MONOTONIC,&before);//guarda o tempo atual em before //enquanto houver informação para ler while (TRUE) { sizeMessage = llread(fd, mensagemPronta); //lê de fd um pacote de informação if(sizeMessage == -1) // se ocorreu algum erro no llread exit(-1); if (sizeMessage == 0) continue; if (isAtEnd(start, sizeOfStart, mensagemPronta, sizeMessage)) // se leu a trama de END { clock_gettime(CLOCK_MONOTONIC,&after);//guarda o tempo atual em after printf("End message received\n"); break; } int sizeWithoutHeader = sizeMessage - 4; //guarda o tamanho do pacote de dados sem o cabeçalho // remove o cabeçalho do nível de aplicação dos pacotes de dados int i = 0; int j = 4; unsigned char messageRemovedHeader[sizeWithoutHeader]; //array que vai guardar os dados recebidos for (; i < sizeMessage; i++, j++) { messageRemovedHeader[i] = mensagemPronta[j]; } //escreve no ficheiro os dados recebidos fwrite(messageRemovedHeader, 1, sizeWithoutHeader, file); } //pré calculo do tempo decorrido com maior precisão before_ns = (before.tv_sec * 1000000000) + before.tv_nsec; after_ns = (after.tv_sec * 1000000000) + after.tv_nsec; //tempo decorrido em segundos double elapsedT = (after_ns - before_ns)*pow(10,-9); //imprime o tamanho do ficheiro e o tempo que demorou a ser transferido printf("File size: %d bytes\nTransfer time: %.4f sec\n", tamanho_int,elapsedT); //fecha o ficheiro escrito fclose(file); //fecha a ligação com a porta série if(llclose(fd) == -1) exit(-1); return 0; }
C
#include<stdio.h> main() { //1.Display the menu printf("pick an item : \n1. Pen\n2. Pencil\n3. Eraser\n4 .Book"); //2.Read their choice int choice=0; scanf("%d",&choice); //3.Display based on their choice switch(choice) { case 1: printf(" You picked Pen."); break; case 2: printf(" You picked Pencil."); break; case 3: printf(" You picked Eraser."); case 4: printf(" You picked Book."); break; default : printf("Invalid choice"); } }
C
#include <stdio.h> int sum (int sum) { static int realSum = 0; realSum = realSum + sum; return realSum; } int main () { printf("%d ", sum(25)); printf("%d ", sum(15)); printf("%d ", sum(30)); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "cs_decode.h" #include "schema.h" static int value_callback(const cs_path_t *path, int value) { for (unsigned i = 0; i < path->depth; i++) { printf(" "); } printf("%d: %d\n", path->values[path->depth - 1], value); return 0; } static int enter_exit_callback(const cs_path_t *path, bool enter) { for (unsigned i = 0; i < path->depth; i++) { printf(" "); } if (enter && path->depth) { printf("%d: ", path->values[path->depth - 1]); } printf("%s\n", enter ? "{" : "}"); return 0; } int main(int argc, char *argv[]) { if (argc != 2) { return 1; } uint8_t *encoded; FILE *fp = fopen(argv[1], "rb"); if (!fp) { return 2; } fseek(fp, 0, SEEK_END); long size = ftell(fp); encoded = malloc(size); fseek(fp, 0L, SEEK_SET); size_t read = fread(encoded, 1, size, fp); if (read != size) { return 3; } fclose(fp); cs_decode(&schema_schema, value_callback, enter_exit_callback, encoded, TYPE_CONFIGURATION); free(encoded); }
C
/*##################################### TIM ################################### : 1. RCC->APB2ENR (TIM 1,8,9,10,11) RCC->APB1ENR () RCC_APB1ENR_TIMEN, - . 2. TIM->CR2, - . 3. TIM->DIER, - : TIM_DIER_UIE - (?); TIM_DIER_UDE - DMA (?). 4. TIM->PSC 5. TIM->ARR 1 = 84 (. system_stm32f4xx.c SetSysClock()) PSC = 8400 !!!!! 8400 - 1 = 8399!!!!! ARR = 10 000 !!!!! 10 000 - 1 = 9999!!!!! (84 000 000 / 8400) * 10 000 = 1 1 . 6. NVIC: NVIC_EnableIRQ(IRQn_Type IRQn). 7. TIM->CR1: TIM_CR1_CEN - ; TIM_CR1_ARPE - . ################################################################################*/ #include "timer.h" void userTimer_Init(Timer* timer) { if((timer->timerPeriod / timer->timerOneCount) > 0xFFFF) return; if(((timer->timerAPBFreq / 1000000) * timer->timerOneCount) > 0xFFFF) return; if(timer->baseTimer == (TIM_TypeDef*)TIM1_BASE) { RCC->APB2ENR |= RCC_APB2ENR_TIM1EN; NVIC_EnableIRQ(TIM1_BRK_TIM9_IRQn); NVIC_EnableIRQ(TIM1_UP_TIM10_IRQn); NVIC_EnableIRQ(TIM1_TRG_COM_TIM11_IRQn); NVIC_EnableIRQ(TIM1_CC_IRQn); } else if(timer->baseTimer == (TIM_TypeDef*)TIM2_BASE) { RCC->APB1ENR |= RCC_APB1ENR_TIM2EN; NVIC_EnableIRQ(TIM2_IRQn); } else if(timer->baseTimer == (TIM_TypeDef*)TIM3_BASE) { RCC->APB1ENR |= RCC_APB1ENR_TIM3EN; NVIC_EnableIRQ(TIM3_IRQn); } else if(timer->baseTimer == (TIM_TypeDef*)TIM4_BASE) { RCC->APB1ENR |= RCC_APB1ENR_TIM4EN; NVIC_EnableIRQ(TIM4_IRQn); } timer->baseTimer->PSC = ((timer->timerAPBFreq / 1000000) * timer->timerOneCount) - 1; timer->baseTimer->ARR = (timer->timerPeriod / timer->timerOneCount) - 1; if(timer->mode == TIMER_MODE_COUNTER) { timer->baseTimer->DIER |= TIM_DIER_UIE; timer->baseTimer->CR1 |= TIM_CR1_ARPE; } else if(timer->mode == TIMER_MODE_PWM) { if(timer->channel == 1) timer->baseTimer->CCER |= TIM_CCER_CC1E; if(timer->channel == 2) timer->baseTimer->CCER |= TIM_CCER_CC2E; if(timer->channel == 3) timer->baseTimer->CCER |= TIM_CCER_CC3E; if(timer->channel == 4) timer->baseTimer->CCER |= TIM_CCER_CC4E; timer->baseTimer->CCMR1 |= TIM_CCMR1_OC2M_1 | TIM_CCMR1_OC2M_2; timer->baseTimer->CCR2 = ((timer->baseTimer->ARR) * timer->pulseWidth) / 100; } } void userTimer_Enable(Timer* timer) { timer->baseTimer->CR1 |= TIM_CR1_CEN; } void userTimer_Disable(Timer* timer) { timer->baseTimer->CR1 &= ~TIM_CR1_CEN; }
C
/* * tiny_avr_application.c * * Created: 29/04/2020 8:40:49 PM * Author : lance initial design is for portrait orientation */ #include <avr/io.h> #include "lcd_library.h" #include "colors.h" #define BUTTON_PRESSED (!(PINB) && (1<<BUTTON)) void display_1(); void display_2(); void display_3(); void display_4(); extern uint16_t image[]; void setup() { // setup the timer TCCR0A = 0x00; TCCR0B = 0x00; PORTB = 0x00; DDRB |= (1<<CS_PIN)|(1<<DC_PIN); //spi board logic pins DDRB &= ~(1<<BUTTON); //set up the button input pin as an input MCUCR &= ~(1<<PUD); //make sure the pull up disable is 0, enabling the pullup PORTB |= (1<<5); //turn on the internal pull up resistor for the button. } int main(void) { /* Replace with your application code */ setup(); spi_setup(); //we need to implement the link below! well some of it atleast :) //https://github.com/thefallenidealist/ili9341/blob/master/glcd.c lcd_init(); lcd_drawPixel(0,0,RED); //display image display_4(); while (1) { } } void display_1() { lcd_fillRectangle(0,0,PORTRAIT_MAX_X,PORTRAIT_MAX_Y, BLUE_NICE); } void display_2() { lcd_fillRectangleTopToBottom(0,0,PORTRAIT_MAX_X,PORTRAIT_MAX_Y,PORTRAIT_MAX_Y-250, BLACK); } void display_3() { lcd_fillRectangleSideToSide(0,0,PORTRAIT_MAX_X,PORTRAIT_MAX_Y, PORTRAIT_MAX_X-150, BLACK); } void display_4() { //draw_bitmap(&image[0], 50, 50, 50, 50,RED); draw_expanded_bitmap(&image[0], 50, 50, 50, 50,4,RED); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <pmmintrin.h> // Print all elements of vector: void vec_print(float* vec, unsigned int element_count) { for (size_t i = 0; i < element_count; i++) { printf("vec[%zu]=%.2f\n", i, vec[i]); } } // Set vector 'out' to 1..element_count // Set all elements of vector 'in' to 2: void vec_reset(float* out, float* in, unsigned int element_count) { for (size_t i = 0; i < element_count; i++) { out[i] = i + 1; in[i] = 2; } } void mult_c(float* out, float* in, unsigned int element_count) { clock_t start = clock(); // Classic C vector multiplication (for loop): for (size_t i = 0; i < element_count; i++) { out[i] = out[i] * in[i]; } printf("C Loop Multiplication: %.6fms\n", (double)(clock() - start) / (CLOCKS_PER_SEC / 1000)); } void mult_asm(float* out, float* in, unsigned int element_count) { clock_t start = clock(); // Use X87 floating point stack for vector multiplication: // Calculate the size of the vector in bytes: size_t byte_length = sizeof(float) * element_count; // ====ASM==== __asm__ __volatile__( ".intel_syntax noprefix \n" "my_label1: \n" "sub rcx, 4 \n" // set zero flag "fld dword ptr [rbx+rcx] \n" "fld dword ptr [rax+rcx] \n" "fmulp st(1), st(0) \n" "fstp dword ptr [rax+rcx] \n" "jnz my_label1 \n" // check zero flag ".att_syntax prefix \n" : :"a"(out), "b"(in), "c"(byte_length) : ); printf("Old ASM Multiplication: %.6fms\n", (double)(clock() - start) / (CLOCKS_PER_SEC / 1000)); } void mult_intrinsics_sse(float* out, float* in, unsigned int element_count) { clock_t start = clock(); // https://software.intel.com/sites/landingpage/IntrinsicsGuide/ // Hints: _mm_store_ps, _mm_load_ps, _mm_mul_ps // Calculating number of iterations needed if we calc 4 floats at a time: // Intrinsics multiplication: unsigned int sse_iter = element_count / 4; for (size_t i = 0; i < sse_iter; i++) { __m128 out_sse = _mm_load_ps(out + 4 * i); __m128 in_sse = _mm_load_ps(in + 4 * i); __m128 result = _mm_mul_ps(out_sse, in_sse); _mm_store_ps(out + 4 * i, result); } printf("SSE with Intrinsics Multiplication: %.6fms\n", (double)(clock() - start) / (CLOCKS_PER_SEC / 1000)); } void mult_asm_sse(float* out, float* in, unsigned int element_count) { clock_t start = clock(); // Calculate the size of the vector in bytes: size_t byte_length = sizeof(float) * element_count; // ====ASM==== // 4 floats per loop iteration: __asm__ __volatile__( ".intel_syntax noprefix \n" "my_label2: \n" "sub rcx, 16 \n" "movaps xmm0, [rbx + rcx] \n" "movaps xmm1, [rax + rcx] \n" "mulps xmm0, [rax + rcx] \n" "movaps [rax + rcx], xmm0 \n" "jnz my_label2 \n" ".att_syntax prefix \n" : :"a"(out), "b"(in), "c"(byte_length) :"xmm0", "xmm1" ); printf("ASM with SSE Multiplication: %.6fms\n", (double)(clock() - start) / (CLOCKS_PER_SEC / 1000)); } void mult_asm_sse_optimized(float* out, float* in, unsigned int element_count) { clock_t start = clock(); // Calculate the size of the vector in bytes: size_t byte_length = sizeof(float) * element_count; // ====ASM==== // 4 floats per loop iteration: __asm__ __volatile__( ".intel_syntax noprefix \n" "xor rcx, rcx \n" "my_label3: \n" "movaps xmm0, [rbx + rcx] \n" "mulps xmm0, [rax + rcx] \n" "movaps [rax + rcx], xmm0 \n" "add rcx, 16 \n" "cmp rcx, rdx \n" "jne my_label3 \n" ".att_syntax prefix \n" : :"a"(out), "b"(in), "d"(byte_length) :"xmm0", "xmm1", "rcx" ); printf("Optimized ASM with SSE Multiplication: %.6fms\n", (double)(clock() - start) / (CLOCKS_PER_SEC / 1000)); } int main(int argc, char** argv) { // Check for argument count: (1. argument is path to binary, 2. argument should be element count of vector) if (argc < 2) { printf("Missing argument: element count\n"); printf("E.g.: vec_mul.out 1000000 \n"); return 0; } // Get the vector size: unsigned int element_count = atoi(argv[1]); // Get the vector size for SSE aka // if element_count is not divisible by 4, get the next divider by 4 unsigned int element_count_sse = element_count % 4 == 0 ? element_count : element_count + (4 - element_count % 4); // element_count % 4 == 0 ? element_count : element_count / 4 * 4 + 4); // Windows: // #include <malloc.h> // float* vec_out = (float*) _aligned_malloc(sizeof(float)*element_count_sse, 16); // Allocate input and output vector (float) of given size: float* vec_out = NULL; posix_memalign((void**)&vec_out, 16, sizeof(float)*element_count_sse); float* vec_in = NULL; posix_memalign((void**)&vec_in, 16, sizeof(float)*element_count_sse); // Reset the vectors: vec_reset(vec_out, vec_in, element_count_sse); // Call classic C multiplication: mult_c(vec_out, vec_in, element_count_sse); // Reset the vectors: vec_reset(vec_out, vec_in, element_count_sse); // Call assembler multiplication mult_asm(vec_out, vec_in, element_count_sse); // Reset the vectors: vec_reset(vec_out, vec_in, element_count_sse); // Call SSE intrinsics multiplication mult_intrinsics_sse(vec_out, vec_in, element_count_sse); // Reset the vectors: vec_reset(vec_out, vec_in, element_count_sse); // Call SSE assembler multiplication mult_asm_sse(vec_out, vec_in, element_count_sse); vec_reset(vec_out, vec_in, element_count_sse); mult_asm_sse_optimized(vec_out, vec_in, element_count_sse); // Free the vectors: free(vec_in); free(vec_out); return 0; }
C
#include <stdio.h> int main(void) { char str[20]; scanf("%s",str); for(int i=0;str[i]!='\0';i++) { if(str[i]>96) { str[i]=str[i]-32; } else if(str[i]<91) { str[i]=str[i]+32; } } printf("%s",str); return 0; }
C
#include<stdio.h> #include <stdlib.h> int main(){ // Writing to a file FILE* fpointer1 = fopen("employees.txt", "w"); // Like printf but for files fprintf(fpointer1, "Jim, Sales\nPan, Reception\nOscar, Accounting"); fclose(fpointer1); // Closes file // Reading from a file char line[255]; FILE* fpointer2 = fopen("employees.txt", "r"); // Gets first line from file and stores it in variable line fgets(line, 255, fpointer2); printf("%s\n", line); // Gets second line from file and stores it in variable line fgets(line, 255, fpointer2); printf("%s\n", line); // Gets third line from file and stores it in variable line fgets(line, 255, fpointer2); printf("%s\n", line); fclose(fpointer2); // Closes file return 0; }
C
#include <sys/socket.h> #include <netinet/in.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <arpa/inet.h> #include <unistd.h> main() { int sock_desc = socket(AF_INET, SOCK_STREAM, 0); char sbuff[1024]; if(sock_desc == -1) { printf("cant create socket\n"); return 0; } struct sockaddr_in client; memset(&client , 0, sizeof(client)); client.sin_family = AF_INET; client.sin_addr.s_addr = inet_addr("192.168.1.30"); client.sin_port = htons(7777); if(connect(sock_desc , (struct sockaddr*)&client, sizeof(client))==-1) { printf("cant connect to server\n"); close(sock_desc); exit(1); } char buf[3][100]={"hi","how are you","exit"}; char c = '\n'; char *p_buf; int k,len; while(1) { gets(buf); len = strlen(buf); p_buf = buf; while(len>0); { k = write(sock_desc, p_buf,len); if(k == -1) { printf("cant write to server!\n"); break; } p_buf+=k; len-=k; } k = read(sock_desc,&sbuff,sizeof(sbuff)); if(k == -1) { printf("cant write to server!\n"); break; } sbuff[k]='\0'; if(strcmp(buf, "exit")==0) break; } close(sock_desc); printf("client disconnected\n"); return 0; }
C
#include <stdio.h> #include <Python.h> PyObject *getMatrixItem(PyObject *matrix, uint32_t x, uint32_t y) { if (y < PyList_Size(matrix) && x < PyList_Size(PyList_GetItem(matrix, y))) { return PyList_GetItem(PyList_GetItem(matrix, y), x); } return PyFloat_FromDouble(0); } static PyObject *dot(PyObject *self, PyObject *args) { PyObject *matrix1, *matrix2, *result; uint32_t size; PyArg_ParseTuple(args, "IOO", &size, &matrix1, &matrix2); result = PyList_New(size); for (uint32_t i = 0; i < size; ++i) { PyObject *resultRow = PyList_New(size); for (uint32_t j = 0; j < size; ++j) { double value = 0; for (uint32_t k = 0; k < size; ++k) { value += PyFloat_AsDouble(getMatrixItem(matrix1, k, i)) * PyFloat_AsDouble(getMatrixItem(matrix2, j, k)); } PyList_SetItem(resultRow, j, PyFloat_FromDouble(value)); } PyList_SetItem(result, i, resultRow); } return result; } static PyMethodDef methods[] = { { .ml_name = "dot", .ml_meth = dot, .ml_flags = METH_VARARGS, .ml_doc = "Do something very useful" }, {NULL, NULL, 0, NULL} }; static PyModuleDef moduleDef = { .m_base = PyModuleDef_HEAD_INIT, // имя модуля .m_name = "matrix", .m_size = -1, .m_methods = methods, }; PyMODINIT_FUNC PyInit_matrix(void) { return PyModule_Create(&moduleDef); }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <signal.h> void pcount(int n, siginfo_t *sig, void *ptr) { static int num = 0; printf("i'm parent now is %d\n",num); num += 2; sleep(1); kill(sig->si_pid, SIGUSR2); } void ccount(int n, siginfo_t *sig, void *ptr) { static int num = 1; printf("i'm child now is %d\n",num); num += 2; sleep(1); kill(sig->si_pid, SIGUSR1); } int main() { pid_t pid = fork(); struct sigaction act; if(pid > 0) { act.sa_flags = 0; sigemptyset(&act.sa_mask); //act.sa_restorer = pcount; act.sa_sigaction= pcount; sigaction(SIGUSR1, &act, NULL); while(1) { sleep(1); } } if(pid == 0) { act.sa_flags = 0; sigemptyset(&act.sa_mask); //act.sa_restorer = ccount; act.sa_sigaction = ccount; sigaction(SIGUSR2, &act, NULL); pid_t ppid = getppid(); kill(ppid, SIGUSR1); while(1) { sleep(1); } } return 0; }
C
/* * Thaddeus002's pccts * * Public Domain. */ /** * \file utils.h * \brief Utilitaries functions for strings handling. */ #ifndef __UTILS_H__ #define __UTILS_H__ /** * Compare two strings case insentive way. * \return 1 if the strings are equal, 0 otherwise */ int ci_strequ(char *a, char *b); /** * Check if string e is a word in string s. * @return 1 for true and 0 for false */ int strmember(char *s, char *e); /** * remove the quotes from a string if there are some. * @param string the string to modify * @return the param "string" */ char *strip_quotes(char *string); /** * Allocate memory and copy a string. * @param original the string to copy * @return a pointer to the newly allocated string or NULL if allocating * failled */ char *copy_string(const char *original); #endif
C
/*! ************************************************************************ * * Copyright (C) 2020 netforklabs All rights reserved. * * 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. * *! ************************************************************************/ /*! ===> Creates on 2021/8/28. <=== */ /*! * @author LAB */ #include <hash_map> void test(Hash_map map){ } int main(void){ Hash_map map; init_hash_map(&map); put_hash_map(map,"aaa","aaa1"); put_hash_map(map,"bbb","aaa2"); put_hash_map(map,"ccc","aaa3"); put_hash_map(map,"ddd","aaa4"); put_hash_map(map,"eee","aaa5"); print_hash_map(map); printf("get:%s\n",get_hash_map(map,"ccc")); remove_hash_map(map,"zzz"); remove_hash_map(map,"aaa"); print_hash_map(map); printf("equal:%d\n",equal_hash_map("aaa","aaa")); printf("equal:%d\n",equal_hash_map("aaa","aa1")); printf("exist:%d\n",exists_hash_map(map,"bbb")); printf("exist:%d\n",exists_hash_map(map,"aaa")); makeEmpty_hash_map(map); print_hash_map(map); printf("input every char exit...\n"); getchar(); return 0; }
C
/* SPDX-License-Identifier: ISC */ #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <signal.h> #include <stdio.h> #include <errno.h> #include "servicecmd.h" static int cmd_disable(int argc, char **argv) { int ret = EXIT_FAILURE; char *linkname, *ptr; struct stat sb; if (check_arguments(argv[0], argc, 2, 3)) return EXIT_FAILURE; for (ptr = argv[1]; isalnum(*ptr) || *ptr == '_'; ++ptr) ; if (*ptr != '\0') { fprintf(stderr, "Invalid service name '%s'\n", argv[1]); tell_read_help(argv[0]); return EXIT_FAILURE; } if (argc == 3) { ret = asprintf(&linkname, "%s/%s@%s", SVCDIR, argv[1], argv[2]); } else { ret = asprintf(&linkname, "%s/%s", SVCDIR, argv[1]); } if (ret < 0) { perror("asprintf"); return EXIT_FAILURE; } if (lstat(linkname, &sb)) { fprintf(stderr, "lstat %s: %s\n", linkname, strerror(errno)); goto out; } if ((sb.st_mode & S_IFMT) != S_IFLNK) { fprintf(stderr, "error: '%s' is not a symlink!", linkname); goto out; } if (unlink(linkname)) { fprintf(stderr, "removing %s: %s\n", linkname, strerror(errno)); goto out; } kill(1, SIGHUP); ret = EXIT_SUCCESS; out: free(linkname); return ret; } static command_t disable = { .cmd = "disable", .usage = "<name> [argument]", .s_desc = "disable a service", .l_desc = "This disables a service by removing the coresponding " "symlink in " SVCDIR ".", .run_cmd = cmd_disable, }; REGISTER_COMMAND(disable)
C
#include<stdio.h> int main() { int num, index; int flag = 0; while (scanf("%d %d", &num, &index)!=EOF) { if (index != 0) { if (flag) printf(" "); printf("%d %d", num*index, index - 1); flag = 1; } } if (flag == 0) { printf("0 0"); } return 0; }
C
#include "menu.h" //Permet de placer le curseur pour crire des coordones prcises (code trouv sur internet) void gotoxy(int x, int y) { HANDLE hConsoleOutput; COORD dwCursorPosition; dwCursorPosition.X = x; dwCursorPosition.Y = y; hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleCursorPosition(hConsoleOutput,dwCursorPosition); } void Curseur(int i, char titre[], int NB_ELT_MENU, int TAILLE_MAX_ELT, char menu[NB_ELT_MENU][TAILLE_MAX_ELT], char temp[NB_ELT_MENU][TAILLE_MAX_ELT]) { int j; //Permet d'ajouter le symbole du curseur devant l'lment du menu choisi strcat(menu[i], "> "); strcat(menu[i], temp[i]); system("CLS"); gotoxy((HORIZONTAL/2)-strlen(titre)/2,5); printf("%s",titre); //Raffiche le menu de base sans curseur for(j=0;j<NB_ELT_MENU;j++) { gotoxy((HORIZONTAL/2)-3,VERTICAL/2+j); printf("%s\n",temp[j]); } //Affiche le curseur devant l'lment du menu choisi gotoxy((HORIZONTAL/2)-3,VERTICAL/2+i); printf("%s\n",menu[i]); } void menu_regle() { //Permet d'afficher les rglesn indications et lments du jeu int action; char titre1[] = "Les regles"; gotoxy(HORIZONTAL/2,VERTICAL/4-3); printf("%s",titre1); char titre2[] = "But du jeu :"; gotoxy(HORIZONTAL/2,(VERTICAL/4)); printf("%s",titre2); gotoxy(5,(VERTICAL/4)+2); printf("Le serpent doit manger le plus de fruits possibles."); gotoxy(5,(VERTICAL/4)+3); printf("Plus il mange de fruits, plus il accelere."); gotoxy(5,(VERTICAL/4)+4); printf("S'il touche un mur ou sa queue, c'est perdu."); char titre3[] = "Symboles :"; gotoxy(strlen(titre3)/2,(2*VERTICAL/4+1)); printf("%s",titre3); gotoxy(strlen(titre3)/2,(2*VERTICAL/4)+3); printf("Fruits = *"); gotoxy(strlen(titre3)/2,(2*VERTICAL/4)+4); printf("Murs = %c", 219); gotoxy(strlen(titre3)/2,(2*VERTICAL/4)+5); printf("Tete = @"); gotoxy(strlen(titre3)/2,(2*VERTICAL/4)+6); printf("Corps = o"); char titre4[] = "Controles"; gotoxy(HORIZONTAL - strlen(titre4)/2,(2*VERTICAL/4+1)); printf("%s",titre4); gotoxy(HORIZONTAL - strlen(titre4)/2,(2*VERTICAL/4)+3); printf("Haut = Z"); gotoxy(HORIZONTAL - strlen(titre4)/2,(2*VERTICAL/4)+4); printf("Gauche = Q"); gotoxy(HORIZONTAL - strlen(titre4)/2,(2*VERTICAL/4)+5); printf("Bas = S"); gotoxy(HORIZONTAL - strlen(titre4)/2,(2*VERTICAL/4)+6); printf("Droite = D"); retour(); } void menu_mode() { int action, i=0; //Affiche le nom du menu char titre[] = "Menu Modes"; gotoxy((HORIZONTAL/2)-strlen(titre)/2,5); printf("%s",titre); //Initialise les elements du menu char temp[NB_ELT_MENU_M][TAILLE_MAX_ELT_M]={"Base","Intermediaire","Avance","Retour"}; for(i=0;i<NB_ELT_MENU_M;i++){ gotoxy((HORIZONTAL/2)-3,VERTICAL/2+i); printf("%s\n",temp[i]); } while(1){ //Initialise un menu vide qui contiendra les elements initialiss ci-avant char menu[NB_ELT_MENU_M][TAILLE_MAX_ELT_M]={"","","",""}; action =_getch(); //Selectionne un lment selon input grace la fonction Curseur switch(action){ case HAUT: i--; if(i<0){ i=NB_ELT_MENU_M-1; } Curseur(i, titre, NB_ELT_MENU_M, TAILLE_MAX_ELT_M, menu,temp); break; case BAS: i++; if(i>NB_ELT_MENU_M-1){ i=0; } Curseur(i, titre, NB_ELT_MENU_M, TAILLE_MAX_ELT_M, menu,temp); break; //Permet de selectionner le mode de jeu case ESPACE: switch(i){ case 0: system("CLS"); jeu_base(); break; case 1: system("CLS"); jeu_intermediaire(); break; case 2: menu_wip(); break; case 3: retour_menu(); break; } break; } } } void menu_principal() { int action, i=0; //Affiche le nom du menu char titre[] = "Bienvenue sur Snake"; gotoxy((HORIZONTAL/2)-strlen(titre)/2,5); printf("%s",titre); //Initialise les elements du menu char temp[NB_ELT_MENU_P][TAILLE_MAX_ELT_P]={"Modes","Options","Regles","Quitter"}; for(i=0;i<NB_ELT_MENU_P;i++){ gotoxy((HORIZONTAL/2)-3,VERTICAL/2+i); printf("%s\n",temp[i]); } //Nom des programmeurs du ce projet char titre3[] = "CEUNINCK Guillaume & MERLY Erwan"; gotoxy(HORIZONTAL/2-strlen(titre3)/2,VERTICAL+1); printf("%s %c",titre3, 169); while(1){ //Initialise un menu vide qui contiendra les elements initialiss ci-avant char menu[NB_ELT_MENU_P][TAILLE_MAX_ELT_P]={"","","",""}; action =_getch(); //Selectionne un lment selon input grace la fonction Curseur switch(action){ case HAUT: i--; if(i<0){ i=NB_ELT_MENU_P-1; } Curseur(i, titre, NB_ELT_MENU_P, TAILLE_MAX_ELT_P, menu,temp); //Nom des programmeurs du ce projet gotoxy(HORIZONTAL/2-strlen(titre3)/2,VERTICAL+1); printf("%s %c",titre3, 169); break; case BAS: i++; if(i>NB_ELT_MENU_P-1){ i=0; } Curseur(i, titre, NB_ELT_MENU_P, TAILLE_MAX_ELT_P, menu,temp); //Nom des programmeurs du ce projet gotoxy(HORIZONTAL/2-strlen(titre3)/2,VERTICAL+1); printf("%s %c",titre3, 169); break; //Permet de selectionner le menu suivant case ESPACE: switch(i){ case 0: system("CLS"); menu_mode(); break; case 1: system("CLS"); menu_wip(); break; case 2: system("CLS"); menu_regle(); break; case 3: exit(0); break; } break; } } } void menu_mort(snake S) { //Permet d'afficher le message de mort pendant un certain temps avant un retour au menu principal int DELAY = 1500; system("CLS"); char titre[] = "GAME OVER"; gotoxy((HORIZONTAL/2)-strlen(titre)/2, VERTICAL/2); printf("%s", titre); gotoxy(0, VERTICAL); //Permet d'afficher le score menu_score(S.score); Sleep(DELAY); retour_menu(); } void menu_score(int score) { //Permet d'afficher le score en bas de l'cran char titre[] = "SCORE"; gotoxy(0,VERTICAL+1); printf("%s = %d",titre,score); } void menu_wip() { //Indique que Options et Avanc n'ont pu tre ralis dans le temps imparti int DELAY = 1500; system("CLS"); char titre[] = "WORK IN PROGRESS"; gotoxy((HORIZONTAL/2)-strlen(titre)/2, VERTICAL/2); printf("%s", titre); gotoxy(0, VERTICAL); Sleep(DELAY); system("CLS"); menu_principal(); } void retour_menu() { //Permet de retourner au menu principal system("CLS"); menu_principal(); } void retour() { //Permet de retourner au menu principal en jeu et crer un bouton retour int action; char titre[] = "RETOUR"; gotoxy(HORIZONTAL/2,VERTICAL+1); printf("%s",titre); //Retour au menu dclenche par la touche Espace action=_getch(); if(action==ESPACE){ retour_menu(); } } void menu_deplacement(int deplacement) { //Permet d'afficher le nombre de dplacement par Snake en bas de l'cran //Ce compteur est rinitialis ds qu'il mange un fruit (autre fonction) char titre[] = "DEPLACEMENTS = "; gotoxy(HORIZONTAL/2+7,VERTICAL+2); printf("%s%d",titre, deplacement); }
C
typedef enum { typeConstant, typeIdentifier, typeOperator } nodeTEnum; // a node is of type constant, identifier, or operator /* constants hold only values, e.g. 1, 2, 3 ... */ typedef struct { int value; } constantNodeType; //CSI3120 extern int symbol_table[1000]; // this is a reference to the symbol table specified on the yacc (.y) file /* the symbol table is implemented by a simple array of ints (our calculator supports integer only) * so the identifiers nodes contain a index to the symbol table */ typedef struct { int identifier_index; } identifierNodeType; /* operators have id, number of operands, and a pointer to operands that is expanded during parsing * the number of operands depends on the expression and operator, e.g. * a= b - c // '-' operator with two operands that may be solved at runtime; * a= -b // '-' operator with one operand */ typedef struct { int operator_id; int number_of_operands; struct nodeTypeTag *poperands[1]; /* operands expanded during parsing */ } operatorNodeType; typedef struct nodeTypeTag { nodeTEnum type; //type union { //this union is allocated depending on the type, constants, identifiers, operators constantNodeType constant; identifierNodeType identifier; operatorNodeType operator_; }; } nodeType;
C
#include <stdlib.h> #include <stdio.h> #include <math.h> double calculate_response(double freq, double sigma) { /* magnitude response of discrete gaussian kernel */ /* in frequency domain */ /* input frequency is normalized so that the Nyquist */ /* frequency is pi */ double t = sigma * sigma; double response = exp(t*(cos(M_PI*freq)-1)); return response; } double calculate_power_spectrum(double freq, double sigma) { /* power spectrum is response magnitude squared */ /* input frequency is normalized so that the Nyquist */ /* frequency is pi */ double response = calculate_response(freq, sigma); return response * response; } double calculate_sigma(double cutoff_freq, double power_spectrum_level) { /* calculate standard deviation of gaussian filter with */ /* specified cutoff frequency. The cutoff frequency is */ /* defined as the frequency at which the power spectrum */ /* drops below the specified level */ /* input frequency is normalized so that the Nyquist */ /* frequency is pi */ /* the power spectrum level should be between o and 1 */ double t = (0.5 * log(power_spectrum_level)) / (cos(M_PI * cutoff_freq) - 1.0); double sigma = sqrt(t); return sigma; } double calculate_cutoff(double sigma, double power_spectrum_level) { /* calculate the cutoff frequency for a gaussian filter */ /* with given standard deviation. The cutoff frequency */ /* is defined as the frequency at which the power */ /* spectrum drops below the specified level */ /* cutoff frequency is normalized so that the */ /* Nyquist frequency is pi */ double t = sigma * sigma; double cos_cutoff = (1/t) * (0.5 * log(power_spectrum_level)) + 1.0; double cutoff = acos(cos_cutoff) / M_PI; return cutoff; }
C
#include <stdlib.h> #include <stdio.h> #include "libmccdaq.h" int main() { puts("Opening connection..."); OpenConnection(); puts("Opened connection..."); /* TriangleOnce(1., -10, 10); uint n_channels = sizeof(channels); uint n_samples = 600; double frequency = 500; double * data = calloc(n_samples * n_channels, sizeof(double)); SampleChannelsAt10V(channels, n_channels, n_samples, frequency, data); for (uint sample = 0; sample < n_samples; sample++) { if (sample % 50 == 0) { for (uint channel = 0; channel < n_channels; channel++) { printf("%10g ", (double) data[sample * n_channels + channel]); } printf("\n"); } } free(data); uint n_samples = LIBMCCDAQ_BULK_TRANSFER_SIZE / 2; const uint8_t channels[] = {11, 7, 12}; const uint8_t gains[] = {10, 2, 5}; const uint n_channels = 3; uint16_t * data = calloc(n_samples * n_channels, sizeof(uint16_t)); puts("Fetching Scan..."); int ret = FetchScan( 0., 19.99, .2, n_samples, channels, gains, n_channels, kDescent, data); if (ret != 0) { puts("ey!"); } else { puts("Fetched Scan..."); for (uint i = 0; i < n_samples; i++) { if (i % 100 == 0) { printf("%d\t%d\t%d\n", data[3*i], data[3*i + 1], data[3*i + 2]); } } } free(data); char str[12]; sprintf(str, "%d", Ping()); puts(str); */ puts("Pinging"); Ping(); puts("Reading Temps..."); uint16_t * readings = calloc(5 * 4, sizeof(uint16_t)); const uint8_t chans[] = {0, 3, 8, 4}; const uint8_t gns[] = {5, 5, 5, 5}; int ret = SampleChannels(10, 100., chans, gns, 4, readings); if (ret != 0) { puts("ey!"); } else { puts("Fetched Scan..."); for (uint i = 0; i < 10; i++) { printf("%d\t%d\t%d\t%d\n", readings[4*i], readings[4*i + 1], readings[4*i + 2], readings[4*i + 3] ); } } return 0; }
C
#include "../ft_printf.h" int ft_print_char(t_lst list_flags, va_list argv) { if (list_flags.minus == 1 && list_flags.width > 1) { ft_putchar_fd(va_arg(argv, int), 1); ft_add_width(' ', list_flags.width - 1); return (list_flags.width); } else if (list_flags.minus == 0 && list_flags.width > 1) ft_add_width((list_flags.zero) ? '0' : ' ', list_flags.width - 1); ft_putchar_fd(va_arg(argv, int), 1); if (list_flags.width > 1) return (list_flags.width); return (1); }
C
#include "instructions.h" #include <stdio.h> #include <stdlib.h> #include <time.h> #include "screen.h" #include "keyboard.h" void sys_addr(Machine *machine, uint16_t opcode) { fprintf(stdout, "Instruction SYS addr (opcode: %x) not implemented. Aborting...\n", opcode); exit(1); } void cls(Machine *machine, uint16_t opcode) { clear_screen(machine->screen); } void ret(Machine *machine, uint16_t opcode) { machine->cpu->pc = machine->cpu->stack[machine->cpu->sp]; printf("Stack pointer: %x\nJumping to address: %x\n\n", machine->cpu->sp, machine->cpu->pc); machine->cpu->sp -= 1; } void jp_addr(Machine *machine, uint16_t opcode) { uint16_t addr = opcode & 0x0FFF; printf("Jumping to address: %x\n\n", addr); (*machine->cpu).pc = addr; } void call_addr(Machine *machine, uint16_t opcode) { uint16_t addr = opcode & 0x0FFF; machine->cpu->sp += 1; machine->cpu->stack[machine->cpu->sp] = machine->cpu->pc; machine->cpu->pc = addr; } void se_vx_byte(Machine *machine, uint16_t opcode) { uint8_t reg = (opcode & 0x0F00) >> 8; uint8_t byte = opcode & 0x00FF; if (machine->cpu->v[reg] == byte) machine->cpu->pc += 2; } void sne_vx_byte(Machine *machine, uint16_t opcode) { uint8_t reg = (opcode & 0x0F00) >> 8; uint8_t byte = opcode & 0x00FF; if (machine->cpu->v[reg] != byte) machine->cpu->pc += 2; } void se_vx_vy(Machine *machine, uint16_t opcode) { uint8_t reg1 = (opcode & 0x0F00) >> 8; uint8_t reg2 = (opcode & 0x00F0) >> 4; if (machine->cpu->v[reg1] == machine->cpu->v[reg2]) machine->cpu->pc += 2; } void ld_vx_byte(Machine *machine, uint16_t opcode) { uint8_t reg = (opcode & 0x0F00) >> 8; uint8_t byte = opcode & 0x00FF; machine->cpu->v[reg] = byte; } void add_vx_byte(Machine *machine, uint16_t opcode) { uint8_t reg = (opcode & 0x0F00) >> 8; uint8_t byte = opcode & 0x00FF; machine->cpu->v[reg] += byte; } void ld_vx_vy(Machine *machine, uint16_t opcode) { uint8_t reg_x = (opcode & 0x0F00) >> 8; uint8_t reg_y = (opcode & 0x00F0) >> 4; machine->cpu->v[reg_x] = machine->cpu->v[reg_y]; } void or_vx_vy(Machine *machine, uint16_t opcode) { uint8_t reg_x = (opcode & 0x0F00) >> 8; uint8_t reg_y = (opcode & 0x00F0) >> 4; machine->cpu->v[reg_x] = machine->cpu->v[reg_x] | machine->cpu->v[reg_y]; } void and_vx_vy(Machine *machine, uint16_t opcode) { uint8_t reg_x = (opcode & 0x0F00) >> 8; uint8_t reg_y = (opcode & 0x00F0) >> 4; machine->cpu->v[reg_x] = machine->cpu->v[reg_x] & machine->cpu->v[reg_y]; } void xor_vx_vy(Machine *machine, uint16_t opcode) { uint8_t reg_x = (opcode & 0x0F00) >> 8; uint8_t reg_y = (opcode & 0x00F0) >> 4; machine->cpu->v[reg_x] = machine->cpu->v[reg_x] ^ machine->cpu->v[reg_y]; } void add_vx_vy(Machine *machine, uint16_t opcode) { uint8_t reg_x = (opcode & 0x0F00) >> 8; uint8_t reg_y = (opcode & 0x00F0) >> 4; uint16_t sum = machine->cpu->v[reg_x] + machine->cpu->v[reg_y]; machine->cpu->v[reg_x] = sum & 0x00FF; machine->cpu->v[0x0F] = (sum >> 8) >= 1; } void sub_vx_vy(Machine *machine, uint16_t opcode) { uint8_t reg_x = (opcode & 0x0F00) >> 8; uint8_t reg_y = (opcode & 0x00F0) >> 4; machine->cpu->v[reg_x] = machine->cpu->v[reg_x] - machine->cpu->v[reg_y]; machine->cpu->v[0x0F] = machine->cpu->v[reg_x] >= machine->cpu->v[reg_y]; } void shr_vx_vy(Machine *machine, uint16_t opcode) { uint8_t reg_x = (opcode & 0x0F00) >> 8; uint8_t reg_y = (opcode & 0x00F0) >> 4; machine->cpu->v[0x0F] = machine->cpu->v[reg_x] & 0x01; machine->cpu->v[reg_x] /= 2; } void subn_vx_vy(Machine *machine, uint16_t opcode) { uint8_t reg_x = (opcode & 0x0F00) >> 8; uint8_t reg_y = (opcode & 0x00F0) >> 4; machine->cpu->v[reg_x] = machine->cpu->v[reg_y] - machine->cpu->v[reg_x]; machine->cpu->v[0x0F] = machine->cpu->v[reg_y] >= machine->cpu->v[reg_x]; } void shl_vx_vy(Machine *machine, uint16_t opcode) { uint8_t reg_x = (opcode & 0x0F00) >> 8; uint8_t reg_y = (opcode & 0x00F0) >> 4; machine->cpu->v[0x0F] = machine->cpu->v[reg_x] & 0x80; machine->cpu->v[reg_x] *= 2; } void sne_vx_vy(Machine *machine, uint16_t opcode) { uint8_t reg1 = (opcode & 0x0F00) >> 8; uint8_t reg2 = (opcode & 0x00F0) >> 4; if (machine->cpu->v[reg1] != machine->cpu->v[reg2]) machine->cpu->pc += 2; } void ld_i_addr(Machine *machine, uint16_t opcode) { uint16_t addr = opcode & 0x0FFF; machine->cpu->i = addr; } void jp_v0_addr(Machine *machine, uint16_t opcode) { uint16_t addr = opcode & 0x0FFF; machine->cpu->pc = machine->cpu->v[0] + addr; } void rnd_vx_byte(Machine *machine, uint16_t opcode) { srand(time(NULL)); uint8_t byte = opcode & 0x00FF; uint8_t reg_x = (opcode & 0x0F00) >> 8; uint8_t rnd_byte = rand() % 256; machine->cpu->v[reg_x] = rnd_byte & byte; } void drw_vx_vy_nibble(Machine *machine, uint16_t opcode) { uint8_t reg_x = (opcode & 0x0F00) >> 8; uint8_t reg_y = (opcode & 0x00F0) >> 4; uint8_t sprite_lenght = opcode & 0x000F; uint16_t i = machine->cpu->i; uint8_t reg_x_val = machine->cpu->v[reg_x]; uint8_t reg_y_val = machine->cpu->v[reg_y]; for (size_t n = 0; n < sprite_lenght; n++) { uint8_t byte = machine->cpu->memory[i + n]; machine->cpu->v[0x0F] = screen_load_byte(machine->screen, byte, reg_x_val, reg_y_val + n); } screen_draw(machine->screen); } void skp_vx(Machine *machine, uint16_t opcode) { uint8_t reg_x = (opcode & 0x0F00) >> 8; if (machine->keyboard->keystate[reg_x]) machine->cpu->pc += 2; } void sknp_vx(Machine *machine, uint16_t opcode) { uint8_t reg_x = (opcode & 0x0F00) >> 8; if (!machine->keyboard->keystate[reg_x]) machine->cpu->pc += 2; } void ld_vx_dt(Machine *machine, uint16_t opcode) { uint8_t reg_x = (opcode & 0x0F00) >> 8; machine->cpu->v[reg_x] = machine->cpu->delay_timer; } void ld_vx_k(Machine *machine, uint16_t opcode) { uint8_t reg_x = (opcode & 0x0F00) >> 8; machine->cpu->v[reg_x] = wait_until_keypress(machine->keyboard); } void ld_dt_vx(Machine *machine, uint16_t opcode) { uint8_t reg_x = (opcode & 0x0F00) >> 8; machine->cpu->delay_timer = machine->cpu->v[reg_x]; } void ld_st_vx(Machine *machine, uint16_t opcode) { uint8_t reg_x = (opcode & 0x0F00) >> 8; machine->cpu->sound_timer = machine->cpu->v[reg_x]; } void add_i_vx(Machine *machine, uint16_t opcode) { uint8_t reg_x = (opcode & 0x0F00) >> 8; machine->cpu->i += machine->cpu->v[reg_x]; } void ld_f_vx(Machine *machine, uint16_t opcode) { uint8_t reg_x = (opcode & 0x0F00) >> 8; uint8_t sprite_value = reg_x & 0x0F; machine->cpu->i = sprite_value * 5; } void ld_b_vx(Machine *machine, uint16_t opcode) { uint8_t reg_x = (opcode & 0x0F00) >> 8; uint16_t i = machine->cpu->i; uint8_t reg_val = machine->cpu->v[reg_x]; machine->cpu->memory[i] = (reg_val / 100) % 10; machine->cpu->memory[i+1] = (reg_val / 10) % 10; machine->cpu->memory[i+2] = reg_val % 10; } void ld_i_vx(Machine *machine, uint16_t opcode) { uint8_t reg_x = (opcode & 0x0F00) >> 8; uint16_t i = machine->cpu->i; for (size_t reg = 0; reg <= reg_x; reg++) machine->cpu->memory[i + reg] = machine->cpu->v[reg]; } void ld_vx_i(Machine *machine, uint16_t opcode) { uint8_t reg_x = (opcode & 0x0F00) >> 8; uint16_t i = machine->cpu->i; for (size_t reg = 0; reg <= reg_x; reg++) machine->cpu->v[reg] = machine->cpu->memory[i + reg]; }
C
#include<stdio.h> #include<stdlib.h> #include<math.h> struct POINT{ double x,y; }; struct POLYGON{ int n_v; struct POINT v[105]; double area; int id; }; struct ID_CONTAINER{ int id; int container; }; int compar1(const void *a,const void *b){ struct POLYGON *p1=(struct POLYGON *)a,*p2=(struct POLYGON *)b; if(p1->area>p2->area) return 1; if(p1->area<p2->area) return -1; return 0; } int compar2(const void *a,const void *b){ struct ID_CONTAINER *id_con1=(struct ID_CONTAINER *)a,*id_con2=(struct ID_CONTAINER *)b; return id_con1->id-id_con2->id; } void cal_area(struct POLYGON *poly){ int i; poly->area=0; for(i=1;i<poly->n_v;i++) poly->area+=poly->v[i].y*poly->v[i-1].x-poly->v[i].x*poly->v[i-1].y; poly->area+=poly->v[0].y*poly->v[poly->n_v-1].x-poly->v[0].x*poly->v[poly->n_v-1].y; poly->area=fabs(poly->area); } char left(struct POINT *p0,struct POINT *p1,struct POINT *p2){ struct POINT v1,v2; v1.x=p0->x-p1->x,v1.y=p0->y-p1->y; v2.x=p1->x-p2->x,v2.y=p1->y-p2->y; if(v2.y>0&&v1.x*v2.y>v1.y*v2.x) return 1; if(v2.y<0&&v1.x*v2.y<v1.y*v2.x) return 1; return 0; } char cross_threshold(struct POINT *p0,struct POINT *p1,struct POINT *p2){ if(p1->y+1e-5>p0->y&&p2->y<p0->y) return 1; if(p2->y+1e-5>p0->y&&p1->y<p0->y) return 1; return 0; } char is_contain(struct POLYGON *poly,struct POINT *p){ int i,next; char result=0; for(i=0;i<poly->n_v;i++){ next=(i+1)%(poly->n_v); if(cross_threshold(p,&(poly->v[i]),&(poly->v[next]))) if(left(p,&(poly->v[i]),&(poly->v[next]))) result=!result; } return result; } int main(){ int cases; char input[300]; struct POLYGON poly[300]; int n_poly,n_point,i,j,id; struct ID_CONTAINER id_cont[300]; scanf("%d",&cases); while(cases--){ scanf("%d",&n_poly); for(i=0;i<n_poly;i++){ int len; char *ptr; double x,y; scanf("%d",&id); fgets(input,300,stdin); poly[i].id=id; poly[i].n_v=0; for(ptr=input;sscanf(ptr,"%lf%lf%n",&x,&y,&len)==2;ptr+=len){ poly[i].v[poly[i].n_v].x=x; poly[i].v[poly[i].n_v].y=y; poly[i].n_v++; } cal_area(&poly[i]); } qsort(poly,n_poly,sizeof(struct POLYGON),compar1); scanf("%d",&n_point); for(i=0;i<n_point;i++){ struct POINT tmp; scanf("%d",&id); id_cont[i].id=id; scanf("%lf%lf",&tmp.x,&tmp.y); for(j=0;j<n_poly;j++) if(is_contain(&poly[j],&tmp)){ id_cont[i].container=poly[j].id; break; } if(j==n_poly) id_cont[i].container=0; } qsort(id_cont,n_point,sizeof(struct ID_CONTAINER),compar2); for(i=0;i<n_point;i++) printf("%d %d\n",id_cont[i].id,id_cont[i].container); if(cases) puts(""); } return 0; }
C
//这个是用C 语言在求根号二的时候出现的错误; test.c:31:17: error: invalid operands to binary % (have ‘double’ and ‘double’) sp =(double)(x%g); 查了一下,结果表明,只能用int型才行,附上当时写的函数 当时的想法,在进行相除的时候,会有小数点,又想保留多位数的小数点,就将 类型命名为double型的; void genhaosign() { double x = 2; double g = 1; double v =1; double s =0; double sp = 0; double sz = 0; double vz = 0; double vp =0; int i = 0; for(i = 0;i <=100; i++) { sz = (double)(x/g); sp =(double)(x%g); //***这个错误,对数据取余只能是int型。 s=sz+sp; vz = (s+g)/2.0;//整数部分; vp =(s+g)/2.0 ;//小数部分; v = vz+vp; g = v; } printf("%d \n",g); } //判断数字 0 ‘0’ 不一样; 空格(' ')--->32 '0'-------->48 '\0'------->0 #define NULL 0 //int isdigit(int c) void digit() { char str[] ={'1','2','3','k','\0','a','l','*','C'};//这个存在潜在的危险,因为最后一个字符不是0; //char str[]="123ikal00ges3!#$";// 这个的最后一个数是 0;‘\0'; int i; for(i = 0 ; str[i] != '\0'; i++)//所以等价的可以这样表示: str[i] != 0; { if(isdigit(str[i])) { printf("这个算数字 \" %c \"\n",str[i]); } else { printf("NO !\n"); } } //指针; char* s="AAA";//创建了一个字符串常量 cout<<s<<endl; = s[0]='B';//但是却对字符串常量进行赋值,错误; cout<<s<<endl; 5.注意指针要分配给足够的空间 指针分配得空间不够 新手在刚刚接触指针的时候经常会忘记给指针分配空间,直接用肯定是有问题的,那么下面的程序呢? char a;//一个字节 char *str=&a;//指向一个字节的内存 strcpy(str,”hello”);//赋值了6个字节,程序崩溃。 cout<<str; //枚举 声明以及应用; include <stdio.h> int main() { enum JJJ //这个是一个大括号 { CUP=10,AAA=20,BBB //都是整形 }; enum JJJ j; //CUP =CUP +10;//这个是错的,常量不能拿来当左值; j =CUP; j =j +CUP +10; printf("%d \n",j); j =j+AAA; printf("%d \n",j); return 0; } }
C
#include <stdio.h> #define MAX 100 void maior_menor(int vet[],int t,int a,int b){ int menor = vet[1]; int maior = vet[0]; for(int i = 0; i<t ;i++){ if(vet[i] < menor ){ menor = vet[i]; } else if(maior < vet[i]){ maior = vet[i]; } } a = menor; b = maior; printf("menor = %d\n",a); printf("maior = %d",b); } int main() { int t=0; int vet[MAX]; int a; int b; scanf("%d",&t); for(int i=0;i<t;i++){ scanf("%d",&vet[i]); } maior_menor(vet, t,a,b); return(0); }
C
#include "order_system.h" int order_matrix[4][3] = { { 0, 0, 0 }, // first up, elevator, down { 0, 0, 0 }, // second up, elevator, down { 0, 0, 0 }, // third up, elevator, down { 0, 0, 0 } // fourth up, elevator, down }; elev_button_type_t button_type[3] = { BUTTON_CALL_UP, BUTTON_COMMAND, BUTTON_CALL_DOWN }; // If there is any orders, returns true (1) int check_if_any_orders() { for (int i = 0; i < 4; ++i) for (int j = 0; j < 3; ++j) if (order_matrix[i][j] != 0) return 1; return 0; } // Checks for order outside the current floor and returns order int get_order(int current_floor) { for (int i = 0; i < 4; ++i) for (int j = 0; j < 3; ++j) if(order_matrix[i][j] && i != current_floor) return i; } int check_if_pickups(int current_dir, int current_floor) { // When moving up, ignore orders down if (current_dir == 1) { for (int i = 0; i < 2; ++i) { if (order_matrix[current_floor][i]) { return 1; } } } // When moving down, ignore orders up else if (current_dir == -1) { for (int i = 1; i < 3; ++i) { if (order_matrix[current_floor][i]) { return 1; } } } else { return 0; } } void finish_order(int current_floor, int current_dir) { if (current_floor == -1) return; rset_order(current_floor, 1); // When in first or fourth floor, all orders must have been serviced if (current_floor == 0) rset_order(current_floor, 0); else if (current_floor == 3) rset_order(current_floor, 2); // Only remove order in the direction the elevator is moving else if (current_dir == 1) rset_order(current_floor, 0); else if (current_dir == -1) rset_order(current_floor, 2); // curentDir == 0 elevator has landed on this floor, and thus all orders are removed else { rset_order(current_floor, 0); rset_order(current_floor, 2); } } void set_order(int m, int n) { order_matrix[m][n] = 1; // Setting a light that doesnt exist should never happen, but redundancy is good. if(!(m == 3 && n == 0) || !(m == 0 && n == 2)) elev_set_button_lamp(button_type[n], m 1); } void rset_order(int m, int n) { order_matrix[m][n] = 0; // Resetting a light that doesnt exist happens a lot, so must check. if(!(m == 3 && n == 0) || !(m == 0 && n == 2)) elev_set_button_lamp(button_type[n], m = 0); } int check_if_order_above(int current_floor) { for (int i = current_floor + 1; i < 4; ++i) for (int j = 0; j < 3; ++j) if (order_matrix[i][j] != 0) return 1; return 0; } int check_if_order_below(int current_floor) { for (int i = current_floor - 1; i > -1; --i) for (int j = 0; j < 3; ++j) if (order_matrix[i][j] != 0) return 1; return 0; }
C
/* * sqlite.c * Cheap Power Meter * Wait for interrupt from Raspberry Pi GPIO board * and insert row into sqlite database. * * Used with light-dependent resistor connected to the Pi, * to measure power usage from fuse box. One blink equals 1 watt hour * * Read more: http://www.hyggeit.dk/2013/04/super-cheap-web-enabled-power.html * * * Copyright (C) 2013 Lasse Mammen <lasse.mammen@gmail.com> * * 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 3 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, see <http://www.gnu.org/licenses/>. */ #include <sqlite3.h> #include "cpm.h" sqlite3 *pDb; sqlite3_stmt *pStmt; char *database_file; void initialize_db(char *dbfile) { sqlite3 *pDb; int rc; char *zErrMsg = 0; char *sql; const char *sql2 = "INSERT INTO watthours (watthour) VALUES (:usage)"; rc = sqlite3_open_v2(dbfile, &pDb, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL); if (rc) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(pDb)); sqlite3_close(pDb); exit(1); } sql = "CREATE TABLE IF NOT EXISTS watthours ( \ id INTEGER PRIMARY KEY AUTOINCREMENT, \ datetime DATETIME DEFAULT CURRENT_TIMESTAMP, \ watthour INTEGER NOT NULL)"; rc = sqlite3_exec(pDb, sql, NULL, 0, &zErrMsg); if (rc != SQLITE_OK) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); sqlite3_close(pDb); exit(1); } sqlite3_prepare_v2(pDb, sql2, strlen(sql), &pStmt, NULL); } void close_db() { sqlite3_close(pDb); } void insert_data(int reading) { const int index = sqlite3_bind_parameter_index(pStmt, ":usage"); sqlite3_bind_int(pStmt, index, reading); if (sqlite3_step(pStmt) != SQLITE_DONE) { fprintf(stderr, "sqlite: SQL error!\n"); } sqlite3_reset(pStmt); } int get_last_data(int minutes, char *dbfile, sql_data *data) { char *sql; int rc; int index; sqlite3 *lDb; sqlite3_stmt *lStmt; rc = sqlite3_open_v2(dbfile, &lDb, SQLITE_OPEN_READONLY, NULL); if (rc) { fprintf(stderr, "sqlite: Can't open database: %s\n", sqlite3_errmsg(lDb)); sqlite3_close(pDb); exit(1); } sql = "select strftime('%Y-%m-%d', datetime('now', 'utc')) as date, \ strftime('%H:%M', datetime('now', 'utc')) as time, sum(watthour) as watt from watthours \ where datetime > datetime('now', 'utc', '-5 minutes');"; rc = sqlite3_prepare_v2(lDb, sql, strlen(sql), &lStmt, NULL); //index = sqlite3_bind_parameter_index(lStmt, ":minutes"); //rc = sqlite3_bind_int(lStmt, index, minutes); // Using parameters ("?") is not if (rc != SQLITE_OK) { fprintf(stderr, "sqlite: %s\n", sqlite3_errmsg(lDb)); sqlite3_finalize(lStmt); sqlite3_close(lDb); return 0; } rc = sqlite3_step(lStmt); if (rc != SQLITE_ROW && rc != SQLITE_DONE) { fprintf(stderr, "sqlite: %s\n", sqlite3_errmsg(lDb)); sqlite3_finalize(lStmt); sqlite3_close(lDb); return 0; } if (rc == SQLITE_DONE) { sqlite3_finalize(lStmt); if (verbose_flag) { fprintf(stderr, "sqlite: No data in query\n"); } sqlite3_close(lDb); return 0; } if (sqlite3_column_int(lStmt, 2) == 0) { sqlite3_finalize(lStmt); if (verbose_flag) { fprintf(stderr, "sqlite: Stale data (err: 1)\n"); } sqlite3_close(lDb); return 0; } data->date = allocate_str((char*) sqlite3_column_text(lStmt, 0)); data->time = allocate_str((char*) sqlite3_column_text(lStmt, 1)); data->watt = sqlite3_column_int(lStmt, 2); sqlite3_finalize(lStmt); sqlite3_close(lDb); return 1; }
C
/* Example for tRF Click Date : apr 2018. Author : Katarina Perendic Test configuration PIC : MCU : P18F87K22 Dev. Board : EasyPIC PRO v7 PIC Compiler ver : v7.2.0.0 --- Description : The application is composed of three sections : - System Initialization - Intializes UART module - Application Initialization - Driver intialization - Application Task - (code snippet) - Checks if new data byte have received in rx buffer (ready for reading), and if ready than reads one byte from rx buffer. In second case aplication task writes message data via UART. */ #include "Click_tRF_types.h" #include "Click_tRF_config.h" const uint8_t MESSAGE_DATA[9] = { 'M', 'i', 'k', 'r', 'o', 'E', 13, 10, 0 }; void systemInit() { mikrobus_uartInit( _MIKROBUS1, &_TRF_UART_CFG[0] ); mikrobus_logInit( _MIKROBUS3, 19200 ); Delay_ms( 100 ); } void applicationInit() { trf_uartDriverInit( (T_TRF_P)&_MIKROBUS1_GPIO, (T_TRF_P)&_MIKROBUS1_UART ); mikrobus_logWrite( "Initialized", _LOG_LINE ); Delay_ms( 100 ); } void applicationTask() { char tmp; uint8_t rdyFlag; // RECEIVER - UART polling rdyFlag = trf_byteReady(); if (1 == rdyFlag) { tmp = trf_readByte(); mikrobus_logWrite( &tmp, _LOG_BYTE ); } // TRANSMITER - TX each 2 sec /*for (tmp = 0; tmp < 9; tmp++) { trf_writeByte( MESSAGE_DATA[tmp] ); mikrobus_logWrite( "MESSAGE SENT", _LOG_LINE ); } Delay_ms(2000);*/ } void main() { systemInit(); applicationInit(); while (1) { applicationTask(); } }
C
/*> stdgui.h <* * * Date: 25/10/1998 * Last Change: 28/11/1998 * * * By NSJ aka Viriato 1998 * * USE AT YOUR OWN RISK, NO WARANTIES OF ANY KIND ARE GIVEN */ #ifndef __stdgui_h__ #define __stdgui_h__ #ifndef NULL #define NULL 0x0 #endif #define RESETMODE set_wrt_mode(0); #define SETMODE set_wrt_mode(1); #define XORMODE set_wrt_mode(2); #define GETMODE set_wrt_mode(3); // Drawing mode consts (line and pixel) #define dRESET 0 #define dSET 1 #define dXOR 2 #define dGET 3 typedef struct TWIN { uchar x1; // Window Total Area uchar y1; uchar x2; uchar y2; uchar maxX, maxY; // Max relative to window's top left corner char has_border; char *title; // If NULL, window has no title bar int display_fn; // Addr of display function (if NULL isn't used) TWIN *next; // Ptr to next window } dll STDGUI { uint SDTGUI () export 0; void initGUI () export 1; void set_wrt_mode (char mode) export 2; void clear () export 3; void pixel (uchar x, uchar y) export 4; uchar getpixel (uchar x, uchar y) export 5; void hline (uchar x1, uchar x2, uchar y) export 6; void vline (uchar x, uchar y1, uchar y2) export 7; void line (uchar x1, uchar y1, uchar x2, uchar y2) export 8; // has no clip yet void rect (uchar x1, uchar y1, uchar x2, uchar y2) export 9; void bar (uchar x1, uchar y1, uchar x2, uchar y2) export 10; void circle (uchar x, uchar y, uchar ray) export 11; // not implemented void poly () export 12; // not implemented void fill_area () export 13; // not implemented void dumm () export 14; // not implemented void create_window (TWIN *win) export 15; void destroy_window (TWIN *win) export 16; // Still buggy... void set_window_title (TWIN *win, char *tit) export 17; void set_window_pos (TWIN *win, uchar x, uchar y) export 18; void set_window_size (TWIN *win, uchar dx, uchar dy) export 19; void show_window (TWIN *win) export 20; void clear_window (TWIN *win) export 21; void set_top_window (TWIN *win) export 22; void change_top_window () export 23; void redraw_all () export 24; // Still missing some cool text function(s) } #endif
C
// // link.c // day10 // // Created by waitwalker on 2021/5/19. // #include "link.h" #include <stdlib.h> #include <string.h> /// 做的是头部之前插入 要把这个节点插在head之前 STU *insertLink(STU *head, STU tmp) { /// 第一次的时候链表应该是空的 ///1. 从堆区空间申请一个待插入的节点空间 STU *pi = (STU *)calloc(1, sizeof(STU)); if (pi == NULL) { perror("error"); return head; } ///2. 将tmp值赋值给 *pi *pi = tmp; pi->next = NULL; //3. 插入链表 if (head == NULL) { /// 链表不存在 head = pi; } else { /// 链表存在(链表头部插入) /// 第一步将pi插入到head之前,指向旧的头部 pi->next = head; /// 第二步将head移到最前面, head指向最新的头节点 head = pi; } return head; } STU *insertLinkEnd(STU *head, STU tmp) { ///1. 为待插入的节点申请空间 必须要做的 STU *pi = (STU *)calloc(1, sizeof(STU)); if (pi == NULL) { perror("pi error"); return head; } ///2. 将tmp数据赋值到*pi里面 *pi = tmp; pi->next = NULL; if (head == NULL) { head = pi; } else { /// 不要随意操作head节点 STU *pd = head; ///2.1 先找到尾部节点 while (pd->next != NULL) { pd = pd->next; } ///2.2 找到尾部的next 为 NULL时将插入节点赋值给尾节点的next if (pd->next == NULL) { pd->next = pi; } } return head; } STU *insertLinkOrder(STU *head, STU tmp) { ///1. 给待插入的节点 申请堆区空间 STU *pi = (STU *)calloc(1, sizeof(STU)); if (pi == NULL) { perror("error"); return head; } ///2. 给申请的空间赋值 将tmp赋值给*pi *pi = tmp; pi->next = NULL; ///3. 将节点插入链表 ///3.1 链表不存在 if (head == NULL) { head = pi; } else { ///3.2 链表存在 ///a 寻找插入点 STU *pb = head; /// 借助一个变量 这个变量保存pb前一个变量 STU *pf = head; /// 如果pb的num比插入的节点的num小同时还没有越界,也就是pb->next != NULL /// 第一个判断语句不成立,说明pi >= Pb 插入要在中间或者前部 /// 第二个判断语句不成立,说明遍历到链表尾部还没有找到比pi大的,说明pi最大,插入在尾部 while (pb->num < pi->num && pb->next != NULL) { /// 先保存pf的位置 pf = pb; pb = pb->next; } // 头部或中部插入 if (pb->num >= pi->num) { /// 头部插入 if (pb == head) { /// 指向旧的头 pi->next = head; /// 更新新的头 head = pi; return head; } else { /// 中部插入 pf->next = pi; pi->next = pb; return head; } } else { /// 找到末尾了 pb->next = pi; return head; } } return head; } STU *searchLink(STU *head, char *name) { ///1. 先判断链表是否存在 if (head == NULL) { perror("link is NULL"); return NULL; } /// 查询链表 STU *pb = head; /// 判断pb是否是末尾并且比较字符串 while (pb->next != NULL && strcmp(name, pb->name) != 0) { pb = pb->next; } if (strcmp(name, pb->name) == 0) { return pb; } else { return NULL; } } STU *deleteLink(STU *head, char *name) { /// 判断链表是否存在 if (head == NULL) { perror("link is NULL"); return head; } /// 实例化一个操作节点 STU *pb = head; STU *pf = head; ///1. 寻找删除点的位置 /// 不相等往下走 同时 不能越界 while (strcmp(pb->name, name) != 0 && pb->next != NULL) { pf = pb; pb = pb->next; } ///2. 找到删除点的位置 if (strcmp(pb->name, name) == 0) { ///3.判断删除节点的位置 ///3.1 删除的节点是头节点 if (pb == head) { head = pb->next; free(pb); printf("删除姓名:%s节点成功\n",name); return head; } else { ///3.2 删除点节点是中部节点 pf->next = pb->next; free(pb); printf("删除姓名:%s节点成功\n",name); return head; } } else { printf("链表中没有查找到待删除数据节点:%s\n",name); return head; } return head; } STU *freeLink(STU *head) { /// 判断链表是否为空 if (head == NULL) { perror("link is NULL"); return head; } else { /// 创建一个操作节点 STU *pd = head; /// 逐个节点释放 while (pd != NULL) { /// head 先保存下一个节点的位置 head = pd->next; /// 释放pd指向的节点 free(pd); /// pd指向head位置 pd = head; } printf("链表释放完成:\n"); return head; } return head; } STU *reverseLink(STU *head) { ///1. 判断链表是否存在 if (head == NULL) { perror("link is NULL"); return head; } else { /// 声明两个中间变量 STU *pb, *pr; /// 首先pb 保存head的下一个节点 pb = head->next; /// 将head的next指针置为NULL head->next = NULL; while (pb != NULL) { /// pr保存pb的next,因为pb的next即将指向head,逆转方向 pr = pb->next; /// 将pd的next转向,指向head pb->next = head; /// head 位置移动到pb位置 head = pb; /// pb移动到pr位置 pb = pr; } printf("链表逆序成功\n"); return head; } return head; } void printLink(STU *head) { if (head == NULL) { printf("链表不存在\n"); return; } STU *pb = head;/// 不要随意操作头节点 while (pb != NULL) { printf("节点当前信息: %d %s %.1f\n",pb->num, pb->name, pb->score); pb = pb->next; } return; }
C
#include<stdio.h> #include<string.h> typedef struct{ char Name[100]; char No[100]; int Grade; }StuType; int main(){ int N,i,j; StuType tmp,max,min; max.Grade=0; min.Grade=100; scanf("%d",&N); for(i=0;i<N;i++){ scanf("%s %s %d",tmp.Name,tmp.No,&tmp.Grade); if(tmp.Grade>max.Grade) max=tmp; if(tmp.Grade<min.Grade) min=tmp; } printf("%s %s\n",max.Name,max.No); printf("%s %s",min.Name,min.No); return 0; }
C
/************************************************************************************ * Copyright (c) 2017 by Ian G. Tayler <ian.g.tayler@gmail.com> * * This file is part of Markovman. * * * * Markovman is distributed as free software under the Artistic License 2.0. * * You should have received a copy of the license together with the source files * * for Markovman. It should be in the main directory, in a file named 'LICENSE'. * ************************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "minunit.h" #include "statemachfull.h" #include "lexerfull.h" #define PLANNED 5 int tests_run = 0; /* * TESTING THE UNIT TEST LIBRARY. */ char *mu_fine_test() { mu_assert("MinUnit isn't working properly", 1); return 0; } /* * TESTING statemach.c */ char *word_basic_allocation_test() { Word *wordptr = (Word*) malloc(sizeof(Word)); wordptr->token = "Walterman"; wordptr->freqlist = malloc(sizeof(int) * 4); int temparray[4] = {23, 17, 65, 34}; memcpy(wordptr->freqlist, temparray, sizeof(int) * 4); mu_assert_running("Allocation of Word didn't work", strcmp("Walterman", wordptr->token) == 0,\ { free(wordptr->freqlist); free(wordptr); }); mu_assert_running("Allocation of Word's freqlist didn't work", wordptr->freqlist[2] == 65, { free(wordptr->freqlist); free(wordptr); }); free(wordptr); /* If we haven't returned yet, then we're fine */ return 0; } /* * TESTING lexer.c */ char *append_test() { int curr_size = sizeof(char) * 2; char *dynstr = malloc(curr_size); curr_size = append_char(&dynstr, 'O', 0, curr_size); curr_size = append_char(&dynstr, 'K', 1, curr_size); curr_size = append_char(&dynstr, 0, 2, curr_size); mu_assert_freeing("Dynstr didn't grow as expected", curr_size == 4, dynstr); mu_assert_freeing("Characters set incorrectly in append_test", dynstr[0] == 'O' && dynstr[1] == 'K' && dynstr[2] == 0, dynstr); return 0; } char *lexer_test() { FILE *fd = fopen("resources/testfile1.txt", "r"); char endchar; mu_assert("Couldn't open file in lexer_test\n", fd != NULL); char *ftoken = get_next_token(fd, &endchar); /* it's a bit hard being safe in this one. */ mu_assert_freeing("Got the wrong token in lexer_test", strcmp(ftoken, "John") == 0, ftoken); free(ftoken); mu_assert("Didn't correctly detect the end symbol in lexer_test", endchar == ' '); char *stoken = get_next_token(fd, &endchar); mu_assert_freeing("Got the wrong second token in lexer_test", strcmp(stoken, "Lennon") == 0, stoken); free(stoken); mu_assert("Didn't correctly detect the second end symbol in lexer_test", endchar == ','); if (fclose(fd) != 0) { fprintf(stderr, "Couldn't properly close file in lexer_test\n"); } return 0; } char *induce_test() { FILE *fd = fopen("resources/testfile1.txt", "r"); Markov *markovman = induce_markov(fd); mu_assert_running("Wrong number of induced words", markovman->lengthwl == 7, free_Markov(markovman);); mu_assert_running("Wrong number of initial words", markovman->lengthip == 1, free_Markov(markovman);); if (fclose(fd) != 0) { fprintf(stderr, "Couldn't properly close file in induce_test\n"); } return 0; } char *all_tests() { /* MinUnit tests */ mu_run_test(mu_fine_test); /* lib/statemach.c tests */ mu_run_test(word_basic_allocation_test); mu_run_test(induce_test); /* lib/lexer.c tests */ mu_run_test(append_test); mu_run_test(lexer_test); return 0; } int main (void) { char *mess = all_tests(); if (mess != NULL) { printf("ERROR: %s\n.", mess); } else { printf("ALL TESTS PASSED.\n"); } printf("RAN %d TESTS. %d PLANNED.\n", tests_run, PLANNED); return mess != NULL; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* rotate.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jhallama <jhallama@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/27 18:01:26 by jhallama #+# #+# */ /* Updated: 2021/07/07 14:11:22 by jhallama ### ########.fr */ /* */ /* ************************************************************************** */ #include "checker.h" void ra(t_stacks *stacks) { size_t i; int tmp; tmp = stacks->a[0]; i = 0; while (i < stacks->a_size - 1 && stacks->a_size) { stacks->a[i] = stacks->a[i + 1]; i++; } stacks->a[i] = tmp; } void rb(t_stacks *stacks) { size_t i; int tmp; tmp = stacks->b[0]; i = 0; while (i < stacks->b_size - 1 && stacks->b_size) { stacks->b[i] = stacks->b[i + 1]; i++; } stacks->b[i] = tmp; } void rra(t_stacks *stacks) { size_t i; int tmp; tmp = stacks->a[stacks->a_size - 1]; i = stacks->a_size - 1; while (i) { stacks->a[i] = stacks->a[i - 1]; i--; } stacks->a[0] = tmp; } void rrb(t_stacks *stacks) { size_t i; int tmp; tmp = stacks->b[stacks->b_size - 1]; i = stacks->b_size - 1; while (i) { stacks->b[i] = stacks->b[i - 1]; i--; } stacks->b[0] = tmp; }
C
// // test.c // 第一个C程序 // // Created by 潘易 on 14-8-31. // Copyright (c) 2014年 xinlan. All rights reserved. // #include <stdio.h> void test() { printf("Test()函数被调用!\n"); }//end function test() int add(int a,int b) { int ret = a + b; printf("%d + %d = %d\n",a,b,ret); return ret; }//end add function
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "personal.h" extern struct personal_data_format *Data; extern int Data_num; int Attest( void ) { int i; char input_name[50]; char input_pass[50]; printf( "name:" ); scanf( "%s", input_name ); printf( "pass:" ); scanf( "%s", input_pass ); printf( "\n" ); for( i = 0; i < Data_num; i++ ) { if( strcmp( ( Data + i )->name, input_name ) == 0 ) { if( strcmp( ( Data + i )->pass, input_pass ) == 0 ) { return( 0 ); } } } return( 1 ); }
C
/* File: list_linked.c */ /* Implementasi Linked List */ #include <stdio.h> #include <list_linked.h> /* Definisi List : */ /* List kosong : FIRST(l) = NULL */ /* Setiap elemen dengan Address p dapat diacu INFO(p), NEXT(p) */ /* Elemen terakhir list: jika addressnya Last, maka NEXT(Last)=NULL */ /* PROTOTYPE */ /****************** PEMBUATAN LIST KOSONG ******************/ void CreateList(LinkedList *l){ /* I.S. sembarang */ /* F.S. Terbentuk list kosong */ FIRST(*l) = NULL; } /****************** TEST LIST KOSONG ******************/ boolean isEmpty(LinkedList l){ /* Mengirim true jika list kosong */ return FIRST(l) == NULL; } /****************** GETTER SETTER ******************/ Pesanan getElmt(LinkedList l, int idx){ /* I.S. l terdefinisi, idx indeks yang valid dalam l, yaitu 0..length(l) */ /* F.S. Mengembalikan nilai elemen l pada indeks idx */ // tetep harus dicacah dari nol int idxcount = 0; Address p = FIRST(l); while (idxcount<idx){ idxcount += 1; p = NEXT(p); } return INFO(p); } void setElmt(LinkedList *l, int idx, Pesanan val){ /* I.S. l terdefinisi, idx indeks yang valid dalam l, yaitu 0..length(l) */ /* F.S. Mengubah elemen l pada indeks ke-idx menjadi val */ int idxcount = 0; Address p = FIRST(*l); while (idxcount<idx){ idxcount += 1; p = NEXT(p); } INFO(p) = val; } int indexOf(LinkedList l, Pesanan val){ /* I.S. l, val terdefinisi */ /* F.S. Mencari apakah ada elemen list l yang bernilai val */ /* Jika ada, mengembalikan indeks elemen pertama l yang bernilai val */ /* Mengembalikan IDX_UNDEF jika tidak ditemukan */ int idxcount = 0; Address p = FIRST(l); boolean found = false; while (p != NULL && !found){ if (isEqualPesanan(INFO(p),val)){ found = true; } else { idxcount += 1; p = NEXT(p); } } if (found){ return idxcount; } else { return IDX_UNDEF; } } /****************** PRIMITIF BERDASARKAN NILAI ******************/ /*** PENAMBAHAN ELEMEN ***/ void insertFirst(LinkedList *l, Pesanan val){ /* I.S. l mungkin kosong */ /* F.S. Melakukan alokasi sebuah elemen dan */ /* menambahkan elemen pertama dengan nilai val jika alokasi berhasil. */ /* Jika alokasi gagal: I.S.= F.S. */ Address p = newNode(val); if (p != NULL){ NEXT(p) = FIRST(*l); FIRST(*l) = p; } } void insertLastLL(LinkedList *l, Pesanan val){ /* I.S. l mungkin kosong */ /* F.S. Melakukan alokasi sebuah elemen dan */ /* menambahkan elemen list di akhir: elemen terakhir yang baru */ /* bernilai val jika alokasi berhasil. Jika alokasi gagal: I.S.= F.S. */ if(isEmpty(*l)){ // kondisi jika l kosong insertFirst(l,val); } else { // jika l tidak kosong Address p = newNode(val); Address last = FIRST(*l); // lakukan pencarian terhadap address last while (NEXT(last) != NULL){ last = NEXT(last); } // address elemen terakhir sudah ketemu NEXT(last) = p; } } void insertAt(LinkedList *l, Pesanan val, int idx){ /* I.S. l tidak mungkin kosong, idx indeks yang valid dalam l, yaitu 0..length(l) */ /* F.S. Melakukan alokasi sebuah elemen dan */ /* menyisipkan elemen dalam list pada indeks ke-idx (bukan menimpa elemen di i) */ /* yang bernilai val jika alokasi berhasil. Jika alokasi gagal: I.S.= F.S. */ if (idx == 0){ insertFirst(l,val); } else { Address p = newNode(val); if (p != NULL){ int idxcount = 0; Address location = FIRST(*l); while (idxcount<idx-1){ idxcount += 1; location = NEXT(location); } // ketika idxcount == idx -1 NEXT(p) = NEXT(location); // next p menunjuk ke address index ke-idx+1 NEXT(location) = p; // next dari location menuju ke address index ke-idx } } } /*** PENGHAPUSAN ELEMEN ***/ void deleteFirst(LinkedList *l, Pesanan *val){ /* I.S. List l tidak kosong */ /* F.S. Elemen pertama list dihapus: nilai info disimpan pada x */ /* dan alamat elemen pertama di-dealokasi */ Address p = FIRST(*l); *val = INFO(p); FIRST(*l) = NEXT(p); free(p); } void deleteLastLL(LinkedList *l, Pesanan *val){ /* I.S. list tidak kosong */ /* F.S. Elemen terakhir list dihapus: nilai info disimpan pada x */ /* dan alamat elemen terakhir di-dealokasi */ Address p = FIRST(*l); Address location = NULL; while (NEXT(p) != NULL){ location = p; p = NEXT(p); // location selalu di belakang p } if (location == NULL){ // jika elemen list l hanya 1 FIRST(*l) = NULL; } else { NEXT(location) = NULL; } *val = INFO(p); free(p); } void deleteAt(LinkedList *l, int idx, Pesanan *val){ /* I.S. list tidak kosong, idx indeks yang valid dalam l, yaitu 0..length(l) */ /* F.S. val diset dengan elemen l pada indeks ke-idx. */ /* Elemen l pada indeks ke-idx dihapus dari l */ if (idx == 0){ deleteFirst(l,val); } else { int idxcount = 0; Address location = FIRST(*l); while (idxcount<idx-1){ idxcount += 1; location = NEXT(location); } Address p = NEXT(location); *val = INFO(p); NEXT(location) = NEXT(p); free(p); } } /****************** PROSES SEMUA ELEMEN LIST ******************/ int lengthLL(LinkedList l){ /* Mengirimkan banyaknya elemen list; mengirimkan 0 jika list kosong */ int idxcount = 0; Address p = FIRST(l); while (p != NULL){ idxcount += 1; p = NEXT(p); } return idxcount; } /* PICK_UP */ int indexOfPesananBuilding(LinkedList to_do, char building){ /* Mengirimkan index pertama to_do yang bangunan pick up pesanannya adalah building atau IDX_UNDEF jika tidak ada */ int idxcount = 0; Address p = FIRST(to_do); boolean found = false; while (p != NULL && !found){ if (PICKUPPESANAN(INFO(p)) == building){ found = true; } else { idxcount += 1; p = NEXT(p); } } if (found){ return idxcount; } else { return IDX_UNDEF; } } int indexOfVIP(LinkedList to_do, char building){ int idxcount = 0; Address p = FIRST(to_do); boolean found = false; while (p != NULL && !found){ if (PICKUPPESANAN(INFO(p)) == building && TIPEITEM(INFO(p))=='V'){ found = true; } else { idxcount += 1; p = NEXT(p); } } if (found){ return idxcount; } else { return IDX_UNDEF; } } Address fSearch(LinkedList L, Pesanan P){ /* Mencari alamat elemen list yang valuenya P */ /* KAMUS */ Address p = FIRST(L); boolean found = false; while (p != NULL && !found){ if (isEqualPesanan(INFO(p),P)){ found = true; } else { p = NEXT(p); } } if (found){ return p; } else { return NULL; } } void DecrementAllPerishableItem(LinkedList *L, int decr){ /* KAMUS */ Address p = FIRST(*L); /* ALGORITMA */ while (p != NULL){ if(TIPEITEM(INFO(p))=='P'){ subtractPtime(&INFO(p), decr); } p = NEXT(p); } } int countWeight(LinkedList L){ /* KAMUS */ Address p = FIRST(L); int sum = 0; /* ALGORITMA */ while (p != NULL){ sum += WEIGHT(INFO(p)); p = NEXT(p); } return sum; } void setBackWeight(LinkedList *L){ /* KAMUS */ Address p = FIRST(*L); /* ALGORITMA */ while (p != NULL){ if(TIPEITEM(INFO(p))=='H'){ WEIGHT(INFO(p)) = 1; } p = NEXT(p); } }
C
#include <GL/glew.h> #include <GL/glut.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdarg.h> #include <math.h> #include "shaders.h" struct shader_program { GLuint program; GLuint vshad, fshad; char *name; char *vshadName, *fshadName; char *vshadFileName, *fshadFileName; }; static void initShader(struct shader_program *p); static int loadShaders(struct shader_program *p, const char *vshad, const char *fshad); static int loadShaderFromFile(GLuint shader, const char *filename); static int loadShaderFromFiles(GLuint shader, int n, ...); static int compile(GLuint shader); static int link(GLuint program); struct shader_program *newShader(const char *vshad, const char *fshad) { struct shader_program *p; p = (struct shader_program *)malloc(sizeof(struct shader_program)); initShader(p); loadShaders(p, vshad, fshad); return p; } void initShader(struct shader_program *p) { memset(p, 0, sizeof(struct shader_program)); p->program = glCreateProgram(); p->vshad = glCreateShader(GL_VERTEX_SHADER); glAttachShader(p->program, p->vshad); p->fshad = glCreateShader(GL_FRAGMENT_SHADER); glAttachShader(p->program, p->fshad); } int loadShaders(struct shader_program *p, const char *vshad, const char *fshad) { int status; fprintf(stderr, "Loading vertex shader %s...\n", vshad); if (p->vshadFileName) free(p->vshadFileName); p->vshadFileName = (char *)malloc(sizeof(char) * (strlen(vshad) + 1)); strcpy(p->vshadFileName, vshad); status = loadShaderFromFiles(p->vshad, 2, vshad, "shaders/noise4D.glsl"); fprintf(stderr, "Loading fragment shader %s...\n", fshad); if (p->fshadFileName) free(p->fshadFileName); p->fshadFileName = (char *)malloc(sizeof(char) * (strlen(fshad) + 1)); strcpy(p->fshadFileName, fshad); status |= loadShaderFromFile(p->fshad, fshad); if (status == 0) status = link(p->program); return status; } void reloadShaders(struct shader_program *p) { loadShaders(p, p->vshadFileName, p->fshadFileName); } int changeVertexShader(struct shader_program *p, const char *vshad) { int status; fprintf(stderr, "Loading vertex shader %s...\n", vshad); if (p->vshadFileName) free(p->vshadFileName); p->vshadFileName = (char *)malloc(sizeof(char) * (strlen(vshad) + 1)); strcpy(p->vshadFileName, vshad); status = loadShaderFromFiles(p->vshad, 2, vshad, "shaders/noise4D.glsl"); if (status == 0) status = link(p->program); return status; } int changeFragmentShader(struct shader_program *p, const char *fshad) { int status; fprintf(stderr, "Loading fragment shader %s...\n", fshad); if (p->fshadFileName) free(p->fshadFileName); p->fshadFileName = (char *)malloc(sizeof(char) * (strlen(fshad) + 1)); strcpy(p->fshadFileName, fshad); status = loadShaderFromFile(p->fshad, fshad); if (status == 0) status = link(p->program); return status; } void switchToShader(struct shader_program *p) { glUseProgram(p->program); } void updateShaderUniforms(struct shader_program *p) { GLint var; float t; int width, height; glUseProgram(p->program); t = (float)glutGet(GLUT_ELAPSED_TIME) / 1000; width = glutGet(GLUT_WINDOW_WIDTH); height = glutGet(GLUT_WINDOW_HEIGHT); var = glGetUniformLocation(p->program, "time"); if (var != -1) glUniform1f(var, t); var = glGetUniformLocation(p->program, "resolution"); if (var != -1) glUniform2i(var, width, height); var = glGetUniformLocation(p->program, "pos"); if (var != -1) glUniform3f(var, 15.0 * cos(t / 10.0), 15.0 * sin(t / 10.0), 3.0 * sin(t / 4.0)); var = glGetUniformLocation(p->program, "fade"); if (var != -1) glUniform1f(var, 1.0); var = glGetUniformLocation(p->program, "light"); if (var != -1) glUniform3f(var, 10.0, 10.0, 10.0); } int loadShaderFromFile(GLuint shader, const char *filename) { char *shaderText; FILE *shaderFile; GLint len; /* TODO read as binary because of \r\n, maybe there's a better way.*/ if ((shaderFile = fopen(filename, "rb")) == NULL) { fprintf(stderr, "failed to open shader source file: %s\n", filename); return 1; } /* TODO catch errors in file reading*/ fseek(shaderFile, 0, SEEK_END); len = ftell(shaderFile); rewind(shaderFile); /* TODO this leaks memory */ shaderText = (char *)malloc(len+1); fread(shaderText, 1, len, shaderFile); shaderText[len]=0; fclose(shaderFile); glShaderSource(shader, 1, (const char **)&shaderText, &len); if (compile(shader) == 0) { fprintf(stderr, "Loaded and compiled successfully.\n"); return 0; } else { return 1; } } int loadShaderFromFiles(GLuint shader, int n, ...) { char **shaderText; FILE *shaderFile; GLint *len; va_list filenames; int i; const char *filename; shaderText = (char **)malloc(n * sizeof(char *)); len = (GLint *)malloc(n * sizeof(GLint)); va_start(filenames, n); for(i = 0; i < n; i++) { filename = va_arg(filenames, const char *); /* TODO read as binary because of \r\n, maybe there's a better way.*/ if ((shaderFile = fopen(filename, "rb")) == NULL) { fprintf(stderr, "failed to open shader source file: %s\n", filename); return 1; } /* TODO catch errors in file reading*/ fseek(shaderFile, 0, SEEK_END); len[i] = ftell(shaderFile); rewind(shaderFile); /* TODO this leaks memory */ shaderText[i] = (char *)malloc(len[i]+1); fread(shaderText[i], 1, len[i], shaderFile); shaderText[i][len[i]]=0; fclose(shaderFile); } va_end(filenames); glShaderSource(shader, n, (const char **)shaderText, len); return compile(shader); } int compile(GLuint shader) { int status; char *infoLog; int logLen; fprintf(stderr, "\tCompiling shader...\n"); glCompileShader(shader); glGetShaderiv(shader, GL_COMPILE_STATUS, &status); if (status != GL_TRUE) { glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLen); infoLog = (char *)malloc(logLen * sizeof(char)); glGetShaderInfoLog(shader, logLen, NULL, infoLog); fprintf(stderr, "Shader failed to compile:\n%s\n", infoLog); return 1; } fprintf(stderr, "\tCompiled successfully.\n"); return 0; } int link(GLuint program) { int status; char *infoLog; int logLen; fprintf(stderr, "Linking shader program...\n"); glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &status); if (status != GL_TRUE) { glGetProgramiv(program, GL_INFO_LOG_LENGTH, &logLen); infoLog = (char *)malloc(logLen * sizeof(char)); glGetProgramInfoLog(program, logLen, NULL, infoLog); fprintf(stderr, "Program failed to link:\n%s\n", infoLog); return 1; } fprintf(stderr, "Linked successfully.\n"); return 0; }
C
/* 02.02.2021 Ozel Veri Yapisi tanimlama Struct Union yapilarinin ortak kullanimi */ #include <stdio.h> #include <stdlib.h> #pragma pack(1) #define VTTYPE_EMPTY 0 #define VTTYPE_BYTE 1 #define VTTYPE_WORD 2 #define VTTYPE_LONG 3 #define VTTYPE_FLOAT 4 typedef struct MYVAR{ unsigned char type; union { char chVal; short shVal; int iVal; double dfVal; }; }MYVAR; int main() { MYVAR tm; tm.type = VTTYPE_FLOAT; tm.dfVal = 5343.67; printf("MYVAR sizeof = %d\n" , sizeof(tm) ); if( tm.type == VTTYPE_EMPTY ) printf("Value is empty!\n"); else if( tm.type == VTTYPE_BYTE ) printf("BYTE = %X\n" , tm.chVal ); else if( tm.type == VTTYPE_WORD ) printf("Word = %d\n" , tm.shVal ); else if( tm.type == VTTYPE_LONG ) printf("Long = %lf\n" , tm.iVal ); else if( tm.type == VTTYPE_FLOAT ) printf("Float = %lf\n" , tm.dfVal ); return 0; }
C
#include <asm/pic.h> #include <asm/io.h> #include <asm/irq_vector.h> #include <kernel/printk.h> /* * http://www.brokenthorn.com/Resources/OSDevPic.html */ /* * i8259A PIC registers */ #define PIC_MASTER_BASE_ADDR 0x20 /* IO base address for master PIC */ #define PIC_SLAVE_BASE_ADDR 0xa0 /* IO base address for slave PIC */ #define PIC_MASTER_COMMAND (PIC_MASTER_BASE_ADDR) #define PIC_MASTER_DATA (PIC_MASTER_BASE_ADDR + 1) #define PIC_SLAVE_COMMAND (PIC_SLAVE_BASE_ADDR) #define PIC_SLAVE_DATA (PIC_SLAVE_BASE_ADDR + 1) /* * i8259A PIC related values */ #define PIC_ICW1_INIT 0x10 /* Initialization - required */ #define PIC_ICW1_ICW4 0x01 /* Indicates that ICW4 will be present */ #define PIC_ICW4_8086 0x01 /* 8086/88 (MCS-80/85) mode */ #define PIC_ICW4_AUTO 0x02 /* Auto (normal) EOI */ #define PIC_CASCADE_IR 2 /* Cascade on IRQ 2 */ /* * This contains the irq mask for both 8259A irq controllers, */ static unsigned int cached_irq_mask = 0xffff; #define cached_master_mask (cached_irq_mask) #define cached_slave_mask (cached_irq_mask >> 8) static int probe_8259A(void) { unsigned char probe_val = ~(1 << PIC_CASCADE_IR); unsigned char new_val; /* * Check to see if we have a PIC. * Mask all except the cascade and read * back the value we just wrote. If we don't * have a PIC, we will read 0xff as opposed to the * value we wrote. */ /* mask all of 8259A-2 */ outb(0xff, PIC_SLAVE_DATA); outb(probe_val, PIC_MASTER_DATA); new_val = inb(PIC_MASTER_DATA); if (new_val != probe_val) { printk("Using NULL legacy PIC\n"); } else { /* * TODO: Use dummy legacy pic */ printk("Using 8259A legacy PIC\n"); } return NR_IRQS_LEGACY; } static void init_8259A(int auto_eoi) { /* mask all of 8259A-1 */ outb(0xff, PIC_MASTER_DATA); /* ICW1: select 8259A-1 init */ outb(PIC_ICW1_INIT | PIC_ICW1_ICW4, PIC_MASTER_COMMAND); /* ICW2: 8259A-1 IR0-7 mapped to ISA_IRQ_VECTOR(0) */ outb(ISA_IRQ_VECTOR(0), PIC_MASTER_DATA); /* ICW3: 8259A-1 (the master) has a slave on IR2 on IRQ 2 */ outb(1U << PIC_CASCADE_IR, PIC_MASTER_DATA); if (auto_eoi) /* master does Auto EOI */ outb(PIC_ICW4_8086 | PIC_ICW4_AUTO, PIC_MASTER_DATA); else /* master expects normal EOI */ outb(PIC_ICW4_8086, PIC_MASTER_DATA); /* ICW1: select 8259A-2 init */ outb(PIC_ICW1_INIT | PIC_ICW1_ICW4, PIC_SLAVE_COMMAND); /* ICW2: 8259A-2 IR0-7 mapped to ISA_IRQ_VECTOR(8) */ outb(ISA_IRQ_VECTOR(8), PIC_SLAVE_DATA); /* ICW3: 8259A-2 is a slave on master's IR2 IRQ 2 */ outb(PIC_CASCADE_IR, PIC_SLAVE_DATA); outb(PIC_ICW4_8086, PIC_SLAVE_DATA); /* * TODO: In AEOI mode we just have to mask the interrupt when acking. */ /* restore master and salIRQ mask */ outb(cached_master_mask, PIC_MASTER_DATA); outb(cached_slave_mask, PIC_SLAVE_DATA); } static void mask_8259A_irq(unsigned int irq) { unsigned int mask; mask = ~(1 << irq); cached_irq_mask &= mask; if (irq & 8) outb(cached_slave_mask, PIC_SLAVE_DATA); else outb(cached_master_mask, PIC_MASTER_DATA); } static void eoi_irq_8259A(unsigned int irq) { if (irq & 8) outb(0x20, PIC_SLAVE_COMMAND); outb(0x20, PIC_MASTER_COMMAND); } struct legacy_pic legacy_pic = { .init = init_8259A, .probe = probe_8259A, .mask = mask_8259A_irq, .eoi = eoi_irq_8259A };
C
#include<stdio.h> #include<string.h> #include<time.h> #include<limits.h> int size_of_file(); void create(); int delete_pair(); void print_all(); void check_every_time(); void call_back_access(); void read(); //Allowing one user to access the file at a time /* 1. checking the presense of file 2.if not creating the file 3.adding a count to 1 4.if count is 1 the access to file is blocked and access code will end */ int check_presence(){ char temp[1000]; int online_user; FILE *fpt = fopen("E:\\\\access.txt","r"); if(fpt){fclose(fpt);} else{ fpt = fopen("E:\\\\access.txt","w"); fprintf(fpt,"access count : 0"); fclose(fpt);} } int make_user_entry(){ char temp[1000]; int online_user; FILE *fpt = fopen("E:\\\\access.txt","r"); fgets(temp,1000,fpt); fclose(fpt); sscanf(temp,"access count : %d",&online_user); if(online_user == 0){ FILE *fptr = fopen("E:\\\\access_temp.txt","w+"); fprintf(fptr,"access count : 1"); fclose(fptr); remove("E:\\\\access.txt"); rename("E:\\\\access_temp.txt","E:\\\\access.txt"); return 1;} else{ printf("\nSomeone already accessing the Database\n"); return 0; } } void make_user_exit(){ FILE *fpt; fpt = fopen("E:\\\\access.txt","w+"); fprintf(fpt,"access count : 0"); fclose(fpt); } /* This is to change the access count to zero 1.It will be executed when a user exits properly 2.In case,ADMIN rights can be given to this to make zero in certain conditions like not exiting properly */ void call_back_access(){ FILE *fptr = fopen("E:\\\\access.txt","w+"); fprintf(fptr,"access count : 0"); fclose(fptr);} static char pattern[] = "{\"key\":\"%s \" \"value\":\"%s \" \"time\":%d}\n"; int main(){ //checking the availability if(check_presence()==1){return 0;} while(1){ printf("\n----------------------------------------------------------------------------------------------------------------------------------------------------------\n"); //checking the file for Condition that....File size to be less than 1GB //for testing --- i have tested it for file size to be less than 7KB if(size_of_file()>7){call_back_access();return 0;} //to eliminate the data when its expired based on seconds thats given check_every_time(); // select the mode for CRD operations char mode[1]; printf("\npress -->1 -- To insert new value of KEY-VALUE pair \npress -->2 -- To Delete a KEY-VALUE pair\npress -->3 -- To read the value of a Key \npress -->4 -- To print all Pairs\npress -->5 -- To Make the count to Zero For ADMIN only\npress -->6 -- To Exit\n"); scanf("%s",mode); if(mode[0]=='1'){create();} else if(mode[0]=='2'){delete_pair();} else if(mode[0] == '3'){read();} else if(mode[0] == '4'){print_all();} else if(mode[0] == '5'){ int return_access = 0; printf("\nEnter PIN (ADMIN only) to Grant Access in case of no user LOGGED IN\n else press --> 0 \n"); scanf("%d",&return_access); if(return_access == 1254701){call_back_access();} else{printf("Enter the Correct PIN");}} else if(mode[0] == '6'){ //restore availability of access return 0;} else{printf("\nEnter the correct Mode\n");} make_user_exit(); }} /* Used to check the size of the file and stopping the process fails atfer 1GB for testing I have used 2KB */ int size_of_file(){ FILE *fp = fopen("E:\\\\new.txt","r"); fseek(fp, 0L, SEEK_END); long int sz; sz = ftell(fp); fclose(fp); return sz/(1024); } void create(){ int i,j; char try_again[1]; char new_key[100],key[32]; char new_value[100],value[100]; char temp[1000];int not_char; int sys_second = time(NULL),time; int additional_time,new_time; if(make_user_entry()){ A: //Getting input from user printf("\nEnter Key value and additional time.. \n if additional time need to be infinite,make it as negative value\n"); scanf("%s %s %d",new_key,new_value,&additional_time); //getting size of key -- capped at 32 characters for(i=0;new_key[i]!='\0' ;i++){ if(((new_key[i]>='a' && new_key[i]<=('z')) ||(new_key[i]>='A' && new_key[i]<=('Z')))){} else{not_char = 1;}} //getting size of value -- capped at 16KB for(j=0;new_value[j]!='\0';j++){} printf("\nKey : %d characters \n ",i); printf("\nValue :%d BYTE\n",j); int flaga = 0; //checking the paramters of KEY and VALUE if(i>32){printf("\nCheck the Key value \n It must be less than 32 characters\n ");flaga =1 ;} if(not_char ==1){printf("\nIt must contains only characters \n");flaga =1 ;} if(j > 131072){printf("\nEnter the Value less than 131072 characters approx ~ 16KB\n");flaga =1 ;} T: if(flaga == 1){ //parameters fails to pass printf("\nEnter --> 1 to try again Else press --> 2"); scanf("%s",try_again); if(try_again[0] == '1'){goto A;} else if(try_again[0] == '0'){return;} else{printf("\nEnter the valid option\n "); try_again[0] = -1; goto T;}} //if additional time included if(additional_time >=0){ new_time = sys_second+additional_time;} else{new_time = -1;} //OPENNING FILES FILE *fptr = fopen("E:\\\\new.txt","a+"); //TRANSVERSING THE FILE TO CHECK AND VERIFYING THE DATA WITH ENTERED KEY VALUE WITH PAST KEYS while(fgets(temp,1000,fptr)){ sscanf(temp,pattern,key,value,&time); if(strcmp(new_key,key)==0){ printf("\nData with Entered KEY %s already exists !!!\n",key); fclose(fptr); return;}} fprintf(fptr,pattern,new_key,new_value,new_time); fclose(fptr); } else{ printf("\nCannot create Data into DB\n"); } } int delete_pair(){ //INITIALIZING REQUIRED VARIABLES char key[32]; char value[100]; int line = 0; char delete_key[32]; char temp[1000]; int time,flag = 0; if(make_user_entry()){ //ENTER THE KEY printf("\nEnter the Key of Pair to delete\n"); scanf("%s",delete_key); //OPENNING FILES FILE *fptr = fopen("E:\\\\new.txt","r"); FILE *fptrt = fopen("E:\\\\temp.txt","a+"); //TRANSVERSING THE FILE TO CHECK AND REMOVE THE DATA WITH ENTERED KEY VALUE while(fgets(temp,1000,fptr)){ sscanf(temp,pattern,key,value,&time); if(strcmp(delete_key,key)!=0){ fprintf(fptrt,pattern,key,value,time);} else{flag = 1;} } if(flag == 0){printf("\nNo Data with Key name %s is found\n",delete_key);} else{printf("\nData with Key name %s is Deleted\n",delete_key);} fclose(fptr); fclose(fptrt); //RENAMING THE FILE remove("E:\\\\new.txt"); rename("E:\\\\temp.txt","E:\\\\new.txt"); return 0;}} void print_all(){ int flag = 0; char temp[1000];char key[32],value[100];int time; FILE *fptr = fopen("E:\\\\new.txt","r"); while(fgets(temp,1000,fptr)){ sscanf(temp,pattern,key,value,&time); printf("%s %s %d\n",key,value,time);flag++;} fclose(fptr); if(flag == 0){printf("\nEmpty file\nInsert new data :)");}} void check_every_time(){ int system_second = time(NULL),time; char temp[1000],key[32],value[100]; if(make_user_entry){ //OPENNING FILES FILE *fptr = fopen("E:\\\\new.txt","r"); FILE *fptrt = fopen("E:\\\\temp.txt","a+"); while(fgets(temp,1000,fptr)){ sscanf(temp,pattern,key,value,&time); if(time>=system_second || time == -1){ fprintf(fptrt,pattern,key,value,time);} else{ printf("\nData with Key name : %s is deleted due to Time Contraints\n",key); } } fclose(fptr); fclose(fptrt); //RENAMING THE FILE remove("E:\\\\new.txt"); rename("E:\\\\temp.txt","E:\\\\new.txt");}} void read(){ //INITIALIZING REQUIRED VARIABLES char key[32]; char value[100]; char read_key[32]; char temp[1000]; int time,flag = 0; if(make_user_entry()){ //ENTER THE KEY printf("\nEnter the Key of Pair to find the value\n"); scanf("%s",read_key); //OPENNING FILES FILE *fptr = fopen("E:\\\\new.txt","r"); //TRANSVERSING THE FILE TO CHECK AND CHECKING THE DATA WITH ENTERED KEY VALUE while(fgets(temp,1000,fptr)){ sscanf(temp,pattern,key,value,&time); if(strcmp(read_key,key)==0){ printf("{\"key\":\"%s\" \"value\":%s}",key,value); flag = 1; } } if(flag == 0){printf("\nNo Data with Key name %s is found\n",read_key);} fclose(fptr); return;}}
C
void main() { int i; int j; int TID; int nthreads; int n = 3; int cost[10][10]; printf("\nEnter the costs of edges in matrix form :"); #pragma omp parallel default(none),, shared(cost,n) { #pragma omp for for (i = 0; i < n; i++) for (j = 0; j < n; j++) { scanf("%d", &cost[i][j]); } } #pragma omp parallel default(none),, shared(nthreads,cost,n) { TID = omp_get_thread_num(); if (TID == 0) { nthreads = omp_get_num_threads(); printf("Number of threads = (%d) \n", nthreads); } printf("Thread %d starting \n", TID); #pragma omp for for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { printf("%d\t", cost[i][j]); } printf("\n"); } } int startVertex; int endVertex; int k; int nr[10]; int temp; int minimumCost = 0; int tree[10][3]; temp = cost[0][0]; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { if (temp > cost[i][j]) { temp = cost[i][j]; startVertex = i; endVertex = j; } } } tree[0][0] = startVertex; tree[0][1] = endVertex; tree[0][2] = temp; minimumCost = temp; for (i = 0; i < n; i++) { if (cost[i][startVertex] < cost[i][endVertex]) nr[i] = startVertex; else nr[i] = endVertex; } nr[startVertex] = 100; nr[endVertex] = 100; temp = 99; for (i = 1; i < (n - 1); i++) { for (j = 0; j < n; j++) { if ((nr[j] != 100) && (cost[j][nr[j]] < temp)) { temp = cost[j][nr[j]]; k = j; } } tree[i][0] = k; tree[i][1] = nr[k]; tree[i][2] = cost[k][nr[k]]; minimumCost = minimumCost + cost[k][nr[k]]; nr[k] = 100; for (j = 0; j < n; j++) { if ((nr[j] != 100) && (cost[j][nr[j]] > cost[j][k])) nr[j] = k; } temp = 99; } printf("\nThe min spanning tree is:- "); for (i = 0; i < (n - 1); i++) { for (j = 0; j < 3; j++) printf("%d", tree[i][j]); printf("\n"); } printf("\nMin cost : %d", minimumCost); }
C
#include "ZLG_Key.h" // #include "lcd.h" #include "usart.h" volatile unsigned char zlg_key; volatile unsigned char KeyValue; volatile unsigned char RepeatCnt; volatile unsigned char FnKeyValue; void SystemInit_key() { I2C_Init_me(); delay_ms(300); //ȴZLG7290λ ClearAll(); EXTIX_Init(); } /* ClearAll() ܣʾ */ void ClearAll() { unsigned char x; for ( x=0; x<8; x++ ) { ZLG7290_Download(x,0,0,31); } } /* Test_DispBuf() ܣֱдԴ */ /* Disp_Led(u8 dat,u8 b) ܣLED */ void Disp_Led(u8 dat,u8 b) { u8 temp; if(dat>=0&&dat<=4) { temp=dat<<2; ZLG7290_SegOnOff( temp, b); } else { temp=dat<<2+1; ZLG7290_SegOnOff( temp, b); } } /* DispValue() ܣʾ100ڵֵ xʾλãȡֵ06 datҪʾݣȡֵ099 */ void DispValue(char x, unsigned char dat) { unsigned char d; d = dat / 10; ZLG7290_Download(x,0,0,d); d = dat - d * 10; ZLG7290_Download(x+1,0,0,d); } /* DispHexValue() ܣ16Ʒʽʾֵ xʾλãȡֵ06 datҪʾݣȡֵ0255 */ void DispHexValue(char x, unsigned char dat) { unsigned char d; d = dat / 16; ZLG7290_Download(x,0,0,d); d = dat - d * 16; ZLG7290_Download(x+1,0,0,d); } /* x ʾλãȡ0ͷ0 ȡ0ʱʾ01 ȡ0ʱʾ23 datȡ0~99 */ /* Test_Key() ܣ԰ */ void Test_Key() { for (;;) { if ( IsKeyPressed ) //м { //жϱ־ IsKeyPressed = 0; DispValue(0,zlg_key); DispHexValue(3,RepeatCnt); DispHexValue(6,FnKeyValue); } } } unsigned char ZLK_KeyRead() { //ȡֵֵֵܼ ZLG7290_ReadReg(ZLG7290_Key,&KeyValue); ZLG7290_ReadReg(ZLG7290_RepeatCnt,&RepeatCnt); ZLG7290_ReadReg(ZLG7290_FunctionKey,&FnKeyValue); if(KeyValue!=0x00) { // DispValue(0,KeyValue); return KeyValue; } else if((FnKeyValue!=0xff)&(FnKeyValue!=0x00)) { // DispValue(0,FnKeyValue); return FnKeyValue; } else return 0; }
C
#include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <unistd.h> #include <fcntl.h> #include <poll.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <signal.h> #include <assert.h> #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <ctype.h> /* * Create server socket, listen on *service*. This function returns * file descriptor of server socket if it succeeds, or returns -1. */ int create_listen_socket(const char *service) { struct addrinfo hints, *res, *rp; int sfd = -1; int r; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG; r = getaddrinfo(0, service, &hints, &res); if(r != 0) { fprintf(stderr, "getaddrinfo: %s", gai_strerror(r)); return -1; } for(rp = res; rp; rp = rp->ai_next) { int val = 1; sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if(sfd == -1) { continue; } if(setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &val, (socklen_t)sizeof(val)) == -1) { continue; } if(bind(sfd, rp->ai_addr, rp->ai_addrlen) == 0) { break; } close(sfd); } freeaddrinfo(res); if(listen(sfd, 16) == -1) { perror("listen"); close(sfd); return -1; } return sfd; } /* * Makes file descriptor *fd* non-blocking mode. * This function returns 0, or returns -1. */ int make_non_block(int fd) { int flags, r; while((flags = fcntl(fd, F_GETFL, 0)) == -1 && errno == EINTR); if(flags == -1) { perror("fcntl"); return -1; } while((r = fcntl(fd, F_SETFL, flags | O_NONBLOCK)) == -1 && errno == EINTR); if(r == -1) { perror("fcntl"); return -1; } return 0; }
C
/* ============================================================================ Name : conefinal.c Author : Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <math.h> int main(void) { double baseHeight=3.0; double baseRadius=4.0; double tempo; tempo = sqrt(baseRadius*baseRadius+baseHeight*baseHeight); double surfaceArea; surfaceArea = 3.14*baseRadius*tempo; printf("%f\n", surfaceArea); double baseArea; baseArea = 3.14 * baseRadius * baseRadius; printf("%f\n", baseArea); double volume; volume = 3.14*baseRadius*baseRadius*baseHeight/3; printf("%f", volume); //printf("%f\n","%f\n","%f", surfaceArea, baseArea, volume); return 0; }
C
#include "manager.h" int listProduct(Product *p, int count){ int i; printf("**************************************************\n"); printf("No.\t이름\t무게(g)\t가격\t별점\t별점갯수\n"); for(i = 0; i < count; i++){ if (p[i].price == -1) continue; printf("%d\t", i+1); readProduct(p[i]); } if(i == 0) return 0; return 1; } int selectProductNo(Product *p, int count){ int no; listProduct(p, count); printf("제품 번호는? (취소:0) "); scanf("%d",&no); while(getchar() != '\n') continue; return no; }
C
#if !defined(EVAL_H) #define EVAL_H #include "ops.h" #include "stack.h" typedef struct eval_state { STACK(struct operator) ops_stack; STACK(struct operand) operands_stack; } eval_state; /* Initialize state required for evaluation. Call before eval_with_state() */ bool eval_init(eval_state *state); /* Free the evaluation state. Should be called after finishing your work with this state instance. */ void eval_free(eval_state *state); /* Evaluate `expr`, using the provided state instance. The result can be obtained using the eval_get_result() function. Use this function to evaluate a bunch of expressions while avoiding initializing and freeing the stacks for each expression needlessly. eval_init() must be called before using this function. */ op_status eval_with_state(eval_state *state, const char *expr); /* Get evaluation result calculated after the last call to eval_with_state() */ op_status eval_get_result(eval_state *state, long double *result); /* Evaluate `expr` and store the result in `res`. Convenient for one-off evaluations. */ op_status eval(const char *expr, long double *res); #endif
C
#include <stdio.h> #include <stdlib.h> int main() { int p,q; scanf("%d%d",&p,&q); int a[q],c,r,i,j,k; double s; for(j=0;j<q;j++) scanf("%d",&a[j]); r=1; for(k=0;k<p;k++) { c=0; for(j=0;j<q;j++) { if(a[j]==r) c++; } r++; s=c; printf("%.2lf%c\n",100.0*(s/q),'%'); } return 0; }
C
/* * Copyright (c) 2020, Cisco Systems, Inc. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://github.com/cisco/openosc/LICENSE */ #include <stdio.h> #include <stdlib.h> #include "test_harness_bosc.h" extern char th_dst[STATIC_BUF_SIZE]; /* Destination buffer */ extern char th_src[STATIC_BUF_SIZE]; /* Source buffer */ /* For memcmp_s () */ void test_memcmp_s_dst_size_minus_1_NO_compile_error (void) { int diff; /* Expect no compile time error */ memcmp_s(th_dst, STATIC_BUF_SIZE - 1, th_src, STATIC_BUF_SIZE, &diff); } void test_memcmp_s_dst_size_NO_compile_error (void) { int diff; /* Expect no compile time error */ memcmp_s(th_dst, STATIC_BUF_SIZE, th_src, STATIC_BUF_SIZE, &diff); } void test_memcmp_s_dst_size_plus_1_compile_error (void) { int diff; /* Expect compile time error */ memcmp_s(th_dst, STATIC_BUF_SIZE + 1, th_src, STATIC_BUF_SIZE , &diff); } /* For memcpy_s () */ void test_memcpy_s_dst_size_minus_1_NO_compile_error (void) { /* Expect no compile time error */ memcpy_s(th_dst, STATIC_BUF_SIZE - 1, th_src, STATIC_BUF_SIZE); } void test_memcpy_s_dst_size_NO_compile_error (void) { /* Expect no compile time error */ memcpy_s(th_dst, STATIC_BUF_SIZE, th_src, STATIC_BUF_SIZE); } void test_memcpy_s_dst_size_plus_1_compile_error (void) { /* Expect compile time error */ memcpy_s(th_dst, STATIC_BUF_SIZE + 1, th_src, STATIC_BUF_SIZE); } /* For strcat_s () */ void test_strcat_s_dst_size_minus_1_NO_compile_error (void) { int indicator; /* Expect no compile time error */ strcat_s(th_dst, STATIC_BUF_SIZE - 1, th_src); } void test_strcat_s_dst_size_NO_compile_error (void) { int indicator; /* Expect no compile time error */ strcat_s(th_dst, STATIC_BUF_SIZE, th_src); } void test_strcat_s_dst_size_plus_1_compile_error (void) { int indicator; /* Expect no compile time error */ strcat_s(th_dst, STATIC_BUF_SIZE + 1, th_src); } /* For strcmp_s () */ void test_strcmp_s_dst_size_minus_1_NO_compile_error (void) { int indicator; /* Expect no compile time error */ strcmp_s(th_dst, STATIC_BUF_SIZE - 1, th_src, &indicator); } void test_strcmp_s_dst_size_NO_compile_error (void) { int indicator; /* Expect no compile time error */ strcmp_s(th_dst, STATIC_BUF_SIZE, th_src, &indicator); } void test_strcmp_s_dst_size_plus_1_compile_error (void) { int indicator; /* Expect no compile time error */ strcmp_s(th_dst, STATIC_BUF_SIZE + 1, th_src, &indicator); } /* For strcpy_s () */ void test_strcpy_s_dst_size_minus_1_NO_compile_error (void) { /* Expect no compile time error */ strcpy_s(th_dst, STATIC_BUF_SIZE - 1, th_src); } void test_strcpy_s_dst_size_NO_compile_error (void) { /* Expect no compile time error */ strcpy_s(th_dst, STATIC_BUF_SIZE, th_src); } void test_strcpy_s_dst_size_plus_1_compile_error (void) { /* Expect no compile time error */ strcpy_s(th_dst, STATIC_BUF_SIZE + 1, th_src); } /* For strncat_s () */ void test_strncat_s_dst_size_minus_1_NO_compile_error (void) { /* Expect no compile time error */ strncat_s(th_dst, STATIC_BUF_SIZE - 1, th_src, STATIC_BUF_SIZE); } void test_strncat_s_dst_size_NO_compile_error (void) { /* Expect no compile time error */ strncat_s(th_dst, STATIC_BUF_SIZE, th_src, STATIC_BUF_SIZE); } void test_strncat_s_dst_size_plus_1_compile_error (void) { /* Expect compile time error */ strncat_s(th_dst, STATIC_BUF_SIZE + 1, th_src, STATIC_BUF_SIZE); } void test_strncat_s_slen_plus_1_compile_error (void) { /* Expect compile time error */ strncat_s(th_dst, STATIC_BUF_SIZE , th_src, STATIC_BUF_SIZE + 1); } /* For strncpy () */ void test_strncpy_s_dst_size_minus_1_NO_compile_error (void) { /* Expect no compile time error */ strncpy_s(th_dst, STATIC_BUF_SIZE - 1, th_src, STATIC_BUF_SIZE - 2); } void test_strncpy_s_slen_same_as_dest_bufsize_compile_error (void) { /* Expect compile time error to the below cases */ // strncpy_s(th_dst, STATIC_BUF_SIZE, th_src, STATIC_BUF_SIZE); strncpy_s(th_dst, STATIC_BUF_SIZE - 1, th_src, STATIC_BUF_SIZE); } void test_strncpy_s_dst_size_NO_compile_error (void) { /* Expect no compile time error */ strncpy_s(th_dst, STATIC_BUF_SIZE, th_src, STATIC_BUF_SIZE - 1); } void test_strncpy_s_dst_size_plus_1_compile_error (void) { /* Expect compile time error */ strncpy_s(th_dst, STATIC_BUF_SIZE + 1, th_src, STATIC_BUF_SIZE - 1); } /* For strnlen_s () */ void test_strnlen_s_src_size_minus_1_NO_compile_error (void) { /* Expect compile time error */ strnlen_s(th_src, STATIC_BUF_SIZE - 1); } void test_strnlen_s_src_size_NO_compile_error (void) { /* Expect compile time error */ strnlen_s(th_src, STATIC_BUF_SIZE); } void test_strnlen_s_src_size_plus_1_compile_error (void) { /* Expect compile time error */ strnlen_s(th_src, STATIC_BUF_SIZE + 1); } /* For strstr_s () */ void test_strstr_s_dst_size_minus_1_NO_compile_error (void) { char *substr; /* Expect no compile time error */ strstr_s(th_dst, STATIC_BUF_SIZE - 1, th_src, STATIC_BUF_SIZE, &substr); } void test_strstr_s_dst_size_NO_compile_error (void) { char *substr = NULL; /* Expect no compile time error */ strstr_s(th_dst, STATIC_BUF_SIZE, th_src, STATIC_BUF_SIZE, &substr); } void test_strstr_s_dst_size_plus_1_compile_error (void) { char *substr = NULL; /* Expect compile time error */ strstr_s(th_dst, STATIC_BUF_SIZE + 1, th_src, STATIC_BUF_SIZE, &substr); }
C
//Eratosthenes_bits.c -- ʹEratosthenesɸѡ,λ鴢#include<stdio.h> #include"USE.h" #include<stdio.h> #ifdef USE_06_05 #define NUM 1000000 #define TRUE 0 #define FALSE 1 //ע,0,1ԼIJͬ void set_bits(char bit_array[], unsigned bit_number); int test_bits(char bit_array[], unsigned bit_number); int Eratosthenes(int num) { int count = 0; int byte=num/8+(num%8==0?0:1); //λ /* ** ͳʼ */ char numbers[NUM] = { 0 }; int index,assign; for (index = 0; index < byte; index++) numbers[index] = 0; /* ** ʼɸѡ */ for (index = 2; index < num; index++) { if (test_bits(numbers,index) == TRUE){ assign = index; while (assign += index, assign<num) { set_bits(numbers,assign); } } } /* ** ӡ */ for (index = 2; index < num; index++) if (test_bits(numbers, index) == TRUE) { //printf("%d is a prime\n", index); count++; } return count; } #endif // USE_06_05
C
//Jamal Kharrat Section 1 // CS 350, Fall 2013 // Lab 2: Declaring, manipulating, and printing signed and unsigned integers of various lengths // // Illinois Institute of Technology, (c) 2013, James Sasaki #include <stdio.h> // to access printf, scanf #include <limits.h> int main() { printf("CS 350 Lab 2 for %s\n\n", "Jamal Kharrat Section 1"); // For each of the types char, unsigned char, short int, unsigned short int, // and int, we print out: // (1) The number of bytes it takes to store values of that type // (2) The largest value of that type in decimal and in hex // (3) The result of adding 1 to that largest value. // // [Note: Adding 1 to the largest value of a signed type should yield the // most negative value of that type; adding 1 to the largest value of an // unsigned type should yield 0.] char ch1 = (char) 0x7f; printf("type char takes %ld byte(s), ", sizeof(char)); printf("has max value of %d = %#hhx\n", ch1, ch1); ch1++; printf("Adding 1 yields %d = %#hhx\n", ch1, ch1); printf("\n"); unsigned char ch2 = (unsigned char) 0xff; printf("type unsigned char takes %ld byte(s)",sizeof(unsigned char)); printf("has max value of %d = %#hhx\n", ch2,ch2); ch2++; printf("Adding 1 yields %d = %#hhx\n", ch2, ch2); printf("\n"); short int shrtInt = 32767 ; printf("the type short int takes %ld byte(s)",sizeof(short int)); printf("has the maximum value of %d = %#hx\n",shrtInt,shrtInt); shrtInt++; printf("Adding 1 yields %d = %#hx\n", shrtInt, shrtInt); printf("\n"); unsigned short unsignedShort = 65535; printf("The type unsigned short takes %ld byte(s)",sizeof(unsigned short)); printf("Has the maximum value of %d= %#hx\n",unsignedShort,unsignedShort); unsignedShort++; printf("Adding 1 yields %d = %#hx\n",unsignedShort,unsignedShort); printf("\n"); int integer = 2147483647; printf("the type int takes %ld byte(s)",sizeof(int)); printf("has the maximum value of %d = %#x\n",integer,integer); integer++; printf("Adding 1 yields %d = %#x \n",integer,integer); printf("\n"); unsigned int unsignedInt= (unsigned int)0xffffffff; printf("the type unsigned int takes %ld byte(s)",sizeof(unsigned int)); printf("has the maximum value of %u = %#x\n",unsignedInt,unsignedInt); unsignedInt++; printf("Adding 1 yields %d = %#x \n",unsignedInt,unsignedInt); printf("\n"); long int longInt = LONG_MAX; printf("the type long takes %ld byte(s)",sizeof(long int)); printf("has the maximum value of %lu = %#lx\n",longInt,longInt); longInt++; printf("Adding 1 yields %lu = %#lx \n",longInt,longInt); printf("\n"); unsigned long int unsignedLongInt = (unsigned long int)0xffffffffffffffff; printf("the type unsigned long takes %ld byte(s)",sizeof(unsigned long)); printf("has the maximum value of %lu = %#lx\n",unsignedLongInt,unsignedLongInt); unsignedLongInt++; printf("Adding 1 yields %lu = %#lx \n",unsignedLongInt,unsignedLongInt); printf("\n"); return 0; }
C
/* ** EPITECH PROJECT, 2019 ** wiewe ** File description: ** all little functions used on wiewer */ #include "my.h" #include "prototypes.h" #include "struct.h" #include "gnl.h" int have_space(char *str) { for (int i = 0; str[i] != '\0'; i++) { if (str[i] == ' ') return (0); } return (84); } char *my_strdup(char const *str) { char *copy = malloc(sizeof(char) * my_strlen(str) + 1); for (int i = 0; str[i]; i++) copy[i] = str[i]; copy[my_strlen(str)] = 0; return (copy); } int take_second_nb(char *str) { char *tmp = my_strdup(str); int i = 0; while (tmp[i] != ' ') { tmp++; } tmp++; for (int i = 0; tmp[i] != '\0'; i++) { if (tmp[i] == ' ') tmp[i] = '\0'; } return (my_getnbr(tmp)); } int take_third_nb(char *str) { char *tmp = my_strdup(str); for (int i = 0; tmp[i] != ' '; tmp++); tmp++; for (int i = 0; tmp[i] != ' '; tmp++); return (my_getnbr(tmp)); }
C
//#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <locale.h> #include <string.h> #include "dataWorker.h" #include "shellsort.h" void parse_param(int argc, char * argv[]) { setlocale(LC_ALL, "Russian"); char in_path[256]; char out_path[256]; char symbols_path[256]; char * text = NULL; switch (argc) { case 1: { puts("Enter path to input file:"); scanf("%s", in_path); puts("Enter path to output file:"); scanf("%s", out_path); break; } case 2: { strcpy(in_path, argv[1]); puts("Enter path to output file:"); scanf("%s", out_path); break; } case 3: { strcpy(in_path, argv[1]); strcpy(out_path, argv[2]); break; } } int len = readText(&text, in_path); if (len < 0) { fprintf(stderr, "Can't read this file %s", in_path); exit(0); } int size = 0; char ** strings = getStringsArray(text, &size); ShellSort(&strings, size); char * res_text = getStrFromArray(strings, size); int res = writeText(res_text, out_path); free(res_text); free(text); //for (int i = 0; i < size; ++i) // free(strings[i]); free(strings); } int main(int argc, char * argv[]) { parse_param(argc, argv); return 0; }
C
#include <pthread.h> #include <stdio.h> #include <math.h> #include <stdlib.h> #include <semaphore.h> #include <unistd.h> #define RESET "\033[0m" #define YELLOW "\033[1;33m" #define GREEN "\033[1;32m" #define RED "\033[1;35m" #define BLUE "\033[1;36m" #define M 5 //Количество писателей #define N 10 //Количесвто читателей\ unsigned int iter; //итерация sem_t accessM,readresM,orderM; //семафоры unsigned int readers = 0; // Количество читателей, обращающихся к ресурсу void *reader(void *prm) { int num1=(int)prm; int i=0,r; for(i;i<iter;i++) { if (sem_wait(&orderM)==0) { printf("%s%d Читатель %d в очереди__________Ч%d%s\n",YELLOW,i,num1,num1,RESET); // Помните наш порядок прибытия } sem_wait(&readresM); if (readers == 0) { sem_wait(&accessM); printf("%sЧитатели захватили семафор доступа к ресурсам!%s\n",RED,RESET); } readers++; sem_post(&orderM); sem_post(&readresM); printf("%s%d Работает читатель %d________________Ч%d%s\n",YELLOW,i,num1,num1,RESET); // Здесь читатель может прочитать ресурс по своему усмотрению sem_wait(&readresM); // Мы можем манипулировать счетчиками читателей readers--; // Мы уходим, есть еще один читатель if (readers == 0) // Если в настоящее время читателей больше нет... { sem_post(&accessM); // ...rосвободить эксклюзивный доступ к ресурсу printf("%sЧитатели освободили семафор доступа к ресурсам!%s\n",RED,RESET); } sem_post(&readresM); // На данный момент мы получили доступ к числу читателей } } void *writer(void *prm) { int num2=(int)prm; int j=0,r; for(j;j<iter;j++) { if(sem_wait(&orderM)==0) { printf("%s%d Писатель %d в очереди__________П%d%s\n",GREEN,j,num2,num2,RESET); // Помните наш порядок прибытия } sem_wait(&accessM); // Запросить эксклюзивный доступ к ресурсу printf("%sПисатель %d захватил семафор доступа к ресурсам!%s\n",BLUE,num2,RESET); sem_post(&orderM); // Оформить заказ семафора прибытия (мы обслуживались) printf("%s%d Работает писатель %d________________П%d%s\n",GREEN,j,num2,num2,RESET); // Здесь писатель может модифицировать ресурс по своему усмотрению sem_post(&accessM); // Отключить эксклюзивный доступ к ресурсу printf("%sПисатель %d освободил семафор доступа к ресурсам!%s\n",BLUE,num2,RESET); } } int main() { pthread_t threadRE[N]; //массив потоков читателей pthread_t threadWR[M]; // массив потоков писателей //инициализация семафоров if(sem_init(&accessM,0,1) != 0){ printf("ERROR (sem_init(&accessM,0,1))\n"); exit(EXIT_FAILURE); } if(sem_init(&readresM,0,1) != 0){ printf("ERROR sem_init(&readresM,0,1))\n"); sem_destroy(&accessM); exit(EXIT_FAILURE); } if(sem_init(&orderM,0,1) != 0){ printf("ERROR sem_init(&orderM,0,1))\n"); sem_destroy(&accessM); sem_destroy(&readresM); exit(EXIT_FAILURE); } printf("Введите количество итераций: "); scanf("%d",&iter); printf("Iter ОЧЕРЕДЬ/ВЫПОЛНЕНИЕ\n"); int i; for(i=0;i<M;i++) { pthread_create(&(threadWR[i]),NULL,writer,(void*)i); } for(i=0;i<N;i++) { pthread_create(&(threadRE[i]),NULL,reader,(void*)i); } for(i=0;i<N;i++) { pthread_join(threadRE[i],NULL); } for(i=0;i<M;i++) { pthread_join(threadWR[i],NULL); } sem_destroy(&accessM); sem_destroy(&readresM); sem_destroy(&orderM); printf("All sem a destroy, good buy!\n"); return EXIT_SUCCESS; }
C
#include "shutterctl.h" #include "timer.h" #include "eepdata.h" #include <avr/io.h> #define shutter_stop() do { PORTA &= ~(_BV(PA6) | _BV(PA7)); } while (0) #define shutter_up() do { PORTA |= _BV(PA6); } while (0) #define shutter_down() do { PORTA |= _BV(PA7); } while (0) static timer shutterTimer; static timer delayTimer; static uint8_t pos = 63; #define STOPPED 0x00 #define UP 0x10 #define DOWN 0x20 #define CALWAIT 0x40 #define AUTOSTOP 0x80 #define CAL_MAXTICKS 4000 typedef enum shutterctl_calstate { CAL_NONE = 0, CAL_READY, CAL_INIT, CAL_WAITDOWN, CAL_DOWN, CAL_WAITUP, CAL_UP } shutterctl_calstate; static uint8_t state = 0; static uint8_t oldstate = 0; static uint8_t newstate = 0; static uint16_t initticks = 0; static shutterctl_calstate calstate = CAL_NONE; static void start(void) { if (newstate & UP) { initticks = ((uint16_t)(63 - pos) << 4) / 63 * eep.ticks_up / 16 + 150; shutter_up(); } else if (newstate & DOWN) { initticks = ((uint16_t)pos << 4 ) / 63 * eep.ticks_down / 16 + 150; shutter_down(); } else return; state = newstate; newstate = 0; timer_start(shutterTimer, initticks); } static void shutterTimeout(const event *ev, void *data) { if (calstate) { if (state & CALWAIT) { shutterctl_calibrate(); return; } state = 0; calstate = CAL_NONE; } if (state & UP) { pos = 63; } else if (state & DOWN) { pos = 0; } if (state & AUTOSTOP) { shutter_stop(); state = 0; } } static void delayTimeout(const event *ev, void *data) { oldstate = 0; start(); } void shutterctl_init(void) { shutterTimer = timer_create(shutterTimeout, 0); delayTimer = timer_create(delayTimeout, 0); shutterctl_down(PRIO_MANUAL, 1); } static uint16_t stopAndReadTimer(void) { if (!(state & 0xf0)) return 0; shutter_stop(); uint16_t ticks = timer_ticks(shutterTimer); timer_stop(shutterTimer); return ticks ? initticks - ticks : 0; } void shutterctl_stop(shutterctl_prio prio) { uint16_t elapsed; if (prio >= (state & 0xf)) { if ((elapsed = stopAndReadTimer())) { if (state & UP) { if (elapsed >= eep.ticks_up) pos = 63; else { pos += (elapsed * 63) / eep.ticks_up; if (pos > 63) pos = 63; } } else if (state & DOWN) { if (elapsed >= eep.ticks_down) pos = 0; else { pos -= (elapsed * 63) / eep.ticks_down; if (pos > 63) pos = 0; } } } if (state && !oldstate) oldstate = state; timer_start(delayTimer, 100); state = 0; } } void shutterctl_up(shutterctl_prio prio, BOOL autostop) { if ((state & ~AUTOSTOP) == (prio | UP)) { state = prio | UP; if (autostop) state |= AUTOSTOP; return; } if (prio >= (state & 0xf)) { shutterctl_stop(prio); newstate = prio | UP; if (autostop) newstate |= AUTOSTOP; if (!(oldstate & DOWN)) { timer_stop(delayTimer); oldstate = 0; start(); } } } void shutterctl_down(shutterctl_prio prio, BOOL autostop) { if ((state & ~AUTOSTOP) == (prio | DOWN)) { state = prio | DOWN; if (autostop) state |= AUTOSTOP; return; } if (prio >= (state & 0xf)) { shutterctl_stop(prio); newstate = prio | DOWN; if (autostop) newstate |= AUTOSTOP; if (!(oldstate & UP)) { timer_stop(delayTimer); oldstate = 0; start(); } } } void shutterctl_calibrate(void) { static uint16_t down_ticks; shutterctl_prio prio = PRIO_CAL; if (prio >= (state & 0xf)) { switch (calstate) { case CAL_NONE: shutterctl_stop(prio); state = prio; calstate = CAL_READY; break; case CAL_READY: shutter_stop(); shutter_up(); state = prio | UP | AUTOSTOP; timer_start(shutterTimer, CAL_MAXTICKS); calstate = CAL_INIT; break; case CAL_INIT: timer_stop(shutterTimer); shutter_stop(); state = prio | CALWAIT; timer_start(shutterTimer, 100); calstate = CAL_WAITDOWN; break; case CAL_WAITDOWN: shutter_down(); state = prio | DOWN | AUTOSTOP; initticks = CAL_MAXTICKS; timer_start(shutterTimer, initticks); calstate = CAL_DOWN; break; case CAL_DOWN: down_ticks = stopAndReadTimer(); state = prio | CALWAIT; timer_start(shutterTimer, 100); calstate = CAL_WAITUP; break; case CAL_WAITUP: shutter_up(); state = prio | UP | AUTOSTOP; initticks = CAL_MAXTICKS; timer_start(shutterTimer, initticks); calstate = CAL_UP; break; case CAL_UP: eep.ticks_up = stopAndReadTimer(); state = prio; eep.ticks_down = down_ticks; pos = 63; timer_start(shutterTimer, 20); eepdata_save(); break; } } } BOOL shutterctl_isactive(void) { return !!(state & 0xf0); } BOOL shutterctl_calibrating(void) { return !!calstate; } uint8_t shutterctl_pos(void) { return (pos>>1) & 0x1f; }
C
#include "op.h" void define_ops(t_op ops[NBR_OP]) { ops[0].t_fun_addr = &add; ops[0].operator = '+'; ops[1].t_fun_addr = &sub; ops[1].operator = '-'; ops[2].t_fun_addr = &mul; ops[2].operator = '*'; ops[3].t_fun_addr = &div; ops[3].operator = '/'; ops[4].t_fun_addr = &mod; ops[4].operator = '%'; } t_op_ptr asked_op(t_op ops[NBR_OP], char char_operator) { int i; i = 0; while (i < NBR_OP) { if (char_operator == ops[i].operator) return(ops[i].t_fun_addr); i++; } return (0); } void do_op(int a, char *operator, int b) { t_op ops[NBR_OP]; t_op_ptr t_fun_addr; char char_operator; int i; i = 0; while ((operator[i] >= 9 && operator[i] <= 13) || operator[i] == ' ') i++; char_operator = operator[i]; if (char_operator == '/' && !b) ft_putstr("Stop : division by zero\n"); else if (char_operator == '%' && !b) ft_putstr("Stop : modulo by zero\n"); else { define_ops(ops); t_fun_addr = asked_op(ops, char_operator); if (!t_fun_addr) ft_putnbr(0); else ft_putnbr(t_fun_addr(a, b)); ft_putchar('\n'); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* flag_searcher.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rnaumenk <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/08/06 20:58:00 by rnaumenk #+# #+# */ /* Updated: 2018/08/06 20:58:01 by rnaumenk ### ########.fr */ /* */ /* ************************************************************************** */ #include "corewar.h" static int get_cycle_to_start(char *str) { int i; long num; if (str == NULL) exit_error("corewar needs at least one bot to work\n"); num = 0; i = 0; while (str[i] >= '0' && str[i] <= '9') num = (num * 10) + str[i++] - 48; if (i == 0 || str[i] != '\0') return (0); else if (num >= 1000000000) exit_error("to many cycles\n"); else if (i > 10) exit_error("incorect number of cycles\n"); return (num); } static int get_numer_of_cycles_before_dump(char *str) { int i; long num; if (str == NULL) exit_error("corewar needs at least one bot to work\n"); num = 0; i = 0; while (str[i] >= '0' && str[i] <= '9') num = (num * 10) + str[i++] - 48; if (i == 0 || str[i] != '\0') exit_error("incorect number of cycles\n"); else if (num >= 1000000000) exit_error("to many cycles\n"); else if (i > 10) exit_error("incorect number of cycles\n"); return (num); } void flag_searcher(t_vm *vm, char **argv, int *i) { if (str_compare(argv[1], "-a") && ++(*i)) vm->a_flag = 1; else if (str_compare(argv[1], "-v") && ++(*i)) { vm->v = 1; *i += ((vm->cycle_to_start = get_cycle_to_start(argv[2])) > 0 ? 1 : 0); } else if (str_compare(argv[1], "-dump")) { vm->dump = get_numer_of_cycles_before_dump(argv[2]); *i += 2; } }
C
/********************************************** * File: factDbl.c * Author: Matthew Morrison * Email: matt.morrison@nd.edu * * Calculates the factorial of an input value **********************************************/ #include <stdio.h> #include "Recurse.h" int main(){ unsigned int factVal = GetValidUInt(); fprintf( stdout, "%u! = %.0lf\n", factVal, factorialDbl( factVal ) ); return 0; }
C
//Includes and Global Variables: #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <ext2fs/ext2_fs.h> #include <string.h> #include <libgen.h> #include <sys/stat.h> #include "type.h" MINODE minode[NMINODE]; MINODE *root; PROC proc[NPROC], *running; int dev; int nblocks; int ninodes; int bmap; int imap; int iblock; /********** Functions as BEFORE ***********/ // Vars for getblock() char buf[BLKSIZE]; int fd; int get_block(int dev, int blk, char buf[ ]){ lseek(fd, (long)blk*BLKSIZE, 0); read(fd, buf, BLKSIZE); } int put_block(int dev, int blk, char buf[ ]) { lseek(fd, (long)blk*BLKSIZE, 0); write(fd, buf, BLKSIZE); } int tst_bit(char *buf, int bit) { int i, j; i = bit / 8; j = bit % 8; if (buf[i] & (1 << j)) return 1; return 0; } int set_bit(char *buf, int bit) { int i, j; i = bit/8; j=bit%8; buf[i] |= (1 << j); } int clr_bit(char *buf, int bit) { int i, j; i = bit/8; j=bit%8; buf[i] &= ~(1 << j); } /////////////////////////////////////////////////////////////// // Vars for get_tokens char *name[128]; char *pname = "/"; int j = 0, n = 0; get_tokens_from_pathname() { printf("\nPathname: %s\n", pname); // May have to remove an initial '/' // Get first token name[0] = strtok(pname, "/"); printf(" - name[0]: %s\n", name[0]); while (name[j] != NULL) { j++; name[j] = strtok(NULL, "/"); printf(" - name[%d]: %s\n", j, name[j]); } n = j; printf(" - n = %d\n", n); } /* 3. FS Level-1 Data Structures PROC* running MINODE *root | | | | ||********************* V | MINODE || PROC[0] V minode[100] || Disk dev ============= |-pointerToCWD-> ============ || ================== |nextProcPtr| | | INODE | || | INODEs |pid = 1 | | | ------- | || ================== |uid = 0 | | | (dev,2) | || |cwd --------->| | refCount | ||********************* | | | dirty | |fd[16] | | | | ------ | | - ALL 0 - | |==========| | ------ | | INODE | | ------ | | ------- | ============= | (dev,ino)| | refCount| PROC[1] ^ | dirty | pid=2 | uid=1 | cwd ----> root minode |==========| */ /* init() // Initialize data structures of LEVEL-1: { //(1). 2 PROCs, P0 with uid=0, P1 with uid=1, all PROC.cwd = 0 proc[0] = malloc(sizeof(PROC)); proc[0]->uid = 0; proc[0]->pid = 0; proc[0]->cwd = 0; proc[1] = malloc(sizeof(PROC)); proc[1]->uid = 1; proc[1]->pid = 0; proc[1]->cwd = 0; //(2). MINODE minode[100]; all with refCount=0 <----------------------------------------MOVED TO PASS1 int i = 0; for (i = 0; i < 100; i++) { minode[i] = malloc(sizeof(MINODE)); minode[i]->refCount = 0; } //(3). MINODE *root = 0; root = 0; } */ //4.1 Write C code for // MINODE *mip = iget(dev, ino) // load INODE at (dev,ino) into a minode[]; return mip->minode[] MINODE *iget(int dev, int ino) { int i, blk, disp; char buf[BLKSIZE]; MINODE *mip; INODE *ip; for (i=0; i < NMINODE; i++){ mip = &minode[i]; if (mip->dev == dev && mip->ino == ino){ mip->refCount++; printf("found [%d %d] as minode[%d] in core\n", dev, ino, i); return mip; } } for (i=0; i < NMINODE; i++){ mip = &minode[i]; if (mip->refCount == 0){ printf("allocating NEW minode[%d] for [%d %d]\n", i, dev, ino); mip->refCount = 1; mip->dev = dev; mip->ino = ino; // assing to (dev, ino) mip->dirty = mip->mounted = mip->mptr = 0; // get INODE of ino into buf[ ] blk = (ino-1)/8 + iblock; // iblock = Inodes start block # disp = (ino-1) % 8; //printf("iget: ino=%d blk=%d disp=%d\n", ino, blk, disp); get_block(dev, blk, buf); ip = (INODE *)buf + disp; // copy INODE to mp->INODE mip->INODE = *ip; return mip; } } printf("PANIC: no more free minodes\n"); return 0; } //4.2 Write C code for // int iput(MINDOE *mip) int iput(MINODE *mip) // dispose of a minode[] pointed by mip { int blk, disp; char buf[BLKSIZE]; INODE *ip; //(1). mip->refCount--; mip->refCount--; //(2). if (mip->refCount > 0) return; if(mip->refCount > 0) return; // if (!mip->dirty) return; if(!mip->dirty) return; //(3). /* write INODE back to disk */ printf("iput: dev=%d ino=%d\n", mip->dev, mip->ino); //Use mip->ino to compute //blk containing this INODE <-----------------------------------------------------------------------Is this right? //disp of INODE in blk blk = (mip->ino-1)/8 + iblock; // iblock = Inodes start block # disp = (mip->ino-1) % 8; get_block(mip->dev, blk, buf); ip = (INODE *)buf + disp; *ip = mip->INODE; put_block(mip->dev, blk, buf); } // Vars for search char dbuf[1024]; int i = 0; // Searches through data blocks to find entry specified by pathname int search(INODE * mip, char * name) { printf("\nSEARCHING FOR: %s", name); for (int i = 0; i < 12; i++) { if (mip->i_block[i] == 0) return 0; get_block(fd, mip->i_block[i], dbuf); // char dbuf[1024] DIR *dp = (SUPER *)dbuf; char *cp = dbuf; while (cp < &dbuf[1024]) { //use dp-> to print the DIR entries as [inode rec_len name_len name] //printf("\n - DIR ENTRY - rec_len: %d, name_len: %d, name: %s", dp->rec_len, dp->name_len, dp->name); if (strcmp(name, dp->name) == 0) { //printf("\n - Name: %s == %s", name, dp->name); printf("\n - Found at INODE: %d\n", dp->inode); return dp->inode; } //printf("\n - Name: %s != %s", name, dp->name); cp += dp->rec_len; dp = (DIR *)cp; //getchar(); } printf(" - Not Found\n"); return 0; } } //4.3 Write C code for // int ino = getino(int *dev, char *pathname) int getino(int *dev, char *pathname) { int i, ino, blk, disp; char buf[BLKSIZE]; INODE *ip; MINODE *mip; printf("getino: pathname=%s\n", pathname); if (strcmp(pathname, "/")==0) return 2; if (pathname[0]=='/') mip = iget(*dev, 2); else mip = iget(running->cwd->dev, running->cwd->ino); strcpy(buf, pathname); //int n = 0; //n = tokenize(buf); // n = number of token strings pname = pathname; get_tokens_from_pathname(); for (i=0; i < n; i++){ printf("===========================================\n"); printf("getino: i=%d name[%d]=%s\n", i, i, name[i]); ino = search(mip, name[i]); if (ino==0){ iput(mip); printf("name %s does not exist\n", name[i]); return 0; } iput(mip); mip = iget(*dev, ino); } return ino; }
C
#include "/d/dagger/aketon/short.h" inherit VAULT; void create() { ::create(); set_property("light",2); set_property("indoors",1); set_short("An elven house of Aketon"); set_long("%^GREEN%^An elven house of Aketon%^RESET%^\n"+ "You are standing in the living room of a tastefully decorated elven"+ " home. The floor is made of a large section of a tree branch that"+ " has been flattened out, it is quite wide here giving you plenty of"+ " room to walk around. There is a bookshelf in one corner that has"+ " a few leather bound volumes but is mostly taken up with small"+ " statues, dried flowers, and various gemstones. There is a lovely"+ " tapestry against the southern wall, with a matching rectangular"+ " mat that covers the center of the floor. There is a curtain of"+ " yellow silk that hangs to the west, giving some privacy to the"+ " next room. There is not much furniture in this room. You notice a"+ " small table with two chairs on the south side, but that is all."); set_smell("default","You are assaulted by the many smells of the " "forest."); set_listen("default","You hear the branches swaying in the wind."); set_items(([ ({"door","golden door"}) : "%^YELLOW%^The door is painted that same"+ " beautiful shade of gold on this side as well, it helps brighten the"+ " room.%^RESET%^", "bookshelf" : "There is a large oak bookshelf in the northeast corner"+ " of the room. You notice a few old and worn leather bound books that"+ " appear to contain mostly poetry or philosophy. Most of the other"+ " shelves are taken up by an interesting gem collection, a few statues"+ " made from various stones, and a couple of dried flowers.", ({"stones","gems","gemstones"}) : "Different gemstones cover the bookshelf."+ " Many are simple geods that have been split open to reveal their"+ " crystalline center. There are a couple gemstones that are a bit more"+ " rare, and a few you can't even place, but you have the feeling that"+ " they have been collected more for intrigue than for actual value.", "statues" : "There are a few statues on the shelves, you see an elephant"+ " carved from ivory, a serpent done in jade, and a cheetah made from"+ " leopard granite that gives the animal beautiful spots.", ({"flowers","dried flowers"}) : "There are a few dried flowers on the"+ " bookshelf as well. You notice a single purple rose as well as a smaller"+ " boquet of delicate wildflowers.", "tapestry" : "Hanging on the southern wall is a beautiful tapestry. It"+ " depicts the fall and has silken threads in the most brilliant and"+ " breath-taking shades of yellows, oranges, reds, and pinks.", ({"rectangular mat","mat"}) : "There is a large rectangular mat that"+ " stretches across the center of the room. It has a yellow border with"+ " a white center, patterned within which are geometric shapes in colors"+ " that nearly match the tapestry hanging on the wall, lovely reds,"+ " yellows, and oranges.", ({"curtain","silk curtain","yellow curtain","yellow silk curtain"}) : "%^YELLOW%^There"+ " is a curtain made of yellow silk that hangs across the entrance to the"+ " west, giving the next room some privacy. The bottom of the curtain is"+ " weighted with a few beads of fools gold.%^RESET%^", "table" : "There is a small wooden table that would be just big enough"+ " for two people to eat off of. It is flanked on either side by two"+ " wooden chairs.", ({"chairs","wooden chairs"}) : "There are two chairs made of oak that"+ " are on either side of the table. They are hand carved and fairly"+ " simple, but someone has carefully engraved beautiful rose and vine"+ " designs along the edges of them.", ])); set_door("golden door",RPATH3+"3one30","southeast",0); set_exits( (["southeast":RPATH3+"3one30", "west":RPATH3+"3one22"]) ); }
C
#include <stdio.h> int calc(int, int); int compars(char*, char*); int length(char *); int main(int argc,char** argv){ char *ville[11]= {"Brest","Grenoble","Lille","Lyon","Marseille","Nantes","Paris","Rennes","Rouen","Strasbourg","Toulouse"}; int ville1 = 0, ville2=0; if(3 != argc){ printf("Nombre de param\212tres insuffisant"); return 1; } int taille; taille = length(argv[1]); int j,i; char temp[taille+1]; for(j=0; j < taille; j++ ){ temp[j] = argv[1][j]; } temp[taille]='\0'; taille = length(argv[2]); char temp2[taille+1]; for(j=0; j < taille; j++ ){ temp2[j] = argv[2][j]; } temp2[taille]='\0'; for(j=0; j<11 ;j++){ if(1 == compars(ville[j],temp)){ ville1 = 1; break; } } for(i=0; i<11 ;i++){ if(1 == compars(ville[i],temp2)){ ville2=1; break; } } if (ville1 == 1 && ville2 ==1){ printf("%d",calc(j,i)); } else printf("-1"); return 0; } int calc(int x, int y){ int distance[11][11] ={ {0, 996, 723, 890, 1286, 305, 564, 245, 424, 1026, 884}, {-1, 0, 750, 104, 286, 711, 576, 747, 590, 505, 543} , {-1, -1, 0, 668, 979, 593, 224, 515, 194, 534, 905}, {-1, -1, -1, 0, 316, 607, 472, 645, 502, 434, 467}, {-1, -1, -1, -1, 0, 890, 769, 938, 757, 750, 400,}, {-1, -1, -1, -1, -1, 0, 386, 106, 315, 832, 559}, {-1, -1, -1, -1, -1, -1, 0, 348, 112, 447, 681}, {-1, -1, -1, -1, -1, -1, -1, 0, 249, 799, 665}, {-1, -1, -1, -1, -1, -1, -1, -1, 0, 497, 665}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 901}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0} }; if(distance[x][y] == -1){ return distance[y][x]; } else return distance[x][y]; } int length(char *t) { int taille = 0; do{ taille ++; }while(t[taille] != '\0'); return taille; } int compars(char* ville, char*temp){ int i,check = 1; for(i=0 ; i<4;i++){ if (ville[i]!= temp[i]){ i=4; check = 0; } } return check; }
C
#include <stdio.h> #include <stdlib.h> int sumdigit(int); int main(int argc, char *argv[]) { int n; n = atoi(*(argv+1)); printf("The sum of the digits of %d = %d\n",n,sumdigit(n)); return 0; } int sumdigit(int n) { int sum=0,rem; while(n > 0) { rem = n%10; sum += rem; n /= 10; } return sum; }
C
#define _POSIX_C_SOURCE 200809L #include "ProtocolS.h" #include <string.h> #include <stdio.h> #include <stdlib.h> #include <arpa/inet.h> #define ERROR 1 #define OK 0 #define SOCKET_CLOSED 2 void protocolS_init(protocolS_t *self, int fd) { socketC_setFd(& self -> peerSocket, fd); } int protocolS_receive(protocolS_t *self, char *buf, int bytesToReceive) { buf[bytesToReceive - 1] = 0; return socketC_receive(&self -> peerSocket, buf, bytesToReceive); } int protocolS_send(protocolS_t *self, char *buf, unsigned int lenght) { unsigned int x = htonl(lenght); int returnValue = socketC_send(&self -> peerSocket, (char*) &x, 4); if (returnValue != ERROR && returnValue != SOCKET_CLOSED) { returnValue = socketC_send(&self -> peerSocket, buf, lenght); } return returnValue; } void protocolS_release(protocolS_t *self) { socketC_release(&self -> peerSocket); }
C
#include <stdio.h> int* sum(int a, int b); int main(void) { int* resp; // resp = sum(10, 20); // Լ ޾Ƶ̴ ڵ printf(" : %d\n", *resp); return 0; } int* sum(int a, int b) { int res; // static res res = a + b; return &res; // res ּҰ ( ִ ּҰ ) }
C
#ifndef __SEMANTIC_PHASE10_H__INCLUDED__ #define __SEMANTIC_PHASE10_H__INCLUDED__ /* SEMANTIC PHASE 10 * * This declares the functions that are used to perform "phase 10" of the * semantic work for HWC: this converts the parse tree into a set of * internal HWC objects; this phase focuses on name resolution. */ #include "pt/all.h" #include "semantic/names.h" #include "semantic/part.h" #include "semantic/plugtype.h" #include "semantic/stmt.h" #include "semantic/expr.h" /* This takes a parse-tree at the file level as input, and returns a * newly-created NameScope object for that file. Inside that NameScope are * pointers to the various declarations inside the file; these allow you to * find the HWC_Part, HWC_PlugType, etc. pointers. * * Note that this function does *NOT* create an HWC_File object; that is * something which you can create to *contain* this NameScope (when/if that * is necessary). * * Also, note that you will be passed an object with a single refCount; if * you discard this NameScope, then you must decrement the refcount on it. */ HWC_NameScope *semPhase10_file(PT_file *parsedFile); /* ------- HELPER FUNCTIONS FOR THE ABOVE ------- * All of the rest of the functions below are helpers for the main function * above. That is, main() will call the above, and it will recurse down * through the structures of the parse tree, building the various semantic * structures. * * The new structure that we build will (more or less) mirror the parse tree, * except that linked lists will be converted into arrays. Also, decl * statements will be inlined into the statement arrays (in the semantic * phase, each statement can only contain a single declaration). * * There are a couple of query functions, which simply return int; these are * used to count the number of elements in a list, so that we can allocate * arrays. * * However, most of the logic in this phase is made up of objects that * convert parse tree structures into semantic structures. These functions * use three different types of return values, depending on the operation * which must be performed: * * - malloc() a struct and return it (like phase10_file() above); return * NULL on error. * * - Take two pointer parameters, an input and output. The output must * be allocated by the caller (often, as part of an array of such * objects). Returns 0 on success, nonzero on error. * * - Take an input parameter, which points to the parse tree, and two * output parameters: a pointer to an array variable, and a pointer * to an integer. Count the size of the parse tree, allocate an * array, fill the array, and store the array pointer and the length * using the output parameters. Returns 0 on success, nonzero on * error. * * In addition to the parameters mentioned above, many functions will also * take secondary paramters, which are important for the conversion * process. */ /* these build entire parts or plugtypes. They return newly-malloc()ed * objects. Each has a secondary parameter, which is the current * file-level name scope. */ HWC_Part *semPhase10_part (PT_part_decl *parsedPart, HWC_NameScope *fileScope); HWC_PlugType *semPhase10_plugtype(PT_plugtype_decl *parsedPlugtype, HWC_NameScope *fileScope); /* this counts the number of statements in a linked list; declarations are * inlined into the count, because each semantic statement can hold only * a *single* declaration. * * This function is *NOT* recursive; BLOCK, IF, and FOR statements each * show up as a single statement in this count (we will recurse when * *building* the statements, and build smaller arrays to represent the * nested statements). * * The input may be NULL; returns 0 in that case. * * Returns a count (which might be zero). Never reports any error. */ int countStmtsInPT(PT_stmt *stmtList); /* this converts an entire list of statements from the parse tree into * an array of semantic statements. Declarations are inlined as noted * previously. * * This function *does* recurse; when converting a BLOCK, IF, or FOR * statement, we will completely build all of the nested statements. * * This function will malloc() an array of semantic statements. If * the input was NULL (meaning no statements), then it will allocate * an array with a single STMT_NOP statement. * * The input is a pointer to the statement list. It also has two * output parameters, where we store the pointer to the allocated * array, and its length. * * The function also includes two name parameters (public and private); * the private may be NULL (in the case of statements inside of a plugtype), * but the public must never be NULL. * * This returns 0 on success, nonzero on error. This function will be * responsible for printing out any error message associated with any error; * the caller is not expected to print *anything*. */ int phase10_stmtList(PT_stmt *stmtList, HWC_Stmt **arr_out, int arrLen_out, HWC_NameScope *publicNames, HWC_NameScope *privateNames); /* these helper functions convert a single PT declaration or statement * into a pre-allocated statement object. The caller is expected to memset() * the struct, and set up the FileRange, mode, and name scopes before making * these calls. * * These functions return 0 on success, nonzero on error. As above, these * functions will print out any error messages required. * * DECL: This is weird, because we are inlining the declarations into the * statements. We call _common() on the first statement in the * inlined set - this fills in the common fields about the declaration * (type, memory, public, etc.). Then the _one() call is called on * each name in the list, passing it a pointer to the common struct * (which, in the case of the first decl, is the *same* object). This * will set up the the per-declaration fields. */ int phase10_stmt_DECL_common(PT_stmt *declStmt, HWC_Stmt *output); int phase10_stmt_DECL_on(PT_decl *declName, HWC_Stmt *output, HWC_Stmt *firstOfList); int phase10_stmt_CONN (PT_stmt *input, HWC_Stmt *output); int phase10_stmt_IF (PT_stmt *input, HWC_Stmt *output); int phase10_stmt_FOR (PT_stmt *input, HWC_Stmt *output); int phase10_stmt_BLOCK (PT_stmt *input, HWC_Stmt *output); int phase10_stmt_ASSERT(PT_stmt *input, HWC_Stmt *output); /* this helper function converts a parse tree expression into a semantic * expression. This returns the newly-created object on success, or NULL * on failure. */ HWC_Expr *phase10_expr(PT_expr *input); #endif
C
#include "stdlib.h" #include "stdint.h" #include "stdio.h" #include "limits.h" #include "string.h" int main() { printf("Implicit Test:\n"); printf("Test int INT32_MAX to short conversion with value loss\n"); int a=INT32_MAX; short c=a; printf("Test int to char\n"); char chc=a; printf("Test implicit long long to int conversion with value loss\n"); long long along=INT64_MAX; int cint=along; printf("Test signed to unsigned cast\n"); int sint=-1; unsigned int uint=sint; printf("Test unsigned to signed cast\n"); unsigned int u=UINT_MAX; int utos=(int)u; printf("Test malloc error:\n"); int amalloc=-111; char * ch=(char *)malloc(sizeof(char)*amalloc); char * cp,*cp1; cp=(char *)malloc(sizeof(char)*INT32_MAX); cp1=(char *)malloc(sizeof(char)*INT32_MAX); if(cp==NULL) { printf("mallocerror\n"); } if(cp1==NULL) { printf("mallocerror1\n"); } printf("Test strncpy:\n"); int scpy=-123; strncpy(cp1,cp,scpy); }
C
/* * Copyright 2011 Colomban Wendling <ban@herbesfolles.org> * * 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., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * */ #include "ggu-git-utils.h" #include <string.h> #include <stdlib.h> #include <sys/wait.h> #include <glib.h> /* FIXME: also check whether the path is known of Git, so don't return Git path * for a file Git don't know but that is in the tree? Or we want to have * it so we might add the file... maybe. */ gboolean ggu_git_parse_path (const gchar *path, gchar **root_, gchar **inner_path_) { gboolean found = FALSE; gchar *root; root = g_strdup (path); while (root && ! found) { gchar *guess; guess = g_build_filename (root, ".git", NULL); found = g_file_test (guess, G_FILE_TEST_IS_DIR); if (! found) { gchar *tmp; tmp = g_path_get_dirname (root); if (g_strcmp0 (tmp, root) == 0) { g_free (tmp); tmp = NULL; } g_free (root); root = tmp; } g_free (guess); } if (found) { if (root_) { *root_ = g_strconcat (root, G_DIR_SEPARATOR_S, NULL); } if (inner_path_) { gsize len = strlen (root); while (path[len] == G_DIR_SEPARATOR || path[len] == '/') { len++; } *inner_path_ = g_strdup (&path[len]); } } g_free (root); return found; } /** * ggu_git_utf8_ensure_valid: * @str: A string * * Makes @str valid UTF-8, replacing invalid bytes by Unicode U+FFFD. * * Returns: A newly allocated copy of @str as a valid UTF-8 string. */ gchar * ggu_git_utf8_ensure_valid (const gchar *str) { const gchar *end; gboolean valid; GString *valid_str; valid_str = g_string_new (NULL); do { valid = g_utf8_validate (str, -1, &end); g_string_append_len (valid_str, str, end - str); if (! valid) { g_string_append_unichar (valid_str, 0xfffd); str = end + 1; } } while (! valid); return g_string_free (valid_str, FALSE); } /** * ggu_git_is_hash: * @hash: a string * * Checks if a string is a possibly valid Git hash * * Returns: whether @str looks OK */ gboolean ggu_git_is_hash (const gchar *hash) { guint i; for (i = 0; hash[i]; i++) { if (! g_ascii_isxdigit (hash[i])) { return FALSE; } } return i == 40; }
C
/*Volume of prism*/ #include <stdio.h> void main(){ float b,h1,h2,vol,area; b = 5; h1 = 5; //base triangle height h2 = 5; //prism height /*printf("Enter the base length of triangle>> "); scanf("%f",&b); printf("Enter the base height of triangle>> "); scanf("%f",&h1); printf("Enter the height of triangle>> "); scanf("%f",&h2);*/ area = (0.5)*b*h1; vol = area*h2; printf("The area of the prism with base triangle length %.2f,height of base triangle %.2f and prism height %.2f is %.2f",b,h1,h2,vol); }
C
#include <func.h> void sigFunc(int signum,siginfo_t *p,void *p1){ sleep(5); } int main(int argc,char* argv[]){ sigset_t mask; sigemptyset(&mask); sigfillset(&mask); // 防止所有信号触及关键代码 int ret=sigprocmask(SIG_BLOCK,&mask,NULL); ERROR_CHECK(ret,-1,"sigprocmask"); struct sigaction act; bzero(&act,sizeof(act)); act.sa_sigaction=sigFunc; act.sa_flags=SA_SIGINFO; sigaddset(&act.sa_mask,SIGINT); sigpending(&mask); if(sigismember(&mask,SIGINT)){ printf("SIGINT is pending\n"); }else{ printf("SIGINT is not pending\n"); } ret=sigprocmask(SIG_UNBLOCK,&mask,NULL);// ERROR_CHECK(ret,-1,"sigprocmask"); printf("programme over\n"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strncmp.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mbutt <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/26 15:09:24 by mbutt #+# #+# */ /* Updated: 2019/03/12 15:34:03 by mbutt ### ########.fr */ /* */ /* ************************************************************************** */ /* ** The strcmp() and strncmp() functions lexicographically compare the ** null-terminated strings s1 and s2. ** The strncmp() function compares not more than n characters. Because strncmp() ** is designed for comparing strings rather than binary data, characters that ** appear after a `\0' character are not compared. ** RETURN VALUES: The strcmp() and strncmp() functions return an integer greater ** than, equal to, or less than 0, according as the string s1 is greater than, ** equal to, or less than the string s2. The comparison is done using unsigned ** characters, so that `\200' is greater than `\0'. */ #include "libft.h" int ft_strncmp(const char *s1, const char *s2, size_t n) { int i; i = 0; while (n && (s1[i] != '\0' || s2[i] != '\0')) { if (s1[i] != s2[i]) return ((unsigned const char)s1[i] - (unsigned const char)s2[i]); n--; i++; } return (0); } /* ** Method 2 by using pointers. ** int ft_strncmp(const char *s1, const char *s2) ** { ** while (n && (*s1 != '\0' || *s2 != '\0')) ** { ** if ((*s1 != *s2)) ** return (*(unsigned const char *)s1 - *(unsigned const char *)s2); ** n--; ** s1++; ** s2++; ** } ** return (0); ** ** } */ /* ** int main (void) ** { ** char *string1 = "Ttesting this test, but is it a good test"; ** char *string2 = "test"; ** size_t n = 4; ** printf("%d", strncmp(string1, string2, n)); ** printf("\n%d", ft_strncmp(string1, string2, n)); ** return(0); ** } */
C
#include <winsock2.h> #include <stdio.h> #include <stdlib.h> #pragma comment(lib, "ws2_32.lib") int envoie(char paquet[]) { WSADATA WSAData; SOCKET sock; SOCKET csock; SOCKADDR_IN sin; SOCKADDR_IN csin; int sinsize = sizeof(csin); WSAStartup(MAKEWORD(2, 0), &WSAData); sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_addr.s_addr = INADDR_ANY; sin.sin_family = AF_INET; sin.sin_port = htons(80); bind(sock, (SOCKADDR *)&sin, sizeof(sin)); listen(sock, 0); csock = accept(sock, (SOCKADDR *)&csin, &sinsize); send(csock, paquet, 16, 0); WSACleanup(); closesocket(csock); return 0; } int reception(char IP[]) { WSADATA WSAData; SOCKET sock; SOCKADDR_IN sin; char buffer[255]; WSAStartup(MAKEWORD(2, 0), &WSAData); sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_addr.s_addr = inet_addr(IP); sin.sin_family = AF_INET; sin.sin_port = htons(80); connect(sock, (SOCKADDR *)&sin, sizeof(sin)); recv(sock, buffer, sizeof(buffer), 0); printf("%s", buffer); closesocket(sock); WSACleanup(); return 0; } int main() { char paquet[] = "gros chien"; envoie(paquet); //char IP[] = "86.195.96.56"; //reception(IP); return 0; }
C
#include<stdio.h> #include<math.h> int i=0; int f(int x) { int s=1; for(i=0; i<x; i++) s*=i+1; return s; } int binomial(int n, int k, int type) { if(type == 1) { return f(n)/(f(k)*f(n-k)); } else if(type == 2) { int s=1; for(i=0; i<k; i++) s*=n-i; s/=f(k); return s; } else { if(k == 0 || n == k) return 1; else return binomial(n-1, k, type) + binomial(n-1, k-1, type); } } int main() { int n,k,type; double temp; printf("enter a natural number n greater or equal to 0\n"); scanf("%lf", &temp); n = (int) temp; if(n==temp && n>=0) { printf("enter a natural number k greater or equal to 0 and smaller than n\n"); scanf("%lf", &temp); k = (int) temp; if(k==temp && k>=0 && n>=k) { printf("enter a natural number type greater than 0 and smaller than 4\n"); scanf("%lf", &temp); type = (int) temp; if(type==temp && type>0 && type<4) { printf("(n, k) = %i\n", binomial(n, k, type)); } else { printf("you didn't enter an integer greeater or equal to 0\n"); return 1; } } else { printf("you didn't enter an integer greeater or equal to 0\n"); return 1; } } else { printf("you didn't enter an integer greeater or equal to 0\n"); return 1; } return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> int main(void){ int req; int ans; int n1 = 0, n2 = 0; do { req=open("/tmp/fifo_req",O_WRONLY); if (req==-1) sleep(1); } while (req==-1); do { ans=open("/tmp/fifo_ans",O_RDONLY); if (ans==-1) sleep(1); } while (ans==-1); do{ char* no1 = malloc(100); char* no2 = malloc(100); char* send = malloc(200); write(STDOUT_FILENO, "NUMBER1: ", strlen("NUMBER1: ")); read(STDOUT_FILENO,no1,100); write(STDOUT_FILENO, "NUMBER2: ", strlen("NUMBER2: ")); read(STDOUT_FILENO,no2,100); sprintf(send, "%s %s", no1, no2); n1 = atof(no1);free(no1); n2 = atof(no2);free(no2); if (n1 == 0 && n2 == 0){ free(send); break; } write(req, send, strlen(send)); free(send); char* res = malloc(100); read(ans, res, 100); printf("%s", res); free(res); }while(1); exit(0); }
C
# include <stdio.h> # include <stdlib.h> # include <string.h> # include <err.h> # include "../headers/analysis.h" # include "../headers/encode.h" const char *alpha_ = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; //----------------------------------------------------------------------------- // Tools functions //----------------------------------------------------------------------------- char* adjustString(char* data, char* input, size_t limit, size_t size , size_t in_len) { if(limit <= size + in_len) { limit = size + in_len + 1; data = realloc(data, size + in_len + 1); } data = strcat(data, input); return data; } size_t getDec(char _char) { size_t i = 0; while(_char != alpha_[i]) ++i; return i; } //----------------------------------------------------------------------------- // End of tools functions //----------------------------------------------------------------------------- char* num_encoding(char* data, size_t len) { // We need to create (len / 3) pair (if len %3 == 0) else add 1 more // then convert it to binary size_t nbpair; if(len < 3) nbpair = 1; else if(len % 3 == 0) nbpair = len / 3; else nbpair = (len / 3) + 1; char* enc_message = calloc(nbpair * 10, sizeof(char)); enc_message[0] = '\0'; size_t size = 0; size_t i = 0; size_t k = 0; while(i < len) { char* pair = calloc(4, sizeof(char)); pair[3] = '\0'; /* * We need to take care of the pair which are composed of 0 * like : 001 or 052 or 000 or 090 ; which might be wrongly recognized * such as : 1 or 52 or 0 or 90 instead of 001/052/000/090 */ for(int y = 0; y < 3 && i < len; ++y, ++i) { pair[y] = data[i]; pair[y + 1] = '\0'; } size_t i_ter = strtol(pair, NULL, 10); char* bits = convertToByte(i_ter); if(k < nbpair - 1) { bits = adjustSizeInv(bits, 10); } else { if(pair[0] == '0' && pair[1] != '0') bits = adjustSizeInv(bits, 7); else if(pair[0] == '0' && pair[1] == '0') bits = adjustSizeInv(bits, 4); } enc_message = adjustString(enc_message, bits, nbpair * 10, size, 10); size += 10; free(pair); free(bits); ++k; /*for(int y = 0; y < 3 && i < len; ++y, ++i) { pair[y] = data[i]; pair[y + 1] = '\0'; } size_t numC = strtol(pair, NULL, 10); char *bits = convertToByte(numC); printf("k = %li && %li\n", k, len / 3); if(k < nbpair - 1) bits = adjustSizeInv(bits, 10); else if(k == (len / 3)) { { if(numC < 100) bits = adjustSizeInv(bits, 7); if(numC < 10) bits = adjustSizeInv(bits, 4); } } enc_message = adjustString(enc_message, bits, nbpair * 10, size, 10); size += 10; //printf("%s ", bits); free(pair); free(bits); ++k;*/ } //printf("\nResult : %s\n", enc_message); return enc_message; } char* alpha_encoding(char* data, size_t len) { // We need to create (len / 3) pair (if len %3 == 0) else add 1 more // then convert it to binary size_t nbpair; if(len % 2 == 0) nbpair = len / 2; else nbpair = (len / 2) + 1; char* enc_message = calloc(nbpair * 10, sizeof(char)); enc_message[0] = '\0'; // put a terminating symbole at the start size_t size = 0; // actual used space of the enc_message pointer size_t i = 0; // position in the input while(i < len) { int* pair = calloc(2, sizeof(int)); for(int y = 0; y < 2 && i < len; ++y, ++i) { pair[y] = getDec(data[i]); if(y + 1 < 2 && i + 1 >= len) pair[y + 1] = -1; } size_t bin_num = 0; // variable for stocking the decimal value of the pair char *bits; // variable for stocking the value converted into binary if(pair[1] == -1) { // if for one character bin_num = pair[0]; bits = convertToByte(bin_num); bits = adjustSize(bits, 6); } else { // else for more than 1 character bin_num = (pair[0] * 45) + pair[1]; bits = convertToByte(bin_num); bits = adjustSize(bits, 11); } /*printf("bin_num : %li\n", bin_num); printf("bits : %s\n", bits);*/ // then we concatenate the binary and the whole encoded message enc_message = adjustString(enc_message, bits, nbpair * 10, size, 11); // we increment the used size of the encoded message var if(pair[1] == -1) size += 6; else size += 11; // we free for avoiding leaking free(pair); free(bits); } return enc_message; } char* byte_encoding(char* data, size_t len) { //printf("Len : %li\n", len); char* enc_message = calloc(len * 8, sizeof(char)); enc_message[0] = '\0'; size_t size = 0; size_t i = 0; while(i < len) { size_t numC = (size_t)data[i]; char *bits = convertToByte(numC); bits = adjustSize(bits, 8); enc_message = adjustString(enc_message, bits, len * 8, size, 8); size += 8; free(bits); /*printf("i : %li\n", i + 1); printf("Dec : %li = %c\n", numC, data[i]);*/ ++i; } return enc_message; }
C
#include <stdio.h> static void swap (int nums[], int i, int j); static void prettyPrint (int nums[], int length); static void shuffle (int nums[], int length); static void sort (int nums[], int low, int high); static void insertion_sort (int nums[], int low, int high); void quicksort (int nums[], int length); int main (void) { int nums[] = { 100, 3983, 839, 93, 738, 9230, 993, 2, 4, 23, 43, 53, 10, 9, 8, 7, 5, 5, 10, 9, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1 }; int length = sizeof(nums) / sizeof(nums[0]); prettyPrint(nums, length); quicksort(nums, length); prettyPrint(nums, length); return 0; } void quicksort (int nums[], int length) { shuffle(nums, length); sort(nums, 0, (length - 1)); } static void sort (int nums[], int low, int high) { if (high <= (low + 10)) { insertion_sort(nums, low, high); return; } int first = low; int second = high; int pivot = nums[low]; int i = low; while (i <= second) { if (nums[i] < pivot) { swap(nums, i++, first++); } else if (nums[i] > pivot) { swap(nums, i, second--); } else { i++; } } sort(nums, low, (first - 1)); sort(nums, (second + 1), high); } static void shuffle (int nums[], int length) { srand(time(NULL)); int i; for (i = 1; i <= (length - 1); i++) { int r = rand(); r = (r % (i + 1)); swap(nums, r, i); } } static void insertion_sort (int nums[], int low, int high) { int i, j; for (i = low; i <= high; i++) { for (j = i; j > 0; j--) { if (nums[j] < nums[j - 1]) { swap(nums, j, (j - 1)); } } } } static void swap (int nums[], int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } static void prettyPrint (int nums[], int length) { int i; for (i = 0; i < length; i++) { printf("%d ", nums[i]); } printf("\n"); }
C
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> int fib(int n){ int next_reuslt; int pre_result = 1; int result = 1; while (n > 2){ n -= 1; next_reuslt = pre_result; pre_result = result; result = next_reuslt + pre_result; } return result; } int main(){ int f,n=0; printf("ڼ쳲:"); scanf("%d", &n); f = fib(n); printf("%d", f); system("pause"); return 0; }
C
#include "led.h" //ʼPE0PE2Ϊ.ʹڵʱ //LED IOʼ void LED_Init(void) { GPIO_InitTypeDef GPIO_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE, ENABLE); //ʹPE˿ʱ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0|GPIO_Pin_2; //LED0-->PE.0 ˿ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; // GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //IOٶΪ50MHz GPIO_Init(GPIOE, &GPIO_InitStructure); //趨ʼGPIOE.0 GPIO_SetBits(GPIOE,GPIO_Pin_0|GPIO_Pin_2); //PE.0 //ֱ۵ // RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOF, ENABLE); //ʹPE˿ʱ // // GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5|GPIO_Pin_6; //LED0-->PE.0 ˿ // GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; // // GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //IOٶΪ50MHz // GPIO_Init(GPIOF, &GPIO_InitStructure); //趨ʼGPIOE.0 // GPIO_SetBits(GPIOF,GPIO_Pin_5|GPIO_Pin_6); //PE.0 }
C
#include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int ar[n]; for(int i=0;i<n;i++) cin>>ar[i]; int jump=0; int i=0; while(i<n) { if(ar[i+2]==0) { jump++; i=i+2; } else if(ar[i+1]==0) { jump++; i++; } } cout<<jump-1<<endl; return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <limits.h> #include "utils.h" //INT_MAXを新しく確保した配列の最後に入れる int *appendMax(int ary[], int size) { int *p;//新しく確保した配列の先頭アドレス //ここにコードを書く p = (int*) malloc((size + 1) * sizeof(int)); int i; for (i =0; i < size+1; i++) { if (i != size) p[i] = ary[i]; else p[i] = INT_MAX; } return p; } //これ以降は変更しない int main(int argc, char *argv[]) { int *numbers, *numbersWithMax, size; //引数で読み込むファイルを指定 char *filename = argv[1]; size = set_array(filename, &numbers); print_array(numbers, size); numbersWithMax = appendMax(numbers, size); print_array(numbersWithMax, size + 1); free(numbersWithMax); return 0; }
C
#include <stdio.h> void non_ref(int i) { printf("non_ref: %016x\n", &i); printf(" : %d\n", i); // 値を使うとき } void ref(int *pi) { printf("ref: %016x\n", pi); printf(" : %d\n", *pi); // 値を使うとき } int main() { // int i = 10; // printf("base: %016x\n", &i); printf(" : %d\n", i); // non_ref(i); ref(&i); // return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* separate_lines.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: apoplavs <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/06/11 12:41:20 by apoplavs #+# #+# */ /* Updated: 2017/06/15 15:38:40 by ikryvenk ### ########.fr */ /* */ /* ************************************************************************** */ #include "asm.h" char **separate_line(char *line, int i, int l, char *str) { char **tab; str[l] = line[i]; while (line[i]) { str[++l] = line[++i]; if (line[i] == LABEL_CHAR && line[i - 1] != DIRECT_CHAR && line[i - 1] != ' ' && line[i - 1] != SEPARATOR_CHAR) str[++l] = ' '; if (line[i] == DIRECT_CHAR || (line[i] == '-' && ft_isdigit(line[i + 1]) && line[i - 1] != DIRECT_CHAR)) { str[l + 1] = str[l]; str[l++] = ' '; } if (str[l] == SEPARATOR_CHAR && str[l - 1] == ' ') { while (str[l - 1] == ' ') l--; str[l] = SEPARATOR_CHAR; } } tab = ft_strsplit(str, ' '); free(str); return (tab); } void trim_line(char *line, t_asm *file) { char **tab; int i; t_line *s; i = 0; convert_tabs(line); s = file->code; while (s->next) s = s->next; s->line = ft_strnew(ft_strlen(line)); tab = separate_line(line, 0, 0, ft_strnew(ft_strlen(line) + 8)); ft_strcpy(s->line, tab[0]); while (tab[++i]) { if (s->line[ft_strlen(s->line) - 1] != SEPARATOR_CHAR) s->line[ft_strlen(s->line)] = ' '; ft_strcat(s->line, tab[i]); } free(line); line = ft_strchr(s->line, COMMENT_CHAR); ft_strclr(line); if (s->line[ft_strlen(s->line) - 1] == ' ') s->line[ft_strlen(s->line) - 1] = '\0'; del_tab(tab); } void make_line(t_asm *file) { t_line *line; t_line *p; line = malloc(sizeof(t_line)); line->line = NULL; line->next = NULL; if (!file->code) file->code = line; else { p = file->code; while (p && p->next) p = p->next; p->next = line; } }
C
#include <CL/cl.h> #include <stdio.h> #include <string.h> #include <malloc.h> int main() { cl_platform_id *platform; cl_uint num_platform; cl_int err; err = clGetPlatformIDs(0,NULL,&num_platform); platform =(cl_platform_id *)malloc(sizeof(cl_platform_id)*num_platform); err = clGetPlatformIDs(num_platform,platform,NULL); for(int i = 0;i < num_platform;i++) { size_t size; err = clGetPlatformInfo(platform[i],CL_PLATFORM_NAME,0,NULL,&size); char *PName = (char *)malloc(size); err = clGetPlatformInfo(platform[i],CL_PLATFORM_NAME,size,PName,NULL); printf("\n CL_PLATFORM_NAME: %s\n",PName); err = clGetPlatformInfo(platform[i],CL_PLATFORM_VENDOR,0,NULL,&size); char *PVendor = (char *)malloc(size); err = clGetPlatformInfo(platform[i],CL_PLATFORM_VENDOR,size,PVendor,NULL); printf("\n CL_PLATFORM_VENDOR: %s\n",PVendor); err = clGetPlatformInfo(platform[i],CL_PLATFORM_VERSION,0,NULL,&size); char *PVersion = (char *)malloc(size); err = clGetPlatformInfo(platform[i],CL_PLATFORM_VERSION,size,PVersion,NULL); printf("\n CL_PLATFORM_VERSION: %s\n",PVersion); err = clGetPlatformInfo(platform[i],CL_PLATFORM_PROFILE,0,NULL,&size); char *PProfile = (char *)malloc(size); err = clGetPlatformInfo(platform[i],CL_PLATFORM_PROFILE,size,PProfile,NULL); printf("\n CL_PLATFORM_PPROFILE: %s\n",PProfile); err = clGetPlatformInfo(platform[i],CL_PLATFORM_EXTENSIONS,0,NULL,&size); char *PExten = (char *)malloc(size); err = clGetPlatformInfo(platform[i],CL_PLATFORM_EXTENSIONS,size,PExten,NULL); printf("\n CL_PLATFORM_EXTENSIONS: %s\n",PExten); free(PName); free(PVendor); free(PVersion); free(PProfile); free(PExten); } }
C
#include <stdio.h> //Add vectors in sum notation and multiply vectors in p-adic notation in GR(9,2) where xi satisfies the monic irreducible //x^2 +4x+8 int mult(int (*x)[2], int (*y)[2], int (*z)[2], int *** a){ int i,j; int w[1][2]; if(x[0][0] == 8 || x[0][1] == 8 || y[0][1] == 8 || y[0][0] == 8){ if(x[0][0] == 8 && x[0][1] != 8 && y[0][1] != 8 && y[0][0] != 8){ z[0][0] = 8; z[0][1] = (x[0][1] + y[0][0]) % 8; } else if(x[0][1] == 8 && x[0][0] != 8 && y[0][1] != 8 && y[0][0] != 8){ z[0][0] = (x[0][0] + y[0][0]) % 8; z[0][1] = (x[0][0] + y[0][1]) % 8; } else if(y[0][1] == 8 && x[0][1] != 8 && x[0][0] != 8 && y[0][0] != 8){ z[0][0] = (x[0][0] + y[0][0]) % 8; z[0][1] = (x[0][1] + y[0][0]) % 8; } else if(y[0][0] == 8 && x[0][1] != 8 && y[0][1] != 8 && x[0][0] != 8){ z[0][0] = 8; z[0][1] = (x[0][0] + y[0][1]) % 8; } else if((y[0][0] ==8 && y[0][1] ==8) || (x[0][0] == 8 && x[0][1] == 8)){ z[0][0] = 8; z[0][1] = 8; } else if((x[0][0] == 8 && x[0][1] != 8 && y[0][0] != 8 && y[0][1] == 8)){ z[0][0] = 8; z[0][1] = (x[0][1] + y[0][0]) % 8; } else if((x[0][0] != 8 && x[0][1] == 8 && y[0][0] == 8 && y[0][1] != 8)){ z[0][0] = 8; z[0][1] = (x[0][0] + y[0][1]) % 8; } else if((x[0][0] != 8 && y[0][0] != 8 && x[0][1] == 8 && y[0][1] == 8)){ z[0][0] = (x[0][0] + y[0][0]) % 8; z[0][1] = 8; } else if((x[0][1] != 8 && y[0][1] != 8 && x[0][0] == 8 && y[0][0] == 8)){ z[0][0] = 8; z[0][1] = 8; } else if((x[0][1] == 8 && y[0][1] == 8 && x[0][0] == 8 && y[0][0] == 8)){ z[0][0] = 8; z[0][1] = 8; } } else{ z[0][0] = (x[0][0] + y[0][0]) % 8; w[0][0] = (x[0][0] + y[0][1]) % 8; w[0][1] = (x[0][1] + y[0][0]) % 8; for(i=0; i<9;i++){ for(j = 0; j< 5; j++){ if((a[i][j][0] == w[0][0] && a[i][j][1] == w[0][1]) || (a[i][j][0] == w[0][1] && a[i][j][1]==w[0][0])){ z[0][1] = i; } } } } return 0; } int sum(int (*x)[2], int (*y)[2], int (*z)[2]){ z[0][0] = (x[0][0]+y[0][0]) % 9; z[0][1] = (x[0][1]+y[0][1]) % 9; return 0; } int main(){ int a[1][2]; int b[1][2]; int c[1][2]; int d[1][2]; char str1[6]; char str2[6]; int p,s,m,i,j,k,l; p = 3; s = p*p; m = s*s; int ***lk1 = (int ***)malloc(9*sizeof(int**)); for(i = 0; i < 9 ; i++){ if(i ==0 || i == 1 || i == 5 || i == 7 || i ==8){ lk1[i] = (int **)malloc(5*sizeof(int *)); for(j = 0; j<5;j++){ lk1[i][j] = (int *)malloc(2*sizeof(int)); } } else if(i == 2 || i == 4){ lk1[i] = (int **)malloc(5*sizeof(int *)); for(j = 0; j<5;j++){ lk1[i][j] = (int *)malloc(2*sizeof(int)); } } else{ lk1[i] = (int **)malloc(5*sizeof(int *)); for(j = 0; j<5;j++){ lk1[i][j] = (int *)malloc(2*sizeof(int)); } } } //Matrix declaration, first dimension is an integer between 0 and 8 which represents //the power of xi left over after adding the powers of xi (8 represents 0 which is //not a power of xi). lk1[0][0][0] = 1; lk1[0][0][1] = 2; lk1[0][1][0] = 3; lk1[0][1][1] = 6; lk1[0][2][0] = 4; lk1[0][2][1] = 4; lk1[0][3][0] = 5; lk1[0][3][1] = 7; lk1[0][4][0] = 11; lk1[0][4][1] = 11; lk1[1][0][0] = 2; lk1[1][0][1] = 3; lk1[1][1][0] = 4; lk1[1][1][1] = 7; lk1[1][2][0] = 5; lk1[1][2][1] = 5; lk1[1][3][0] = 6; lk1[1][3][1] = 0; lk1[1][4][0] = 11; lk1[1][4][1] = 11; lk1[2][0][0] = 1; lk1[2][0][1] = 7; lk1[2][1][0] = 3; lk1[2][1][1] = 4; lk1[2][2][0] = 5; lk1[2][2][1] = 0; lk1[2][3][0] = 6; lk1[2][3][1] = 6; lk1[2][4][0] = 11; lk1[2][4][1] = 11; lk1[3][0][0] = 1; lk1[3][0][1] = 6; lk1[3][1][0] = 2; lk1[3][1][1] = 0; lk1[3][2][0] = 3; lk1[3][2][1] = 4; lk1[3][3][0] = 4; lk1[3][3][1] = 5; lk1[3][4][0] = 7; lk1[3][4][1] = 7; lk1[4][0][0] = 1; lk1[4][0][1] = 3; lk1[4][1][0] = 2; lk1[4][1][1] = 7; lk1[4][2][0] = 5; lk1[4][2][1] = 6; lk1[4][3][0] = 0; lk1[4][3][1] = 0; lk1[4][4][0] = 11; lk1[4][4][1] = 11; lk1[5][0][0] = 1; lk1[5][0][1] = 1; lk1[5][1][0] = 2; lk1[5][1][1] = 4; lk1[5][2][0] = 3; lk1[5][2][1] = 0; lk1[5][3][0] = 6; lk1[5][3][1] = 7; lk1[5][4][0] = 11; lk1[5][4][1] = 11; lk1[6][0][0] = 1; lk1[6][0][1] = 4; lk1[6][1][0] = 2; lk1[6][1][1] = 2; lk1[6][2][0] = 2; lk1[6][2][1] = 7; lk1[6][3][0] = 3; lk1[6][3][1] = 5; lk1[6][4][0] = 7; lk1[6][4][1] = 0; lk1[7][0][0] = 1; lk1[7][0][1] = 0; lk1[7][1][0] = 2; lk1[7][1][1] = 5; lk1[7][2][0] = 3; lk1[7][2][1] = 3; lk1[7][3][0] = 4; lk1[7][3][1] = 6; lk1[7][4][0] = 11; lk1[7][4][1] = 11; lk1[8][0][0] = 1; lk1[8][0][1] = 5; lk1[8][1][0] = 2; lk1[8][1][1] = 6; lk1[8][2][0] = 3; lk1[8][2][1] = 7; lk1[8][3][0] = 4; lk1[8][3][1] = 0; lk1[8][4][0] = 11; lk1[8][4][1] = 11; int lt[81][4]; FILE *file; file = fopen("lt.txt","r"); if(file == NULL){ printf("unable to open file \n"); } for(i = 0; i < 81; i++){ for(j = 0; j < 4 ; j++){ if(!fscanf(file, "%d", &lt[i][j])){ break; } } } fclose(file); printf("Enter the first vector entry by entry separated by a space: \n"); scanf("%d %d", &a[0][0], &a[0][1]); printf("Enter the second vector entry by entry separated by a space: \n"); scanf("%d %d", &b[0][0], &b[0][1]); printf("Enter operation (either sum or mult): \n"); scanf("%s", &str1); if(strcmp(str1, "sum")==0){ sum(a,b,c); printf("the sum is (%d, %d) \n", c[0][0], c[0][1]); } else{ mult(a,b,c,lk1); printf("the product is (%d, %d) \n", c[0][0], c[0][1]); } printf("Continue? (y/n): \n"); scanf("%s", &str2); if(strcmp(str2,"y")==0){ printf("Enter the first vector entry by entry separated by a space: \n"); scanf("%d %d", &a[0][0], &a[0][1]); printf("Enter the second vector entry by entry separated by a space: \n"); scanf("%d %d", &b[0][0], &b[0][1]); printf("Enter operation (either sum or mult): \n"); scanf("%s", &str1); if(strcmp(str1, "sum")==0){ sum(a,b,c); printf("the sum is (%d, %d) \n", c[0][0], c[0][1]); } else{ mult(a,b,c,lk1); printf("the product is (%d, %d) \n", c[0][0], c[0][1]); } printf("Continue? (y/n): \n"); scanf("%s", &str2); } else{ printf("Done \n"); } //mult(a,b,c,lk1); return 0; }
C
#include "cpfphig/cpfphig.h" #include "cpfphig/list.h" #include "cpfphig/unit/mock/list_mock.h" #include "cpfphig/malloc.h" #include "cpfphig/free.h" #include <stdarg.h> #include <stddef.h> #include <setjmp.h> #include <cmocka.h> #include <stdio.h> static void arguments( void** state ) { int item = 11; struct cpfphig_error error = CPFPHIG_CONST_CPFPHIG_ERROR; printf("invalid List\n"); assert_int_equal( CPFPHIG_FAIL, real_cpfphig_list_push( NULL, &item, NULL ) ); printf("invalid List with error\n"); expect_value( cpfphig_error_message_call, Error_Type, cpfphig_system_error ); expect_string( cpfphig_error_message_call, Format, "List is NULL"); assert_int_equal( CPFPHIG_FAIL, real_cpfphig_list_push( NULL, &item, &error ) ); } static void first_push( void** state ) { struct cpfphig_list list = CPFPHIG_CONST_CPFPHIG_LIST; int item = 11; expect_value(cpfphig_malloc, Size, sizeof( struct cpfphig_list_node ) ); will_return( cpfphig_malloc, CPFPHIG_OK ); assert_int_equal(CPFPHIG_OK, real_cpfphig_list_push( &list, &item, NULL ) ); assert_non_null( list.first ); assert_non_null( list.last ); assert_null( list.first->next ); assert_null( list.first->previous ); expect_any( cpfphig_free, Ptr ); will_return( cpfphig_free, CPFPHIG_OK ); assert_int_equal( CPFPHIG_OK, cpfphig_free( &(list.first), NULL ) ); } static void subsequent_push( void** state ) { struct cpfphig_list list = CPFPHIG_CONST_CPFPHIG_LIST; int first_item = 11; int second_item = 22; expect_value(cpfphig_malloc, Size, sizeof( struct cpfphig_list_node ) ); will_return( cpfphig_malloc, CPFPHIG_OK ); assert_int_equal(CPFPHIG_OK, real_cpfphig_list_push( &list, &first_item, NULL ) ); expect_value(cpfphig_malloc, Size, sizeof( struct cpfphig_list_node ) ); will_return( cpfphig_malloc, CPFPHIG_OK ); assert_int_equal(CPFPHIG_OK, real_cpfphig_list_push( &list, &second_item, NULL ) ); assert_non_null( list.first ); assert_non_null( list.last ); assert_int_equal( 11, *(int*)(list.first->item) ); assert_int_equal( 22, *(int*)(list.last->item) ); assert_non_null( list.first->next ); assert_null( list.first->previous ); assert_null( list.last->next ); assert_non_null( list.last->previous ); assert_int_equal( 11, *(int*)(list.last->previous->item) ); assert_int_equal( 22, *(int*)(list.first->next->item) ); expect_any_count( cpfphig_free, Ptr, 2 ); will_return_count( cpfphig_free, CPFPHIG_OK, 2 ); assert_int_equal( CPFPHIG_OK, cpfphig_free( &(list.first->next), NULL ) ); assert_int_equal( CPFPHIG_OK, cpfphig_free( &(list.first), NULL ) ); } static void push_null( void** state ) { struct cpfphig_list list = CPFPHIG_CONST_CPFPHIG_LIST; expect_value(cpfphig_malloc, Size, sizeof( struct cpfphig_list_node ) ); will_return( cpfphig_malloc, CPFPHIG_OK ); assert_int_equal(CPFPHIG_OK, real_cpfphig_list_push( &list, NULL, NULL ) ); assert_null( list.first->item ); expect_any( cpfphig_free, Ptr ); will_return( cpfphig_free, CPFPHIG_OK ); assert_int_equal( CPFPHIG_OK, cpfphig_free( &(list.first), NULL ) ); } static void fail_malloc_is_fail( void** state ) { struct cpfphig_list list = CPFPHIG_CONST_CPFPHIG_LIST; int item = 11; expect_value(cpfphig_malloc, Size, sizeof( struct cpfphig_list_node ) ); will_return( cpfphig_malloc, CPFPHIG_FAIL ); assert_int_equal(CPFPHIG_FAIL, real_cpfphig_list_push( &list, &item, NULL ) ); } int main( void ) { const struct CMUnitTest tests[] = { cmocka_unit_test(arguments), cmocka_unit_test(first_push), cmocka_unit_test(subsequent_push), cmocka_unit_test(push_null), cmocka_unit_test(fail_malloc_is_fail), }; return cmocka_run_group_tests(tests, NULL, NULL); }
C
/* * (C) Jack Hay, Apr 2021 */ #ifndef _DISPLAY_DISPLAY_H #define _DISPLAY_DISPLAY_H #include <stdint.h> #include <stddef.h> #define DISPLAY_WIDTH 512 #define DISPLAY_HEIGHT 384 /** * Initialize the display */ void init_display(); /** * Clear the screen */ void clear_screen(); /** * Write a message to the console * @param x position x * @param y position y * @param msg the message to write */ void draw_str(int x, int y, char *msg); #endif /*_DISPLAY_DISPLAY_H*/
C
#include <stdio.h> #include <stdlib.h> typedef struct node { char *data; struct node *next; } node; void printList(node *head){ node *current = head; for(;current !=NULL;current = current->next){ printf("%s \n",current->data); } } int main(){ node *first = NULL; node second={"first",NULL}; first = (node*)malloc(sizeof(node)); first->data = "rishabh"; first->next = &second; printList(first); return 0; }
C
/* Copyright (c) 2016 Qualcomm Technologies International, Ltd. */ /* %%version */ /** * \file * Header with definitions for streaming data buffers. */ #ifndef BUFFER_MSG_H #define BUFFER_MSG_H #include "buffer/buffer.h" /* Use #ifdef to allow this to be overridden in config file */ #ifndef BUFFER_MSG_RING_SIZE /** * Size of message ring used. * * Note that one entry must remain empty: otherwise there * is an ambiguity in the case that \c front == \c behind whether * the ring is full or empty. * * Powers of two are recommended as the compiler optimizes modular * arithmetic in this case. */ #define BUFFER_MSG_RING_SIZE (16) #endif struct BUFFER_MESSAGE_META_FNS; /** * Message buffer structure * This encapsulates a standard \c BUFFER implementation. */ typedef struct BUFFER_MSG_ss { /** * Instance of a standard (non-message based) buffer that this type * extends. */ BUFFER buf; /** * The entry before the first valid entry in the message ring. * When this is advanced the entry becomes valid. */ uint16 front; /** * The last entry that has not been despatched by the downstream * end. If \c front == \c back there are no messages to despatch. */ uint16 back; /** * The last entry for which the data memory has not been freed. * If \c back == \c behind then there are no despatched messages * waiting to be freed and if \c front == \c back == \c behind * then the message ring is empty. */ uint16 behind; /** * The number of bytes of the message at back that have been consumed * by upstream protocol modules. This is used to adjust the returned * length and pointers when the back message is accessed. */ uint16 back_header_bytes_consumed; /** * Array of message lengths indexed by front/back/behind */ uint16 msg_lengths[BUFFER_MSG_RING_SIZE]; /** * Pointer to meta data array that contains BUFFER_MSG_RING_SIZE elements * of a type specific to the buffer specialisation. */ void * meta; /** * Optional pointer to a table of functions for deallocating metadata in * cases where the provenance of the metadata memory is unknown to the * message handling code (e.g. bc_buf_adapter). */ const struct BUFFER_MSG_META_FNS *meta_fns; } BUFFER_MSG; /** * "Virtual function" table for custom metadata handling */ typedef struct BUFFER_MSG_META_FNS { /** Create meta-data for all messages * * \param b message aware buffer * \param meta_data_length fixed meta-data length */ void (* create)(BUFFER_MSG *b, uint16 meta_data_length); /** Add a meta-data entry * * \param b message aware buffer * \param meta_length length of meta-data entry to add * \param meta_data pointer to meta-data entry to add */ void (* add_entry)(BUFFER_MSG *b, uint16 meta_data_length, const void *meta_data); /** Find the meta data entry for the first message * * \param b The buffer to search meta data * \param len Location to store meta data length * \return A pointer to the meta data, or NULL if there is no data. * If len is not NULL, then *len is set to the number of bytes * of meta data available. The returned pointer is valid until * the owning message is cleared. */ void* (* peek) (BUFFER_MSG *b, uint16 *len); /** Free a meta-data entry * * \param b message aware buffer * \param pos index of the meta-data entry to be freed */ void (* free_entry)(BUFFER_MSG *b, uint16f pos); /** Free meta-data for all messages * * \param b message aware buffer */ void (* destroy)(BUFFER_MSG *b); } BUFFER_MSG_META_FNS; /** Add a message to the buffer. This updates front and index. */ void buf_add_to_front(BUFFER_MSG *buf, uint16 len); /** Add a message to the buffer with associated meta data * \param buf Pointer to the BUFFER_MSG structure * \param len Length of data to be added (should already be in the mmu) * \param meta_type Type of the metadata this buffer uses * \param meta_data Pointer to the meta data for this message */ #define BUF_ADD_TO_FRONT_META(buf, len, meta_type, meta_data) \ do { \ *BUF_GET_FRONT_META((buf), meta_type) = *(meta_data);\ buf_add_to_front((buf), (len)); \ } while(0) /** * Get a pointer to the meta data for an entry in the message ring. * \param buf Pointer to the BUFFER_MSG structure * \param entry Entry number in the message ring * \param meta_type Type of the metadata this buffer uses */ #define BUF_GET_ENTRY_META(buf, entry, meta_type) \ (((meta_type *)(buf)->meta) + (entry)) /** * Get a pointer to the meta data for an entry in the message ring. * \param buf Pointer to the BUFFER_MSG structure * \param entry Entry number in the message ring * \param meta_size_bytes Size of the metadata this buffer uses */ #define BUF_GET_ENTRY_GENERIC_META(buf, entry, meta_size_bytes) \ (((uint8 *)(buf)->meta) + meta_size_bytes * \ ((entry) % BUFFER_MSG_RING_SIZE)) /** * Get a pointer to the meta data for the next message to be added to the * message buffer. * \param buf Pointer to the BUFFER_MSG structure * \param meta_type Type of the metadata this buffer uses */ #define BUF_GET_FRONT_META(buf, meta_type) \ (((meta_type *)(buf)->meta) + (buf)->front) /** * Get a pointer to the meta data for the next message to be added to the * message buffer. This is for generic meta data where the type isn't known. * \param buf Pointer to the BUFFER_MSG structure * \param meta_size_bytes Size of the metadata this buffer uses */ #define BUF_GET_FRONT_GENERIC_META(buf, meta_size_bytes) \ (((uint8 *)(buf)->meta) + meta_size_bytes * (buf)->front) /** * Get a pointer to the meta data for the next message to be consumed from the * message buffer. * \param buf Pointer to the BUFFER_MSG structure * \param meta_type Type of the metadata this buffer uses */ #define BUF_GET_BACK_MSG_META(buf, meta_type) \ (((meta_type *)(buf)->meta) + (buf)->back) /** * Get a pointer to the meta data for the next message to be consumed from the * message buffer. This is for generic meta data where the type isn't known. * \param buf Pointer to the BUFFER_MSG structure * \param meta_size_bytes Size of the metadata this buffer uses */ #define BUF_GET_BACK_GENERIC_MSG_META(buf, meta_size_bytes) \ (((uint8 *)(buf)->meta) + meta_size_bytes * (buf)->back) /** * Get a pointer to the meta data for the next message to be freed from the * message buffer. * \param buf Pointer to the BUFFER_MSG structure * \param meta_type Type of the metadata this buffer uses */ #define BUF_GET_BEHIND_MSG_META(buf, meta_type) \ (((meta_type *)(buf)->meta) + (buf)->behind) /** * Get a pointer to the meta data for the next message to be freed from the * message buffer. This is for generic meta data where the type isn't known. * \param buf Pointer to the BUFFER_MSG structure * \param meta_size_bytes Size of the metadata this buffer uses */ #define BUF_GET_BEHIND_MSG_GENERIC_META(buf, meta_size_bytes) \ (((uint8 *)(buf)->meta) + meta_size_bytes * (buf)->behind) /** Fully consumes the message being read, but leaves outdex alone. * This is for cases where we consume the message in fragments, so * that when we come to throw it away entirely outdex is already * where it should be. */ void buf_update_back_only(BUFFER_MSG *msg_buf); /** Fully consumes the message being read. This updates back and outdex. */ void buf_update_back(BUFFER_MSG *buf); /** * If possible, undo the last update of back (and outdex). It's possible * if the old back is still ahead of (or equal to) behind. */ bool buf_unupdate_back(BUFFER_MSG *buf); /** Free up a message from the buffer. * This updates behind and tail and frees the mmu pages. */ void buf_update_behind_free(BUFFER_MSG *buf); /** Free up a message from the buffer without freeing mmu pages (allows it * to be overwritten). * This updates behind and tail. */ void buf_update_behind(BUFFER_MSG *buf); /** Advance an index round the ring */ #define BUF_NEXT_MSG(ind) (uint16)(((ind) + 1) % BUFFER_MSG_RING_SIZE) #define BUF_PREV_MSG(ind) (uint16)(((ind) + BUFFER_MSG_RING_SIZE - 1) % BUFFER_MSG_RING_SIZE) /** Cheap macro to test for any messages to send */ #define BUF_ANY_MSGS_TO_SEND(buf) ((buf)->front != (buf)->back) /** Cheap macro to indicate number of messages to send */ #define BUF_NUM_MSGS_TO_SEND(buf) \ ((((buf)->front - (buf)->back) + BUFFER_MSG_RING_SIZE) % BUFFER_MSG_RING_SIZE) /** Cheap macro to test for any messages sent but not freed */ #define BUF_ANY_MSGS_SENT(buf) ((buf)->back != (buf)->behind) /** Cheapish macro to test for any messages available * * This takes account of the fact that the \c front is not allowed * to advance into the \c behind. */ #define BUF_ANY_MSGS_AVAILABLE(buf) \ ((buf)->behind != BUF_NEXT_MSG((buf)->front)) /** Cheapish macro to count number of messages available * * This takes account of the fact that the \c front is not allowed * to advance into the \c behind. */ #define BUF_NUM_MSGS_AVAILABLE(buf) \ ((((buf)->behind - ((buf)->front + 1)) + BUFFER_MSG_RING_SIZE) % \ BUFFER_MSG_RING_SIZE) /** Cheapish macro to count the number of messages that are in use */ #define BUF_NUM_MSGS_USED(buf) \ ((((buf)->front - (buf)->behind) + BUFFER_MSG_RING_SIZE) % \ BUFFER_MSG_RING_SIZE) /** Map in the buffer for writing the current message (at front) * This should be followed by a call to \c buf_add_to_front() to inform * downstream modules of the data. */ #define buf_map_front_msg(msg_buf) \ (buf_raw_write_only_map_8bit(&(msg_buf)->buf)) /** Get the length of the message at the back of a message ring. * * The downstream end uses this to retrieve metadata about data * for onward transmission (updating outdex). */ #define buf_get_back_msg_len(buf) (uint16)((buf)->msg_lengths[(buf)->back] \ - (buf)->back_header_bytes_consumed) /** Map in the buffer for reading the current message (at back) * The downstream protocol modules use this to read the message with the * headers of the upstream modules removed. */ #define buf_map_back_msg(msg_buf) (buf_raw_read_map_8bit(&(msg_buf)->buf) \ + (msg_buf)->back_header_bytes_consumed) /** * Map in the buffer for reading and modifying the current message (at back) */ #define buf_map_back_msg_rd_wr(msg_buf) \ (buf_raw_write_map_8bit_position(&(msg_buf)->buf, (msg_buf)->buf.outdex) \ + (msg_buf)->back_header_bytes_consumed) /** Consumes header bytes from the message currently being read (at back). */ #define buf_consume_header_bytes(msg_buf, octets) \ ((msg_buf)->back_header_bytes_consumed = \ (uint16)((msg_buf)->back_header_bytes_consumed + (octets))) /** Get the length of the message at the behind of a message ring. * * The downstream end uses this to retrieve metadata about data * for buffer freeing (updating tail). */ #define buf_get_behind_msg_len(buf) ((buf)->msg_lengths[(buf)->behind]) /** * Function to register that a message buffer will be having entries freed * or referenced by a pointer into the mapped memory. This is needed if * calls to \c buf_free_entries_from_ptr() need to be used. * \param buf Message buffer that needs to be referenced by data pointer */ void buf_register_msg_buf_for_ptr_access(BUFFER_MSG * buf); /** * Function to unregister a message buffer that was previously registered * by a call to \c buf_register_msg_buf_for_ptr_access(). * \param buf Message buffer that was previously registered */ void buf_unregister_msg_buf_for_ptr_access(BUFFER_MSG * buf); /** * Function to free buffer message entries and pages given a pointer * that lies within one of the entries. Updates \c behind and \c free * in the message_buf structure. Asserts if the pointer does not match * any BUFFER_MSG registered by \c buf_register_msg_buf_for_ptr_access(). * \param ptr Pointer that points into a previously registered message buffer */ void buf_free_entries_from_ptr(void * ptr); /** * Combine the two packets at adjacent message ring entries into a single * entry with length equal to the combined length and meta data equal to * the first in the message ring. This is only for use on packets that are * between back and behind entries not including the one at back. * Entries prior to the one specified up to the behind entry are * shuffled along the message ring by one to close the gap that this * combining produces. The behind pointer is then advanced. * \param msg_buf Message buffer with entries to combine * \param entry The message ring entry to be combined with the following one. * \param meta_size_bytes The size of meta data entries for this buffer * \return The combined length if the entries were combined or zero * if the combining couldn't be done. */ uint16 buf_combine_entries(BUFFER_MSG * msg_buf, uint16 entry, uint16 meta_size_bytes); /** * Combine the two packets at adjacent message ring entries into a single * entry. Identical to \c buf_combine_entries() but specifying the entry * by the offset of the data in the buffer. * \param msg_buf Message buffer with entries to combine * \param offset Offset of the start of the data in the buffer which * specifies the message ring entry to be combined with the following one. * \param meta_size_bytes The size of meta data entries for this buffer * \return The combined length if the entries were combined or zero * if the combining couldn't be done. */ uint16 buf_combine_entries_at_offset(BUFFER_MSG * msg_buf, uint16 offset, uint16 meta_size_bytes); #endif /* BUFFER_MSG_H */
C
#include <stdio.h> /** * main - Entry point * * Return: Always 0 (Success) */ int main(void) { long int i, ant = 1, act = 2, buff; printf("1, 2, "); for (i = 2; i <= 49; i++) { buff = ant + act; ant = act; act = buff; if (i != 49) printf("%ld, ", buff); else printf("%ld\n", buff); } return (0); }
C
/* 用 C 语言实现一个简易的计算器: - 两个数字之间的加,减,乘,除 */ #include <stdio.h> int main() { double number1=0.0; double number2=0.0; char operation; // 获取用户输入的计算表达式 printf("\nPlease input your number and operation:\n"); scanf("%lf%c%lf", &number1, &operation, &number2); switch (operation) { case '+': printf("Answer: %lf\n", number1 + number2); break; case '-': printf("Answer: %lf\n", number1 - number2); break; case '*': printf("Answer: %lf\n", number1 * number2); break; case '/': if (number2 == 0) { printf("\n\n\aDivision by zero error!\n"); } else { printf("Answer: %lf\n", number1 / number2); } break; case '%': if((long)number2==0) { printf("\n\n\aDivision by zero error!\n"); } else { printf("Answer: %ld\n", (long)number1%(long)number2); } break; default: printf("\n\n\aDivision by zero error!\n"); break; } return 0; }