language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_putpiece.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lfujimot <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/02/14 18:05:28 by lfujimot #+# #+# */ /* Updated: 2018/02/26 14:52:22 by lfujimot ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/ft_filler.h" t_pos ft_pieceleftup(t_game *game) { int j; int i; t_pos pos; pos.x = -1; pos.y = -1; j = 0; i = 0; while (game->piece[0][i]) { j = 0; while (game->piece[j]) { if (game->piece[j][i] == '*') { pos.x = i; pos.y = j; return (pos); } j++; } i++; } return (pos); } t_pos ft_piecerightdown(t_game *game) { int j; int i; t_pos pos; pos.x = -1; pos.y = -1; i = game->wp - 1; while (i >= 0) { j = game->hp - 1; while (j >= 0) { if (game->piece[j][i] == '*') { pos.x = i; pos.y = j; return (pos); } j--; } i--; } return (pos); } static t_pos ft_getpiecepos(t_game *game) { t_pos piecepos; if (game->direction == RIGHT) piecepos = ft_pieceleftup(game); else piecepos = ft_piecerightdown(game); ft_befwh(game, piecepos); ft_aftwh(game, piecepos); return (piecepos); } int ft_putpiece(t_game *game) { t_pos piecepos; int tmp; if (game->action == CUT) { piecepos = ft_getpiecepos(game); if (ft_fill(game, piecepos) == -1) { game->action = CLOSE; if (ft_close(game) == 1) return (ft_strangle(game)); } } else if (game->action == CLOSE || ft_isclosed(game) != 1) { tmp = ft_close(game); if (tmp == 1 || tmp == -1) return (ft_strangle(game)); } else if (game->action == STRANGLE) return (ft_strangle(game)); return (0); }
C
#include <stdio.h> #include <stdint.h> #include "../include/index.h" void main(void){ //Iniciaando a memória sb(0, 0, 0x04); sb(0, 1, 0x03); sb(0, 2, 0x02); sb(0, 3, 0x01); sb(4, 0, 0xFF); sb(4, 1, 0xFE); sb(4, 2, 0xFD); sb(4, 3, 0xFC); sw(12, 0, 0xFF); sw(16, 0, 0xFFFF); sw(20, 0, 0xFFFFFFFF); sw(24, 0, 0x80000000); //imprimindo a memória for(int i =0; i<=6; i++) printf("mem[%d] = %.8x\n", i, mem[i]); printf("\n///////////// função lb ///////////\n"); printf("lb(4,0) = %.8x\n", lb(4,0)); printf("lb(4,1) = %.8x\n", lb(4,1)); printf("lb(4,2) = %.8x\n", lb(4,2)); printf("lb(4,3) = %.8x\n", lb(4,3)); printf("\n///////////// função lbu ////////////\n"); printf("lbu(4,0) = %.8x\n", lbu(4,0)); printf("lbu(4,1) = %.8x\n", lbu(4,1)); printf("lbu(4,2) = %.8x\n", lbu(4,2)); printf("lbu(4,3) = %.8x\n", lbu(4,3)); printf("\n///////////// função lw ////////////\n"); printf("lw(12,0) = %.8x\n", lw(12,0)); printf("lw(16,0) = %.8x\n", lw(16,0)); printf("lw(20,0) = %.8x\n", lw(20,0)); }
C
// // Created by Hood on 5/17/2019. // #include <assert.h> #include <ctype.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "combinatorics.h" #include "FpVector.h" #include "MilnorAlgebra.h" // Private functions uint get_profile_name(char *buffer, Profile P); uint Profile__getExponent(Profile P, uint p, uint index){ if(index < P.p_part_length){ return integer_power(p, P.p_part[index]); } if(P.truncated){ return 1; } return -1; } uint Profile_getName(char *buffer, Profile P){ uint len = 0; len += sprintf(buffer + len, "Profile( truncated=%s, ", P.truncated ? "true" : "false"); if(P.generic){ len += sprintf(buffer + len, "q_part=%x, ", P.q_part); } len += sprintf(buffer + len, "p_part="); len += array_toString(buffer + len, P.p_part, P.p_part_length); len += sprintf(buffer + len, ")"); return len; } Profile *Profile_construct(bool generic, uint q_part_length, uint * q_part, uint p_part_length, uint *p_part, bool truncated){ Profile * result = malloc(sizeof(Profile) + p_part_length * sizeof(uint)); result->generic = generic; if(q_part_length == 0 && p_part_length == 0 && !truncated){ result->restricted = false; result->truncated = false; result->q_part = -1; result->p_part_length = 0; result->p_part = NULL; return result; } result->restricted = true; result->truncated = truncated; result->generic = generic; for(uint i = 0; i<q_part_length; i++){ result->q_part += (q_part[i] & 1) << i; } result->p_part_length = p_part_length; if(p_part_length > 0){ result->p_part = (uint*)(result + 1); memcpy(result->p_part, p_part, p_part_length*sizeof(uint)); } else { result->p_part = NULL; } return result; } void Profile_free(Profile *profile){ free(profile); } void MilnorAlgebra__generateName(MilnorAlgebra *A){ // We never initialized it to NULL so this causes trouble. // if (A->algebra.name != NULL) { // return; // } char buffer[200]; uint len = 0; len += sprintf(buffer + len, "MilnorAlgebra(p=%d", A->algebra.p); if(A->generic != (A->algebra.p != 2)){ len += sprintf(buffer + len, ", generic=%s", A->generic ? "true" : "false"); } if(A->profile.restricted){ len += sprintf(buffer + len, ", "); len += Profile_getName(buffer + len, A->profile); } len += sprintf(buffer + len, ")"); char *result = malloc((len + 1)* sizeof(char)); memcpy(result, buffer, len + 1); A->algebra.name = result; } uint MilnorAlgebra_basisElement_toKey(char *buffer, MilnorBasisElement *b){ // Copy bytes representing MilnorBasisElement to a string. // printf("making hash.\n"); // printf(" pointer address: %x\n", (int)b->p_part); uint len = 0; memcpy(buffer + len, &b->q_part, sizeof(uint)); len += sizeof(uint); memcpy(buffer + len, b->p_part, b->p_length * sizeof(uint)); len += b->p_length * sizeof(uint); // Ensure that none of the chars in our key are 0. // A zero would terminate our key early. for(uint i = 0; i < len; i++){ buffer[i] = (buffer[i] << 1) | 1; } // Now add string terminating null character. buffer[len] = '\0'; return len; } uint MilnorAlgebra_basisElementIndex_toString(Algebra *this, char *buffer, int degree, uint idx){ MilnorAlgebra *A = (MilnorAlgebra *)this; MilnorBasisElement *b = MilnorAlgebra_basisElement_fromIndex(A, degree, idx); return MilnorAlgebra_basisElement_toString(buffer, A, b); } uint MilnorAlgebra_basisElement_toString(char *buffer, MilnorAlgebra *A, MilnorBasisElement *b){ if(b->p_length == 0 && b->q_part == 0){ buffer[0] = '1'; buffer[1] = '\0'; return 1; } int len = 0; char P_or_Sq[4]; if(A->generic){ if(b->q_part != 0){ len += sprintf(buffer + len, "Q("); uint idx = 0; for(uint q_part = b->q_part; q_part > 0; q_part >>= 1){ if((q_part & 1) != 0){ len += sprintf(buffer + len, "%d,", idx); } idx ++; } len += sprintf(buffer + len, ")"); } if(b->p_length != 0 && b->q_part != 0){ len += sprintf(buffer + len, " * "); } sprintf(P_or_Sq, "P("); } else { sprintf(P_or_Sq, "Sq("); } if(b->p_length != 0){ len += sprintf(buffer + len, "%s", P_or_Sq); for(uint i = 0; i < b->p_length; i++){ len += sprintf(buffer + len, "%d,", b->p_part[i]); } len--; // drop trailing comma len += sprintf(buffer + len, ")"); } return len; } void MilnorAlgebra_basisElement_print(char *fmt_string, MilnorAlgebra *algebra, MilnorBasisElement *b){ char buffer[2000]; MilnorAlgebra_basisElement_toString(buffer, algebra, b); printf(fmt_string, buffer); } // Note: This function returns a pointer to a substring of the original string. // If the given string was allocated dynamically, the caller must not overwrite // that pointer with the returned value, since the original pointer must be // deallocated using the same allocator with which it was allocated. The return // value must NOT be deallocated using free() etc. char *trimwhitespace(char *str){ char *end; // Trim leading space for(;isspace((unsigned char)*str); str++){ }; if(*str == 0) { // All spaces? return str; } // Trim trailing space end = str + strlen(str) - 1; while(end > str && isspace((unsigned char)*end)) end--; // Write new null terminator character end[1] = '\0'; return str; } // Parses elements like P(0,1) or Q(0,1) * P(0,1) MilnorBasisElement *MilnorAlgebra_basisElement_fromString(MilnorAlgebra * algebra, char* elt_string){ char *idx_string, *string, *tofree; char * Q_or_P; uint p = algebra->algebra.p; uint q = algebra->generic ? 2*p-2 : 1; tofree = string = strdup(elt_string); uint Q_part[20] = {0}; uint P_part[20] = {0}; uint Q_part_len = 0; uint P_part_len = 0; uint q_degree = 0; uint p_degree = 0; while ((Q_or_P = strsep(&string, "*")) != NULL){ Q_or_P = trimwhitespace(Q_or_P); uint* target = Q_part; uint len = 0; uint *Q_or_P_len = &Q_part_len; if(Q_or_P[0] == 'P'){ target = P_part; Q_or_P_len = &P_part_len; } if(Q_or_P[0] == 'S'){// Presumably the S is part of "Sq" target = P_part; Q_or_P_len = &P_part_len; Q_or_P++;// "Sq("" is three characters, one longer than "Q(" or "P(" } Q_or_P += 2; // "Q(" and "P(" are two characters Q_or_P[strlen(Q_or_P)-1] = '\0'; char *end; while((idx_string = strsep(&Q_or_P, ",")) != NULL){ target[len] = strtoul(idx_string, &end, 10); len ++; } *Q_or_P_len = len; } free(tofree); tofree = NULL; string = NULL; int* tau_degrees = getTauDegrees(p); int* xi_degrees = getXiDegrees(p); uint Q_bit_string = 0; for(uint i = 0; i < Q_part_len; i++){ Q_bit_string += (1 << Q_part[i]); q_degree += tau_degrees[Q_part[i]]; } for(uint i = 0; i < P_part_len; i++){ p_degree += xi_degrees[i] * P_part[i] * q; } MilnorBasisElement result; result.p_part = P_part; result.p_length = P_part_len; result.p_degree = p_degree; result.q_part = Q_bit_string; result.q_degree = q_degree; uint idx = MilnorAlgebra_basisElement_toIndex(algebra, &result); return MilnorAlgebra_basisElement_fromIndex(algebra, result.p_degree + result.q_degree, idx); } uint MilnorAlgebra_element_toString(Algebra *this, char *buffer, int degree, Vector * m){ MilnorAlgebra *algebra = (MilnorAlgebra*)this; uint len = 0; for( VectorIterator it = Vector_getIterator(m); it.has_more; it = Vector_stepIterator(it) ){ if(it.value == 0){ continue; } if(it.value != 1) { len += sprintf(buffer + len, "%d * ", it.value); } MilnorBasisElement *b = MilnorAlgebra_basisElement_fromIndex(algebra, degree, it.index); len += MilnorAlgebra_basisElement_toString(buffer + len, algebra, b); len += sprintf(buffer + len, " + "); } if(len == 0){ len += sprintf(buffer + len, "0"); } else { // Remove trailing " + " len -= 3; buffer[len] = '\0'; } return len; } void MilnorElement_print(char *fmt_string, MilnorAlgebra *algebra, uint degree, Vector *m){ char buffer[2000]; uint len = MilnorAlgebra_element_toString((Algebra *)algebra, buffer, degree, m); assert(len < 2000); printf(fmt_string, buffer); } uint MilnorMatrix_toString(char *buffer, uint M[MAX_XI_TAU][MAX_XI_TAU], uint rows, uint cols){ uint len = 0; len += sprintf(buffer + len, "[\n"); for(uint row = 0; row < rows; row++) { len += sprintf(buffer + len, " "); len += array_toString(buffer + len, M[row], cols); len += sprintf(buffer + len, ","); } len += sprintf(buffer + len, "]\n"); return len; }
C
#include <stdio.h> #include <ctype.h> #include <stdlib.h> char* CorrectMistakes() { char input[255], ch, toCap = 0, prevCh = 0; int len = 0; printf("Enter text:\n>> "); while (1) { if (prevCh == 0 && len < 253) ch = getchar(); else ch = prevCh; if (ch == '\n') break; switch (ch) { case '.': case '!': case '?': toCap = 1; case ',': case ':': case ';': if (prevCh != '.' && prevCh != '!' && prevCh != '?' && prevCh != 0) toCap = 0; input[len++] = ch; case ' ': input[len++] = ' '; do { ch = getchar(); if (ch == '\n') break; } while (ch == ' '); prevCh = ch; break; default: prevCh = 0; if (toCap) { input[len++] = toupper(ch); toCap = 0; } else input[len++] = ch; } } input[len] = '\0'; printf("Corrected text:\n%s\n", input); return input; } void main() { char* text = CorrectMistakes(); }
C
#include "menu.h" // /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\ * init() is an interface that initializes the game. * * * * @param time The time played sofar in Hangman the game. * * * * @param board The scoreboard of all people who have played * * this game. * * * * @param games_played Total games of Hangman played. * \* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ void init(double *time, PLAYER board[100], int *games_played) { read_in_time(time); read_board_in(board); read_in_stats(games_played); sort_board(board); store_board(board); store_time(*time); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\ * start() is an interface that starts the threads * * for the game. * * * \* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ void start(void) { // pthread_t dict_thread; pthread_t game_thread; // pthread_create(&dict_thread, NULL, dict_init, (void *)&dictionary); pthread_create(&game_thread, NULL, navigate_menu, NULL); // pthread_join(dict_thread, NULL); pthread_join(game_thread, NULL); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\ * print_menu() Displays the menu options for Hangman. * * * \* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ void print_menu(void) { printf("\033[0;32m----------Welcome to Hangman----------\033[0m\n"); printf("---------- Play ----------\n"); printf("---------- Score Board ----------\n"); printf("---------- Stats ----------\n"); printf("---------- Exit ----------\n"); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\ * navigate_menu() Allows the user to select a menu option. * * * * @return An integer, returns 1 if the user does not exit. * * the game. * \* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ void *navigate_menu(void *nothing) { char option[MAX_SIZE] = {[0 ... MAX_SIZE - 1] = 0}; struct PLAYER board[100] = {[0 ... 99] = {"", 0, 0, 0}}; int games_played = 0; double time = 0; while (1) { system("clear"); print_menu(); init(&time, board, &games_played); get_string(option, MAX_SIZE, "Please provide your option: "); to_lower(option); if (strcmp(option, "play") == 0) { play(board, &time, &dictionary); games_played++; store_board(board); store_stats(games_played); store_time(time); } else if (strcmp(option, "score board")) { print_board(board); } else if (strcmp(option, "stats") == 0) { print_stats(games_played); print_time(time, games_played); } else if (strcmp(option, "exit") == 0) { exit(0); } } return NULL; }
C
#include <stdio.h> #include <stdlib.h> #include "koolplot.h" #define OFFSET 0.1 int main () { FILE *fp; int m=0, i; double temp1, temp2; fp = fopen ("pontos.txt", "rt"); if (!fp) return NULL; // Contando pontos... while (!feof(fp)) { fscanf(fp, "%lf %lf", &temp1, &temp2); m++; } fclose (fp); m--; // Agora sim, lendo pontos! double a[m], b[m], xMin, xMax, yMin, yMax; fp = fopen ("pontos.txt", "rt"); for (i=0; i < m; i++) fscanf(fp, "%lf %lf",&a[i], &b[i]); fclose (fp); Plotdata x, y; point(x, y, a[0], b[0]); xMin = xMax = a[0]; yMin = yMax = b[0]; //printf ("Pontos lidos:\n"); for (i = 1; i < m; i++) { //printf ("%lf %lf\n", a[i], b[i]); point(x, y, a[i], b[i]); if(xMin > a[i]){ xMin = a[i]; } if(xMax < a[i]){ xMax = a[i]; } if(yMin > b[i]){ yMin = b[i]; } if(yMax < b[i]){ yMax = b[i]; } } axesBotLeft(x, y,xMin - OFFSET * (xMax - xMin), yMin - OFFSET * (yMax - yMin)); axesTopRight(x, y, xMax + OFFSET * (xMax - xMin), yMax + OFFSET * (yMax - yMin)); plot(x, y); }
C
#define _GNU_SOURCE #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <wait.h> #include <stdlib.h> #include <sys/shm.h> #include <sys/mman.h> #include <fcntl.h> /* Child Processes1 */ int ch1task(int *X, int N, int sleeptime) { usleep(sleeptime); int i; for(i=0;i<N;i++) (*X)++; // = *sh_data_p +1; return 0; } /* Child Processes2 */ int ch2task(int *X, int N, int sleeptime) { usleep(sleeptime); int i; for(i=0; i<N; i++) (*X)--; // = *sh_data_p -1; return 0; } int main(int argc, char *argv[]) { /* Parsing */ int sleeptime1; int sleeptime2; if (argc <= 1) {sleeptime1 = 0;sleeptime2 = 0;} else{ sleeptime1 = atoi(argv[1]); sleeptime2 = atoi(argv[2]); } /* Global configuration */ int N = 10; int n = 2; // number of processes /* Shared memory information */ const char *shmName = "/SHM"; size_t SIZE = sizeof(int); int *X; int shm_fd; /* Creating Shared memory */ shm_fd = shm_open(shmName, O_CREAT | O_RDWR, 0666); if (shm_fd == -1) {printf("Shared failed in CREATing\n"); return 1;} if (ftruncate(shm_fd,SIZE)) printf("[ERROR] Failed to ftruncate()\n"); X = (int *) mmap(0,SIZE,PROT_READ|PROT_WRITE,MAP_SHARED,shm_fd,0); if(X == MAP_FAILED) {printf("Map Failed\n");return 1;} /* Shared Data initialization */ *X = 0; /* Creating Child Processes */ pid_t ch1, ch2; ch1 = fork(); if (ch1) { /* Parent Process */ ch2 = fork(); if (ch2) { /* Parent Process in deeper but same */ while (n>0) {wait(NULL); --n;} printf("%d\n",*X); } else { /* Child Process 02 */ ch2task(X,N,sleeptime1); } } else { /* Child Process 01 */ ch1task(X,N,sleeptime2); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "QueueList.h" #include "../../02-Linked-List/ListNode.h" QueueList* createQueueList() { QueueList *temp=(QueueList*)malloc(sizeof(QueueList)); temp->rear=NULL; temp->front=NULL; return temp; } int isEmpty(QueueList *queue) { if(!queue->front) { return 1; } else { return 0; } } void enQueue(QueueList *queue, int value) { ListNode *node=createNode(value); if(!queue->rear) { queue->rear=node; } else { queue->rear->next=node; queue->rear=node; } if(!queue->front) { queue->front=node; } } int deQueue(QueueList *queue) { if(isEmpty(queue)) { fprintf(stderr, "Queue is empty\n"); exit(0); } else { int temp=queue->front->value; ListNode *previous=queue->front; queue->front=queue->front->next; if(!queue->front) { queue->rear=NULL; } free(previous); return temp; } }
C
/* The program demonstrates a new version of the static detector used in the IMU calibration procedure, see @article{Tedaldi2014, archivePrefix = {arXiv}, arxivId = {ISSN 1476-2986}, author = {Tedaldi, David and Pretto, Alberto and Menegatti, Emanuele}, doi = {10.1109/ICRA.2014.6907297}, eprint = {ISSN 1476-2986}, journal = {1. Tedaldi D, Pretto A, Menegatti E. A robust easy to implement method IMU calibration without Extern. equipments. Proc - IEEE Int Conf Robot Autom. 2014;3042–9. Proc. - IEEE Int. Conf. Robot. Autom.}, pages = {3042--3049}, pmid = {16830938}, title = {{A robust and easy to implement method for IMU calibration without external equipments}}, year = {2014} } As an input is used CSV file (space idented) with such columns: ustime, gx, gy, gz, az, ay, az The output is CSV file with columns: ustime, gx, gy, gz, ax, ay, az, interval_type(0-static, 1-dynamic, 2- too short dynamic) */ #include "stat_detector.h" #define MAX_VAL 32676.0 int main(int argc, char **argv){ double time_window = 0.5; // in seconds double min_static_len = 1.0; // in seconds double min_dynamic_len = 0.4; // in seconds Fmatrix_ptr data; if (argc >= 2) { printf("CSV file is given: %s\n", argv[1]); if (!read_csv(argv[1], &data)) { fprintf(stderr, "Can't read the data from the CSV file."); exit(1); } } else { printf("Please, provide a CSV file name in arguments\n"); free_matrix(data); return(0); } if (argc == 5) { time_window = (double)atof(argv[2]); min_static_len = (double)atof(argv[3]); min_dynamic_len = (double)atof(argv[4]); } printf("Detector's parameters are used: win lenght = %.2f sec, min static lenght = %.2f sec and min dynamic length = %.2f sec\n", time_window, min_static_len, min_dynamic_len); Fmatrix_ptr detected_intervals; Fmatrix_ptr output_data; clock_t t = clock(); unsigned int int_num = detect_intervals(data, &detected_intervals, &output_data, time_window, min_static_len, min_dynamic_len); t = clock() - t; if (int_num > 0) { printf("Intervals detected in %.2f sec\n", ((double)t)/CLOCKS_PER_SEC); printf("Detection results:\n"); printf("%8s %8s %8s %8s %8s\n", "Start", "Stop", "Type", "Quality", "Reserved"); print_fmat(detected_intervals); save_matrix2csv(detected_intervals, "intervals.csv", NULL); printf("Detected intervals were saved in: intervals.csv\n"); const char *header [] = {"ustime", "gx", "gy", "gz", "ax", "ay", "az", "static"}; save_matrix2csv(output_data, "out.csv", header); printf("Output data were saved in: out.csv\n"); } else { printf("Static intervals are not detected.\n"); } free_matrix(data); free_matrix(detected_intervals); free_matrix(output_data); return(1); }
C
#include <stdint.h> #include <stdbool.h> #include "tm4c123gh6pm.h" #define RED_LED_MASK 2 #define BLUE_LED_MASK 4 #define GREEN_LED_MASK 8 //----------------------------------------------------------------------------- // Hardware Target //----------------------------------------------------------------------------- // Target Platform: EK-TM4C123GXL // Target uC: TM4C123GH6PM // System Clock: - // Hardware configuration: // PWM Interface: // M1PWM5 (PF1), M1PWM6 (PF2) and M1PWM7 (PF3) are connected to the 2nd controller /* PWM1 * Generator 0 -> A M1-PWM0 * Generator 0 -> B M1-PWM1 * Generator 1 -> A M1-PWM2 * Generator 1 -> B M1-PWM3 * Generator 2 -> A M1-PWM4 * Generator 2 -> B M1-PWM5 * Generator 3 -> A M1-PWM6 * Generator 3 -> B M1-PWM7 */ //----------------------------------------------------------------------------- // Global variables //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Subroutines //----------------------------------------------------------------------------- // Initialize PWM for on-board LED's void initLEDPWM() { // Configure HW to work with 16 MHz XTAL, PLL enabled, sysdivider of 5, creating system clock of 40 MHz SYSCTL_RCC_R = SYSCTL_RCC_XTAL_16MHZ | SYSCTL_RCC_OSCSRC_MAIN | SYSCTL_RCC_USESYSDIV | (4 << SYSCTL_RCC_SYSDIV_S); // Set GPIO ports to use APB (not needed since default configuration -- for clarity) SYSCTL_GPIOHBCTL_R = 0; // Enable clocks SYSCTL_RCGCPWM_R |= SYSCTL_RCGCPWM_R1; SYSCTL_RCGCGPIO_R |= SYSCTL_RCGCGPIO_R5; _delay_cycles(3); // Configure three on-board LEDs GPIO_PORTF_DIR_R |= RED_LED_MASK | BLUE_LED_MASK | GREEN_LED_MASK; // make bit 1,2,3 GPIO outputs GPIO_PORTF_DR2R_R |= RED_LED_MASK | BLUE_LED_MASK | GREEN_LED_MASK; // set drive strength to 2mA GPIO_PORTF_DEN_R |= RED_LED_MASK | BLUE_LED_MASK | GREEN_LED_MASK; // enable digital GPIO_PORTF_AFSEL_R |=BLUE_LED_MASK; // select auxilary function GPIO_PORTF_PCTL_R &= ~(GPIO_PCTL_PF1_M | GPIO_PCTL_PF2_M |GPIO_PCTL_PF3_M); GPIO_PORTF_PCTL_R |= GPIO_PCTL_PF2_M1PWM6; // Configure PWM module 1 to drive on-board RGB LEDs // RED on M1PWM5 (PF1), M1PWM2B // BLUE on M0PWM6 (PF2), M1PWM3A // GREEN on M0PWM7 (PF3), M1PWM3B SYSCTL_SRPWM_R = SYSCTL_SRPWM_R1; // reset PWM1 module SYSCTL_SRPWM_R = 0; // leave reset state PWM1_2_CTL_R = 0; // turn-off PWM1 generator 2 PWM1_3_CTL_R = 0; // turn-off PWM0 generator 3 PWM1_2_GENB_R = PWM_1_GENB_ACTCMPBD_ZERO | PWM_1_GENB_ACTLOAD_ONE; // output 3 on PWM0, gen 1b, cmpb PWM1_3_GENA_R = PWM_1_GENA_ACTCMPAD_ZERO | PWM_1_GENA_ACTLOAD_ONE; // output 4 on PWM0, gen 2a, cmpa PWM1_3_GENB_R = PWM_1_GENB_ACTCMPBD_ZERO | PWM_1_GENB_ACTLOAD_ONE; // output 5 on PWM0, gen 2b, cmpb PWM1_2_LOAD_R = 256; // set period to 40 MHz sys clock / 2 / 255 = 78.43137 kHz PWM1_3_LOAD_R = 256; PWM1_INVERT_R = PWM_INVERT_PWM5INV | PWM_INVERT_PWM6INV | PWM_INVERT_PWM7INV; // invert outputs so duty cycle increases with increasing compare values PWM1_2_CMPB_R = 0; // red off (0=always low, 1023=always high) PWM1_3_CMPA_R = 0; // blue off PWM1_3_CMPB_R = 0; // green off PWM1_2_CTL_R = PWM_1_CTL_ENABLE; // turn-on PWM1 generator 2 PWM1_3_CTL_R = PWM_1_CTL_ENABLE; // turn-on PWM1 generator 3 PWM1_ENABLE_R = PWM_ENABLE_PWM5EN | PWM_ENABLE_PWM6EN | PWM_ENABLE_PWM7EN; // enable outputs } //uint8_t rgb = 1 for RedLED, rgb = 2 for Blue LED, rgb =3 for Green LED void setLEDPWM(uint8_t rgb, uint8_t cmpb) { if (rgb == 1) PWM1_2_CMPB_R = cmpb; else if (rgb == 2) PWM1_3_CMPA_R = cmpb; else if (rgb == 3) PWM1_3_CMPB_R = cmpb; } void uninitPWM() { GPIO_PORTF_AFSEL_R &= ~(RED_LED_MASK | BLUE_LED_MASK | GREEN_LED_MASK); // use GPIO to control the LEDs GPIO_PORTF_PCTL_R &= ~(GPIO_PCTL_PF1_M | GPIO_PCTL_PF2_M |GPIO_PCTL_PF3_M); }
C
/* * hBridge_mega168p.c * * Created: 2017/01/12 13:56:51 * Author : Someone's Garden */ #include <avr/io.h> #include <util/delay.h> #include <avr/interrupt.h> #include "../lib/USART.h" #include "../lib/pinDefines.h" static inline void setBridgeState(uint8_t bridgeA, uint8_t bridgeB){ if(bridgeA){ PORTD |=(1 << PD6); LED_PORT |=(1 << LED0); }else{ PORTD &= ~(1 << PD6); LED_PORT &= ~(1 << LED0); } if(bridgeB){ PORTD |= (1 << PD5); LED_PORT |=(1<<LED1); } else{ PORTD &= ~(1<<PD5); LED_PORT &= ~(1<<LED1); } } int mega168p_hBridge(void) { DDRD |= (1<<PD6); DDRD |= (1<<PD5); LED_DDR |= (1<<LED0); LED_DDR |= (1<<LED1); while (1) { setBridgeState(1,0); /* "forward" */ _delay_ms(2000); setBridgeState(0,0); /* "Stop" */ _delay_ms(2000); setBridgeState(0,1); /* "Reverse" */ _delay_ms(2000); setBridgeState(1,1); /* ALSO stop */ _delay_ms(2000); setBridgeState(1,0); /* "Backward" */ _delay_ms(2000); setBridgeState(0,1); _delay_ms(75); setBridgeState(0,0);//set back _delay_ms(2000); } return (0); }
C
/** * ex0702.c * solution to ex0702 */ #include <stdio.h> #include <ctype.h> #define MAX_LINE 128 /* max number of chars in one line */ #define OCT_LEN 6 /* length of an octal value */ int inc( int p, int n ); int main( int argc, char **argv ) { int hexal = 0; int octal = 1; /* by default, we use octal to print non-graphic char */ while ( --argc && *(*++argv) == '-' ) { while ( *++(*argv) ) { switch ( *(*argv ) ) { case 'o': octal = 1; break; case 'h': hexal = 1; break; default: break; } } } printf( "hexal %d, octal %d\n", hexal, octal ); char ch; int pos; int step; pos = 0; while ( (ch = getchar()) != EOF ) { if ( isgraph( ch ) ) { step = 1; putchar( ch ); } else { step = OCT_LEN; if ( hexal ) { printf( " \\%03x ", ch ); } else { printf( " \\%03o ", ch ); } if ( ch == '\n' ) { pos = 0; putchar( '\n' ); } } pos = inc( pos, step ); } return 0; } int inc( int pos, int n ) { if ( pos + n < MAX_LINE ) { return pos + n; } else { putchar( '\n' ); return n; } }
C
#ifndef PAGING_H #define PAGING_H #include "common.h" #include "mm.h" #define PAGE_MASK (~(PAGE_SIZE-1)) /* pte_t represents l1 directory Flags bits: only * are used for now *0 - present bit *1 - R/W bit 2- U/S 3- PWT 4-PCD 5- Access bit 6- Dirty bit (ignored for 4k page) *7- Page size 0-for 4k 1-for 2M *8- Global bit (ignored for 4k page) 12-PAT */ typedef struct pte { addr_t present : 1; // Page present in memory addr_t rw : 1; // Read-only if clear, readwrite if set addr_t user : 1; // Supervisor level only if clear addr_t pwt :1 ; addr_t pcd :1 ; addr_t accessed : 1; // Has the page been accessed since last refresh? addr_t dirty : 1; // Has the page been written to since last refresh? addr_t pat :1 ; addr_t global :1 ; addr_t avl : 3; // available addr_t frame : 40; // Frame address (shifted right 12 bits) addr_t count :11; addr_t nx :1; } pte_t; /* pde_t represents l2 directory Flags bits: only * are used for now *0 - present bit *1 - R/W bit 2- U/S 3- PWT 4-PCD 5- Access bit 6- Dirty bit (ignored for 4k page) *7- Page size 0-for 4k 1-for 2M *8- Global bit (ignored for 4k page) 12-PAT */ typedef struct __pde { addr_t present : 1; // Page present in memory addr_t rw : 1; // Read-only if clear, readwrite if set addr_t user : 1; // Supervisor level only if clear addr_t pwt :1 ; addr_t pcd :1 ; addr_t accessed : 1; // Has the page been accessed since last refresh? addr_t dirty : 1; // Has the page been written to since last refresh? ignored for 2M addr_t ps :1 ; // page size 2M=1 4k=0 addr_t global :1 ; // ignored in 4k addr_t avl : 3; // available /* addr_t pat :1 ; */ /* unsigned flags :12; */ addr_t frame :40; addr_t count :11; addr_t nx :1; } __attribute__((packed)) pde_t; /*typedef struct pte_table { pte_t pte[1024]; } page_table_t; */ typedef struct pde_table /* level2 table */ { pde_t pde[512]; } pde_table_t; /* virtual address is 48 bits : 9+9+9+9 + 12 entries in page table = 2 pow 9 = 512 4 levels : l4 l3 l2 l1 for 4k pages else 3 levele : l4 l3 l2 for 2M pages pde_t is a l2 page directory physical addess is 52 bit long. any entry in the page directory is 52-12=40 bit long to get the address of next level directory l2 entries or PDE for 2M pages: 21bits + 31 bits = 52 bit physical 31 bits present in PDE , out of 40 bits only 31 bits are used and rest are reserved l2 entries or PDE for 4k pages: level3_table : covers 512*512*2M = 512G level2_table; : covers 512*2M = 1G */ #define L4_INDEX(x) (((addr_t)x&0xff8000000000)>>39) #define L3_INDEX(x) (((addr_t)x&0x007fc0000000)>>30) #define L2_INDEX(x) (((addr_t)x&0x00003fe00000)>>21) #define L1_INDEX(x) (((addr_t)x&0x0000001ff000)>>12) extern addr_t g_kernel_page_dir; /** Sets up the environment, page directories etc and enables paging. **/ addr_t initialise_paging(); /** Causes the specified page directory to be loaded into the CR3 register. **/ void switch_page_directory(addr_t *new_dir); /** Handler for page faults. **/ void page_fault(); #endif
C
/* * cc3000_event_handler.c * * Created on: 05.09.2013 * Author: Johannes */ #include "cc3000_event_handler.h" #include "cc3000_platform.h" #include "cc3000_general.h" #include "cc3000_hci.h" #include "cc3000_spi.h" // the desired state (is beeing increased after a command has been sent) volatile uint32 cc3000_desired_state = 0; // the current state (is beeing increased after a expected command has been received) volatile uint32 cc3000_current_state = 0; // buffer to hold the received payload uint8 cc3000_return_buffer[CC300_SPI_RX_BUFFER_SIZE]; // number of bytes returned uint8 cc3000_return_buffer_size = 0; // do wee need to close a socket? uint8 cc3000_close_socket = 0; //prototype void cc3000_set_return(uint8 *data, uint8 offset, uint8 size); //***************************************************************************** // //! cc3000_event_handler //! //! @param data //! //! @return returns 1 when done //! //! @brief handles all incomming data from cc3000 // //***************************************************************************** uint8 cc3000_event_handler(uint8 *data){ uint8 count; uint8 hci_type; uint8 buffer_count; uint16 hci_opcode; uint16 hci_args_length; #if (CC3000_TRACE_LEVEL & CC3000_TRACE_LEVEL_DEBUG) debug_str("cc3000_event_handler\n"); #endif // determine the message type hci_type = data[HCI_TYPE_OFFSET]; #if (CC3000_TRACE_LEVEL & CC3000_TRACE_LEVEL_DEBUG) debug_str("type:\n"); debug_int_hex(hci_type); debug_nl(); #endif switch (hci_type){ case HCI_TYPE_EVENT: // determine opcode hci_opcode = data[HCI_OPCODE_MSB_OFFSET]; hci_opcode <<= 8; hci_opcode += data[HCI_OPCODE_LSB_OFFSET]; // determine args_length hci_args_length = data[HCI_ARGS_LENGTH_MSB_OFFSET]; hci_args_length <<= 8; hci_args_length += data[HCI_ARGS_LENGTH_LSB_OFFSET]; #if (CC3000_TRACE_LEVEL & CC3000_TRACE_LEVEL_DEBUG) debug_str("opcode:\n"); debug_int_hex_16bit(hci_opcode); debug_str("args_length:\n"); debug_int_hex_16bit(hci_args_length); #endif // did we expect the returned opcode? if(hci_opcode == cc3000_expect){ //we expected this command so we can increase the current state cc3000_current_state++; cc3000_expect = 0; printf("***we got the expected command***\n\r"); } // is this an unsolicited event? if(hci_opcode & HCI_EVNT_UNSOL_BASE){ switch (hci_opcode){ case HCI_EVNT_DATA_UNSOL_FREE_BUFF: //ToDo: clean this up #if (CC3000_TRACE_LEVEL & CC3000_TRACE_LEVEL_DEBUG) debug_str("Free buffer!\n"); #endif buffer_count = data[5]; // 16 bits but who cares for (count = 0; count < buffer_count; count++) { uint16 my_buffers_free = data[5+2+2+(count*2)]; cc3000_free_buffers += my_buffers_free; } break; default: break; } }else if(hci_opcode & HCI_EVNT_WLAN_UNSOL_BASE){ switch (hci_opcode){ case HCI_EVNT_WLAN_KEEPALIVE: break; case HCI_EVNT_WLAN_UNSOL_CONNECT: #if (CC3000_TRACE_LEVEL & CC3000_TRACE_LEVEL_UNSOL) debug_str("***we are connected***\n"); #endif cc3000_state.connected = 1; break; case HCI_EVNT_WLAN_UNSOL_DISCONNECT: #if (CC3000_TRACE_LEVEL & CC3000_TRACE_LEVEL_UNSOL) debug_str("***we are disconnected***\n"); #endif cc3000_state.connected = 0; break; case HCI_EVNT_WLAN_UNSOL_INIT: case HCI_EVNT_WLAN_ASYNC_SIMPLE_CONFIG_DONE: break; case HCI_EVNT_WLAN_UNSOL_DHCP: cc3000_state.ip[0] = data[5]; cc3000_state.ip[1] = data[6]; cc3000_state.ip[2] = data[7]; cc3000_state.ip[3] = data[8]; #if (CC3000_TRACE_LEVEL & CC3000_TRACE_LEVEL_UNSOL) debug_str("***we got an IP***\n"); debug_int(cc3000_state.ip[3]); debug_putc('.'); debug_int(cc3000_state.ip[2]); debug_putc('.'); debug_int(cc3000_state.ip[1]); debug_putc('.'); debug_int(cc3000_state.ip[0]); debug_putc('.'); debug_nl(); // only in case of dhcp debug_str("from:\n"); debug_int(data[16]); debug_putc('.'); debug_int(data[15]); debug_putc('.'); debug_int(data[14]); debug_putc('.'); debug_int(data[13]); debug_nl(); #endif cc3000_state.dhcp_complete = 1; break; case HCI_EVNT_WLAN_ASYNC_PING_REPORT: break; case HCI_EVNT_BSD_TCP_CLOSE_WAIT: // ToDO: close the socket here #if (CC3000_TRACE_LEVEL & CC3000_TRACE_LEVEL_UNSOL) debug_str("we should close the socket now...\n\r"); #endif cc3000_close_socket = 1; break; default: break; } }else{ // this is a "normal event" // we do not need to differentiate.. we just copy the received data into a buffer switch (hci_opcode){ case HCI_CMND_READ_BUFFER_SIZE: case HCI_CMND_WLAN_CONFIGURE_PATCH: case HCI_NETAPP_DHCP: case HCI_NETAPP_PING_SEND: case HCI_NETAPP_PING_STOP: case HCI_NETAPP_ARP_FLUSH: case HCI_NETAPP_SET_DEBUG_LEVEL: case HCI_NETAPP_SET_TIMERS: case HCI_EVNT_NVMEM_READ: case HCI_EVNT_NVMEM_CREATE_ENTRY: case HCI_CMND_NVMEM_WRITE_PATCH: case HCI_NETAPP_PING_REPORT: case HCI_EVNT_MDNS_ADVERTISE: case HCI_CMND_SETSOCKOPT: case HCI_CMND_WLAN_CONNECT: case HCI_CMND_WLAN_IOCTL_STATUSGET: case HCI_EVNT_WLAN_IOCTL_ADD_PROFILE: case HCI_CMND_WLAN_IOCTL_DEL_PROFILE: case HCI_CMND_WLAN_IOCTL_SET_CONNECTION_POLICY: case HCI_CMND_WLAN_IOCTL_SET_SCANPARAM: case HCI_CMND_WLAN_IOCTL_SIMPLE_CONFIG_START: case HCI_CMND_WLAN_IOCTL_SIMPLE_CONFIG_STOP: case HCI_CMND_WLAN_IOCTL_SIMPLE_CONFIG_SET_PREFIX: case HCI_CMND_EVENT_MASK: case HCI_EVNT_WLAN_DISCONNECT: case HCI_EVNT_SOCKET: case HCI_EVNT_BIND: case HCI_CMND_LISTEN: case HCI_EVNT_CLOSE_SOCKET: case HCI_EVNT_CONNECT: case HCI_EVNT_NVMEM_WRITE: case HCI_EVNT_READ_SP_VERSION: case HCI_EVNT_BSD_GETHOSTBYNAME: case HCI_EVNT_ACCEPT: case HCI_EVNT_RECV: case HCI_EVNT_RECVFROM: case HCI_EVNT_SENDTO: case HCI_EVNT_SELECT: case HCI_CMND_GETSOCKOPT: case HCI_CMND_WLAN_IOCTL_GET_SCAN_RESULTS: case HCI_CMND_SIMPLE_LINK_START: case HCI_NETAPP_IPCONFIG: cc3000_set_return(data,HCI_ARGS_OFFSET,hci_args_length); break; default: break; } } break; case HCI_TYPE_DATA: // determine opcode hci_opcode = data[HCI_OPCODE_LSB_OFFSET]; // Payload length hci_args_length = data[HCI_ARGS_LENGTH_MSB_OFFSET]; hci_args_length <<= 8; hci_args_length += data[HCI_ARGS_LENGTH_LSB_OFFSET]; hci_args_length += data[2]; // did we expect the returned opcode? if(hci_opcode == cc3000_expect){ //we expected this command so we can increase the current state cc3000_current_state++; cc3000_expect = 0; } switch (hci_opcode){ case HCI_DATA_RECV: cc3000_set_return(data,2,hci_args_length); break; default: break; } break; default: break; } return 1; } //***************************************************************************** // //! cc3000_is_ready //! //! @param none //! //! @return returns 1 when the expected message was received form the cc3000 //! //! @brief this is called by the flow_hanlder to determine if the expected //! data has been received // //***************************************************************************** uint8 cc3000_is_ready(void){ return (cc3000_desired_state == cc3000_current_state) ? 1 : 0; } /// Wait for the current CC3000 request to complete void cc3000_wait(void) { while (!cc3000_is_ready()) {} } //***************************************************************************** // //! cc3000_set_return //! //! @param data the returned data from the cc3000 //! //! @param offset the offset of the payload //! //! @param size the length of the payload //! //! @return none //! //! @brief frees the received data from the header and saves the payload //! in the return buffer //! // //***************************************************************************** void cc3000_set_return(uint8 *data, uint8 offset, uint8 size){ uint8 count; //cc3000_return_buffer_size = size; for(count = 0; count < size; count++){ cc3000_return_buffer[count] = data[count+offset]; } } //***************************************************************************** // //! cc3000_get_return_uint8 //! //! @param offset //! //! @return returns one byte from the return buffer //! //! @brief see: @return //! // //***************************************************************************** uint8 cc3000_get_return_uint8(uint8 offset){ return cc3000_return_buffer[0+offset]; } //***************************************************************************** // //! cc3000_get_return_int8 //! //! @param offset //! //! @return returns one byte from the return buffer //! //! @brief see: @return //! // //***************************************************************************** int8 cc3000_get_return_int8(uint8 offset){ return cc3000_return_buffer[0+offset]; } //***************************************************************************** // //! cc3000_get_return_uint32 //! //! @param offset //! //! @return returns 4 bytes from the return buffer as uint32 //! //! @brief see: @return //! // //***************************************************************************** uint32 cc3000_get_return_uint32(uint8 offset){ uint32 ret_data; ret_data = cc3000_return_buffer[3+offset]; ret_data <<= 8; ret_data += cc3000_return_buffer[2+offset]; ret_data <<= 8; ret_data += cc3000_return_buffer[1+offset]; ret_data <<= 8; ret_data += cc3000_return_buffer[0+offset]; return ret_data; } uint16 cc3000_get_return_uint16(uint8 offset){ uint16 ret_data; ret_data = cc3000_return_buffer[1+offset]; ret_data <<= 8; ret_data += cc3000_return_buffer[0+offset]; return ret_data; } //***************************************************************************** // //! cc3000_get_return_int32 //! //! @param offset //! //! @return returns 4 bytes from the return buffer as int32 //! //! @brief see: @return //! // //***************************************************************************** int32 cc3000_get_return_int32(uint8 offset){ int32 ret_data; ret_data = cc3000_return_buffer[3+offset]; ret_data <<= 8; ret_data += cc3000_return_buffer[2+offset]; ret_data <<= 8; ret_data += cc3000_return_buffer[1+offset]; ret_data <<= 8; ret_data += cc3000_return_buffer[0+offset]; return ret_data; } //***************************************************************************** // //! cc3000_get_return_stream //! //! @param data pointer to buffer //! //! @param offset offset //! //! @param size bytes to receive //! //! @return none //! //! @brief fills the given buffer with a data stream //! and stops if the size exceeds the args_length //! // //***************************************************************************** void cc3000_get_return_stream(uint8*data, uint8 offset,uint8 size){ uint8 count; for(count = 0; count < size; count++){ //data[count] = cc3000_return_buffer[count+offset]; *data++ = cc3000_return_buffer[count+offset]; //if(count+offset == cc3000_return_buffer_size){ // printf("ERR: cc3000_get_return_stream\n\r"); // break; //} } } //***************************************************************************** // //! get_return_size //! //! @param none //! //! @return number of bytes in buffer //! //! @brief returns the number of bytes in the return buffer to determine //! the size of a given return buffer //! // //***************************************************************************** uint8 get_return_size(void){ return cc3000_return_buffer_size; }
C
#include<stdio.h> #include<stdlib.h> struct NODE { int data; struct NODE* next; }; struct NODE *newNode(int data){ struct NODE *new_node = (struct NODE *)malloc (sizeof(struct NODE)); new_node->data = data; new_node->next = NULL; return new_node; free(new_node); } void push (struct NODE ** head_ref ,int val){ static int num=1;//value that to be added struct NODE *new_node=(struct NODE*)malloc(sizeof (struct NODE)); new_node = newNode(val); new_node->next = *head_ref; *head_ref = new_node; printf("%d th digit is %d\n",num ,new_node->data);num++; free(new_node); } struct NODE* addTwoNumber(struct NODE *num1 ,struct NODE *num2){ struct NODE *result=NULL,*preNode=NULL,*tmp; int sum ,carry=0; while(num1 !=NULL || num2 !=NULL){ sum = carry + (num1? num1->data: 0) + (num2? num2->data: 0); if(sum>=10 && sum <=19)carry=1; else if (sum >=20)carry=2; else carry =0; sum=sum % 10; tmp = newNode(sum); if (result == NULL){ result = tmp; preNode=tmp; } else { preNode->next =tmp ; preNode=tmp; } if (num1)num1=num1->next; if (num2)num2=num2->next; } if(carry>0){ tmp=newNode(carry); preNode->next =tmp; } return result; } void printNumber( struct NODE *n){ while(n->next !=NULL){ printf("%d",n->data); n=n->next; } printf("\n"); } int main (){ int t;//number of test cases scanf("%d",&t); printf("t=%d\n",t); for(int a=0; a<t; a++){ int n1,n2; struct NODE *first = NULL; struct NODE *second = NULL; struct NODE *result = NULL; scanf("%d %d",&n1,&n2); for (int i=0; i<n1; i++){ int digit; scanf("%d",&digit); push(&first,digit); } printNumber(first); for(int i=0;i<n2;i++){ int digit; scanf("%d",&digit); push(&second,digit); } printf("\n"); printNumber(second); printf("\n"); int opcode; scanf("%d",&opcode); result=addTwoNumber(first,second); printNumber(result); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* read_options.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: emuckens <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/10/24 14:50:47 by emuckens #+# #+# */ /* Updated: 2018/10/24 14:53:49 by emuckens ### ########.fr */ /* */ /* ************************************************************************** */ #include "pushswap.h" static int is_option(ENV *e, char c) { if (ft_isalpha(c) || !c) { if (!ft_strchr("cdfhilnorsva", c)) { error(e, INPUT, -1, OPTION); return (0); } return (1); } return (0); } /* ** Read arguments starting with -, modify binary tracker ** Input: argv, argc, pointer on number of arguments counted as options ** Note: num is to adjust number arguments read as input ** Returns -1 if option error, otherwise 1. Options value is stored in env */ int read_options(ENV *e, char **argv, int argc, int *num) { int arg; int i; int ret; int options; options = 0; if ((arg = 1) && !argv[1][0]) return (-1); while (argv[arg][0] == '-' && is_option(e, argv[arg][1]) && --argc) { if ((i = 1) && argv[arg][0] == '-' && !argv[arg][1]) return (-error(e, INPUT, -1, OPTION)); while ((ret = is_option(e, argv[arg][i])) == 1) { options |= (1 << (argv[arg][i] - 'a')); ++i; } if (++arg && ret < 0) return (-1); if (++(*num) && argc == 1 && (*num = -1)) break ; } if (((e->options = options) & OPT_HELP)) display_help(e); return (1); }
C
/*--------------------------------------------------------------*/ /*Inclusin de archivos /*--------------------------------------------------------------*/ #include <stdio.h> #include <conio.h> /*--------------------------------------------------------------*/ /*Declaracin de constantes y macros /*--------------------------------------------------------------*/ #define N 2 #define M 2 /*--------------------------------------------------------------*/ /*Declaracin de estructuras /*--------------------------------------------------------------*/ typedef int TMatNum[N][M]; /*--------------------------------------------------------------*/ /*Declaracin de prototipos de funciones /*--------------------------------------------------------------*/ void LeerMatriz(TMatNum); void mostrarMatriz(TMatNum); int RecorrerMatriz(TMatNum); int CalcularCuadrado(int); /*--------------------------------------------------------------*/ /*Definicin de la funcin principal /*--------------------------------------------------------------*/ int main() { //VARIABLES TMatNum matrizNum; int numero; //COMIENZO printf("\nTP1-EJ05 - Suma los cuadrados de los coeficientes de una matriz"); printf("\n---------------------------------------------------------------"); printf("\n\n"); LeerMatriz(matrizNum); numero = RecorrerMatriz( matrizNum); printf("\nLa suma de los cuadrados de los coeficientes de la matriz es: %i", numero); printf("\n\nPresione cualquier tecla para salir..."); getch(); } /*--------------------------------------------------------------*/ /*Funcin : LeerMatriz /*Propsito: Lee una matriz de enteros por teclado /*Entrada : enteros /*Salida : matriz de enteros /*Pre : /*Pos : matriz de enteros con N x M /*--------------------------------------------------------------*/ void LeerMatriz(TMatNum matrizNum) { int i,j; for (i = 0; i < N; i++) { for (j=0;j<M;j++) { printf("Ingrese el elemento para la posicion %i / %i de la matriz: ", i,j); scanf("%d", &matrizNum[i][j]); } } } /*--------------------------------------------------------------*/ /*Funcin : Verificacion /*Propsito: /*Entrada : /*Salida : /*Pre : /*Pos : /*--------------------------------------------------------------*/ int RecorrerMatriz(TMatNum matriz) { int valor=0; int i,j; int res=0; int suma=0; for(i=0;i<N;i++) { for(j=0;j<M;j++) { res = CalcularCuadrado(matriz[i][j]); suma = suma + res; } } return suma; } /*--------------------------------------------------------------*/ /*Funcin : CalcularCuadrado /*Propsito: /*Entrada : /*Salida : /*Pre : /*Pos : /*--------------------------------------------------------------*/ int CalcularCuadrado(num) { int cuad; cuad = num*num; return cuad; }
C
#ifndef MERGER_H #define MERGER_H #include <stdint.h> #include <stdbool.h> #include "Utility.h" #define DEBOUNCE_INTERVAL (100) #define GLOBAL_TIMEOUT (100) #define SEARCH_MATCH 1 #define SEARCH_UNMATCH 0 typedef enum SensorState { SensorStateIdle = 0, SesnorStateDownPending, SensorStateDown, SensorStateMove, SensorStateUpPending, SensorStateUp }SensorState; extern bool globalTriggerTimeout; extern int32_t globalTimeoutInMs; extern bool allSensorConfigurationsReceived; extern int numberOfSensorConfigurationsReceived; /* Adds sensor configuration to internal array and sets flag when all configurations are added. The configuartions are used for mapping coordniates. * * @return true on success, false on fail. */ bool AddSensorConfiguration(SensorConfiguration sensorConfiguration); /* Merge touch and process the touch according to the above flowchart. * This is the single entry point for incoming touch. * * @return processed indexedMessage, NULL if invalidated or error occured. */ IndexedMessage * MergeTouch(IndexedMessage * indexedMessage); /* Gets the current push index for the buffer. * * @return touchBufPushIndex. */ int TouchBufGetCurrentPushIndex(void); /* Pops touch at custom position with the option of updating the pop index. * * @return touch, NULL if unsuccessful. */ TouchInfo * TouchBufPopCustom(int offset, bool updatePopIndex); /* Pops last written touch from buffer. * * @return touch, NULL if buffer is empty. */ TouchInfo * TouchBufPopLastWritten(void); /* Pops touch from buffer and updates the pop index. * * @return touch, NULL if buffer is empty. */ TouchInfo * TouchBufPop(void); /* Push a touch to the buffer and updates the push index. * * @return push index. */ int TouchBufPush(TouchInfo * info); /* Copy parameters into a Touchinfo struct for later processing. */ void CopyTouchInfo(TouchInfo * dest, const uint32_t xInput, const uint32_t yInput, const ApplicationTouchEvent eventInput, const uint64_t timestampInput, SensorConfiguration * configurationInput); /* Timeout handle function. Resets the internal state machine. */ void TimeoutCallback(void); /* Sets the timeout flags. */ void TriggerTimeout(int32_t timeout); /* Prints out the timestamp and state for a touch. */ void DumpTouchInfo(TouchInfo * info); /* Gets a string describing the sensor position. */ const char * GetSensorPositionName(SensorPosition sensorPosition); /* Gets a string describing the touch state. */ char * GetTouchStateName(ApplicationTouchEvent event); #endif // MERGER_H
C
#include<stdio.h> #include<string.h> int main( void ) { printf( "Kelime Uzunlugu: %d\n", strlen("Merhaba") ); return 0; }
C
#include <stdio.h> #include <inttypes.h> #include <string.h> #include <libgen.h> #include "ism.h" #include "mainview.h" static char *dirpath; static void tileset(char *codept, char *name, int sx, int sy) { terminal_setf("%s: %s/../Resources/%s-%dx%d.png, size=%dx%d, resize=%dx%d," "resize-filter=nearest, align=bottom-right;", codept, dirpath, name, sx, sy, sx, sy, sx*2, sy*2 ); } int main(int argc, char* argv[]) { char *path = strdup(argv[0]); dirpath = dirname(path); terminal_open(); terminal_setf( "window: size=120x80, cellsize=20x20, resizeable=true, fullscreen=true, title='Ism %d.%d';" "input: filter={keyboard}", ISM_VERSION_MAJOR, ISM_VERSION_MINOR ); tileset("0xE0000", "Potash", 10, 10); tileset("0xE0100", "tiles", 10, 10); tileset("0xE0200", "mountain", 30, 30); tileset("0xE0201", "mountain", 20, 20); tileset("0xE0202", "mountain", 30, 20); terminal_clear(); free(path); map_config config = { .seed = 1234, .width = 500, .height = 500, .ocean_level = 0, .base_rainfall = 1.f, .rainfall_factor = 2.f, .land_mass_scale = 3, .fault_scale = 10, .erosion_scale = 8, .forest_scale = 40, .coast_complexity = 8, .fault_complexity = 8, .erosion_complexity = 12, .forest_complexity = 3, }; mainview view = { .width = 120, .height = 80, .map_scroll_x = 58, .map_scroll_y = 50, .game_map = map_generate(config), }; mainview_draw(&view); /* int c = 0x2980; for (int y = 0; y < 16; y++) { for (int x = 0; x < 32; x++) { terminal_put(x * 2, y * 2, c++); } } terminal_put(10, 5, 0x256D); terminal_put(11, 5, 0x2510); terminal_put(10, 6, 0x2514); terminal_put(11, 6, 0x2518); terminal_put(5, 5, 0x2229); terminal_put(4, 5, 0x005E); terminal_put(4, 9, 0x007B); terminal_put(5, 9, 0x263A); */ terminal_refresh(); while (1) { int key = terminal_read(); if (key == TK_ESCAPE || key == TK_CLOSE) { break; } switch (key) { case TK_UP: mainview_scroll_map(&view, 0, -1); break; case TK_DOWN: mainview_scroll_map(&view, 0, 1); break; case TK_LEFT: mainview_scroll_map(&view, -1, 0); break; case TK_RIGHT: mainview_scroll_map(&view, 1, 0); break; } mainview_draw(&view); } terminal_close(); return 0; }
C
#include<stdio.h> int main(){ //declare variables char sString[1000], dCounter, dLength, dMax; //promt the user printf("\n Please insert the string: \n"); scanf("%s", sString); dLength = strlen(sString); dCounter=1; dMax=dCounter; //for loop for(int i=0; i<dLength; i++){ if(dCounter>dMax){ dMax=dCounter; }//endif if(sString[i] != sString[i+1]){ dCounter++; }//endif else { dCounter=0; } //endelse }//end for printf("\n Length of the longest substring without repeating characters is: %d", dMax); return 0; }
C
#include<stdio.h> #include<string.h> void trimLeft(char s[]){ int i=0, j; while(s[0]==' '){ for(j=0;j<strlen(s)-1;j++){ s[j]=s[j+1]; } s[strlen(s)-1]='\0'; } } void trimRight(char s[]){ int i=strlen(s)-1; while(s[i]==' '){ s[i--]='\0'; } } void trimMiddle(char s[]){ int i=0,j; while(s[i]==' ') i++; for(i;i<strlen(s);i++){ if((s[i]==' ')&&(s[i+1]==' ')){ for(j=i;j<strlen(s)-1;j++){ s[j]=s[j+1]; } s[strlen(s)-1]='\0'; i--; } } } void menu(){ printf("Chuong trinh \n"); printf("Author: Anh Khoa\n\n"); printf("1.Trim left \n"); printf("2.Trim right \n"); printf("3 Trim middle\n"); printf("4.Exit \n"); } int choose(){ printf("Your choise: "); int n; scanf("%d",&n); return n; } int main(){ char s[20]; int c; printf("Enter string: "); gets(s); do{ menu(); c = choose(); switch(c) { case 1: trimLeft(s); printf("Result: %s\n\n\n",s); break; case 2: trimRight(s); printf("Result: %s\n\n\n",s); break; case 3: trimMiddle(s); printf("Result: %s\n\n\n",s); break; case 4: break; default: printf("Wrong choise!\n\n\n"); break; } } while(c!=4); }
C
#ifndef _SPI_IMPL_H #define _SPI_IMPL_H #ifndef F_CPU #define F_CPU 16000000UL #endif /** * MOSI , MISO , SCK and SS PORT can be changed using this macros in * the Makefile */ #ifndef #define DDR_SPI DDRB #endif #ifndef #define PORT_SPI PORTB #endif #ifndef #define DD_MOSI DDB3 #endif #ifndef #define DD_SCK DDB5 #endif #ifndef #define DD_MISO DDB4 #endif #ifndef #define DD_SS DDB2 #endif #include <inttypes.h> /** * Global SPI bus init * @param lsbfirst if 0: most significant bit is transmitted first * @param master if 1: initiatization as master else as slave * @param mode The 4 data transfer modes according to the datasheet * @param clock_rate value between 0-3 ! It helps dividing clock freq by 4^(clock_rate+1) * @param dblclkrate if 1: double the frequency of the SPI communication */ void spi_init( uint8_t lsbfirst, uint8_t master, uint8_t mode, uint8_t clock_rate, uint8_t dblclkrate ); /** * initialize SPI as a master with a specified clock rate * Here we don't enable the double SPI Speed bit and * the data are sent MSB to LSB and the mode of transmission * is the default one * * @param clock_rate the clock rate of the SPI connection */ void spi_master_init(uint8_t clock_rate); /** * Initialize SPI as a slave with a specified clock rate * Here the data mode is the default one 0 and data are sent MSB to LSB. * @param clock_rate the clock rate of the SPI connection */ void spi_slave_init(uint8_t clock_rate); /** * Send data over the SPI link * @param data Data to be send over the SPI connection */ void spi_transmit( uint8_t data); /** * Receive data over SPI connection * @return data received on the SPI link */ uint8_t spi_receive(void); #endif //_SPI_IMPL_H
C
#include <string.h> #include "jmalloc.h" #include "jarray.h" #define _JAP(ja) ((struct _j_array*)(&ja[0]-sizeof(struct _j_array))) size_t jarrLen(ja_t arr){ return _JAP(arr)->len; } size_t jarrUnused(ja_t arr){ return _JAP(arr)->unused; } size_t jarrCap(ja_t arr){ return _JAP(arr)->len + _JAP(arr)->unused; } ja_t jarrCreate(size_t size){ jarray* arr = NULL; if (NULL == (arr = (jarray*)jmalloc(sizeof(jarray) + size * sizeof(arraynode)))) { return NULL; } arr->dup = NULL; arr->cmp = NULL; arr->free = NULL; arr->len = 0; arr->unused = size; return &arr->buf[0]; } ja_t jarrResize(ja_t arr, size_t size){ jarray* o = _JAP(arr); jarray* a = NULL; if (NULL == (a = jarrCreate(size))) { return NULL; } memcpy(&a->buf[0], arr, (size < _JAP(arr)->len) ? size : _JAP(arr)->len); a->len = o->len; a->unused = size - a->len; jarrRelease(arr); return a; } ja_t jarrClear(ja_t arr){ jarray* a = _JAP(arr); while (a->len--) { if (a->free) { a->free(a->buf[a->len]); } else { jfree(a->buf[a->len]); } } a->len = 0; return arr; } void jarrRelease(ja_t arr){ jarrClear(arr); jfree(_JAP(arr)); } void jarrSetDup(ja_t arr,void *(*dup)(void *)){ _JAP(arr)->dup = dup; } void jarrSetDup(ja_t arr,void(*free)(void *)){ _JAP(arr)->free = free; } void jarrSetDup(ja_t arr,int(*cmp)(void *, void *)){ _JAP(arr)->cmp = cmp; } size_t jarrEnlarge(ja_t arr){ if (_JAP(arr)->len == 0) return 1; return _JAP(arr)->len + 1 + _JAP(arr)->len / 2; } ja_t jarrAdd(ja_t arr,void * value){ if (_JAP(arr)->unused) { arr[_JAP(arr)->len] = value; _JAP(arr)->len++; _JAP(arr)->unused--; return arr; } jarray* a = jarrResize(arr, jarrEnlarge(arr)); if (NULL == a) { return NULL; } a->buf[a->len] = value; a->unused--; return &a->buf[0]; } ja_t jarrErase(ja_t arr,int at){ if (at >= _JAP(arr)->len) { return arr; } memcpy(arr[at], arr[at + 1], sizeof(arraynode)*(_JAP(arr)->len - at - 1)); _JAP(arr)->len--; _JAP(arr)->unused++; return arr; } ja_t jarrConcat(ja_t arr, ja_t append){ size_t newsize = jarrCap(arr); while (newsize < jarrCap(arr) + jarrLen(append)) { newsize = jarrEnlarge(arr); } arr = jarrResize(arr, newsize); memcpy(&arr[_JAP(arr)->len], append, sizeof(arraynode)*_JAP(append)->len); _JAP(arr)->len += _JAP(append)->len; _JAP(arr)->unused -= _JAP(append)->unused; return arr; } void * jarrAt(ja_t arr, int at){ if (at >= _JAP(arr)->len) { return NULL; } return arr[at]; } size_t jarrFind(ja_t arr, size_t offset, void * key){ if (_JAP(arr)->cmp) { for (int i = offset; i < _JAP(arr)->len; i++) { if (0 == _JAP(arr)->cmp(arr[i], key)) { return i; } } return -1; } for (int i = offset; i < _JAP(arr)->len; i++) { if (arr[i] == key) { return i; } } return -1; } void jarrReverse(ja_t arr){ if (_JAP(arr)->len <= 1)return; size_t i = 0, j = _JAP(arr)->len - 1; arraynode* tmp = NULL; while (i < j) { tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; i++; j--; } } size_t jarrCountAll(ja_t arr, size_t offset, void * key){ size_t count = 0; if (_JAP(arr)->cmp) { for (int i = offset; i < _JAP(arr)->len; i++) { if (0 == _JAP(arr)->cmp(arr[i], key)) { count++; } } } else { for (int i = offset; i < _JAP(arr)->len; i++) { if (arr[i], key) { count++; } } } return count; } size_t jarrFindFirstIf(ja_t arr, size_t offset, void * key, int(*cmp)(void *, void *)){ for (int i = offset; i < _JAP(arr)->len; i++) { if (0 == cmp(arr[i], key)) { return i; } } return -1; }
C
#include <stdio.h> #include <ctype.h> #include <string.h> #include <math.h> int main(){ int i, numero; printf("entre com um numero:"); scanf("%d",&numero); for(i=1; i<=numero/2; i++) if(primo(i)&&primo(numero-i)) printf("%d + %d\n", i, numero-i); return 0; } int primo(int numero){ int i, checa=1; for(i=2;i<=numero/2;i++) if(numero%i==0){ checa=0; break; } return (numero<=1)? 0: checa; }
C
/* Provides C functions: imageinterp_get_roi, imageinterp_get_roi_corners. For Python extension module, compile with -DPYTHON_EXTENSION. Author: Pearu Peterson Created: June 2011 */ #include <math.h> /* imageinterp_get_roi function returns a subimage (roi) of an image using interpolation. Input parameters ---------- image_width, image_height : int Specify the number of columns and rows of the image. image : double* Specify pointer to image array that uses row-storage order. image_di_size, image_dj_size : double Specify pixel sizes of image. i0, j0, i1, j1 : double Specify roi center line. width : double Specify roi width in image units. roi_width, roi_height : int Specify the number of columns and rows of the roi image. interpolation : int Specify interpolation method: 0=nearest-neighbor interpolation, 1=bilinear, 2=bicubic Output parameters ----------------- roi : double * Specify pointer to roi array (row-storage order) Notes ----- If the image pixel sizes are dx and dy then the roi pixel sizes will be DX = L / roi_width DY = width / roi_height where L = hypot((i1-i0)*dx, (j1-j0)*dy) */ /* http://en.wikipedia.org/wiki/Cubic_interpolation */ inline double CINT(double x, double pm1, double p0, double p1, double p2) { return 0.5 * (x*((2-x)*x-1)*(pm1) + (x*x*(3*x-5)+2)*(p0) + (x*((4-3*x)*x+1))*p1 + ((x-1)*x*x)*p2); } void imageinterp_get_roi(int image_width, int image_height, double *image, double di_size, double dj_size, double i0, double j0, double i1, double j1, double width, int roi_width, int roi_height, double *roi, int interpolation ) { #define GET_IMAGE(I, J) (((I)>=0 && (I)<image_width && (J)>=0 && (J)<image_height) ? (*(image + (J)*image_width + (I))) : 0.0) #define GET_ROI(I, J) (*(roi + (J)*roi_width + (I))) int ri, rj; int ii, ji, ii1, ji1; double i, j; double l = hypot((i1-i0)*di_size, (j1-j0)*dj_size); double dt = (roi_width>1?1.0 / (roi_width-1):0.0); double ds = (roi_height>1?1.0 / (roi_height-1):0.0); double di = -(j1-j0)/l*width*0.5*dj_size/di_size; double dj = +(i1-i0)/l*width*0.5*di_size/dj_size; double t; double s; double v; double is, js; double rmi, rmj; double bm1, b0, b1, b2; for (rj=0; rj<roi_height; ++rj) { s = (double)rj * ds; is = (1.0-s)*(i0 - di) + s*(i0 + di); js = (1.0-s)*(j0 - dj) + s*(j0 + dj); for (ri=0; ri<roi_width; ++ri) { t = (double)ri * dt; i = (1.0-t)*is + t*(is+i1-i0); j = (1.0-t)*js + t*(js+j1-j0); ii = floor(i); ji = floor(j); rmi = i-ii; rmj = j-ji; ii1 = ii+1; ji1 = ji+1; switch (interpolation) { case 1: /* bilinear interpolation */ v = (GET_IMAGE(ii,ji)*(1.0-rmi)+GET_IMAGE(ii1,ji)*rmi)*(1.0-rmj) +(GET_IMAGE(ii,ji1)*(1.0-rmi)+GET_IMAGE(ii1,ji1)*rmi)*rmj; break; case 2: /* bicubic interpolation */ bm1 = CINT(rmi, GET_IMAGE(ii-1, ji-1), GET_IMAGE(ii, ji-1), GET_IMAGE(ii+1, ji-1), GET_IMAGE(ii+2, ji-1)); b0 = CINT(rmi, GET_IMAGE(ii-1, ji), GET_IMAGE(ii, ji), GET_IMAGE(ii+1, ji), GET_IMAGE(ii+2, ji)); b1 = CINT(rmi, GET_IMAGE(ii-1, ji+1), GET_IMAGE(ii, ji+1), GET_IMAGE(ii+1, ji+1), GET_IMAGE(ii+2, ji+1)); b2 = CINT(rmi, GET_IMAGE(ii-1, ji+2), GET_IMAGE(ii, ji+2), GET_IMAGE(ii+1, ji+2), GET_IMAGE(ii+2, ji+2)); v = CINT(rmj, bm1, b0, b1, b2); break; case 0: default: /* nearest-neighbor interpolation */ v = GET_IMAGE(ii, ji); } GET_ROI(ri, rj) = v; } } } void imageinterp_get_roi_corners(int image_width, int image_height, double di_size, double dj_size, int i0, int j0, int i1, int j1, double width, double *lli, double *llj, double *lri, double *lrj, double *uri, double *urj, double *uli, double *ulj) { double l = hypot((i1-i0)*di_size, (j1-j0)*dj_size); double di = -(double)(j1-j0)/l*width*0.5*dj_size/di_size; double dj = +(double)(i1-i0)/l*width*0.5*di_size/dj_size; *lli = i0 - di; *llj = j0 - dj; *lri = i1 - di; *lrj = j1 - dj; *uri = i1 + di; *urj = j1 + dj; *uli = i0 + di; *ulj = j0 + dj; } #ifdef PYTHON_EXTENSION #include <Python.h> #define PY_ARRAY_UNIQUE_SYMBOL PyArray_API #include "numpy/arrayobject.h" #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ #define PyMODINIT_FUNC void #endif static PyObject *py_imageinterp_get_roi(PyObject *self, PyObject *args) { PyObject* image = NULL; PyObject* roi = NULL; double i0, i1, j0, j1; double di_size, dj_size; double roi_di_size, roi_dj_size; int roi_width = 0, roi_height = 0; int interpolation; double w, l; npy_intp roi_dims[] = {0, 0}; if (!PyArg_ParseTuple(args, "O(dd)(dd)(dd)di", &image, &di_size, &dj_size, &i0, &i1, &j0, &j1, &w, &interpolation)) return NULL; if (!(PyArray_Check(image) && PyArray_TYPE(image) == PyArray_DOUBLE && PyArray_NDIM(image)==2)) { PyErr_SetString(PyExc_TypeError,"1st argument must be rank-2 double array object"); return NULL; } l = hypot((i1-i0)*di_size, (j1-j0)*dj_size); roi_width = (int)(hypot(i1-i0, j1-j0)+1); roi_height = ceil((double)roi_width * w / (l+1.0)); roi_di_size = l / roi_width; roi_dj_size = w / roi_height; roi_dims[0] = roi_height; roi_dims[1] = roi_width; roi = PyArray_SimpleNew(2, roi_dims, PyArray_DOUBLE); imageinterp_get_roi(PyArray_DIMS(image)[1], PyArray_DIMS(image)[0], PyArray_DATA(image), di_size, dj_size, i0, j0, i1, j1, w, roi_width, roi_height, PyArray_DATA(roi), interpolation ); return Py_BuildValue("N(dd)", roi, roi_di_size, roi_dj_size); } static PyObject *py_imageinterp_get_roi_corners(PyObject *self, PyObject *args) { int i0, i1, j0, j1, image_width, image_height; double w; double di_size, dj_size; double lli, llj, lri, lrj, uri, urj, uli, ulj; if (!PyArg_ParseTuple(args, "(ii)(dd)(ii)(ii)d", &image_width, &image_height, &di_size, &dj_size, &i0, &i1, &j0, &j1, &w)) return NULL; imageinterp_get_roi_corners(image_width, image_height, di_size, dj_size, i0, j0, i1, j1, w, &lli, &llj, &lri, &lrj, &uri, &urj, &uli, &ulj ); return Py_BuildValue("(dd)(dd)(dd)(dd)",lli, llj, lri, lrj, uri, urj, uli, ulj); } static PyMethodDef module_methods[] = { {"get_roi", py_imageinterp_get_roi, METH_VARARGS, "get_roi(image, (di, dj), (i0, i1), (j0, j1), w, interpolation) -> roi"}, {"get_roi_corners", py_imageinterp_get_roi_corners, METH_VARARGS, "get_roi_corners((w,h), (di,dj), (i0, i1), (j0, j1), w) -> (ll,lr,ur,ul)"}, {NULL} /* Sentinel */ }; PyMODINIT_FUNC initimageinterp(void) { PyObject* m = NULL; import_array(); if (PyErr_Occurred()) {PyErr_SetString(PyExc_ImportError, "can't initialize module imageinterp (failed to import numpy)"); return;} m = Py_InitModule3("imageinterp", module_methods, "Provides get_roi, get_roi_corners functions."); } #endif
C
#include <stdio.h> int main() { char a[11]; void rank(char a[11]); gets(a); rank(a); return 0; } void rank(char a[11]) { int i,m,n; char b[10]={0},max='0'; for (m=0;m<=9;m++) { for (i=0;i<=9;i++) if (max<=a[i]) {max=a[i]; n=i;} b[m]=max; a[n]='0'; max='0'; } puts(b); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { char nachname[30]; float note; } student; int main(int argc, char const *argv[]){ int N; printf("Wie viele Daten einlesen? N = "); scanf("%i", &N); student **studArg = malloc(sizeof(student) * N); char name[30]; float note; for(size_t i = 0; i < N; i++){ printf("Note"); scanf("%f", &note); if(note < 1.0 || note > 5.0){ puts("falsche Eingabe"); i--; continue; } printf("Name"); scanf("%s", name); student *s = malloc(sizeof(student)); strcpy(s->nachname, name); s->note = note; studArg[i] = s; } float bestGrade = 5.0; float gradeSum = 0.0; for(size_t i = 0; i < N; i++){ if (studArg[i]->note < bestGrade) { bestGrade = studArg[i]->note; } gradeSum += studArg[i]->note; } for(size_t i = 0; i < N; i++){ if(studArg[i]->note == bestGrade) printf("%s:%f\n", studArg[i]->nachname, studArg[i]->note); } printf("Durchschnitt %f", gradeSum / N); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_int_type.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddraco <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/07/26 14:58:44 by ddraco #+# #+# */ /* Updated: 2020/07/28 01:29:06 by ddraco ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/ft_processor.h" #include "../includes/ft_utils.h" static int ft_print_spaces(t_data *data, int arg_len, ssize_t arg) { int spaces; int preci; int width; char what_symb; spaces = 0; width = data->width; if (arg < 0) preci = (data->precision >= arg_len ? data->precision + 1 : arg_len); else preci = (data->precision >= arg_len ? data->precision : arg_len); spaces = (width > preci ? width - preci : 0); if (data->flag_zero == '0') what_symb = '0'; else what_symb = ' '; ft_putchar_n(what_symb, spaces); return (spaces); } static int ft_print_zero(t_data *data, int arg_len, ssize_t arg) { int precision; int count_zero; precision = data->precision; if (arg >= 0) count_zero = precision > arg_len ? precision - arg_len : 0; else { arg_len--; count_zero = precision > arg_len ? precision - arg_len : 0; } ft_putchar_n('0', count_zero); return (count_zero); } int ft_int_type(t_data *data, va_list *args) { ssize_t arg; int i; int arg_len; arg = va_arg(*args, int); arg_len = ft_len_int(arg); arg_len = (data->precision == 0 && arg == 0 ? 0 : arg_len); i = arg_len; data->flag_zero == '0' && arg < 0 ? ft_putchar_n('-', 1) : 0; if (data->flag_minus == '.') i += ft_print_spaces(data, arg_len, arg); data->flag_zero == '.' && arg < 0 ? ft_putchar_n('-', 1) : 0; i += ft_print_zero(data, arg_len, arg); if (!(data->precision == 0 && arg == 0)) arg >= 0 ? ft_putnbr_fd(arg, 1) : ft_putnbr_fd(arg * (-1), 1); if (data->flag_minus == '-') i += ft_print_spaces(data, arg_len, arg); return (i); }
C
#include <stdio.h> #include "semver.h" int main(void) { semver_t v; semver_bump (&v); const char ver[] = "1.0.0"; const int valid = semver_is_valid(ver); printf("%s is valid: %d\n", ver, valid); return 0; }
C
#include <stdio.h> #include <dos.h> void main(void) { struct fatinfo fat; getfatd(&fat); printf("Sectors per cluster %d\n", fat.fi_sclus); printf("Clusters per disk %u\n", fat.fi_nclus); printf("Bytes per cluster %d\n", fat.fi_bysec); printf("Disk type %x\n", fat.fi_fatid & 0xFF); }
C
#include <stm32f10x.h> void delay(void); int main(void){ int n = 0; int button; // Enable the GPIOA (bit 2) and GPIOC (bit 4) // See 6.3.7 in stm32f100x reference manual RCC->APB2ENR |= (0x10 | 0x04); // Set GPIOC Pin 8 abd Pin 9 to outputs // 7.2.2 in stm32f100x reference manual GPIOC->CRH = 0x11; // Set GPIOA Pin 0 to input floating // 7.2.1 in stm32f100x reference manual GPIOA->CRL = 0x04; while(1){ delay(); // Read the button - the button pulls down PAO to logic 0 button = ((GPIOA->IDR & 0x1) == 0); n++; // see 7.2.5 in stm32f100x reference manual if(n & 1){ GPIOC->BSRR = (1<<8); }else{ GPIOC->BSRR = (1<<24); } if((n & 4) && button){ GPIOC->BSRR = (1<<9); }else{ GPIOC->BSRR = (1<<25); } } } void delay(void){ int i = 100000; // About 1/4 second delay while(i-- > 0){ asm("nop"); } }
C
/********************************************************* * From C PROGRAMMING: A MODERN APPROACH, Second Edition * * By K. N. King * *********************************************************/ #define THIS_FILE "ch13ex06.c, page 309" #define PRINT_FILE_INFO \ printf("C Programming, A Modern Approach: %s\n", THIS_FILE); /* Edit strcmp() function to use pointer arithmetic instead of integer indexes. */ #include <stdbool.h> /* C99 only */ #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <time.h> #include <string.h> /* defines */ #define LINE_LEN 80 /* external variables */ /* function prototypes */ int read_line(char str[], int n); void capitalise(int n, char str[n]); void censor(char str[], const char hide[]); int my_strcmp(char *s, char *t); /* main() */ /******************************************************** * main: ********************************************************/ int main(void) { PRINT_FILE_INFO /* stores up to LINE_LEN char, allows space for null terminator */ char word1[LINE_LEN + 1]; char word2[LINE_LEN + 1]; printf("Enter two words to compare.\n"); printf("Word one: "); read_line(word1, LINE_LEN); printf("Word two: "); read_line(word2, LINE_LEN); printf("Result of comparison: %d\n", my_strcmp(word1, word2)); return 0; } /* function definitions */ int my_strcmp(char *s, char *t) { while (*s == *t) { if (*s == '\0') return 0; s++, t++; } return *s - *t; } int read_line(char str[], int n) { int ch, i = 0; while ((ch = getchar()) != '\n') { if (i == 0) /* skip leading whitespace */ if (isspace(ch)) continue; if (i < n) { str[i++] = ch; } } str[i] = '\0'; /* terminate string */ return i; /* number of char stored in str[] */ }
C
/* ** EPITECH PROJECT, 2018 ** get_next_line.c ** File description: ** my function getline */ #include "include/my.h" char *str_dup_gnl(char *str) { char *result; int index = -1; while (str[++index]); result = malloc(index + 1); if (!result) return (NULL); result[index] = '\0'; index = -1; while (str[++index]) result[index] = str[index]; return (result); } char *str_join_gnl(char *str1, char *str2) { char *result; int indexStr1 = 0; int indexStr2 = 0; while (str2[indexStr2] || str1[indexStr1]) { if (str1[indexStr1]) indexStr1++; if (str2[indexStr2]) indexStr2++; } result = malloc(indexStr1 + indexStr2 + 1); result[indexStr1 + indexStr2] = '\0'; indexStr1 = -1; while (str1[++indexStr1]) result[indexStr1] = str1[indexStr1]; for (int index = 0; index < indexStr2; index++) result[indexStr1 + index] = str2[index]; free(str1); free(str2); return (result); } char *read_gnl(int fd, char **result, int totNb) { char *buff = malloc(READ_SIZE + 1); char *prev = NULL; int charNb = read(fd, buff, READ_SIZE); int index = -1; buff[charNb] = '\0'; for (int i = 0; i < charNb && !*result; i++) if (buff[i] == '\n') { *result = malloc(totNb + i + 1); (*result)[totNb + i] = '\0'; prev = (buff[i + 1] != '\0') ? str_dup_gnl(buff + i + 1) : NULL; } (!charNb && totNb) ? *result = malloc(totNb + 1) : NULL; (!charNb && totNb) ? (*result)[totNb] = '\0' : 1; if (*result == NULL && charNb) prev = read_gnl(fd, result, totNb + charNb); while (buff[++index] != '\n' && buff[index] && *result) (*result)[totNb + index] = buff[index]; free(buff); return (prev); } char *get_next_line(int fd) { static char *prev = NULL; char *result = NULL; char *prevTmp = NULL; int index = -1; while (prev && prev[++index]) if (prev[index] == '\n') { prev[index] = '\0'; result = str_dup_gnl(prev); prevTmp = prev; prev = str_dup_gnl(prev + index + 1); free(prevTmp); return (result); } prevTmp = (fd > 0 && read(fd, prevTmp, 0) == 0) ? read_gnl(fd, &result, 0) : NULL; if (prev) result = (result) ? str_join_gnl(prev, result) : prev; prev = prevTmp; return (result); }
C
//////////////////////////////////////////////////////////////////////////////// // Comments // Solution to ex. 3-2. // // Reads & prints input, with two possible contingencies: // //// 1) If it reads a newline or tab character before a literal '\n' or '\t', //// then it prints this newline or tab--and all subsequent newline and tab //// characters--respectively as a literal '\n' or '\t'. // //// 2) If it reads a literal '\n' or '\t' before a newline or tab character, //// then it prints this literal '\n' or '\t'--and all subsequent literal '\n' //// and '\t's--respectively as a newline or tab character. // N.B. I started working on this, worked worked worked, finished--and realized // I had a solution that printed correct output, but which completely failed // the exercise. I then wrote a correct version, but didn't have the heart to // delete what I'd already made. This is that "failure". // Bug: the final newline is very tricky. Depending on the source of the stdin, // the terminal will either add it's own newline automatically or not. For // example, // //// $printf 'hello\\n\ngoodbye' | ./3-2 // or //// $./3-2 <test_only-ws_no-term-nl // // *will not* receive a final newline. However, // //// $echo -e 'hello\\n\ngoodbye' | ./3-2 // or //// $./3-2 <test_only-ws_term-nl // // *will* receive a final newline. This is a function of the system, and I have // no idea how to address it correctly. Ugly workarounds abound, though, and // I include one in this folder. To use, simply pipe output into it, e.g. // //// $./3-2 <test_only-ws_no-term-nl | ./newliner // or //// $./3-2 <test_only-ws_term-nl | ./newliner //////////////////////////////////////////////////////////////////////////////// // Libraries #include <stdio.h> //////////////////////////////////////////////////////////////////////////////// // Symbolic Constants #define DFLT 0 // DeFauLT (i.e. neither converting white space characters to // literal representations, nor vice versa) #define WS2L 1 // White Space TO Literal (i.e. convert white space // characters to literal representations) #define L2WS 2 // Literal TO White Space (i.e. convert literal representations // to white space characters) //////////////////////////////////////////////////////////////////////////////// int main( void ) { int cdbl[ 2 ], cnvstt = DFLT; // DouBLe Character string, CoNVersion STaTe while( ( cdbl[ 1 ] = getchar() ) != EOF ) { /* Reads ahead if the latest input character is a '\' */ if( cdbl[ 1 ] == '\\' ) { cdbl[ 0 ] = cdbl[ 1 ]; if( ( cdbl[ 1 ] = getchar() ) == EOF ) // prevents overflow { putchar( cdbl[ 0 ] ); break; } } /* Determines conversion state: white space to literal or vice versa */ if( cnvstt == DFLT ) { if( cdbl[ 0 ] == '\\' && ( cdbl[ 1 ] == 'n' || cdbl[ 1 ] == 't' ) ) { cnvstt = L2WS; } else if( cdbl[ 1 ] == '\n' || cdbl[ 1 ] == '\t' ) { cnvstt = WS2L; } } /* Prints output */ if( cdbl[ 0 ] == '\\' ) { if( cnvstt == L2WS && cdbl[ 1 ] == 'n' ) { putchar( '\n' ); } else if( cnvstt == L2WS && cdbl[ 1 ] == 't' ) { putchar( '\t' ); } else { printf( "%c%c", cdbl[ 0 ], cdbl[ 1 ] ); } cdbl[ 0 ] -= 1; // makes cdbl[ 0 ] != '\' } else if( cnvstt == WS2L && cdbl[ 1 ] == '\n' ) { printf( "\\n" ); } else if( cnvstt == WS2L && cdbl[ 1 ] == '\t' ) { printf( "\\t" ); } else { putchar( cdbl[ 1 ] ); } } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int Main(int argc, char *argv[]) { int first_iteration; int index; int temp_index; FILE *input_file_ptr; FILE *output_file_ptr; int verbose_level = 1; char *input_file_name_default = "input.txt"; char *input_file_name = 0; char *output_file_name_default = "output.txt"; char *output_file_name = 0; int num_case; int case_id; long t; long tc; long t; long wg; long k; long lg; long ix; long tot; long st; long fac; int valid_flag; for (index = 1; index < argc; index++) { if ((strcmp(argv[index], "-i") == 0) && ((index + 1) < argc)) { input_file_name = argv[++index]; } else if ((strcmp(argv[index], "-o") == 0) && ((index + 1) < argc)) { output_file_name = argv[++index]; } else if (strcmp(argv[index], "-v") == 0) { verbose_level = atoi(argv[++index]); } else { printf("Error parsing arguments!\n"); printf("Usage: template.bin -i <input_file_name> -o <output_file_name>"); printf(" -v <verbose_level>\n"); return 0; } } if (input_file_name == 0) { input_file_name = input_file_name_default; } if (output_file_name == 0) { output_file_name = output_file_name_default; } input_file_ptr = fopen(input_file_name, "r"); if (input_file_ptr == 0) { printf("Error opening input file.\n"); return 0; } output_file_ptr = fopen(output_file_name, "w"); if (input_file_ptr == 0) { printf("Error opening output file.\n"); return 0; } temp_index = fscanf(input_file_ptr, "%d", &num_case); if (verbose_level >= 2) { printf(" Number of test cases: %d\n", num_case); } for (case_id = 1; case_id <= num_case; case_id++) { temp_index = fscanf(input_file_ptr, "%ld %ld %ld", &t, &st, &tot); if (verbose_level >= 3) { printf(" input: %ld %ld %ld", t, st, tot); } valid_flag = 1; if (((st > 0) && (tot == 0)) || ((st < 100) && (tot == 100))) { valid_flag = 0; } fac = 100; if ((st % 2) == 0) { fac /= 2; if ((st % 4) == 0) { fac /= 2; } } if ((st % 5) == 0) { fac /= 5; if ((st % 25) == 0) { fac /= 5; } } if (fac > t) { valid_flag = 0; } if (verbose_level >= 1) { printf(" Case #%d: ", case_id); if (valid_flag == 0) { printf("Broken\n"); } else { printf("Possible\n"); } } if (valid_flag == 0) { fprintf(output_file_ptr, "Case #%d: Broken\n", case_id); } else { fprintf(output_file_ptr, "Case #%d: Possible\n", case_id); } } fclose(input_file_ptr); fclose(output_file_ptr); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <cs50.h> int main() { // instruction on how to play games printf("Welcome to treasure hunt, please enter direction and steps you would like to go and the computer will guide you to the treasure you want.\n"); char d; int x, y, d1; //getting random number x = 1+ rand() % 100; y = 1+ rand() % 100; //starting the loop while (x!=0 || y!=0) { printf("Enter the direction(E,W,N,S) and number: "); scanf("%c %d", &d, &d1); //starting switch to check cases switch (d) { case 'E' : { x =x + d1; if (x == 0 && y >0) printf("Head north \n"); else if(x==0 && y < 0) printf("Head south\n"); else if(y==0 && x > 0) printf("Head west\n"); else if(y==0 && x < 0) printf("Head east\n"); else if (x != 0 && x>0) printf("Head north west\n"); else if (x!=0 && x<0) printf("Head north east\n"); break; } case 'W' : { x = x - d1 ; if (x == 0 && y >0) printf("Head north \n"); else if(x==0 && y < 0) printf("Head south\n"); else if(y==0 && x > 0) printf("Head west\n"); else if(y==0 && x < 0) printf("Head east\n"); else if (x != 0 && x>0) printf("Head north west\n"); else if (x!= 0 && x<0) printf("Head north east\n"); break; } case 'S' : { y = y + d1; if (x == 0 && y >0) printf("Head north \n"); else if(x==0 && y < 0) printf("Head south\n"); else if(y==0 && x > 0) printf("Head west\n"); else if(y==0 && x < 0) printf("Head east\n"); else if (y != 0 && y>0) printf("Head north west\n"); else if(y != 0 && y<0 ) printf("Head south west\n"); break; } case 'N' : { y = y - d1; if (x == 0 && y >0) printf("Head north \n"); else if(x==0 && y < 0) printf("Head south\n"); else if(y==0 && x > 0) printf("Head west\n"); else if(y==0 && x < 0) break; } default: printf("Invalid input\n"); //this code is to clear buffer if you don't understand this don't i also don't while ( getchar() != '\n' ); break; } } //end of loop you won game printf("Treasure found\n"); return 0; }
C
#include <stdio.h> #include <time.h> #include <stdlib.h> void quick_sort(int a[], int l, int r){ if (l >= r) return; //this kinds of intervals are already sorter, no need to consider them int rand_index = rand() % (r - l + 1) + l; //picking random index from our interval int rnd_num = a[rand_index]; //extracting the number from this random index //placing all numbers less or equal than "rnd_num" to the left of the array int numbers_moved = 0; for (int i = l; i <= r; ++i){ if (a[i] <= rnd_num){ int x = a[i]; a[i] = a[l + numbers_moved]; a[l + numbers_moved] = x; numbers_moved++; } } //"rnd_num" should be placed on top of numbers than are less than "rnd_num" for (int i = l; i <= r; ++i){ if (a[i] == rnd_num){ a[i] = a[l + numbers_moved - 1]; a[l + numbers_moved - 1] = rnd_num; break; } } //dividing into two intervals, numbers placed before "rnd_num" quick_sort(a, l, l + numbers_moved - 2); //numbers placed after "rnd_num" quick_sort(a, l + numbers_moved, r); } int main() { srand(time(NULL)); int n; scanf("%d", &n); int a[n]; for (int i = 0; i < n; ++i){ scanf("%d", &a[i]); } quick_sort(a, 0, n - 1); for (int i = 0; i < n; ++i){ printf("%d ", a[i]); } return 0; }
C
#include "stack.h" #define STACK_SIZE 3 // Backing store int StackStore[STACK_SIZE]; // Pointers to stack elements for adding and retrieving int* topPtr; int* bottomPtr; int* currentPtr; // LIFO Stack is Empty if currentPtr == 0; // LIFO Stack is Full if currentPtr == topPtr (points to top element in the Stack); // Initialize internals of the stack void stack_init(void) { topPtr = &StackStore[STACK_SIZE-1]; bottomPtr = &StackStore[0]; currentPtr = 0; for(int i=0; i<STACK_SIZE; i++) { StackStore[i] = '\0'; } } // Add data to stack // If stack is full return error // Otherwise return success int stack_push(int data) { if (stack_isFull() == 1) { // stack is full return -1; } if (currentPtr == 0) { currentPtr = bottomPtr; } else { currentPtr++; } *currentPtr = data; return 0; } // Get data from stack // If stack is empty return error // Otherwise return success int stack_pop(int* data) { if (stack_isEmpty() == 1) { // stack is empty return -1; } *data = *currentPtr; if (currentPtr == bottomPtr) { currentPtr = 0; } else { currentPtr--; } return 0; } // Check if stack is empty // If stack is empty return 1 // Otherwise return 0 int stack_isEmpty() { if (currentPtr == 0) return 1; else return 0; } // Check if stack is full // If stack is full return 1 // Otherwise return 0 int stack_isFull() { if (currentPtr == topPtr) return 1; else return 0; }
C
/* demo-udp-03: udp-send: a simple udp client send udp messages sends a sequence of messages (the # of messages is defined in MSGS) The messages are sent to a port defined in SERVICE_PORT usage: udp-send Paul Krzyzanowski */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <netdb.h> #include <sys/socket.h> //#include "port.h" #define BUFLEN 2048 #define MSGS 10 /* number of messages to send */ //int main(void) // nn , send times int udp_broadcast_send(char *server,int nport,char *buf,int len,int nn) { struct sockaddr_in myaddr, remaddr; int fd, i, slen=sizeof(remaddr); //char *server = "127.255.255.255"; /* change this to use a different server */ //char buf[BUFLEN]; //int nport=9010; int so_broadcast=1; /* create a socket */ if ((fd=socket(AF_INET, SOCK_DGRAM, 0))==-1){ printf("socket created\n"); return -3; } /* bind it to all local addresses and pick any port number */ memset((char *)&myaddr, 0, sizeof(myaddr)); myaddr.sin_family = AF_INET; myaddr.sin_addr.s_addr = htonl(INADDR_ANY); myaddr.sin_port = htons(0); printf(" sender port : %d \n", ntohs(myaddr.sin_port)); if (bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) { perror("bind failed"); close(fd); return -1; } if(-1 == setsockopt(fd,SOL_SOCKET,SO_BROADCAST,&so_broadcast,sizeof so_broadcast)) fprintf(stderr," setsockopt BROADCAST error\n"); /* now define remaddr, the address to whom we want to send messages */ /* For convenience, the host address is expressed as a numeric IP address */ /* that we will convert to a binary format via inet_aton */ memset((char *) &remaddr, 0, sizeof(remaddr)); remaddr.sin_family = AF_INET; remaddr.sin_port = htons(nport); if (inet_aton(server, &remaddr.sin_addr)==0) { fprintf(stderr, "inet_aton() failed\n"); close(fd); return -2; } for(i=0;i<nn;i++){ printf("Sending packet %d to %s port %d\n", i, server, nport); if (sendto(fd, buf, len, 0, (struct sockaddr *)&remaddr, slen)==-1){ printf("sendto error \n"); close(fd); return -4; } if(nn>1) sleep(10); } close(fd); return 0; } int main(int argc,char *argv[]) { char addr[100]; int nport; char buf[2000]; int len; int nn; strcpy(addr,"127.255.255.255"); nport=9010; strcpy(buf," msg udp broadcast send "); len = strlen(buf); nn = 1; printf(" usage: udp_broadcast_send ip_addr port times msg_send \n"); printf(" usage: udp_broadcast_send \n"); printf(" usage: udp_broadcast_send 127.255.255.255 \n"); printf(" usage: udp_broadcast_send 127.255.255.255 9010 \n"); printf(" usage: udp_broadcast_send 127.255.255.255 9010 5 \n"); printf(" usage: udp_broadcast_send 127.255.255.255 9010 5 msg.send.msg.send \n"); switch(argc){ case 5: strcpy(buf,argv[4]); len=strlen(buf); case 4: nn=atoi(argv[3]); case 3: nport=atoi(argv[2]); case 2: strcpy(addr,argv[1]); default: break; } udp_broadcast_send(addr,nport,buf,len,nn); return 0; }
C
#include<stdio.h> #include<math.h> int ispal(long double num) { long double r=0,n=num; printf("%Le ",r); while(n>0) { r*=10; r+=fmod(n,10); n/=10; } if(num==r) return 1; return 0; } int main() { long double a,b,i,fk; int t,c,k=1; scanf("%d",&t); while(t--) { c=0; printf("Case #%d: ",k); scanf("%Lf",&a); scanf("%La",&b); printf("%Lf %Lf",a,b); for(i=a;i<=b;i++) {printf(" Le"); if(ispal(i)) { fk=sqrt(i); if(fk*fk==i) if(ispal(fk)) c++; } } printf("%d",c); if(t>0) printf("\n"); k++; } return 0; }
C
#include <stdio.h> #include <sys/stat.h> #include <string.h> #include <stdlib.h> void print_usage(FILE *stream, char progname[]); int main(int argc, char *argv[]) { long int accessmode; if(argc != 3) { print_usage(stderr, argv[0]); return 1; } /* check for octal numbers */ if(strspn(argv[1], "01234567\n") != strlen(argv[1]) || (strlen(argv[1]) != 3 && strlen(argv[1]) != 4)) { print_usage(stderr, argv[0]); return 1; } /* convert to octal and set the permissions */ accessmode = strtol(argv[1], NULL, 8); if(chmod(argv[2], accessmode) == -1) { perror("Can't change permissions.\n"); } return 0; } void print_usage(FILE *stream, char progname[]) { fprintf(stream, "Usage: %s <numerical permissions> <path>\n", progname); }
C
#include <sys/syscall.h> #include <unistd.h> #define msg_stdout "output to stdout\n" #define msg_stderr "output to stderr\n" int __attribute__((__weak__)) asm_syscall(int nr, ...) { (void)nr; return 0; } int __attribute__((__weak__)) asm_fork(void) { return asm_syscall(__NR_fork); } int __attribute__((__weak__)) asm_write(int fd, const char *buf, size_t count) { return asm_syscall(__NR_write, fd, buf, count); } void __attribute__((__weak__)) asm_exit(int status) { asm_syscall(__NR_exit, status); } void test_asm(void) { } int main(void) { int rc; rc = asm_write(STDOUT_FILENO, msg_stdout, sizeof(msg_stdout)); if (rc < 0) asm_exit(-1); asm_fork(); if (rc < 0) asm_exit(-1); asm_write(STDERR_FILENO, msg_stderr, sizeof(msg_stderr)); if (rc < 0) asm_exit(-1); asm_exit(0); }
C
// main_c.c #include <stdio.h> //直接使用cpp的标识符 extern int _Z3maxii(int,int); int main(void){ //直接使用cpp的标识符 int i = _Z3maxii(11,12); printf("max value:%d", i); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include "listDEC.h" List *list_new() { //creamos la estructura y pedimos memoria para la estructura List *list = (List *)malloc(sizeof(list)); if (list == NULL) return NULL; //seteamos la cabeza y la cola list->head = NULL; list->tail = (Nodo *)malloc(sizeof(Nodo)); ; list->tam = 0; list->posMarker = 0; return list; } //inserta un elemento en la posicion especifica //devuelve un bool si hubo un error o no bool list_append(List *list, void *elemento) { Nodo *nuevo = (Nodo *)malloc(sizeof(Nodo)); if (!nuevo) return false; nuevo->dato = *(size_t *)elemento; if (list->head == NULL) { list->head = nuevo; list->tail = nuevo; list->pos = nuevo; nuevo->next = list->head; nuevo->prev = list->tail; list->tam = 1; list->pos = nuevo; } else { list->tail->next = nuevo; nuevo->next = list->head; nuevo->prev = list->tail; list->tail = nuevo; list->head->prev = list->tail; list->tam += 1; } return true; } //inserta un dato detras del nodo que apunta pos void list_insert(List *list, void *value) { Nodo *nuevo = (Nodo *)malloc(sizeof(Nodo)); if (!nuevo) return false; nuevo->dato = *(size_t *)value; if ((list->posMarker) == 0) { Nodo *head = list->head; list->head = nuevo; head->prev = list->head; list->head->prev = list->tail; list->tail->next = list->head; list->head->next = head; } else { Nodo *tempNodo = list->pos; Nodo *tempNodoPrev = tempNodo->prev; printf("TempNodo: [%d][%d][%d]\n", tempNodo->prev->dato, tempNodo->dato, tempNodo->next->dato); list->pos = nuevo; nuevo->next = tempNodo; tempNodo->prev = nuevo; nuevo->prev = tempNodoPrev; tempNodoPrev->next = nuevo; } list->pos = list->head; printf("Pos: [%d][%d][%d]\n", list->pos->prev->dato, list->pos->dato, list->pos->next->dato); list->tam++; list->posMarker = 0; } //devuelve el valor del elemento segun el indice void *list_get(List *list, size_t indice) { // if (indice < 0 || indice >= list->tam) // return NULL; // Nodo *tmpList; // tmpList = list->head; // for (char i = 0; i < indice; i++) // { // tmpList = tmpList->next; // } // return tmpList->dato; } //devuelve el valor del elemento segun el indice void list_edit_node(List *list, void *value) { list->pos->dato = *(size_t *)value; } //recorre la lista de izquierda a derecha a travez de sus nodos void *list_move_node(List *list, char move) { switch (move) { case 'a': list->posMarker--; if (list->posMarker < 0) list->posMarker = list->tam - 1; list->pos = list->pos->prev; break; case 'd': list->posMarker++; if (list->posMarker >= list->tam) list->posMarker = 0; list->pos = list->pos->next; break; default: break; } } //Recorre e imprime toda la lista void list_run(List *list) { Nodo *nodo; nodo = list->head; printf("["); for (int i = 0; i < (int)list->tam; i++) { printf(" %d, ", (int)nodo->dato); nodo = nodo->next; } printf("]\n"); } //obtiene el tamaño del list size_t list_length(List *list) { return list->tam; } //elimina el nodo que apunta pos void list_remove(List *list) { if ((list->posMarker) == 0) { Nodo *head = list->head; list->head = list->head->next; list->head->prev = list->tail; list->tail->next = list->head; free(head); } else if (list->posMarker == (list->tam - 1)) { Nodo *tail = list->tail; list->tail = list->tail->prev; list->tail->next = list->head; list->head->prev = list->tail; free(tail); } else { Nodo *nextNode = list->pos->next; Nodo *prevNode = list->pos->prev; prevNode->next = nextNode; nextNode->prev = prevNode; free(list->pos); } list->pos = list->head; list->tam--; list->posMarker = 0; } //destruye el list de la memoria void list_destroy(List *list) { Nodo *tmpNode = list->head; Nodo *nextNode = NULL; free(list->head); for (size_t i = 0; i < list->tam - 1; i++) { nextNode = tmpNode->next; free(tmpNode); tmpNode = nextNode; } free(list); }
C
/*! * @file pksav/math/base256.h * @ingroup PKSav * @brief Conversions between Base-10 and Base-256 numbers. * * Copyright (c) 2016 Nicholas Corgan (n.corgan@gmail.com) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #ifndef PKSAV_MATH_BASE256_H #define PKSAV_MATH_BASE256_H #include <pksav/config.h> #include <pksav/error.h> #include <stdint.h> #include <stdlib.h> #ifdef __cplusplus extern "C" { #endif //! Convert a Base-256 number to Base-10. /*! * \param buffer where original Base-256 number is stored * \param num_bytes number of bytes to convert * \param result_out converted Base-10 number * \returns PKSAV_ERROR_NONE upon success * \returns PKSAV_ERROR_NULL_POINTER if buffer or result_out is NULL */ PKSAV_API pksav_error_t pksav_from_base256( const uint8_t* buffer, size_t num_bytes, uint32_t* result_out ); //! Convert a Base-10 number to Base-256. /*! * \param num Base-10 number to convert * \param buffer_out where to store converted Base-256 number * \param buffer_size size of the buffer_out parameter * \returns PKSAV_ERROR_NONE upon success * \returns PKSAV_ERROR_NULL_POINTER if buffer_out is NULL */ PKSAV_API pksav_error_t pksav_to_base256( uint32_t num, uint8_t* buffer_out, size_t buffer_size ); #ifdef __cplusplus } #endif #endif
C
#include <unistd.h> #include <stdio.h> #include <sys/socket.h> #include <sys/types.h> #include <stdlib.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <string.h> #include <inttypes.h> #include <time.h> int main(int argc, char *argv[]) { srand(time(NULL)); // setting the seed of the random number generator //variables struct sockaddr_in src_address, server_address, dest_address; // address struct for the sourc, server and destination sockets int s_socket_fd, d_socket_fd; // file descriptors for the sockets for server and destination . int opt = 1; // options for the socket int s_port, d_port; // for storing source/server and client port numbers int loss_rate; // for storing loss rate int src_addr_len, dest_addr_len; // for storing size of source and destination structure int n; // for number of bytes of received data char buffer[4086] = " "; // buffer to store intermediate incoming streaming data if(argc!=6) // if the correct number of arguments are not found { fprintf(stderr,"\n Please enter the Input arguments in the following order \n"); fprintf(stderr," Source IP, Source Port, Destination IP, Destination Port, Loss rate\n"); return -1; } s_port = atoi(argv[2]); // converting input source port number string to integer d_port = atoi(argv[4]); // converting input destination port number string to integer loss_rate = atoi(argv[5]); // converting input loss rate number string to integer // Creating socket file descriptor if ((s_socket_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket failed"); exit(EXIT_FAILURE); } printf("\n Opened server socket for video stream reception \n"); // Creating socket file descriptor if ((d_socket_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket failed"); exit(EXIT_FAILURE); } printf("\n Opened destination socket for transmission \n"); // Attaching options to the port setsockopt(s_socket_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)); // making both sockets for source and destination as internet sockets server_address.sin_family = AF_INET; dest_address.sin_family = AF_INET; // assigning the port values for both source and destination server_address.sin_port = htons( s_port ); dest_address.sin_port = htons( d_port ); // assigning the IP addresses for both source and destination inet_aton(argv[1], &server_address.sin_addr); inet_aton(argv[3], &dest_address.sin_addr); // Forcefully attaching socket to the source port if (bind(s_socket_fd, (struct sockaddr *)&server_address,sizeof(server_address))<0) { perror("bind failed"); exit(EXIT_FAILURE); } printf("Successfully bound the source socket for receiving from source on port %d\n",s_port); dest_addr_len = sizeof(dest_address); // length of destination structure while (1) { n = recvfrom(s_socket_fd,buffer,4086,0,((struct sockaddr *) &src_address),((socklen_t *) &src_addr_len)); // receiving from source if( ((rand()%100)+1) > loss_rate ) // simple probability for making sure you transmit keeping loss rate sendto(d_socket_fd,buffer,n,0,((struct sockaddr *) &dest_address),(*((socklen_t *) &dest_addr_len))); // send to a destination on a different socket //printf("Sent packet"); } // close the sockets close(d_socket_fd); close(s_socket_fd); return 0; }
C
#include <assert.h> #include <stdlib.h> #include <stdio.h> #include "singly_linked_list.h" int test_create_singly_linked_list() { SinglyLinkedList* list = create_singly_linked_list(); if ( NULL == list ) { return -1; } free( list ); return 0; } int test_get_head_singly_linked_list() { SinglyLinkedListElement* res; int result = 0; SinglyLinkedListElement* e1 = create_singly_linked_list_element( 1 ); SinglyLinkedListElement* e2 = create_singly_linked_list_element( 2 ); SinglyLinkedListElement* e3 = create_singly_linked_list_element( 3 ); SinglyLinkedList* list = create_singly_linked_list(); SinglyLinkedListElement* r1 = append_singly_linked_list( list, e1 ); SinglyLinkedListElement* r2 = append_singly_linked_list( list, e2 ); SinglyLinkedListElement* r3 = append_singly_linked_list( list, e3 ); res = get_head_singly_linked_list( list ); if ( get_data_singly_linked_list_element( e1 ) != get_data_singly_linked_list_element( res ) ) { result = -1; } free( e1 ); free( e2 ); free( e3 ); free( r1 ); free( r2 ); free( r3 ); free( list ); return result; } int test_get_tail_singly_linked_list() { SinglyLinkedListElement* res; int result = 0; SinglyLinkedListElement* e1 = create_singly_linked_list_element( 1 ); SinglyLinkedListElement* e2 = create_singly_linked_list_element( 2 ); SinglyLinkedListElement* e3 = create_singly_linked_list_element( 3 ); SinglyLinkedList* list = create_singly_linked_list(); SinglyLinkedListElement* r1 = append_singly_linked_list( list, e1 ); SinglyLinkedListElement* r2 = append_singly_linked_list( list, e2 ); SinglyLinkedListElement* r3 = append_singly_linked_list( list, e3 ); res = get_tail_singly_linked_list( list ); if ( get_data_singly_linked_list_element( e3 ) != get_data_singly_linked_list_element( res ) ) { result = -1; } free( e1 ); free( e2 ); free( e3 ); free( r1 ); free( r2 ); free( r3 ); free( list ); return result; } int test_get_element_at_singly_linked_list() { SinglyLinkedListElement* res1; SinglyLinkedListElement* res2; SinglyLinkedListElement* res3; int result = 0; SinglyLinkedListElement* e1 = create_singly_linked_list_element( 1 ); SinglyLinkedListElement* e2 = create_singly_linked_list_element( 2 ); SinglyLinkedListElement* e3 = create_singly_linked_list_element( 3 ); SinglyLinkedList* list = create_singly_linked_list(); SinglyLinkedListElement* r1 = append_singly_linked_list( list, e1 ); SinglyLinkedListElement* r2 = append_singly_linked_list( list, e2 ); SinglyLinkedListElement* r3 = append_singly_linked_list( list, e3 ); res1 = get_element_at_singly_linked_list( list, 0 ); if ( get_data_singly_linked_list_element( res1 ) != get_data_singly_linked_list_element( e1 ) ) { result = -1; } res2 = get_element_at_singly_linked_list( list, 1 ); if ( get_data_singly_linked_list_element( res2 ) != get_data_singly_linked_list_element( e2 ) ) { result = -1; } res3 = get_element_at_singly_linked_list( list, 2 ); if ( get_data_singly_linked_list_element( res3 ) != get_data_singly_linked_list_element( e3 ) ) { result = -1; } free( e1 ); free( e2 ); free( e3 ); free( r1 ); free( r2 ); free( r3 ); free( list ); return result; } int test_is_equal_singly_linked_list() { int result = 0; SinglyLinkedListElement* a1 = create_singly_linked_list_element( 1 ); SinglyLinkedListElement* a2 = create_singly_linked_list_element( 2 ); SinglyLinkedListElement* a3 = create_singly_linked_list_element( 3 ); SinglyLinkedListElement* b1 = create_singly_linked_list_element( 1 ); SinglyLinkedListElement* b2 = create_singly_linked_list_element( 2 ); SinglyLinkedListElement* b3 = create_singly_linked_list_element( 3 ); SinglyLinkedList* list1 = create_singly_linked_list(); SinglyLinkedList* list2 = create_singly_linked_list(); SinglyLinkedListElement* ra1 = append_singly_linked_list( list1, a1 ); SinglyLinkedListElement* ra2 = append_singly_linked_list( list1, a2 ); SinglyLinkedListElement* ra3 = append_singly_linked_list( list1, a3 ); SinglyLinkedListElement* rb1 = append_singly_linked_list( list2, b1 ); SinglyLinkedListElement* rb2 = append_singly_linked_list( list2, b2 ); SinglyLinkedListElement* rb3 = append_singly_linked_list( list2, b3 ); if ( is_equal_singly_linked_list( list1, list2 ) == -1 ) { result = -1; } free( a1 ); free( a2 ); free( a3 ); free( b1 ); free( b2 ); free( b3 ); free( ra1 ); free( ra2 ); free( ra3 ); free( rb1 ); free( rb2 ); free( rb3 ); free( list1 ); free( list2 ); return result; } int test_shallow_copy_singly_linked_list() { SinglyLinkedList* list_copy; int result = 0; SinglyLinkedListElement* a1 = create_singly_linked_list_element( 1 ); SinglyLinkedListElement* a2 = create_singly_linked_list_element( 2 ); SinglyLinkedListElement* a3 = create_singly_linked_list_element( 3 ); SinglyLinkedList* list = create_singly_linked_list(); SinglyLinkedListElement* r1 = append_singly_linked_list( list, a1 ); SinglyLinkedListElement* r2 = append_singly_linked_list( list, a2 ); SinglyLinkedListElement* r3 = append_singly_linked_list( list, a3 ); list_copy = shallow_copy_singly_linked_list( list ); if ( is_equal_singly_linked_list( list, list_copy ) == -1 ) { result = -1; } free( a1 ); free( a2 ); free( a3 ); free( r1 ); free( r2 ); free( r3 ); free( list ); free( list_copy ); return result; } int test_prepend_singly_linked_list() { int result = 0; SinglyLinkedListElement* e1 = create_singly_linked_list_element( 1 ); SinglyLinkedListElement* e2 = create_singly_linked_list_element( 2 ); SinglyLinkedListElement* e3 = create_singly_linked_list_element( 3 ); SinglyLinkedList* list = create_singly_linked_list(); SinglyLinkedListElement* r1 = prepend_singly_linked_list( list, e3 ); SinglyLinkedListElement* r2 = prepend_singly_linked_list( list, e2 ); SinglyLinkedListElement* r3 = prepend_singly_linked_list( list, e1 ); if ( get_size_singly_linked_list( list ) != 3 ) { result = -1; } free( e1 ); free( e2 ); free( e3 ); free( r1 ); free( r2 ); free( r3 ); free( list ); return result; } int test_append_singly_linked_list() { int result = 0; SinglyLinkedListElement* e1 = create_singly_linked_list_element( 1 ); SinglyLinkedListElement* e2 = create_singly_linked_list_element( 2 ); SinglyLinkedListElement* e3 = create_singly_linked_list_element( 3 ); SinglyLinkedList* list = create_singly_linked_list(); SinglyLinkedListElement* r1 = append_singly_linked_list( list, e1 ); SinglyLinkedListElement* r2 = append_singly_linked_list( list, e2 ); SinglyLinkedListElement* r3 = append_singly_linked_list( list, e3 ); if ( get_size_singly_linked_list( list ) != 3 ) { result = -1; } free( e1 ); free( e2 ); free( e3 ); free( r1 ); free( r2 ); free( r3 ); free( list ); return result; } /** * Before remove: _____________ _____________ _____________ _____________ _____________ | | | | | | | | | | | | | | | o--->| 21 | |--->| 32 | |--->| 16 | |--->| 12 | |--->| 14 | |---o |______|______| |______|______| |______|______| |______|______| |______|______| After remove: _____________ _____________ _____________ _____________ | | | | | | | | | | | | o--->| 32 | |--->| 16 | |--->| 12 | |--->| 14 | |---o |______|______| |______|______| |______|______| |______|______| */ int test_remove_head_singly_linked_list() { int result = 0; SinglyLinkedListElement* new_head; SinglyLinkedListElement* e1 = create_singly_linked_list_element( 21 ); SinglyLinkedListElement* e2 = create_singly_linked_list_element( 32 ); SinglyLinkedListElement* e3 = create_singly_linked_list_element( 16 ); SinglyLinkedListElement* e4 = create_singly_linked_list_element( 12 ); SinglyLinkedListElement* e5 = create_singly_linked_list_element( 14 ); SinglyLinkedList* list = create_singly_linked_list(); SinglyLinkedListElement* r1 = append_singly_linked_list( list, e1 ); SinglyLinkedListElement* r2 = append_singly_linked_list( list, e2 ); SinglyLinkedListElement* r3 = append_singly_linked_list( list, e3 ); SinglyLinkedListElement* r4 = append_singly_linked_list( list, e4 ); SinglyLinkedListElement* r5 = append_singly_linked_list( list, e5 ); remove_element_singly_linked_list( list, e1 ); new_head = get_head_singly_linked_list( list ); if ( get_data_singly_linked_list_element( new_head ) != get_data_singly_linked_list_element( e2 ) ) { result = -1; } if ( -1 == result ) { free( r1 ); } free( e1); free( e2 ); free( e3 ); free( e4 ); free( e5 ); free( r2 ); free( r3 ); free( r4 ); free( r5 ); free( list ); return result; } /** * Before remove: _____________ _____________ _____________ _____________ _____________ | | | | | | | | | | | | | | | o--->| 21 | |--->| 32 | |--->| 16 | |--->| 12 | |--->| 14 | |---o |______|______| |______|______| |______|______| |______|______| |______|______| After remove: _____________ _____________ _____________ _____________ | | | | | | | | | | | | o--->| 21 | |--->| 32 | |--->| 12 | |--->| 14 | |---o |______|______| |______|______| |______|______| |______|______| */ int test_remove_middle_singly_linked_list() { int result = 0; SinglyLinkedListElement* e1 = create_singly_linked_list_element( 21 ); SinglyLinkedListElement* e2 = create_singly_linked_list_element( 32 ); SinglyLinkedListElement* e3 = create_singly_linked_list_element( 16 ); SinglyLinkedListElement* e4 = create_singly_linked_list_element( 12 ); SinglyLinkedListElement* e5 = create_singly_linked_list_element( 14 ); SinglyLinkedList* list = create_singly_linked_list(); SinglyLinkedListElement* r1 = append_singly_linked_list( list, e1 ); SinglyLinkedListElement* r2 = append_singly_linked_list( list, e2 ); SinglyLinkedListElement* r3 = append_singly_linked_list( list, e3 ); SinglyLinkedListElement* r4 = append_singly_linked_list( list, e4 ); SinglyLinkedListElement* r5 = append_singly_linked_list( list, e5 ); remove_element_singly_linked_list( list, e3 ); if ( get_size_singly_linked_list( list ) != 4 ) { result = -1; } if ( -1 == result ) { free( r3 ); } free( e1 ); free( e2 ); free( e3 ); free( e4 ); free( e5 ); free( r1 ); free( r2 ); free( r4 ); free( r5 ); free( list ); return result; } /** * Before remove: _____________ _____________ _____________ _____________ _____________ | | | | | | | | | | | | | | | o--->| 21 | |--->| 32 | |--->| 16 | |--->| 12 | |--->| 14 | |---o |______|______| |______|______| |______|______| |______|______| |______|______| After remove: _____________ _____________ _____________ _____________ | | | | | | | | | | | | o--->| 21 | |--->| 32 | |--->| 16 | |--->| 12 | |---o |______|______| |______|______| |______|______| |______|______| */ int test_remove_tail_singly_linked_list() { int result = 0; SinglyLinkedListElement* new_tail; SinglyLinkedListElement* e1 = create_singly_linked_list_element( 21 ); SinglyLinkedListElement* e2 = create_singly_linked_list_element( 32 ); SinglyLinkedListElement* e3 = create_singly_linked_list_element( 16 ); SinglyLinkedListElement* e4 = create_singly_linked_list_element( 12 ); SinglyLinkedListElement* e5 = create_singly_linked_list_element( 14 ); SinglyLinkedList* list = create_singly_linked_list(); SinglyLinkedListElement* r1 = append_singly_linked_list( list, e1 ); SinglyLinkedListElement* r2 = append_singly_linked_list( list, e2 ); SinglyLinkedListElement* r3 = append_singly_linked_list( list, e3 ); SinglyLinkedListElement* r4 = append_singly_linked_list( list, e4 ); SinglyLinkedListElement* r5 = append_singly_linked_list( list, e5 ); remove_element_singly_linked_list( list, e5 ); new_tail = get_tail_singly_linked_list( list ); if ( get_data_singly_linked_list_element( new_tail ) != get_data_singly_linked_list_element( e4 ) ) { result = -1; } if ( -1 == result ) { free( r5 ); } free( e1 ); free( e2 ); free( e3 ); free( e4 ); free( e5 ); free( r1 ); free( r2 ); free( r3 ); free( r4 ); free( list ); return result; } /** * Before remove: _____________ _____________ _____________ _____________ _____________ | | | | | | | | | | | | | | | o--->| 21 | |--->| 32 | |--->| 16 | |--->| 12 | |--->| 14 | |---o |______|______| |______|______| |______|______| |______|______| |______|______| After remove: _____________ _____________ _____________ _____________ _____________ | | | | | | | | | | | | | | | o--->| 21 | |--->| 32 | |--->| 16 | |--->| 12 | |--->| 14 | |---o |______|______| |______|______| |______|______| |______|______| |______|______| */ int test_remove_none_singly_linked_list() { int result = 0; SinglyLinkedListElement* e1 = create_singly_linked_list_element( 21 ); SinglyLinkedListElement* e2 = create_singly_linked_list_element( 32 ); SinglyLinkedListElement* e3 = create_singly_linked_list_element( 16 ); SinglyLinkedListElement* e4 = create_singly_linked_list_element( 12 ); SinglyLinkedListElement* e5 = create_singly_linked_list_element( 14 ); SinglyLinkedListElement* e6 = create_singly_linked_list_element( 17 ); SinglyLinkedList* list = create_singly_linked_list(); SinglyLinkedListElement* r1 = append_singly_linked_list( list, e1 ); SinglyLinkedListElement* r2 = append_singly_linked_list( list, e2 ); SinglyLinkedListElement* r3 = append_singly_linked_list( list, e3 ); SinglyLinkedListElement* r4 = append_singly_linked_list( list, e4 ); SinglyLinkedListElement* r5 = append_singly_linked_list( list, e5 ); remove_element_singly_linked_list( list, e6 ); if ( get_size_singly_linked_list( list ) != 5 ) { result = -1; } free( e1 ); free( e2 ); free( e3 ); free( e4 ); free( e5 ); free( e6 ); free( r1 ); free( r2 ); free( r3 ); free( r4 ); free( r5 ); free( list ); return result; } /** * Before remove: o---o After remove: o---o */ int test_remove_from_empty_singly_linked_list() { int result = 0; SinglyLinkedListElement* e1 = create_singly_linked_list_element( 21 ); SinglyLinkedList* list = create_singly_linked_list(); remove_element_singly_linked_list( list, e1 ); if ( get_size_singly_linked_list( list ) != 0 ) { result = -1; } if ( NULL != get_head_singly_linked_list( list ) ) { result = -1; } if ( NULL != get_tail_singly_linked_list( list ) ) { result = -1; } free( e1 ); free( list ); return result; } int test_remove_all_singly_linked_list() { int result = 0; SinglyLinkedListElement* e1 = create_singly_linked_list_element( 1 ); SinglyLinkedListElement* e2 = create_singly_linked_list_element( 2 ); SinglyLinkedListElement* e3 = create_singly_linked_list_element( 3 ); SinglyLinkedListElement* e4 = create_singly_linked_list_element( 4 ); SinglyLinkedListElement* e5 = create_singly_linked_list_element( 5 ); SinglyLinkedList* list = create_singly_linked_list(); append_singly_linked_list( list, e1 ); append_singly_linked_list( list, e2 ); append_singly_linked_list( list, e3 ); append_singly_linked_list( list, e4 ); append_singly_linked_list( list, e5 ); remove_all_singly_linked_list( list ); if ( get_size_singly_linked_list( list ) != 0 ) { result = -1; } if ( NULL != get_head_singly_linked_list( list ) ) { result = -1; } if ( NULL != get_tail_singly_linked_list( list ) ) { result = -1; } free( e1 ); free( e2 ); free( e3 ); free( e4 ); free( e5 ); free( list ); return result; } int main() { assert( test_create_singly_linked_list() == 0 ); assert( test_get_head_singly_linked_list() == 0 ); assert( test_get_tail_singly_linked_list() == 0 ); assert( test_get_element_at_singly_linked_list() == 0 ); assert( test_is_equal_singly_linked_list() == 0 ); assert( test_shallow_copy_singly_linked_list() == 0 ); assert( test_prepend_singly_linked_list() == 0 ); assert( test_append_singly_linked_list() == 0 ); assert( test_remove_head_singly_linked_list() == 0 ); assert( test_remove_middle_singly_linked_list() == 0 ); assert( test_remove_tail_singly_linked_list() == 0 ); assert( test_remove_none_singly_linked_list() == 0 ); assert( test_remove_from_empty_singly_linked_list() == 0 ); assert( test_remove_all_singly_linked_list() == 0 ); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: aagripin <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/11/20 13:33:24 by aagripin #+# #+# */ /* Updated: 2019/12/16 12:19:49 by aagripin ### ########.fr */ /* */ /* ************************************************************************** */ #include "../incl/pws.h" void free_stack(t_stack **stack) { t_stack *ptr; if (!*stack) return ; while (*stack) { ptr = *stack; *stack = (*stack)->next; free(ptr); ptr = NULL; } } t_unit find_top(t_stack **stack) { t_unit tmp; t_stack *ptr; tmp.nbr = 0; tmp.position = 0; if (!*stack) return (tmp); ptr = *stack; tmp.nbr = ptr->nbr; tmp.position = ptr->position; while (ptr) { ptr = ptr->next; if (ptr) if (tmp.nbr < ptr->nbr) { tmp.nbr = ptr->nbr; tmp.position = ptr->position; } } return (tmp); } t_unit find_low(t_stack **stack) { t_unit tmp; t_stack *ptr; ptr = *stack; tmp.nbr = ptr->nbr; tmp.position = ptr->position; while (ptr) { ptr = ptr->next; if (ptr) if (tmp.nbr > ptr->nbr) { tmp.nbr = ptr->nbr; tmp.position = ptr->position; } } return (tmp); } t_unit find_last(t_stack **stack, int pivot) { t_stack *ptr; t_unit tmp; ptr = *stack; tmp.nbr = 0; tmp.position = 0; while (ptr) { if (ptr->nbr <= pivot) { tmp.nbr = ptr->nbr; tmp.position = ptr->position; } ptr = ptr->next; } return (tmp); }
C
#include "errors.h" #include <stdio.h> // Return an error message. static const char *error_message(error err) { switch (err) { case SUCCESS: return "success"; case ERR_PARSE_INT_INVALID: return "can't parse integer (invalid argument)"; case ERR_PARSE_INT_OVERFLOW: return "can't parse integer (outside valid range)"; case ERR_OUT_OF_MEMORY: return "out of memory"; case ERR_REALLOC: return "failed to reallocate memory"; case ERR_OPEN: return "can't open file"; case ERR_CLOSE: return "can't close file"; case ERR_READ: return "can't read from file"; case ERR_EOF: return "reached end of file"; default: return "unknown error"; } } void print_error(error err) { if (err == SUCCESS) { fputs("No error\n", stderr); } fprintf(stderr, "Error: %s\n", error_message(err)); }
C
#include "stm32f10x_it.h" #include "stm32f10x.h" #include "user_msgheap.h" #include "user_uart.h" #include "user_global.h" static int heap_sp = 0; static u8 heap_msg[HEAP_SIZE][MSG_MAX_LENGTH]; static int heap_sp_send = 0; static u8 heap_send_msg[HEAP_SIZE][MSG_MAX_LENGTH]; u8 pushMsg(u8 msg[],u8 len) { int i=0; u8 *ptr = 0; if(len>MSG_MAX_LENGTH || isHeapFull()) { return MSG_HEAP_FALSE; } ptr = heap_msg[heap_sp]; for(i=0;i<len;i++) { *(ptr+i) = msg[i]; } *(ptr+i)='\0'; heap_sp++; return MSG_HEAP_SUCCESS; } u8 popMsg(u8 msg[],u8 len) { int i=0; u8 *ptr = 0; if(isHeapEmpty()) { return MSG_HEAP_FALSE; } heap_sp--; ptr = heap_msg[heap_sp]; for(i=0;i<len;i++) { msg[i] = *(ptr+i) ; } msg[i]='\0'; return MSG_HEAP_SUCCESS; } u8 clearHeap(void) { int i=0; int j=0; for(i=0;i<HEAP_SIZE;i++) { for(j=0;j<MSG_MAX_LENGTH;j++) { heap_msg[i][j] = 0; } } heap_sp = 0; return 0; } u8 isHeapFull(void) { if(heap_sp ==HEAP_SIZE) { return HEAP_ISFULL; } else { return HEAP_NOTFULL; } } u8 isHeapEmpty(void) { if(heap_sp == 0) { return HEAP_ISEMPTY; } else { return HEAP_NOTEMPTY; } } /////////////////////////////////////////////////// u8 isHeapSendMsgFull(void) { if(heap_sp_send ==HEAP_SIZE) { return HEAP_ISFULL; } else { return HEAP_NOTFULL; } } u8 isHeapSendMsgEmpty(void) { if(heap_sp_send == 0) { return HEAP_ISEMPTY; } else { return HEAP_NOTEMPTY; } } u8 pushSendMsg(u8 msg[],u8 len) { int i=0; u8 *ptr = 0; if(len>MSG_MAX_LENGTH || isHeapSendMsgFull()) { return MSG_HEAP_FALSE; } ptr = heap_send_msg[heap_sp_send]; for(i=0;i<len;i++) { *(ptr+i) = msg[i]; } *(ptr+i)='\0'; heap_sp_send++; return MSG_HEAP_SUCCESS; } u8 popSendMsg(u8 msg[]) { int i=0; u8 *ptr = 0; if(isHeapSendMsgEmpty()) { return MSG_HEAP_FALSE; } heap_sp_send--; ptr = heap_send_msg[heap_sp_send]; for(i=0;i<MSG_MAX_LENGTH;i++) { msg[i] = *(ptr+i) ; if(*(ptr+i) == '\0') { break; } } return MSG_HEAP_SUCCESS; }
C
#include "holberton.h" /** * leet - finds a sepsifc letter and replace it by an intger *@s: string *Return: a string */ char *leet(char *s) { int counter, sec = 0; char uppercase[] = {'a', 'e', 'o', 't', 'l'}; char lowercase[] = {'A', 'E', 'O', 'T', 'L'}; int numbers[] = {'4', '3', '0', '7', '1'}; for (counter = 0; s[counter] != '\0'; counter++) { for (sec = 0; numbers[sec] != '\0'; sec++) { if ((s[counter] == lowercase[sec]) || (s[counter] == uppercase[sec])) { s[counter] = numbers[sec]; } } } return (s); }
C
/** * @file lv_txt_ap.c * */ /********************* * INCLUDES *********************/ #include <stddef.h> #include "lv_bidi.h" #include "lv_txt.h" #include "lv_txt_ap.h" #include "lv_mem.h" #include "../draw/lv_draw.h" /********************* * DEFINES *********************/ /********************** * TYPEDEFS **********************/ typedef struct { uint8_t char_offset; uint16_t char_end_form; int8_t char_begining_form_offset; int8_t char_middle_form_offset; int8_t char_isolated_form_offset; struct { uint8_t conj_to_previous; uint8_t conj_to_next; } ap_chars_conjunction; } ap_chars_map_t; /********************** * STATIC PROTOTYPES **********************/ #if LV_USE_ARABIC_PERSIAN_CHARS == 1 static uint32_t lv_ap_get_char_index(uint16_t c); static uint32_t lv_txt_lam_alef(uint32_t ch_curr, uint32_t ch_next); static bool lv_txt_is_arabic_vowel(uint16_t c); /********************** * STATIC VARIABLES **********************/ const ap_chars_map_t ap_chars_map[] = { /*{Key Offset, End, Beginning, Middle, Isolated, {conjunction}}*/ {1, 0xFE84, -1, 0, -1, {1, 0}}, // أ {2, 0xFE86, -1, 0, -1, {1, 0}}, // ؤ {3, 0xFE88, -1, 0, -1, {1, 0}}, // ﺇ {4, 0xFE8A, 1, 2, -1, {1, 0}}, // ئ {5, 0xFE8E, -1, 0, -1, {1, 0}}, // آ {6, 0xFE90, 1, 2, -1, {1, 1}}, // ب {92, 0xFB57, 1, 2, -1, {1, 1}}, // پ {8, 0xFE96, 1, 2, -1, {1, 1}}, // ت {9, 0xFE9A, 1, 2, -1, {1, 1}}, // ث {10, 0xFE9E, 1, 2, -1, {1, 1}}, // ج {100, 0xFB7B, 1, 2, -1, {1, 1}}, // چ {11, 0xFEA2, 1, 2, -1, {1, 1}}, // ح {12, 0xFEA6, 1, 2, -1, {1, 1}}, // خ {13, 0xFEAA, -1, 0, -1, {1, 0}}, // د {14, 0xFEAC, -1, 0, -1, {1, 0}}, // ذ {15, 0xFEAE, -1, 0, -1, {1, 0}}, // ر {16, 0xFEB0, -1, 0, -1, {1, 0}}, // ز {118, 0xFB8B, -1, 0, -1, {1, 0}}, // ژ {17, 0xFEB2, 1, 2, -1, {1, 1}}, // س {18, 0xFEB6, 1, 2, -1, {1, 1}}, // ش {19, 0xFEBA, 1, 2, -1, {1, 1}}, // ص {20, 0xFEBE, 1, 2, -1, {1, 1}}, // ض {21, 0xFEC2, 1, 2, -1, {1, 1}}, // ط {22, 0xFEC6, 1, 2, -1, {1, 1}}, // ظ {23, 0xFECA, 1, 2, -1, {1, 1}}, // ع {24, 0xFECE, 1, 2, -1, {1, 1}}, // غ {30, 0x0640, 0, 0, 0, {1, 1}}, // - (mad, hyphen) {31, 0xFED2, 1, 2, -1, {1, 1}}, // ف {32, 0xFED6, 1, 2, -1, {1, 1}}, // ق {135, 0xFB8F, 1, 2, -1, {1, 1}}, // ک {33, 0xFEDA, 1, 2, -1, {1, 1}}, // ﻙ {141, 0xFB93, 1, 2, -1, {1, 1}}, // گ {34, 0xFEDE, 1, 2, -1, {1, 1}}, // ل {35, 0xFEE2, 1, 2, -1, {1, 1}}, // م {36, 0xFEE6, 1, 2, -1, {1, 1}}, // ن {38, 0xFEEE, -1, 0, -1, {1, 0}}, // و {37, 0xFEEA, 1, 2, -1, {1, 1}}, // ه {39, 0xFEF0, 0, 0, -1, {1, 0}}, // ى {40, 0xFEF2, 1, 2, -1, {1, 1}}, // ي {170, 0xFBFD, 1, 2, -1, {1, 1}}, // ی {7, 0xFE94, 1, 2, -1, {1, 0}}, // ة {206, 0x06F0, 1, 2, -1, {0, 0}}, // ۰ {207, 0x06F1, 0, 0, 0, {0, 0}}, // ۱ {208, 0x06F2, 0, 0, 0, {0, 0}}, // ۲ {209, 0x06F3, 0, 0, 0, {0, 0}}, // ۳ {210, 0x06F4, 0, 0, 0, {0, 0}}, // ۴ {211, 0x06F5, 0, 0, 0, {0, 0}}, // ۵ {212, 0x06F6, 0, 0, 0, {0, 0}}, // ۶ {213, 0x06F7, 0, 0, 0, {0, 0}}, // ۷ {214, 0x06F8, 0, 0, 0, {0, 0}}, // ۸ {215, 0x06F9, 0, 0, 0, {0, 0}}, // ۹ LV_AP_END_CHARS_LIST }; /********************** * MACROS **********************/ /********************** * GLOBAL FUNCTIONS **********************/ uint32_t _lv_txt_ap_calc_bytes_cnt(const char *txt) { uint32_t txt_length = 0; uint32_t chars_cnt = 0; uint32_t current_ap_idx = 0; uint32_t i, j; uint32_t ch_enc; txt_length = _lv_txt_get_encoded_length(txt); i = 0; j = 0; while (i < txt_length) { ch_enc = _lv_txt_encoded_next(txt, &j); current_ap_idx = lv_ap_get_char_index(ch_enc); if (current_ap_idx != LV_UNDEF_ARABIC_PERSIAN_CHARS) { ch_enc = ap_chars_map[current_ap_idx].char_end_form; } if (ch_enc < 0x80) { chars_cnt++; } else if (ch_enc < 0x0800) { chars_cnt += 2; } else if (ch_enc < 0x010000) { chars_cnt += 3; } else { chars_cnt += 4; } i++; } return chars_cnt + 1; } void _lv_txt_ap_proc(const char *txt, char *txt_out) { uint32_t txt_length = 0; uint32_t index_current, idx_next, idx_previous, i, j; uint32_t *ch_enc; uint32_t *ch_fin; char *txt_out_temp; txt_length = _lv_txt_get_encoded_length(txt); ch_enc = (uint32_t *)lv_mem_alloc(sizeof(uint32_t) * (txt_length + 1)); ch_fin = (uint32_t *)lv_mem_alloc(sizeof(uint32_t) * (txt_length + 1)); i = 0; j = 0; while (j < txt_length) { ch_enc[j++] = _lv_txt_encoded_next(txt, &i); } ch_enc[j] = 0; i = 0; j = 0; idx_previous = LV_UNDEF_ARABIC_PERSIAN_CHARS; while (i < txt_length) { index_current = lv_ap_get_char_index(ch_enc[i]); idx_next = lv_ap_get_char_index(ch_enc[i + 1]); if (lv_txt_is_arabic_vowel(ch_enc[i])) { // Current character is a vowel ch_fin[j] = ch_enc[i]; i++; j++; continue; // Skip this character } else if (lv_txt_is_arabic_vowel(ch_enc[i + 1])) { // Next character is a vowel idx_next = lv_ap_get_char_index(ch_enc[i + 2]); // Skip the vowel character to join with the character after it } if (index_current == LV_UNDEF_ARABIC_PERSIAN_CHARS) { ch_fin[j] = ch_enc[i]; j++; i++; idx_previous = LV_UNDEF_ARABIC_PERSIAN_CHARS; continue; } uint8_t conjunction_to_previuse = (i == 0 || idx_previous == LV_UNDEF_ARABIC_PERSIAN_CHARS) ? 0 : ap_chars_map[idx_previous].ap_chars_conjunction.conj_to_next; uint8_t conjunction_to_next = ((i == txt_length - 1) || idx_next == LV_UNDEF_ARABIC_PERSIAN_CHARS) ? 0 : ap_chars_map[idx_next].ap_chars_conjunction.conj_to_previous; uint32_t lam_alef = lv_txt_lam_alef(index_current, idx_next); if (lam_alef) { if (conjunction_to_previuse) { lam_alef ++; } ch_fin[j] = lam_alef; idx_previous = LV_UNDEF_ARABIC_PERSIAN_CHARS; i += 2; j++; continue; } if (conjunction_to_previuse && conjunction_to_next) { ch_fin[j] = ap_chars_map[index_current].char_end_form + ap_chars_map[index_current].char_middle_form_offset; } else if (!conjunction_to_previuse && conjunction_to_next) { ch_fin[j] = ap_chars_map[index_current].char_end_form + ap_chars_map[index_current].char_begining_form_offset; } else if (conjunction_to_previuse && !conjunction_to_next) { ch_fin[j] = ap_chars_map[index_current].char_end_form; } else { ch_fin[j] = ap_chars_map[index_current].char_end_form + ap_chars_map[index_current].char_isolated_form_offset; } idx_previous = index_current; i++; j++; } ch_fin[j] = 0; for (i = 0; i < txt_length; i++) { ch_enc[i] = 0; } for (i = 0; i < j; i++) { ch_enc[i] = ch_fin[i]; } lv_mem_free(ch_fin); txt_out_temp = txt_out; i = 0; while (i < txt_length) { if (ch_enc[i] < 0x80) { *(txt_out_temp++) = ch_enc[i] & 0xFF; } else if (ch_enc[i] < 0x0800) { *(txt_out_temp++) = ((ch_enc[i] >> 6) & 0x1F) | 0xC0; *(txt_out_temp++) = ((ch_enc[i] >> 0) & 0x3F) | 0x80; } else if (ch_enc[i] < 0x010000) { *(txt_out_temp++) = ((ch_enc[i] >> 12) & 0x0F) | 0xE0; *(txt_out_temp++) = ((ch_enc[i] >> 6) & 0x3F) | 0x80; *(txt_out_temp++) = ((ch_enc[i] >> 0) & 0x3F) | 0x80; } else if (ch_enc[i] < 0x110000) { *(txt_out_temp++) = ((ch_enc[i] >> 18) & 0x07) | 0xF0; *(txt_out_temp++) = ((ch_enc[i] >> 12) & 0x3F) | 0x80; *(txt_out_temp++) = ((ch_enc[i] >> 6) & 0x3F) | 0x80; *(txt_out_temp++) = ((ch_enc[i] >> 0) & 0x3F) | 0x80; } i++; } *(txt_out_temp) = '\0'; lv_mem_free(ch_enc); } /********************** * STATIC FUNCTIONS **********************/ static uint32_t lv_ap_get_char_index(uint16_t c) { for (uint8_t i = 0; ap_chars_map[i].char_end_form; i++) { if (c == (ap_chars_map[i].char_offset + LV_AP_ALPHABET_BASE_CODE)) { return i; } else if (c == ap_chars_map[i].char_end_form //is it an End form || c == (ap_chars_map[i].char_end_form + ap_chars_map[i].char_begining_form_offset) //is it a Beginning form || c == (ap_chars_map[i].char_end_form + ap_chars_map[i].char_middle_form_offset) //is it a middle form || c == (ap_chars_map[i].char_end_form + ap_chars_map[i].char_isolated_form_offset)) { //is it an isolated form return i; } } return LV_UNDEF_ARABIC_PERSIAN_CHARS; } static uint32_t lv_txt_lam_alef(uint32_t ch_curr, uint32_t ch_next) { uint32_t ch_code = 0; if (ap_chars_map[ch_curr].char_offset != 34) { return 0; } if (ch_next == LV_UNDEF_ARABIC_PERSIAN_CHARS) { return 0; } ch_code = ap_chars_map[ch_next].char_offset + LV_AP_ALPHABET_BASE_CODE; if (ch_code == 0x0622) { return 0xFEF5; // (lam-alef) mad } if (ch_code == 0x0623) { return 0xFEF7; // (lam-alef) top hamza } if (ch_code == 0x0625) { return 0xFEF9; // (lam-alef) bot hamza } if (ch_code == 0x0627) { return 0xFEFB; // (lam-alef) alef } return 0; } static bool lv_txt_is_arabic_vowel(uint16_t c) { return (c >= 0x064B) && (c <= 0x0652); } #endif
C
#include <unistd.h> #include <stdio.h> #include <stdlib.h> int etages_par_block(int size) { int nombre_ligne_par_etage = size + 3; return nombre_ligne_par_etage; } int nombre_etoiles_derniere_ligne(int size) { int block; int nombre_etoiles_derniere_ligne = 7; int decrementation_par_block = 2; for (block = 2; block <= size; block++) { int incrementation_etoiles = 0; if (block == 2 || block == 3) { nombre_etoiles_derniere_ligne = nombre_etoiles_derniere_ligne - decrementation_par_block; } else if (block != 2 && block != 3 && block % 2 == 0) { decrementation_par_block = decrementation_par_block + 2; nombre_etoiles_derniere_ligne = nombre_etoiles_derniere_ligne - decrementation_par_block; } else { nombre_etoiles_derniere_ligne = nombre_etoiles_derniere_ligne - decrementation_par_block; } for (int ligne = 1; ligne < etages_par_block(block); ligne++) { incrementation_etoiles = incrementation_etoiles + 2; } nombre_etoiles_derniere_ligne = nombre_etoiles_derniere_ligne + incrementation_etoiles; } return nombre_etoiles_derniere_ligne; } int nombre_etoiles_premiere_ligne(int size) { int ligne = etages_par_block(size); int nombre_etoiles_premiere_ligne = nombre_etoiles_derniere_ligne(size); int decrementation = 0; while (ligne > 1) { decrementation = decrementation + 2; ligne--; } nombre_etoiles_premiere_ligne = nombre_etoiles_premiere_ligne - decrementation; return nombre_etoiles_premiere_ligne; } int calcul_espace_vide_premiere_ligne(int size) { int largeur_totale = nombre_etoiles_derniere_ligne(size); int espace_flan = largeur_totale / 2; int nombre_total_etoiles = nombre_etoiles_premiere_ligne(size); int nombre_etoiles_necessaires = nombre_total_etoiles / 2; int espace_vide = espace_flan - nombre_etoiles_necessaires; return espace_vide; } void feuillage(int size) { int block = 1; while (block <= size) { int espace_vide_flan_gauche = nombre_etoiles_derniere_ligne(size) / 2; int nombre_etoiles_ligne1; nombre_etoiles_ligne1 = nombre_etoiles_premiere_ligne(block); int nombre_etoiles_flan_gauche; nombre_etoiles_flan_gauche = nombre_etoiles_ligne1 / 2; int ligne_par_block = etages_par_block(block); for (int ligne = 1; ligne <= ligne_par_block; ligne++) { int i = 0; while (i < espace_vide_flan_gauche - nombre_etoiles_flan_gauche) { write(1, " ", 1); i++; } int j = 0; while (j < nombre_etoiles_ligne1) { write(1, "*", 1); j++; } write(1, "\n", 1); espace_vide_flan_gauche = espace_vide_flan_gauche - 1; nombre_etoiles_ligne1 = nombre_etoiles_ligne1 + 2; } block++; } } void tronc(int size) { int espace_vide_flan_gauche = nombre_etoiles_derniere_ligne(size) / 2; int tronc_flanc_gauche; tronc_flanc_gauche = size / 2; if (size % 2 == 0) { size++; for (int ligne = 1; ligne < size; ligne++) { int i = 0; while (i < espace_vide_flan_gauche - tronc_flanc_gauche) { write(1, " ", 1); i++; } int j = 0; while (j < size) { write(1, "|", 1); j++; } write(1, "\n", 1); } } else { size = size; for (int ligne = 1; ligne <= size; ligne++) { int i = 0; while (i < espace_vide_flan_gauche - tronc_flanc_gauche) { write(1, " ", 1); i++; } int j = 0; while (j < size) { write(1, "|", 1); j++; } write(1, "\n", 1); } } } void tree(int size) { feuillage(size); tronc(size); } int main(int argc, char **argv) { int size = atoi(argv[1]); tree(size); }
C
/* ************************************************************************** */ /* LE - / */ /* / */ /* algo.c .:: .:/ . .:: */ /* +:+:+ +: +: +:+:+ */ /* By: mjalenqu <mjalenqu@student.le-101.fr> +:+ +: +: +:+ */ /* #+# #+ #+ #+# */ /* Created: 2019/06/05 14:41:32 by zseignon #+# ## ## #+# */ /* Updated: 2019/06/06 15:02:58 by mjalenqu ### #+. /#+ ###.fr */ /* / */ /* / */ /* ************************************************************************** */ #include "hotrace.h" void print_keyword(char *keyword, char *value) { if (value != NULL) ft_putendl(value); else { ft_putstr(keyword); ft_putendl(": Not found."); } } void search(char **data, t_ul hash, char *keyword) { int i; int ret; int lenght; i = 0; ret = 0; lenght = ft_strlen(keyword); while (data[i]) { if (hash == ((t_ul **)data)[i][0]) { if (ft_strlen(data[i] + 8) == lenght) { if (data[i][8] == keyword[0] || data[i][9] == keyword[0]) { if (ft_strcmp(data[i] + 8, keyword) == 0) { print_keyword(keyword, data[i] + 9 + ft_strlen(keyword)); return ; } } } } i++; } print_keyword(keyword, NULL); } /* static char *check_key_word(char *data, char *keyword) { int i = 0; while (data[i] == keyword[i] && data[i] != '\0') i += 1; if (data[i] == '\0') return (&data[i + 1]); return (NULL); } void search(char **data, t_ul hash, char *keyword) { int i; char *p; i = 0; while (data[i] != NULL) { if ((((t_ul **)data)[i][0] & ~hash) == 0 && (p = check_key_word(&((char **)data)[i][8], keyword)) != NULL) { print_keyword(keyword, p); break ; } i += 1; } if (p == NULL) print_keyword(keyword, NULL); }*/
C
#include <stdio.h> #include "comments.h" #include "stopif.h" #define NAME_LENGTH 20 void printAuthors(const char *authorName, const char *anonName) { printf("\"%s\" is now \"%s\"\n", authorName, anonName); } char* anonymizeAuthor(binn *anonAuthors, const xmlChar *authorName) { static int authorsCount = 0; char *name = (char*)authorName; char *newName = binn_object_str(anonAuthors, name); if (newName) return newName; newName = malloc(NAME_LENGTH); if (newName == NULL) { printf("Couldn't allocate memory for %s!\n", name); return NULL; } snprintf(newName, NAME_LENGTH,"Author%d", ++authorsCount); binn_object_set_str(anonAuthors, name, newName); binn_object_set_str(anonAuthors, newName, name); printAuthors(name, newName); free(newName); return binn_object_str(anonAuthors, name); } void saveAuthors(binn *anonAuthors) { FILE *fp = fopen(binnFile, "w"); fwrite(binn_ptr(anonAuthors), binn_size(anonAuthors), 1, fp); fclose(fp); } int anonymizeAuthors(const xmlXPathObjectPtr authors) { binn *anonAuthors = binn_object(); for (int i=0; i < authors->nodesetval->nodeNr; i++){ xmlChar *authorName = (xmlChar*)""; authorName = xmlNodeGetContent(authors->nodesetval->nodeTab[i]); char *anonAuthor = anonymizeAuthor(anonAuthors, authorName); if (anonAuthor == NULL) { printf("Couldn't anonymize %s!\n", authorName); return 0; } xmlNodeSetContent(authors->nodesetval->nodeTab[i], (xmlChar*)anonAuthor); xmlFree(authorName); } saveAuthors(anonAuthors); binn_free(anonAuthors); return 1; } char *data; binn *readAuthors() { FILE *fp = fopen(binnFile, "rb"); if (fp == NULL) { printf("Couldn't open bin file (%s)!\n", binnFile); return NULL; } fseek(fp, 0, SEEK_END); long fsize = ftell(fp); fseek(fp, 0, SEEK_SET); data = malloc(fsize + 1); if (data == NULL) { puts("Couldn't allocate memory for data!"); return NULL; } size_t result = fread(data, fsize, 1, fp); if (result != 1) { printf("Couldn't read bin file (%s)!\n", binnFile); return NULL; } fclose(fp); data[fsize] = 0; binn *obj = binn_open(data); return obj; } int deanonymizeAuthors(const xmlXPathObjectPtr authors) { binn *anonAuthors = readAuthors(); if (anonAuthors == NULL) return 0; for (int i=0; i < authors->nodesetval->nodeNr; i++){ xmlChar *anonName = (xmlChar*)""; anonName = xmlNodeGetContent(authors->nodesetval->nodeTab[i]); char *author = binn_object_str(anonAuthors, (char*)anonName); if (author != NULL) { xmlNodeSetContent(authors->nodesetval->nodeTab[i], (xmlChar*)author); printAuthors((char*)anonName, author); } xmlFree(anonName); } free(data); binn_free(anonAuthors); return 1; } int processAuthors(const xmlXPathObjectPtr authors) { if (deanonymize) return deanonymizeAuthors(authors); return anonymizeAuthors(authors); } int anonymizeComments(XMLBuff *infile) { const xmlChar *authorPath = (xmlChar*)"//w:comment/@w:author"; xmlDocPtr doc = xmlReadMemory(infile->data, infile->size, infile->name, NULL, 0); Stopif(!doc, return 0, "Unable to parse file %s!\n", infile->name); xmlXPathContextPtr context = xmlXPathNewContext(doc); Stopif(!context, return 0, "Unable to create new XPath context!\n"); const xmlChar* prefix = (xmlChar*)"w"; const xmlChar* ns = (xmlChar*)"http://schemas.openxmlformats.org/wordprocessingml/2006/main"; Stopif(xmlXPathRegisterNs(context, prefix, ns), return 0, "Can't add namespace!\n"); xmlXPathObjectPtr authors = xmlXPathEvalExpression(authorPath, context); Stopif(!authors, return 0, "Something is wrong with XPATH %s!\n", authorPath); Stopif(!processAuthors(authors), return 0, "Can't process authors!\n"); xmlChar *buf; xmlDocDumpMemoryEnc(doc, &buf, &infile->size, "UTF-8"); infile->data = (char*)buf; Stopif(!infile->size, return 0, "Unable to save file %s!\n", infile->name); xmlXPathFreeObject(authors); xmlXPathFreeContext(context); xmlFreeDoc(doc); xmlCleanupParser(); return 1; }
C
/* * ByteHelpers.h * * Created: 4/3/2013 4:00:36 PM * Author: Jonas */ #ifndef BYTEHELPERS_H_ #define BYTEHELPERS_H_ // most significant and least significant byte helper functions inline char msb (uint16_t twoByteVal) { return (twoByteVal >> 8); } inline char lsb (uint16_t twoByteVal) { return twoByteVal & 0xff; } inline uint16_t combineTwoBytes (char msByte, char lsByte) { return (msByte << 8) + lsByte; } // the following comes from Arduino's Wire library twi.h #ifndef cbi #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit)) #endif #ifndef sbi #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit)) #endif #endif /* BYTEHELPERS_H_ */
C
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<ctype.h> #include<math.h> int main(){ int i = 0,len = 0,j = 0,a = 0; char line[1024]; scanf("%s",line); for(i = 0;i<5;i++) { if(i<4) { printf("%c ",line[i]); }else{ printf("%c\n",line[i]); } } }
C
#ifndef UNORDERED_SET_H #define UNORDERED_SET_H #include <stdlib.h> #include <stdbool.h> #ifdef __cplusplus extern "C" { #endif typedef struct unordered_set_entry { void* key; size_t hash_value; struct unordered_set_entry* chain_next; struct unordered_set_entry* prev; struct unordered_set_entry* next; } unordered_set_entry; typedef struct unordered_set { unordered_set_entry** table; unordered_set_entry* head; unordered_set_entry* tail; size_t (*hash_function) (void*); int (*equals_function) (void*, void*); size_t mod_count; size_t table_capacity; size_t size; size_t mask; size_t max_allowed_size; float load_factor; } unordered_set; typedef struct unordered_set_iterator { unordered_set* set; unordered_set_entry* next_entry; size_t iterated_count; size_t expected_mod_count; } unordered_set_iterator; /*************************************************************************** * Allocates a new, empty set with given hash function and given equality * * testing function. * ***************************************************************************/ unordered_set* unordered_set_alloc(size_t initial_capacity, float load_factor, size_t (*p_hash_function)(void*), int (*p_equals_function)(void*, void*)); /*************************************************************************** * Initializes the given memory area to represent an unordered, hash table * * -based set. * ***************************************************************************/ int unordered_set_init(unordered_set* p_memory, size_t initial_capacity, float load_factor, size_t(*p_hash_function)(void*), int(*p_equals_function)(void*, void*)); /*************************************************************************** * Adds 'p_element' to the set if not already there. Returns true if the * * structure of the set changed. * ***************************************************************************/ int unordered_set_add(unordered_set* p_set, void* p_element); /*************************************************************************** * Returns true if the set contains the element. * ***************************************************************************/ int unordered_set_contains(unordered_set* p_set, void* p_element); /*************************************************************************** * If the element is in the set, removes it and returns true. * ***************************************************************************/ int unordered_set_remove(unordered_set* p_set, void* p_element); /*************************************************************************** * Removes all the contents of the set. * ***************************************************************************/ void unordered_set_clear(unordered_set* p_set); /*************************************************************************** * Returns the size of the set. * ***************************************************************************/ size_t unordered_set_size(unordered_set* p_set); /*************************************************************************** * Checks that the set is in valid state. * ***************************************************************************/ int unordered_set_is_healthy(unordered_set* p_set); /*************************************************************************** * Deallocates the entire set. Only the set and its nodes are deallocated. * * The user is responsible for deallocating the actual data stored in the * * set. * ***************************************************************************/ void unordered_set_free(unordered_set** p_set); /*************************************************************************** * Destroys but does not deallocate the set. * ***************************************************************************/ void unordered_set_destroy(unordered_set* p_set); /*************************************************************************** * Returns the iterator over the set. The nodes are iterated in insertion * * order. * ***************************************************************************/ unordered_set_iterator* unordered_set_iterator_alloc(unordered_set* p_set); /*************************************************************************** * Constructs a set iterator view over the set. * ***************************************************************************/ void unordered_set_iterator_init(unordered_set* p_set, unordered_set_iterator* p_iterator); /*************************************************************************** * Returns the number of elements not yet iterated over. * ***************************************************************************/ size_t unordered_set_iterator_has_next(unordered_set_iterator* p_iterator); /*************************************************************************** * Loads the next element in the iteration order. Returns true if advanced * * to the next element. * ***************************************************************************/ int unordered_set_iterator_next(unordered_set_iterator* p_iterator, void** pp_element); /*************************************************************************** * Returns true if the set was modified during the iteration. * ***************************************************************************/ int unordered_set_iterator_is_disturbed(unordered_set_iterator* p_iterator); /*************************************************************************** * Destructs an iterator over a set view. * ***************************************************************************/ void unordered_set_iterator_destruct(unordered_set_iterator** p_iterator); /*************************************************************************** * Deallocates the set iterator. * ***************************************************************************/ void unordered_set_iterator_free(unordered_set_iterator* p_iterator); /* Contains the unit tests. */ void unordered_set_test(); #ifdef __cplusplus } #endif #endif /* UNORDERED_SET_H */
C
/* * File: led.c * Author: simpspr * * Created on August 27, 2015, 3:15 PM */ #include "led.h" void initLEDs() { //Enables the three LEDs on the PIC32 starter kit as OUTPUTs TRISDbits.TRISD0 = OUTPUT; turnOffLED(1); TRISDbits.TRISD1 = OUTPUT; turnOffLED(2); TRISDbits.TRISD2 = OUTPUT; turnOffLED(3); } void turnOnLED(int led) { if (led == 1) { LED1 = LEDON; } else if (led == 2) { LED2 = LEDON; } else { LED3 = LEDON; } } void turnOffLED(int led) { if (led == 1) { LED1 = LEDOFF; } else if (led == 2) { LED2 = LEDOFF; } else { LED3 = LEDOFF; } }
C
#include <stdio.h> int main()//Main method { char county[ 30 ];//Variable for holding county name char voting_station[ 50 ];//Variable for holding the name of the voting station char over70remark[30]="Success";//Remark if the percentage turnout is over 70% char below70over50remark[30]="More Civic Education";//Remark if the percentage turnout is over 50% but below 70% char below50remark[30]="Investigate";//Remark if the percentage turnout is below 50% int registered_voters;//Variable for holding the number of registered voters int expected_voters;//Variable for holding the number of voters expected to register double percent_registered;// (number of voters expected to register/number of registered voters)*100 FILE *IEBC_Ptr; /* IEBC_Ptr = Data from IEBC II.txt file pointer */ if ( ( IEBC_Ptr = fopen( "IEBC Downloads/Data from IEBC II.txt", "r" ) ) == NULL ) printf( "File could not be opened\n" );//File opening is unsuccessful else { printf( "%-10s%-10s%-10s%-5s%-20s%-10s\n", "County", "Station", "Expected", "Registered", " % Turnout", "Remarks\n_________________________________________________________________________\n" ); fscanf( IEBC_Ptr, "%s%s%d%d%lf", county, voting_station, &expected_voters, &registered_voters, &percent_registered ); while ( !feof( IEBC_Ptr ) ) {//If the end of file character is not encountered if(percent_registered>75){ printf( "%-10s%-13s%-10d%-10d%-10.2f%s\n", county, voting_station, expected_voters, registered_voters, percent_registered, over70remark); fscanf( IEBC_Ptr, "%s%s%d%d%lf", county, voting_station, &expected_voters, &registered_voters, &percent_registered );} if(percent_registered<=75&&percent_registered>50){ printf( "%-10s%-13s%-10d%-10d%-10.2f%s\n", county, voting_station, expected_voters, registered_voters, percent_registered, below70over50remark); fscanf( IEBC_Ptr, "%s%s%d%d%lf", county, voting_station, &expected_voters, &registered_voters, &percent_registered );} if(percent_registered<50){ printf( "%-10s%-13s%-10d%-10d%-10.2f%5s\n", county, voting_station, expected_voters, registered_voters, percent_registered, below50remark ); fscanf( IEBC_Ptr, "%s%s%d%d%lf", county, voting_station, &expected_voters, &registered_voters, &percent_registered );} } fclose( IEBC_Ptr );//Close the file } return 0;//Indication of successful execution of program }
C
#include "libcrypt.h" unsigned char a[1000000]; main() { int i; SHS_CTX context; for (i=0; i<1000000; i++) a[i] = 'a'; i = 0; shsInit(&context); while (i<1000000) { shsUpdate(&context, a, 4); i += 4; } shsFinal(&context); printf("totlen = %d\n", context.totalLength); for (i=0; i<5; i++) printf("%08lx ", context.h[i]); printf("\n\n"); shsInit(&context); shsUpdate(&context, a, 1000000); shsFinal(&context); for (i=0; i<5; i++) printf("%08lx ", context.h[i]); printf("\n\n"); }
C
#include <stdio.h> #include <stdlib.h> #define maxsize 100 typedef int datatype; typedef struct { datatype data[maxsize]; int rear,front; }CSeQueue; CSeQueue* Init(CSeQueue *q) { q = malloc(sizeof(CSeQueue)); q->front = q->rear = 0; printf("ʼɹ"); return q; } // void InQueue(CSeQueue *q, int x) { if(q->front == (q->rear+1) % maxsize) { printf("\n"); } else { q->data[q->rear] = x; q->rear = (q->rear+1) % maxsize; printf("ӳɹ\n"); } } // void OutQueue(CSeQueue *q, datatype *x) { if(q->front == q->rear) { printf("Ϊ\n"); } else { *x = q->data[q->front]; q->front = (q->front+1) % maxsize; } } //ж϶ǷΪ void EmptyQueue(CSeQueue *q) { if(q->front == q->rear) { printf("ջΪ\n"); printf("%d,%d\n",q->rear,q->front); } else { printf("ջΪ\n"); } } //ӡԪ void PrintQueue(CSeQueue *q) { if(q->front == q->rear) { printf("ջΪ\n"); } else{ int len = q->rear - q->front,i; for(i = 0; i < len; i++) { printf("%d ",q->data[i]); } printf("\n"); } } int main () { int d; CSeQueue q; Init(&q); EmptyQueue(&q); InQueue(&q,29); InQueue(&q,5); InQueue(&q,4); PrintQueue(&q); OutQueue(&q,&d); OutQueue(&q,&d); PrintQueue(&q); return 0; }
C
#include "ficheros.h" const char *nombre_archivo; int ninodo; int permisos; int main (int argc, char **argv){ if(argc < 3){ fprintf(stderr, MSG_ERROR("permitir.c") "Sintaxis: permitir <nombre_dispositivo> <ninodo> <permisos>\n"); return(-1); }else{ nombre_archivo = argv[1]; ninodo = atoi(argv[2]); //Usar atoi... los valores de String son diferentes a los enteros. permisos = *((unsigned char*) argv[3]);//atoi(argv[3]); //Usar atoi... los valores de String son diferentes a los enteros. bmount(nombre_archivo); mi_chmod_f(ninodo,permisos); bumount(); } }
C
#include<stdio.h>//STD I/O #include<stdlib.h>//LIB OPERATIONS #include<string.h>//STRING OPERATIONS #include<sys/types.h>//DIFFERENT TYPES OF DATA TYPES #include<sys/socket.h>// #include<arpa/inet.h> //MICRO DEFINE OR FUNCTION DEFINE #include <sys/socket.h>//SYSTEM CALLS #include<netinet/in.h>/* Provides support for 3rd party protocol stack*/ void main(void) {int clifd,n; int bytesReceived=0; struct sockaddr_in clientaddr; char recvBuff[3000]; //socket clifd=socket(AF_INET,SOCK_STREAM,0); //0 indicates optional. AF :- All families if(clifd==-1) perror("\n Socket is not created."); else printf("\n Socket created successfully."); //sockaddr_in clientaddr.sin_family=AF_INET; //sin:- sockaddr_in clientaddr.sin_addr.s_addr=inet_addr("127.0.0.1"); clientaddr.sin_port=htons(3848);//hostbyte order to network byte order conversion // bind if(bind(clifd,(struct sockaddr *)&clientaddr,sizeof(clientaddr))==-1) perror("\n Bind unsuccessful"); else printf("\n Bind successful."); //connect if(connect(clifd,(struct sockaddr *)&clientaddr,sizeof(clientaddr))==-1) //clientaddr must have the values of server. perror("\n Connection failed "); else printf("\n Connection established "); int i=0; printf("\n**WELCOME TO BANKINFO**\n"); printf("\n\t\nTo which of the following Landmarks you are closest:"); printf("\n1:RS Puram\n"); printf("\n2:Gandhipuram\n"); printf("\n3:Peelamedu(Avinashi Road)\n"); printf("\n4:EXIT\n"); printf("\nSelect nearest choice of your current location\n"); printf("\n\n\n\t\t\tBANKINFO---BANKINFO---BANKINFO"); int choice; printf("\n\nEnter your choice::"); scanf("%d",&choice); switch(choice) { case 1: printf("So you are near RS Puram"); break; case 2: printf("So you are near Gandhipuram"); break; case 3: printf("So you are near Peelamedu(Avinashi Road)"); } n=write(clifd,&choice,sizeof(int)); while((bytesReceived = read(clifd, recvBuff, 3000)) > 0) { printf("\nBytes received %d\n",bytesReceived); // recvBuff[n] = 0; // fwrite(recvBuff, 1,bytesReceived,fp); printf("%s \n", recvBuff); } close(clifd); }
C
/* * string.c * * Created on: 09.07.2018 * Author: Dominik */ #include <stdio.h> #include "string2.h" int strcmp(char *s1, char *s2) { for(int i = 0; s1[i] != 0 && s2[i] != 0; i++) { if(s1[i] > s2[i]) { return 1; } if(s1[i] < s2[i]) { return -1; } } return 0; } int strspn(char *s1, char *s2) { int i; for(i = 0; s1[i] != 0 && s2[i] != 0; i++) { if(s1[i] != s2[i]) { return i; } } if(s1[i] == 0) { return i; } return 0; } int strlen(char *s) { int i = 0; while(s[i] != 0) { i++; } return i; } int firstIndexOf(char *s, char c) { for(int i = 0; s[i] != 0; i++) { if(s[i] == c) { return i; } } return -1; } int lastIndexOf(char *s, char c){ int i = -1; for(int j = 0; s[j] != 0; j++) { if(s[j] == c) { i = j; } } return i; } int replace(char *s, char c1, char c2) { for(int i = 0; s[i] != 0; i++) { if(s[i] == c1) { s[i] = c2; } } return 0; } int toUpperCase(char *s) { for(int i = 0; s[i] != 0; i++) { if(s[i] > 96 && s[i] < 123) { s[i] -= 32; } } return 0; } int swap(char **s1, char **s2) { char *themp; themp = *s1; *s1= *s2; *s2 = themp; return 0; }
C
/* *ַеӢַдСдת */ #include <ctype.h> #include <stdio.h> /*---ַеӢַתΪдĸ---*/ void str_toupper(char str[]) { unsigned i = 0; while (str[i]) { str[i] = toupper(str[i]); i++; } } /*---ַеӢַתΪСдĸ---*/ void str_tolower(char str[]) { unsigned i = 0; while (str[i]) { str[i] = tolower(str[i]); i++; } } int main(void) { char str[100]; int cln_buf; printf("ַ"); scanf("%s", str); while((cln_buf = getchar()) != '\n' && cln_buf != EOF) ; str_toupper(str); printf("дĸ%s\n", str); str_tolower(str); printf("Сдĸ%s\n", str); return(0); }
C
/*------------------------------------------------------------------ Name: Ranjan Mishra Roll Number: 1519 Date of Submission: 15th oct 2015 Deadline date: 16th Oct 2015 Program description: 2dimensional tree and range search on it. Acknowledgements: --------------------------------------------------------------------*/ /* Struct to contain a single two dimensional point * it has x and y components */ typedef struct point{ double x; double y; }Point; /* struscture of a node for 2D tree * it has two pointers for its right and left children * and a point struct as defined above */ typedef struct node{ Point p; struct node *left; struct node *right; }Node; /* Desc: This function allocates the memory for given number(n) of points Arguments: It takes number of points to be allocted spaces as input of integer type Return: It returns the pointer to the alloctaed space */ Point* alloacate(int n); /* Desc: This function sorts the points in the given array of points Arguments: It takes the pointer to the array of points, start index and end index of array positions tobe sorted and dimension information based on which sorting is to be done, in this case 0 for X and 1 for Y dimensions. Return: None. */ void sortPoints(Point *points, int start, int end, int dim); /* Desc: This function inserts the given points in the tree Arguments: It takes array of points to be inserted and start and end of the array, and the dimnsion info as above Return: It returns the root of the tree created */ Node* insert(Point *points, int start, int end, int dim); /* Desc: This function searches the points which lie in given rectangular range Argumnets: The tree root node, range of the rectangle as x, x1 and y, y1 and dim info as above Return: None, it prints the points within the range. */ void searchRange(double x, double x1, double y, double y1, Node *root, int dim);
C
/** @file * Interfejs klasy obsługującej tryb interaktywny (interactive mode). * * @author Michał Orzyłowski <mo418334@students.mimuw.edu.pl> */ #ifndef INTERACTIVE_MODE_H #define INTERACTIVE_MODE_H #include "gamma.h" /** @brief Obsługuje interactive mode (tryb interaktywny). * Główna funkcja zarządzająca działaniem w trybie interaktywnym. Wywołuje w * pętli funkcję przeprowadzającą jedną turę gry. Na koniec działania wypisuje * podsumowanie gry i zwalnia pamięć alokowaną na @ref gamma_t. * @param[in,out] g - wskaźnik na strukturę przechowującą stan gry. * @return Wartość 0, jeśli rozgrywka w trybie interaktywnym zakończyła się w * sposób prawidłowy lub 1, gdy nie utworzono rozgrywki ze względu na zbyt dużą * plansze. */ int interactive_mode(gamma_t *g); #endif /* INTERACTIVE_MODE_H */
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* major_minor.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cbretagn <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/08/06 15:48:09 by cbretagn #+# #+# */ /* Updated: 2019/08/16 14:54:19 by cbretagn ### ########.fr */ /* */ /* ************************************************************************** */ #include "../ft_ls.h" t_dstring *push_major(t_dstring *to_print, t_file *file, int padding) { char *temp; int i; to_print = push_str(to_print, " ", 0); if (file->type[0] == 'b' || file->type[0] == 'c') { temp = ft_itoa(major(file->device)); i = padding - ft_strlen(temp); while (--i >= 0) to_print = push_str(to_print, " ", 0); to_print = push_str(to_print, temp, 1); to_print = push_str(to_print, ",", 0); } else { while (--padding >= 0) to_print = push_str(to_print, " ", 0); } return (to_print); } t_dstring *push_minor(t_dstring *to_print, t_file *file, int padding) { char *temp; int i; temp = ft_itoa(minor(file->device)); i = padding - ft_strlen(temp); while (--i > 0) to_print = push_str(to_print, " ", 0); to_print = push_str(to_print, temp, 1); return (to_print); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct hash_buckets_s { char* key; void* value; struct hash_buckets_s* next; } hash_buckets_t; typedef struct hasht_s { hash_buckets_t** buckets; size_t size; } hasht_t; hasht_t* hasht_create(size_t size); void hasht_free(hasht_t* hasht); int hasht_insert(hasht_t* hasht, const char* key, void* value); int hasht_remove(hasht_t* hasht, const char* key); void* hasht_get(hasht_t* hasht, const char* key);
C
#include <stdio.h> int main() { int a, b; printf("Input height:"); scanf("%d", &a); printf("Input width:"); scanf("%d", &b); for(int i=1; i<=a; i++) { for(int j=1; j<=b; j++) //In the lecture you said possibly two nested loops, an extra for loop made it complicated so i used an if else statement { if (i>1 && i<a && j>1 && j<b) { printf(" "); } else { printf("*"); } } puts(""); } return 0; }
C
#ifndef _DISPATCHER_CLASS_H_ #define _DISPATCHER_CLASS_H_ // DEFINITIONS // #if (1) #define BIT(n) (0x01<<(n)) #define IRQ_TM 0 #define IRQ_KB 1 #define IRQ_COM2 3 #define IRQ_COM1 4 #define IRQ_RTC 8 #define IRQ_MS 12 #define SP_ADDR_COM2 0x2F8 #define SP_ADDR_COM1 0x3F8 #endif // LOCAL INCLUDES // #include "InputClass.h" #include "ClockClass.h" #include "GraphicsClass.h" #include "GameLogicClass.h" #include "SerialPortClass.h" typedef struct dispatcher_class DispatcherClass; typedef enum { KB = 1, MS = 2, RTC = 3, SP = 4, TM = 5 } devices_t; /* Default constructor * */ DispatcherClass* newDispatcher(); /* Destructor * * @param Dispatcher A pointer to the "class" */ void deleteDispatcher(DispatcherClass* Dispatcher); /* Initializer * * @param Dispatcher A pointer to the "class" * @param Clock A pointer to the ClockClass * @param Input A pointer to the InputClass * @param Graphics A pointer to the GraphicsClass * * @return False if a error occurs. True otherwise */ bool DispatcherInitialize(DispatcherClass* Dispatcher, ClockClass* Clock, InputClass* Input, GameLogicClass* GameLogic, GraphicsClass* Graphics); /* Shutdown * * @param Dispatcher A pointer to the "class" */ void DispatcherShutdown(DispatcherClass* Dispatcher); bool DispatcherInitializeSerialPort(DispatcherClass* Dispatcher, SerialPortClass* SerialPort); void DispatcherShutdownSerialPort(DispatcherClass* Dispatcher); /* Dispatch a message * * @param Dispatcher A pointer to the "class" */ void DispatcherRun(DispatcherClass* Dispatcher); /* Initialize Clock * * @param Dispatcher A pointer to the "class" * * @return False if a error occurs. True otherwise */ static bool DispatcherInitializeClock(DispatcherClass* Dispatcher, ClockClass* Clock); /* Shutdown Clock * * @param Dispatcher A pointer to the "class" */ static void DispatcherShutdownClock(DispatcherClass* Dispatcher); /* * * @param Dispatcher A pointer to the "class" * * @return False if a error occurs. True otherwise */ static bool DispatcherInitializeInput(DispatcherClass* Dispatcher, InputClass* Input); /* * * @param Dispatcher A pointer to the "class" */ static void DispatcherShutdownInput(DispatcherClass* Dispatcher); /* * @param Dispatcher A pointer to the "class" * * @return False if a error occurs. True otherwise */ static bool DispatcherSubscribeInt(DispatcherClass* Dispatcher, devices_t device, unsigned long flags); /* * * @return False if a error occurs. True otherwise */ static bool DispatcherUnsubscribeInt(DispatcherClass* Dispatcher, devices_t device); /* * * @param Dispatcher A pointer to the "class" * * @return False if a error occurs. True otherwise */ static bool DispatcherHandleInt(DispatcherClass* Dispatcher, devices_t device); /* * * @param Dispatcher A pointer to the "class" */ static int DispatcherGetIRQLine(DispatcherClass* Dispatcher, devices_t device); /* * * @param Dispatcher A pointer to the "class" */ static int DispatcherGetHookID(DispatcherClass* Dispatcher, devices_t device); /* * * @param Dispatcher A pointer to the "class" */ static int DispatcherGetIRQSet(DispatcherClass* Dispatcher, devices_t device); /* * * @param Dispatcher A pointer to the "class" */ static void DispatcherSetHookID(DispatcherClass* Dispatcher, devices_t device, int hookID); /* * @param Dispatcher A pointer to the "class" * * @return True if interrupt subscription is enabled */ static void DispatcherSetIRQSet(DispatcherClass* Dispatcher, devices_t device, bool enable); #endif
C
#include "example_config.h" #if COMPILE_CONNECTOR_TIMEOUT #include "knet.h" /* ͻ - ص */ void connector_cb(channel_ref_t* channel, channel_cb_event_e e) { if (e & channel_cb_event_connect_timeout) { /* ӳɹ */ channel_ref_close(channel); /* ӳʱ˳ѭ */ loop_exit(channel_ref_get_loop(channel)); } else if (e & channel_cb_event_close) { /* ˳ѭ */ printf("connect failed!\n"); loop_exit(channel_ref_get_loop(channel)); } } int main() { /* ѭ */ loop_t* loop = loop_create(); /* ͻ */ channel_ref_t* connector = loop_create_channel(loop, 8, 1024); /* ûص */ channel_ref_set_cb(connector, connector_cb); /* */ if (error_ok != channel_ref_connect(connector, "127.0.0.1", 8000, 2)) { printf("remote unreachable\n"); } else { /* */ loop_run(loop); } /* , connector, acceptorҪֶ */ loop_destroy(loop); return 0; } #endif /* COMPILE_CONNECTOR_TIMEOUT */
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* drawing.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ibaran <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/14 12:42:19 by ibaran #+# #+# */ /* Updated: 2019/03/19 14:17:53 by ibaran ### ########.fr */ /* */ /* ************************************************************************** */ #include <pthread.h> #include "fractol.h" void *f_xloop(void *ptr) { t_fractol *fractol; t_thread *thread; thread = (t_thread*)ptr; fractol = thread->fractol; thread->x = MIN_X; thread->j = 0; while (thread->j < IMAGE_X) { MATRIX[thread->i][thread->j].x = thread->x; MATRIX[thread->i][thread->j].y = thread->y; MATRIX[thread->i][thread->j].iter = thread->function(fractol, thread->i, thread->j); thread->x += STEP_X; thread->j++; } return (NULL); } size_t f_fill_matrix(t_fractol *fractol, int function()) { double y; int i; t_thread thread_y[IMAGE_Y]; i = 0; y = MIN_Y; while (i < IMAGE_Y) { thread_y[i].fractol = fractol; thread_y[i].function = function; thread_y[i].i = i; thread_y[i].y = y; pthread_create(&(thread_y[i].thread_id), NULL, f_xloop, &(thread_y[i])); y += STEP_Y; i++; } i = 0; while (i < IMAGE_Y) { pthread_join(thread_y[i].thread_id, NULL); i++; } return (0); } size_t f_draw(t_fractol *fractol) { if (ft_strcmp(fractol->name, "Mandelbrot") == 0) f_fill_matrix(fractol, &f_mandelbrot); if (ft_strcmp(fractol->name, "Julia") == 0) f_fill_matrix(fractol, &f_julia); if (ft_strcmp(fractol->name, "BurningShip") == 0) f_fill_matrix(fractol, &f_burning_ship); mlx_put_image_to_window(MLX_PTR, WIN_PTR, IMG_PTR, (WINDOW_X - IMAGE_X) / 2, (WINDOW_Y - IMAGE_Y) / 2); return (0); }
C
#include "LCD.h" #include "timing.h" #include "subroutine.h" void init_lcd() { ms_delay(15); //Start up delay cmd(0x38); //Function set (8 bit, 2 line, 5x7) lcdDelay(); cmd(0x06); //Entry mode (Left to right, inc) lcdDelay(); cmd(0x0C); //display (Display on, cursor off) lcdDelay(); cmd(0x06); //Entry mode (Left to right, inc) lcdDelay(); cmd(LCD_CLEAR); //CLEAR screen to remove any garbage ms_delay(2); } //inserts the pre-defined bitmap into the user chosen location void customChar(unsigned char *array, char location) { char i; cmd(0x40+(location*8)); for(i = 0; i < 8; i++) { write_char(array[i]); } cmd(0x80); } void cmd(unsigned char cmd) { //load the command onto the bus (8 bit mode) write_byte = cmd; //command RS = 0; E = 1; lcdDelay(); E = 0; //give extra time for slower commands. if(cmd == LCD_CLEAR || cmd == LCD_HOME || cmd == LCD_LINE_1 || cmd == LCD_LINE_2) ms_delay(2); } void write_char(unsigned char letter) { write_byte = letter; RS = 1; //word E = 1; lcdDelay(); E = 0; } void write_string(unsigned char* string) { unsigned char i; for(i = 0; string[i] != '\0'; i++) { if(string[i] == '\n') { new_line(); } else { write_char(string[i]); } } } void write_int(unsigned char value) { //converts the unsigned char number into ASCII //sends the ASCII array to the LCD write_string(convert(value)); } void new_line() { if(!current_line) { cmd(LCD_LINE_2); } else { cmd(LCD_LINE_1); } current_line = ~current_line; }
C
/* * tclIndexObj.c -- * * This file implements objects of type "index". This object type is used * to lookup a keyword in a table of valid values and cache the index of * the matching entry. Also provides table-based argv/argc processing. * * Copyright (c) 1990-1994 The Regents of the University of California. * Copyright (c) 1997 Sun Microsystems, Inc. * Copyright (c) 2006 Sam Bromley. * * See the file "license.terms" for information on usage and redistribution of * this file, and for a DISCLAIMER OF ALL WARRANTIES. */ #import "Tcl_ParseArgsObjv.h" #include <string.h> /* * Prototypes for functions defined later in this file: */ static void PrintUsage(Tcl_Interp *interp, const Tcl_ArgvInfo *argTable); /* *---------------------------------------------------------------------- * * Tcl_ParseArgsObjv -- * * Process an objv array according to a table of expected command-line * options. See the manual page for more details. * * Results: * The return value is a standard Tcl return value. If an error occurs * then an error message is left in the interp's result. Under normal * conditions, both *objcPtr and *objv are modified to return the * arguments that couldn't be processed here (they didn't match the * option table, or followed an TCL_ARGV_REST argument). * * Side effects: * Variables may be modified, or procedures may be called. It all depends * on the arguments and their entries in argTable. See the user * documentation for details. * *---------------------------------------------------------------------- */ int Tcl_ParseArgsObjv( Tcl_Interp *interp, /* Place to store error message. */ const Tcl_ArgvInfo *argTable, /* Array of option descriptions. */ int *objcPtr, /* Number of arguments in objv. Modified to * hold # args left in objv at end. */ Tcl_Obj *const *objv, /* Array of arguments to be parsed. */ Tcl_Obj ***remObjv) /* Pointer to array of arguments that were not * processed here. Should be NULL if no return * of arguments is desired. */ { Tcl_Obj **leftovers; /* Array to write back to remObjv on * successful exit. Will include the name of * the command. */ int nrem; /* Size of leftovers.*/ register const Tcl_ArgvInfo *infoPtr; /* Pointer to the current entry in the table * of argument descriptions. */ const Tcl_ArgvInfo *matchPtr; /* Descriptor that matches current argument */ Tcl_Obj *curArg; /* Current argument */ const char *str = NULL; register char c; /* Second character of current arg (used for * quick check for matching; use 2nd char. * because first char. will almost always be * '-'). */ int srcIndex; /* Location from which to read next argument * from objv. */ int dstIndex; /* Used to keep track of current arguments * being processed, primarily for error * reporting. */ int objc; /* # arguments in objv still to process. */ int length; /* Number of characters in current argument */ if (remObjv != NULL) { /* * Then we should copy the name of the command (0th argument). The * upper bound on the number of elements is known, and (undocumented, * but historically true) there should be a NULL argument after the * last result. [Bug 3413857] */ nrem = 1; leftovers = ckalloc((1 + *objcPtr) * sizeof(Tcl_Obj *)); leftovers[0] = objv[0]; } else { nrem = 0; leftovers = NULL; } /* * OK, now start processing from the second element (1st argument). */ srcIndex = dstIndex = 1; objc = *objcPtr-1; while (objc > 0) { curArg = objv[srcIndex]; srcIndex++; objc--; str = Tcl_GetStringFromObj(curArg, &length); if (length > 0) { c = str[1]; } else { c = 0; } /* * Loop throught the argument descriptors searching for one with the * matching key string. If found, leave a pointer to it in matchPtr. */ matchPtr = NULL; infoPtr = argTable; for (; infoPtr != NULL && infoPtr->type != TCL_ARGV_END ; infoPtr++) { if (infoPtr->keyStr == NULL) { continue; } if ((infoPtr->keyStr[1] != c) || (strncmp(infoPtr->keyStr, str, length) != 0)) { continue; } if (infoPtr->keyStr[length] == 0) { matchPtr = infoPtr; goto gotMatch; } if (matchPtr != NULL) { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "ambiguous option \"%s\"", str)); goto error; } matchPtr = infoPtr; } if (matchPtr == NULL) { /* * Unrecognized argument. Just copy it down, unless the caller * prefers an error to be registered. */ if (remObjv == NULL) { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "unrecognized argument \"%s\"", str)); goto error; } dstIndex++; /* This argument is now handled */ leftovers[nrem++] = curArg; continue; } /* * Take the appropriate action based on the option type */ gotMatch: infoPtr = matchPtr; switch (infoPtr->type) { case TCL_ARGV_CONSTANT: *((int *) infoPtr->dstPtr) = PTR2INT(infoPtr->srcPtr); break; case TCL_ARGV_INT: if (objc == 0) { goto missingArg; } if (Tcl_GetIntFromObj(interp, objv[srcIndex], (int *) infoPtr->dstPtr) == TCL_ERROR) { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "expected integer argument for \"%s\" but got \"%s\"", infoPtr->keyStr, Tcl_GetString(objv[srcIndex]))); goto error; } srcIndex++; objc--; break; case TCL_ARGV_STRING: if (objc == 0) { goto missingArg; } *((const char **) infoPtr->dstPtr) = Tcl_GetString(objv[srcIndex]); srcIndex++; objc--; break; case TCL_ARGV_REST: /* * Only store the point where we got to if it's not to be written * to NULL, so that TCL_ARGV_AUTO_REST works. */ if (infoPtr->dstPtr != NULL) { *((int *) infoPtr->dstPtr) = dstIndex; } goto argsDone; case TCL_ARGV_FLOAT: if (objc == 0) { goto missingArg; } if (Tcl_GetDoubleFromObj(interp, objv[srcIndex], (double *) infoPtr->dstPtr) == TCL_ERROR) { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "expected floating-point argument for \"%s\" but got \"%s\"", infoPtr->keyStr, Tcl_GetString(objv[srcIndex]))); goto error; } srcIndex++; objc--; break; case TCL_ARGV_FUNC: { Tcl_ArgvFuncProc *handlerProc = (Tcl_ArgvFuncProc *) infoPtr->srcPtr; Tcl_Obj *argObj; if (objc == 0) { argObj = NULL; } else { argObj = objv[srcIndex]; } if (handlerProc(infoPtr->clientData, argObj, infoPtr->dstPtr)) { srcIndex++; objc--; } break; } case TCL_ARGV_GENFUNC: { Tcl_ArgvGenFuncProc *handlerProc = (Tcl_ArgvGenFuncProc *) infoPtr->srcPtr; objc = handlerProc(infoPtr->clientData, interp, objc, &objv[srcIndex], infoPtr->dstPtr); if (objc < 0) { goto error; } break; } case TCL_ARGV_HELP: PrintUsage(interp, argTable); goto error; default: Tcl_SetObjResult(interp, Tcl_ObjPrintf( "bad argument type %d in Tcl_ArgvInfo", infoPtr->type)); goto error; } } /* * If we broke out of the loop because of an OPT_REST argument, copy the * remaining arguments down. Note that there is always at least one * argument left over - the command name - so we always have a result if * our caller is willing to receive it. [Bug 3413857] */ argsDone: if (remObjv == NULL) { /* * Nothing to do. */ return TCL_OK; } if (objc > 0) { memcpy(leftovers+nrem, objv+srcIndex, objc*sizeof(Tcl_Obj *)); nrem += objc; } leftovers[nrem] = NULL; *objcPtr = nrem++; *remObjv = ckrealloc(leftovers, nrem * sizeof(Tcl_Obj *)); return TCL_OK; /* * Make sure to handle freeing any temporary space we've allocated on the * way to an error. */ missingArg: Tcl_SetObjResult(interp, Tcl_ObjPrintf( "\"%s\" option requires an additional argument", str)); error: if (leftovers != NULL) { ckfree(leftovers); } return TCL_ERROR; } /* *---------------------------------------------------------------------- * * PrintUsage -- * * Generate a help string describing command-line options. * * Results: * The interp's result will be modified to hold a help string describing * all the options in argTable. * * Side effects: * None. * *---------------------------------------------------------------------- */ static void PrintUsage( Tcl_Interp *interp, /* Place information in this interp's result * area. */ const Tcl_ArgvInfo *argTable) /* Array of command-specific argument * descriptions. */ { register const Tcl_ArgvInfo *infoPtr; int width, numSpaces; #define NUM_SPACES 20 static const char spaces[] = " "; char tmp[TCL_DOUBLE_SPACE]; Tcl_Obj *msg; /* * First, compute the width of the widest option key, so that we can make * everything line up. */ width = 4; for (infoPtr = argTable; infoPtr->type != TCL_ARGV_END; infoPtr++) { int length; if (infoPtr->keyStr == NULL) { continue; } length = strlen(infoPtr->keyStr); if (length > width) { width = length; } } /* * Now add the option information, with pretty-printing. */ msg = Tcl_NewStringObj("Command-specific options:", -1); for (infoPtr = argTable; infoPtr->type != TCL_ARGV_END; infoPtr++) { if ((infoPtr->type == TCL_ARGV_HELP) && (infoPtr->keyStr == NULL)) { Tcl_AppendPrintfToObj(msg, "\n%s", infoPtr->helpStr); continue; } Tcl_AppendPrintfToObj(msg, "\n %s:", infoPtr->keyStr); numSpaces = width + 1 - strlen(infoPtr->keyStr); while (numSpaces > 0) { if (numSpaces >= NUM_SPACES) { Tcl_AppendToObj(msg, spaces, NUM_SPACES); } else { Tcl_AppendToObj(msg, spaces, numSpaces); } numSpaces -= NUM_SPACES; } Tcl_AppendToObj(msg, infoPtr->helpStr, -1); switch (infoPtr->type) { case TCL_ARGV_INT: Tcl_AppendPrintfToObj(msg, "\n\t\tDefault value: %d", *((int *) infoPtr->dstPtr)); break; case TCL_ARGV_FLOAT: Tcl_AppendPrintfToObj(msg, "\n\t\tDefault value: %g", *((double *) infoPtr->dstPtr)); sprintf(tmp, "%g", *((double *) infoPtr->dstPtr)); break; case TCL_ARGV_STRING: { char *string = *((char **) infoPtr->dstPtr); if (string != NULL) { Tcl_AppendPrintfToObj(msg, "\n\t\tDefault value: \"%s\"", string); } break; } default: break; } } Tcl_SetObjResult(interp, msg); } /* * Local Variables: * mode: c * c-basic-offset: 4 * fill-column: 78 * End: */
C
// // Created by 苏汉宇 on 17/6/27. // #include "hashTable.h" #include <stdlib.h> #include <string.h> static int hashcode(const char *s) { int len = strlen(s); const unsigned char *name = (const unsigned char *)s; unsigned long h = 0, g; int i; for(i=0;i<len;i++) { h = (h << 4) + (unsigned long)(name[i]); //hash左移4位,当前字符ASCII存入hash if ((g = (h & 0xF0000000UL))!=0) h ^= (g >> 24); h &= ~g; //清空28-31位。 } h = (int)h % HASHTABLE_SIZE; return h; } // 创建hashTable HashTable* create_hash_table() { HashTable* hashTable = (HashTable*)malloc(sizeof(HashTable)); // 初始化新申请的内存空间 memset(hashTable, 0, sizeof(HashTable)); if(IS_NULL(hashTable))return NULL; return hashTable; } // 根据键 获取值 HashNode* hash_find(HashTable* ht, char* key) { if(IS_NULL(ht))return NULL; HashNode* pNode; // 根据键 用函数运算出索引值 int code = hashcode(key); // printf("%s-->%d\n", key, code); pNode = ht->Node[code % HASHTABLE_SIZE]; if(IS_NULL(pNode))return NULL; while (pNode) { if (*(pNode->key) == *key) { return pNode; } pNode = pNode->next; } return NULL; } // 向hashTable中加数据 int hash_put(HashTable* ht, char* key, int data) { HashNode* pNode; size_t code = hashcode(key); // printf("the code is %d\n", code); if(IS_NULL(ht))return FAILED; if(IS_NULL(ht->Node[ code ])){ pNode = (HashNode*)malloc(sizeof(HashNode)); pNode->value = data; pNode->key = key; ht->Node[ code ] = pNode; return SUCCESS; } // 是否已经存在这个值了 if(!IS_NULL(hash_find(ht, key))){ return FAILED; } // 这里说明已经碰撞了,往对应的链表中放了 pNode = ht->Node[ code ]; while(!IS_NULL(pNode->next)){ pNode = pNode->next; } pNode->next = (HashNode*)malloc(sizeof(HashNode)); pNode->next->value = data; return SUCCESS; } // 打印HashTable void print_hashTable(HashTable* ht) { if( !IS_NULL(ht) ){ for (int i = 0; i < HASHTABLE_SIZE; ++i) { printf("%d\n", ht->Node[i]->value); } } }
C
#include<stdio.h> int main(){ int a[100],l, n,i,j,k,max,nextmax,temp; printf("\n Enter n: "); scanf("%d",&n); l = 2*n-1; printf("\n Enter %d numbers: ",n); for(i=n;i<(2*n);i++) scanf("%d",&a[i]); i=l; while(i>1){ if(a[i]>a[i-1]){ a[i/2] = a[i]; } else { a[i/2] = a[i-1]; } i=i-2; } for(i=1; i<2*n;i++) printf("%d ",a[i]); printf("\nMax = %d",a[1]); if(a[2]>a[3]) { i = 2; nextmax = a[3]; } else { i=3; nextmax = a[2]; } do{ printf("\ni=%d,nextmax=%d",i,nextmax); if(a[2*i]>a[2*i+1]){ if(a[2*i+1]>nextmax) nextmax = a[2*i+1]; i = 2*i; } else { if(a[2*i]>nextmax) nextmax = a[2*i]; i = 2*i+1; } printf("\ni=%d,nextmax=%d",i,nextmax); }while(2*i<l); printf("\n Next max: %d",nextmax); }
C
/**************************************************************************** * A SIMPLE MATCHING ALGO WITH SUPPORT FOR INDELS * * Author: H. Pag\`es * ****************************************************************************/ #include "Biostrings.h" static void test_match_pattern_indels(const char *p, const char *s, int max_nmis, const char *expected_matches) { Chars_holder P, S; Rprintf("P=%s S=%s max_nmis=%d expected_matches=%s\n", p, s, max_nmis, expected_matches); P.ptr = p; P.length = strlen(P.ptr); S.ptr = s; S.length = strlen(S.ptr); _match_pattern_indels(&P, &S, max_nmis, 1, 1); return; } /* * In order to avoid pollution by redundant matches, we report only the "best * local matches". A substring S' of S is a best local match iff: * (a) nedit(P, S') <= max_nmis * (b) for every substring S1 of S', nedit(P, S1) > nedit(P, S') * (c) for every substring S2 of S that contains S', nedit(P, S2) >= nedit(P, S') * One nice property of best local matches is that their first and last letters * are guaranteed to match letters in P. * The report_provisory_match() function will store a provisory match and will * hold it until it is replaced by a better one or until it's guaranteed to be * a best local match (then it's reported as a match). */ static int provisory_match_start, provisory_match_end, provisory_match_width, provisory_match_nedit; static void report_provisory_match(int start, int width, int nedit) { int end; end = start + width - 1; if (provisory_match_nedit != -1) { // Given how we walk on S, 'start' is always guaranteed to be > // 'provisory_match_start'. if (end > provisory_match_end) _report_match(provisory_match_start, provisory_match_width); else if (nedit > provisory_match_nedit) return; } provisory_match_start = start; provisory_match_end = end; provisory_match_width = width; provisory_match_nedit = nedit; return; } static ByteTrTable byte2offset; void _match_pattern_indels(const Chars_holder *P, const Chars_holder *S, int max_nmis, int fixedP, int fixedS) { int i0, j0, max_nmis1, nedit1, width1; char c0; const BytewiseOpTable *bytewise_match_table; Chars_holder P1; if (P->length <= 0) error("empty pattern"); bytewise_match_table = _select_bytewise_match_table(fixedP, fixedS); _init_byte2offset_with_Chars_holder(&byte2offset, P, bytewise_match_table); provisory_match_nedit = -1; // means no provisory match yet j0 = 0; while (j0 < S->length) { while (1) { c0 = S->ptr[j0]; i0 = byte2offset.byte2code[(unsigned char) c0]; if (i0 != NA_INTEGER) break; j0++; if (j0 >= S->length) goto done; } P1.ptr = P->ptr + i0 + 1; P1.length = P->length - i0 - 1; max_nmis1 = max_nmis - i0; if (max_nmis1 >= 0) { if (max_nmis1 == 0) { nedit1 = _nmismatch_at_Pshift(&P1, S, j0 + 1, max_nmis1, bytewise_match_table); width1 = P1.length; } else { nedit1 = _nedit_for_Ploffset(&P1, S, j0 + 1, max_nmis1, 1, &width1, bytewise_match_table); } if (nedit1 <= max_nmis1) { report_provisory_match(j0 + 1, width1 + 1, nedit1 + i0); } } j0++; } done: if (provisory_match_nedit != -1) _report_match(provisory_match_start, provisory_match_width); return; }
C
#include "acc.h" #define NLOOP 1000 int counter; /* this is incremented by the threads */ void *doit(void *); int main(int argc, char **argv) { pthread_t tidA, tidB, tidC; pthread_create(&tidA, NULL, &doit, NULL); pthread_create(&tidB, NULL, &doit, NULL); pthread_create(&tidC, NULL, &doit, NULL); /* 4wait for both threads to terminate */ pthread_join(tidA, NULL); pthread_join(tidB, NULL); pthread_join(tidC, NULL); exit(0); } void * doit(void *vptr) { int i, val, j; /* * Each thread fetches, prints, and increments the counter NLOOP times. * The value of the counter should increase monotonically. */ for (i = 0; i < NLOOP; i++) { val = counter; printf("TID-%d: %d, loop-%d\n", pthread_self(), val + 1,i); counter = val + 1; /* do nothing. Hope we have a thread switching */ for(j = 0; j < 50000; j++){ } } return(NULL); }
C
// 总体思路:依次判断每个身份证号,若有郊,将索引值赋予acceess数组,index为代表无效身份证的个数 #include <stdio.h> int main() { int n; scanf("%d", &n); int access[100], index=0; char numble[100][19]; char M[12] = "10X98765432"; int X[17] = {7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2}; for(int i=0; i<n; i++) scanf("%s", numble[i]); int sum; //加权求和 char z; //z值 for(int i=0; i<n; i++) { sum = 0; int j; for (j=0; j<17; j++) { if (numble[i][j] < '0' || numble[i][j] > '9') break; sum += (numble[i][j] - '0') * X[j]; } z = M[sum%11]; if ( j<17 || numble[i][17] != z ) access[index ++] = i; } if (index == 0) { printf("All passed"); } else { for(int i=0; i<index; i++) printf("%s\n", numble[access[i]]); } return 0; }
C
// // main.c // aufgabe_5 // // Created by Niklas Stöhr on 02/11/17. // Copyright © 2017 Niklas Stoehr. All rights reserved. // // // code mainly taken from http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html /* ** server.c -- a stream socket server demo */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <sys/wait.h> #include <signal.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> #include <math.h> #define BACKLOG 10 // how many pending connections queue will hold // arguments are: PORT und TEXTDATEI (inklusive Pfad und .txt) //_____________________________________________________________ const char * sentenceFinder ( char *filename ){ //count number of rows int numRows = 0; int i = 0; // sentences from Textfile char* sentences[100]; // open file FILE *file = fopen ( filename, "r" ); if ( file != NULL ) { char line [ 10000 ]; /* or other suitable maximum line size */ while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */ { //fputs ( line, stdout ); /* write the line */ //add each rows into array of sentences sentences[i]=strdup(line); i++; numRows++; } fclose ( file ); } else { perror ( filename ); /* why didn't the file open? */ exit(-1); } printf("\n"); //check to be sure going into array correctly for (int j=0 ; j<numRows; j++) { printf("%s", sentences[j]); } printf("\n"); srand ( time(NULL) ); int random = rand() % numRows; char *selectedSentence = sentences[random]; return selectedSentence; } //_____________________________________________________________ void sigchld_handler(int s) { // waitpid() might overwrite errno, so we save and restore it: int saved_errno = errno; while(waitpid(-1, NULL, WNOHANG) > 0); errno = saved_errno; } // get sockaddr, IPv4 or IPv6: void *get_in_addr(struct sockaddr *sa) { if (sa->sa_family == AF_INET) { return &(((struct sockaddr_in*)sa)->sin_addr); } return &(((struct sockaddr_in6*)sa)->sin6_addr); } //_____________________________________________________________ // Main int main(int argc, char *argv[]) { int sockfd, new_fd; // listen on sock_fd, new connection on new_fd struct addrinfo hints, *servinfo, *p; struct sockaddr_storage their_addr; // connector's address information socklen_t sin_size; struct sigaction sa; int yes=1; char s[INET6_ADDRSTRLEN]; int rv; // Korrekte Anzahl der Konsolenargumente: 2 if (argc != 3) { fprintf(stderr,"Bitte 2 Konsolenargumente übergeben\n"); exit(1); } // read argument Filename char *readIn = argv[2]; char * filename = (char *) malloc(1000); strcat(filename, readIn); printf("Pfad und Name der Datei: %s \n", filename); memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // use my IP if ((rv = getaddrinfo(NULL, argv[1], &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // loop through all the results and bind to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("server: socket"); continue; } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("server: bind"); continue; } break; } freeaddrinfo(servinfo); // all done with this structure if (p == NULL) { fprintf(stderr, "server: failed to bind\n"); exit(1); } if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } sa.sa_handler = sigchld_handler; // reap all dead processes sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; if (sigaction(SIGCHLD, &sa, NULL) == -1) { perror("sigaction"); exit(1); } printf("server: waiting for connections...\n"); while(1) { // main accept() loop sin_size = sizeof their_addr; new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size); if (new_fd == -1) { perror("accept"); continue; } inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof s); printf("server: got connection from %s\n", s); if (!fork()) { // this is the child process close(sockfd); // child doesn't need the listener // Retrieving Quote const char *quote = sentenceFinder(filename); printf("\n Neuer ausgewählter Spruch ist: %s \n", quote); if (send(new_fd, quote, strlen(quote)+1, 0) == -1) perror("send"); close(new_fd); exit(0); } close(new_fd); // parent doesn't need this } return 0; }
C
#include <stdio.h> #include <math.h> int x[13]; float data[13][3]; const float PI = 3.14159f; void temp(); void deg(); float trigonometri(); float radian(); main() { printf("\n =|------------------------|=\n"); printf(" ==| Azis Jabbar Susetio |==\n"); printf(" ===| 4210141021 |===\n"); printf(" ==| 1 - D4 Game Technology |==\n"); printf(" =|------------------------|=\n"); temp(); deg(); } void temp() { int i,j; j=0; for(i=0;i<=360;i+=30) { x[j]=i; j++; } } void deg() { int i; for(i=0;i<13;i++) { printf("%4i ",x[i]); trigonometri(x[i]); printf("\n"); } } float trigonometri(int d){ printf("%4.1f",sin(radian(d))); printf("%7.1f",cos(radian(d))); printf("%10.1f",tan(radian(d))); } float radian(int d){ return d / 180.0 * PI; }
C
#include "buzzmsg.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <math.h> /****************************************/ /****************************************/ static int32_t MAX_MANTISSA = 2147483646; // 2 << 31 - 2; /****************************************/ /****************************************/ void buzzmsg_serialize_u8(buzzdarray_t buf, uint8_t data) { buzzdarray_push(buf, &data); } /****************************************/ /****************************************/ int64_t buzzmsg_deserialize_u8(uint8_t* data, buzzdarray_t buf, uint32_t pos) { if(pos + sizeof(uint8_t) > buzzdarray_size(buf)) return -1; *data = buzzdarray_get(buf, pos, uint8_t); return pos + sizeof(uint8_t); } /****************************************/ /****************************************/ void buzzmsg_serialize_u16(buzzdarray_t buf, uint16_t data) { uint16_t x = htons(data); buzzdarray_push(buf, (uint8_t*)(&x)); buzzdarray_push(buf, (uint8_t*)(&x)+1); } /****************************************/ /****************************************/ int64_t buzzmsg_deserialize_u16(uint16_t* data, buzzdarray_t buf, uint32_t pos) { if(pos + sizeof(uint16_t) > buzzdarray_size(buf)) return -1; *data = buzzdarray_get(buf, pos, uint8_t) + (buzzdarray_get(buf, pos+1, uint8_t) << 8); *data = ntohs(*data); return pos + sizeof(uint16_t); } /****************************************/ /****************************************/ void buzzmsg_serialize_u32(buzzdarray_t buf, uint32_t data) { uint32_t x = htonl(data); buzzdarray_push(buf, (uint8_t*)(&x)); buzzdarray_push(buf, (uint8_t*)(&x)+1); buzzdarray_push(buf, (uint8_t*)(&x)+2); buzzdarray_push(buf, (uint8_t*)(&x)+3); } /****************************************/ /****************************************/ int64_t buzzmsg_deserialize_u32(uint32_t* data, buzzdarray_t buf, uint32_t pos) { if(pos + sizeof(uint32_t) > buzzdarray_size(buf)) return -1; *data = buzzdarray_get(buf, pos, uint8_t) + (buzzdarray_get(buf, pos+1, uint8_t) << 8) + (buzzdarray_get(buf, pos+2, uint8_t) << 16) + (buzzdarray_get(buf, pos+3, uint8_t) << 24); *data = ntohl(*data); return pos + sizeof(uint32_t); } /****************************************/ /****************************************/ void buzzmsg_serialize_float(buzzdarray_t buf, float data) { /* The mantissa */ int32_t mant; /* The exponent */ int32_t exp; /* * Split the data into a normalized fraction (nf) and an integral power of 2 * when data == 0, nf = 0 and exp = 0 * otherwise data = nf * 2^exp and nf is in +-[0.5,1) */ float nf = frexpf(data, &exp); /* Take the magnitude of nf and translate it by -0.5 */ nf = fabsf(nf) - 0.5f; /* Now we can safely test for zero */ if(nf < 0.0f) { /* The mantissa is zero */ mant = 0; } else { /* Let's calculate the mantissa * * Idea: * nf now is in [0,0.5), we want to map it to the entire range of uint32_t * * 1. multiply nf by 2 so it's in [0,1) * 2. multiply the result by the maximum value for the mantissa * 3. problem: 0 maps to 0 and it would indistinguishable from nf == 0 above * solution: simply sum 1 to the mantissa */ mant = (int32_t)(nf * 2.0f * MAX_MANTISSA) + 1; /* Now take care of the sign */ if(data < 0.0f) mant = -mant; } /* Serialize the data */ buzzmsg_serialize_u32(buf, mant); buzzmsg_serialize_u32(buf, exp); } /****************************************/ /****************************************/ int64_t buzzmsg_deserialize_float(float* data, buzzdarray_t buf, uint32_t pos) { /* Make sure enough bytes are left to read */ if(pos + 2*sizeof(uint32_t) > buzzdarray_size(buf)) return -1; /* Read the mantissa and the exponent */ int32_t mant; int32_t exp; pos = buzzmsg_deserialize_u32((uint32_t*)(&mant), buf, pos); pos = buzzmsg_deserialize_u32((uint32_t*)(&exp), buf, pos); /* A zero mantissa corresponds to a zero float */ if(mant == 0) { *data = 0; } else { /* We must calculate the float * * Idea: use the function ldexpf(), which is the opposite of frexpf() * For this, we need to transform the mantissa into a normalized * fraction in the range [0.5,1) * * 1. Take the absolute value of the mantissa, which is in [1, MAX_MANTISSA+1] * 2. Subtract 1, so it's in [0, MAX_MANTISSA] * 3. divide by MAX_MANTISSA, so it's in [0,1) * 4. divide by 2, so it's in [0,0.5) * 5. Add 0.5, so it's in [0.5,1) */ *data = (float)(abs(mant) - 1) / (2.0f * MAX_MANTISSA) + 0.5f; /* Now use ldexpf() to calculate the absolute value */ *data = ldexpf(*data, exp); /* Finally take care of the sign */ if(mant < 0) *data = -*data; } return pos; } /****************************************/ /****************************************/ void buzzmsg_serialize_string(buzzdarray_t buf, const char* data) { /* Get the length of the string */ uint16_t len = strlen(data); /* Push that into the buffer */ buzzmsg_serialize_u16(buf, len); /* Go through the characters and push them into the buffer */ const char* c = data; while(*c) { buzzdarray_push(buf, (uint8_t*)(c)); ++c; } } /****************************************/ /****************************************/ int64_t buzzmsg_deserialize_string(char** data, buzzdarray_t buf, uint32_t pos) { /* Make sure there are enough bytes to read the string length */ if(pos + sizeof(uint16_t) > buzzdarray_size(buf)) return -1; /* Read the string length */ uint16_t len; pos = buzzmsg_deserialize_u16(&len, buf, pos); /* Make sure there are enough bytes to read the string itself */ if(pos + len > buzzdarray_size(buf)) return -1; /* Create a buffer for the string */ *data = (char*)malloc(len * sizeof(char) + 1); /* Read the string characters */ memcpy(*data, (uint8_t*)buf->data + pos, len * sizeof(char)); /* Set the termination character */ *(*data + len) = 0; /* Return new position */ return pos + len; } /****************************************/ /****************************************/
C
#include <stdlib.h> #include <stdio.h> #include <limits.h> #include <omp.h> #include <dijkstra.h> #include <floyd.h> /** * Programa principal */ int main(int argc, char **argv) { // Algoritmos // 0 dijkstra // 1 floyd-warshall int algorithm = 0; // Quantidade padrao de threads // 0 default // n for parallel threads int nthreads = 1; // Quantidade de juncoes int n; // Quantidade de arestas int m; // Recebe argumentos if (argc > 1) { algorithm = atoi(argv[1]); if (algorithm != 0 && algorithm != 1) { printf("ERROR: invalid algorithm\nInform:\n\t0 dijkstra\n\t1 floyd-warshall\n"); return EXIT_FAILURE; } if (argc > 2) { nthreads = atoi(argv[2]); if (nthreads < 0) { printf("ERROR: invalid number of threads\nInform:\n\t0 for default\n\tn for n parallel threads\n"); return EXIT_FAILURE; } } } // Le quantidade de juncoes e de arestas scanf("%d", &n); scanf("%d", &m); // Validacao da entrada if (n < 2 || n > 1000) { printf("ERROR: invalid n value\n"); return EXIT_FAILURE; } if (m < n - 1 || m > (n * (n - 1)) / 2) { printf("ERROR: invalid m value\n"); return EXIT_FAILURE; } // Dijkstra if (algorithm == 0) { Graph graph; int i; int A, B, W; int *allNodes, min; // Aloca e cria grafo da cidade createGraph(&graph); allNodes = (int *)malloc(sizeof(int) * n); if (allNodes == NULL) { printf("ERROR: could not allocate memory for graph (Dijkstra)\n"); return EXIT_FAILURE; } // Adiciona todos os vertices for (i = 0; i < n; i++) { addNode(&graph, i+1); } // Adiciona todas arestas for (i = 0; i < m; i++) { scanf("%d %d %d", &A, &B, &W); addBothEdge(&graph, A, B, W); } #ifdef _OPENMP if (nthreads > 0) { omp_set_num_threads(nthreads); } #pragma omp parallel for #endif // Executa Dijkstra para todos os vertices for (i = 0; i < n; i++) { allNodes[i] = dijkstra(&graph, i+1); } // Pega o menor valor min = INT_MAX; for (i = 0; i < n; i++) { if (allNodes[i] < min) { min = allNodes[i]; } } // Imprime resposta printf("%d\n", min); destroyGraph(&graph); free(allNodes); // Floyd-Warshall } else if (algorithm == 1) { int i, j, k, w; // Aloca e inicializa a matriz da cidade (grafo) int **town = (int **)malloc(sizeof(int *) * n); if (town == NULL) { printf("ERROR: could not allocate memory for graph (Floyd-Warshall)\n"); return EXIT_FAILURE; } for (i = 0; i < n; i++) { town[i] = (int *)malloc(sizeof(int) * n); if (town[i] == NULL) { printf("ERROR: could not allocate memory for graph (Floyd-Warshall)\n"); return EXIT_FAILURE; } for (j = 0; j < n; j++) { if (i == j) town[i][j] = 0; // distancia 0 de uma cidade para ela mesma else town[i][j] = INT_MAX; // INT_MAX significa nao ha aresta de i para j } } // Vai lendo os dados e populando o grafo for (k = 0; k < m; k++) { scanf("%d %d %d", &i, &j, &w); // Adiciona ambas arestas town[i-1][j-1] = w; town[j-1][i-1] = w; } // Faz o processamento utilizando o algoritmo de Floyd-Warshall printf("%d\n", floyd(town, n, nthreads)); // Libera grafo da cidade for (i = 0; i < n; i++) free(town[i]); free(town); } return EXIT_SUCCESS; }
C
#include <stdio.h> int main(void){ int peopleNum, pizzaNum, pieceNum; int leftover, personGetsPiece; printf("How many people?"); scanf("%d", &peopleNum); printf("How many pizzas do you have?"); scanf("%d", &pizzaNum); printf("How many pieces a pizza has?"); scanf("%d", &pieceNum); personGetsPiece = pizzaNum*pieceNum/peopleNum; leftover = (pizzaNum*pieceNum)%peopleNum; printf("%d people with %d pizzas\n", peopleNum, pizzaNum); printf("Each person gets %d pieces of pizza.\n", personGetsPiece); printf("There are %d leftover pieces\n", leftover); return 0; }
C
/* * mjime051_lab8_part1.c * * Created: 5/1/2019 10:28:19 AM * Author : matt_ */ #include <avr/io.h> void ADC_init() { ADCSRA |= (1 << ADEN) | (1 << ADSC) | (1 << ADATE); // ADEN: setting this bit enables analog-to-digital conversion. // ADSC: setting this bit starts the first conversion. // ADATE: setting this bit enables auto-triggering. Since we are // in Free Running Mode, a new conversion will trigger whenever // the previous conversion completes. } int main(void) { /* Replace with your application code */ //DDRA = 0x00; PORTA = 0xFF; DDRB = 0xFF; PORTB = 0x00; //DDRD = 0x00; PORTD = 0x00; ADC_init(); unsigned short x = 0x00; unsigned char max = 127; while (1) { x = ADC & 0x00FF; if(x >= (max/2)){ PORTB = 0x01; } else { PORTB = 0x00; } } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "AUTOCELL.h" AT* init_random_table(int w, int h, int* r, int* n, int nn) { printf("Creating table...\n"); printf("Performing mallocs\n"); AT* at = (AT*) malloc(sizeof(AT)); int* new_cells = (int*) malloc(w * h * sizeof(int)); int* new_buffer = (int*) malloc(w * h * sizeof(int)); printf("Assigning variables\n"); at->generation = 0; at->width = w; at->height = h; at->rules = r; at->neighborhood = n; at->num_neighbors = nn; at->cells = new_cells; at->buffer = new_buffer; srand(time(NULL)); printf("Initializing cells\n"); for(int i = 0; i < at->width; i++) { for(int j = 0; j < at->height; j++) { int index = i + (j * at->width); at->cells[index] = rand() % 2; } } printf("Initializing buffer\n"); for(int k = 0; k < at->width; k++) { for(int l = 0; l < at->height; l++) { int index = k + (l * at->width); at->buffer[index] = 0; } } return at; } AT* init_preset_table(int w, int h, int* r, int* n, int nn, int* c) { printf("Creating table...\n"); printf("Performing mallocs\n"); AT* at = (AT*) malloc(sizeof(AT)); int* new_buffer = (int*) malloc(w * h * sizeof(int)); printf("Assigning variables\n"); at->generation = 0; at->width = w; at->height = h; at->rules = r; at->neighborhood = n; at->num_neighbors = nn; at->cells = c; at->buffer = new_buffer; srand(time(NULL)); printf("Initializing buffer\n"); for(int k = 0; k < at->width; k++) { for(int l = 0; l < at->height; l++) { int index = k + (l * at->width); at->buffer[index] = 0; } } return at; } void delete_table(AT* at) { printf("Deleting table...\n"); printf("Freeing cells\n"); free(at->cells); printf("Freeing buffer\n"); free(at->buffer); printf("Freeing automata table\n"); free(at); } int get_cell(AT* at, int x, int y) { int index = x + (y * at->width); return at->cells[index]; } int get_neighbor_wrap(AT* at, int n, int x, int y) { int nbr_x = x + at->neighborhood[2 * n]; int nbr_y = y + at->neighborhood[2 * n + 1]; if(nbr_x < 0) { nbr_x = nbr_x + at->width; } else if(nbr_x >= at->width) { nbr_x = nbr_x - at->width; } if(nbr_y < 0) { nbr_y = nbr_y + at->height; } else if(nbr_y >= at->height) { nbr_y = nbr_y - at->height; } int nbr_index = nbr_x + (nbr_y * at->width); return at->cells[nbr_index]; } int get_neighbor_wall(AT* at, int n, int x, int y, int wall_state) { int nbr_x = x + at->neighborhood[2 * n]; int nbr_y = y + at->neighborhood[(2 * n) + 1]; if((nbr_x < 0) || (nbr_x >= at->width) || (nbr_y < 0) || (nbr_y >= at->height)) { return wall_state; } int nbr_index = nbr_x + (nbr_y * at->width); return at->cells[nbr_index]; } void calc_next_state(AT* at, int x, int y) { int nbr_sum = 0; for(int n = 0; n < at->num_neighbors; n++) { nbr_sum += get_neighbor_wrap(at, n, x, y); } int next_state = at->rules[nbr_sum]; int index = x + (y * at->width); if(next_state >= 0) { at->buffer[index] = next_state; } else { at->buffer[index] = at->cells[index]; } } void update_table(AT* at) { for( int i = 0; i < at->width; i++ ) { for( int j = 0; j < at->height; j++ ) { calc_next_state(at, i, j); } } int* temp = at->cells; at->cells = at->buffer; at->buffer = temp; at->generation++; } void print_table_states(AT* at) { printf("Printing automata table at generation %d\n\n", at->generation); for(int j = 0; j < at->height; j++) { for(int i = 0; i < at->width; i++) { printf(" %d", get_cell(at, i, j)); } printf("\n"); } printf("\n"); } void print_table_characters(AT* at) { printf("Printing automata table at generation %d\n\n", at->generation); for(int j = 0; j < at->height; j++) { for(int i = 0; i < at->width; i++) { if(get_cell(at, i, j) == 1) printf("O"); else printf(" "); } printf("\n"); } printf("\n"); }
C
// Esercizio2 // // Creato da Alberto Giunta il 26/09/2013 // Matricola: 0000691428 #include <stdio.h> int main () { /* solitamente non è richiesto, ma in questo esercizio lascio uno spazio tra la sequenza di escape e il resto della stringa per migliorare la leggibilità del codice */ puts("Stampo stringhe a video utilizzando le sequenze di escape conosciute\n"); puts("\" stampo i doppi apici"); puts("\' stampo l'apice singolo"); puts("\\ stampo il backslash"); puts("\? stampo il punto interrogativo"); //le funzioni di escape fin'ora usate vengono utilizzate per stampare caratteri //che altrimenti verrebbero confusi con caratteri "di servizio" del linguaggio C printf("vado a capo\n\n"); puts("\a il computer emette un suono"); puts("cancello l'ultimo carattere\b"); puts("\t tabulazione orizzontale"); puts("\v tabulazione verticale"); puts("carattere nullo o fine strin\0ga"); return 0; }
C
/* * ???? * Created on: 2013-1-13 * ?? * Author: ??? */ int main() { int r = 0, c = 0; cin >> r >> c; int mountain[r + 2][c + 2]; for (int i = 0; i < r + 2; i++) for (int j = 0; j < c + 2; j++) { if (i == 0 || j == 0 || i == r + 1 || j == c + 1) mountain[i][j] = 0; else cin >> mountain[i][j]; } for (int i = 1; i < r + 1; i++) for (int j = 1; j < c + 1; j++) { if ((mountain[i][j] >= mountain[i - 1][j]) && (mountain[i][j] >= mountain[i + 1][j]) && (mountain[i][j] >= mountain[i][j - 1]) && (mountain[i][j] >= mountain[i][j + 1])) cout << i-1 << " " << j-1 << endl; } return 0; }
C
#include <stdio.h> #include <signal.h> #include <stdlib.h> #include <netinet/in.h> #include <string.h> #include <sys/socket.h> #include <unistd.h> #include <dirent.h> #include <sys/types.h> #include <time.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> static int main_socket_fd; int isNumber(char *str) // Checks if the given string is a numerical string, returns 0 if the string is a numerical string, else -1. { int i = 0; for (i = 0; i < strlen(str); i++) { if (isdigit(str[i]) == 0) { return -1; } } return 0; } typedef struct message // A linked list struct to maintain the messages. { int fd; char* msg_content; struct message *next_msg; } message; void freeHandler() // Handler for SIGINT. { close(main_socket_fd); exit(0); } int main(int argc, char *argv[]) { signal(SIGINT, freeHandler); //--Variables initialization--// int private_socket_fd = 0; int bind_status = 0; int listen_status = 0; int read_status = 0; int write_status = 0; int private_index = 0; //--Buffers initialization--// char buff[4096]; char guest[30]; char guest_num[7]; int private_sockets[1000]; private_sockets[0] = 0; bzero(buff, 4096); bzero(private_sockets, 1000); bzero(guest_num, 7); bzero(guest, 30); //--Server Code--// struct sockaddr_in server_addr; fd_set main_set; fd_set copy_read; int max = 0; fd_set copy_write; message *msg = NULL; message *first_msg = NULL; message *last_msg = NULL; message *pulled_msg = NULL; int messages_num = 0; main_socket_fd = socket(AF_INET, SOCK_STREAM, 0); max = 1 + main_socket_fd; server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(atoi(argv[1])); bind_status = bind(main_socket_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)); if(argc != 2) // If there are too many or less arguments than needed. { fprintf(stderr,"Usage: server <port> \n"); close(main_socket_fd); exit(1); } if(isNumber(argv[1])==-1) // If port argument is not a numerical or a negative port. { fprintf(stderr,"Usage: server <port> \n"); close(main_socket_fd); exit(1); } if (bind_status == -1) { perror("Error while binding the socket. \n"); close(main_socket_fd); exit(1); } listen_status = listen(main_socket_fd, 5); if (listen_status == -1) { perror("Error while listening to the socket. \n"); close(main_socket_fd); exit(1); } FD_ZERO(&main_set); FD_SET(main_socket_fd, &main_set); while (1) { copy_write = main_set; copy_read = main_set; bzero(buff, 4096); select(max, &copy_read, &copy_write, NULL, NULL); if (FD_ISSET(main_socket_fd, &copy_read)) { private_socket_fd = accept(main_socket_fd, NULL, NULL); if (private_socket_fd < 0) { perror("Error while listening to the socket. \n"); close(main_socket_fd); exit(1); } if (private_socket_fd >= max) max = private_socket_fd + 1; FD_SET(private_socket_fd, &main_set); private_sockets[private_index] = private_socket_fd; private_index++; } for (int i = 0 ; i < private_index; i++) { if (FD_ISSET(private_sockets[i], &copy_read)) { read_status = read(private_sockets[i], buff, 4096); printf("Server is ready to read from private-socket number: %d\n", private_socket_fd); if (read_status == 0) { FD_CLR(private_sockets[i], &main_set); close(private_sockets[i]); private_sockets[i] = -1; } else if (read_status > 0) { if (messages_num == 0) { msg = (message *)calloc(1,sizeof(message)); msg->fd = private_sockets[i]; msg->next_msg = NULL; msg->msg_content = (char*)calloc(1+strlen(buff),sizeof(char)); strcpy(msg->msg_content, buff); first_msg = msg; last_msg = msg; messages_num++; } else { msg = (message *)calloc(1,sizeof(message)); msg->fd = private_sockets[i]; msg->next_msg = last_msg->next_msg; msg->msg_content = (char*)calloc(1+strlen(buff),sizeof(char)); strcpy(msg->msg_content, buff); last_msg->next_msg = msg; last_msg = msg; messages_num++; } } } } if (messages_num > 0) { for (int i = 0; i < private_index; i++) { pulled_msg = first_msg; if (private_sockets[i] != pulled_msg->fd && private_sockets[i] != -1) { printf("Server is ready to write to socket: %d\n", private_sockets[i]); sprintf(guest_num, "%d", pulled_msg->fd); bzero(guest,30); strcpy(guest, "guest"); strcat(guest, guest_num); strcat(guest, ": "); write_status = write(private_sockets[i], guest, strlen(guest)); write_status = write(private_sockets[i], pulled_msg->msg_content, strlen(pulled_msg->msg_content)); if (write_status < 0) { perror("Error while writing to the socket.\n"); close(main_socket_fd); exit(1); } } else continue; } if (pulled_msg != NULL) { first_msg = pulled_msg->next_msg; free(pulled_msg->msg_content); free(pulled_msg); messages_num--; } } } close(main_socket_fd); return 0; }
C
#include<stdio.h> #include<math.h> int main() { int i, j, n, arr[10][10], sum = 0, sum1 = 0, a = 0, normal; printf("Enter the number of rows (columns ) of the matrix: \n"); scanf("%d",&n); printf("\nEnter the %d elements of the first matrix: \n", n*n); for(i=0; i<n; i++) { for(j=0; j<n; j++) { scanf("%d", &arr[i][j]); a = arr[i][j]*arr[i][j]; sum1 +=a; } } normal = sqrt((double)sum1); printf("\n\nThe normal of the given matrix is: %d\n\n", normal); for(i=0; i<n; i++) { sum = sum + arr[i][i]; } printf("The Trace of the given matrix is: %d\n\n", sum); return 0; }
C
#include "../machine.h" /* checks if all entries of a vector are finite */ extern int finite __PARAMS( (double v)); int C2F(vfinite)(int *n, double *v) { int i; for (i=0; i < *n; i++) if (finite(v[i])==0) return 0; return 1; }
C
#include <stdio.h> #include <stdlib.h> #include "3-calc.h" /** * op_add - Add two integers * * @a: First integer. * @b: Second integer. * Return: The result of the opration */ int op_add(int a, int b) { int res; res = 0; res = a + b; return (res); } /** * op_sub - substract two integers * * @a: The operator * @b: The function associated * Return: The result of the opration */ int op_sub(int a, int b) { int res; res = 0; res = a - b; return (res); } /** * op_mul - mul two integers * * @a: First intiger * @b: Second intiger * Return: The result of the opration */ int op_mul(int a, int b) { int res; res = 0; res = a * b; return (res); } /** * op_div - div two intigers * * @a: First intiger * @b: Second intiger * Return: The result of the opration */ int op_div(int a, int b) { if (b != 0) { int res; res = 0; res = a / b; return (res); } printf("Error\n"); exit(100); } /** * op_mod - Show the module of two intigers * * @a: First intiger * @b: Second entiger * Return: The result of the opration */ int op_mod(int a, int b) { if (b != 0) { int res; res = 0; res = a % b; return (res); } printf("Error\n"); exit(100); }
C
#include<stdio.h> #include<stdlib.h> #include<time.h> #define MAX 100 #define MAXNUMBER 20 void create_random(int *tab); void count_frequency(int *tab, int *freq); void draw_histogram(int *freq); int main ( void) { int table[MAX]; int frequency[MAXNUMBER]; /* INIT RANDOM TABLE */ printf("\n\t - NUMBERS -\n\n"); create_random(table); /* INIT FREQUANCY ARRAY */ for(int j= 0; j <MAXNUMBER; j++){ frequency[j] = 0; } /* COUNT FREQUENCY OF RANDOM NUMBERS */ count_frequency(table, frequency); /* DRAW FREQUENCY */ printf("\n\t - FREQUENCY -\n\n"); draw_histogram(frequency); } void create_random(int* table) { srand((int)time(0)); for (int i = 0; i < MAX; i++){ int ran = rand() % MAXNUMBER; table[i] = ran; printf("%d", table[i]); } printf("\n"); } void count_frequency(int* array, int* frequency) { for (int i = 0; i< MAX; i++){ frequency[array[i]] ++; } } void draw_histogram(int* frequency) { for (int i = 0; i < MAXNUMBER; i++) { if (frequency[i] != 0) { printf("\t%d\t", i); for (int j = 0; j < frequency[i]; j++) { printf("x"); } printf("%s", "\n"); } } }
C
#include<stdio.h> #include<math.h> #define _USE_MATH_DEFINES #define N 320 #define PI 3.1415 FILE *fin; FILE *forigin_spec; FILE *flow_time_env; FILE *fhigh_time_env; FILE *flog_spec_env; FILE *flow_lifter; void n_dft(double* signal, double* spec_mag, int N_PT); void read_data(FILE *fp, double* signal, int N_PT, short *data); void hamming_window(double *signal, double* window_signal, int N_PT); void copy_spec(double* spec_mag, double* log_spec_mag, int N_PT); void log_spec(double* log_spec_mag, int N_PT); void inv_n_dft(double* spec_mag, double* signal, int N_PT); void lowtime_liftering(double* log_spec_mag, double* low_lifter_cc, int N_PT, int lifter_point); void hightime_liftering(double* log_spec_mag, double* high_lifter_cc, int N_PT, int lifter_point); void get_envlp_file(FILE *fp, double* spec_env, int N_PT); void get_log_env(FILE *fp, double* spec_mag, int N_PT); int main(void) { //double spec_real[N], spec_imag[N], freq; double signal[N], spec_mag[N], window_signal[N], log_spec_mag[N]; double cepstrum[N], low_lifter_cc[N], high_lifter_cc[N], low_log_mag_spec_env[N], high_log_mag_spec_env[N]; short data; int count = 0; // FILE CONNECT & EXCEPTION HANDLE // fopen_s(&fin, "Male.raw", "rb"); fopen_s(&flow_time_env, "low_time_env.txt", "wb"); fopen_s(&fhigh_time_env, "high_time_env.txt", "wb"); fopen_s(&forigin_spec, "origin_spec.txt", "wb"); fopen_s(&flog_spec_env, "log_spec.txt", "wb"); fopen_s(&flow_lifter, "low_lifter.txt", "wb"); if (fin == NULL || flow_time_env == NULL || fhigh_time_env == NULL || forigin_spec == NULL || flog_spec_env == NULL) { printf("NULL POINT EXCEPTION - \n"); return 1; } // FILE READ read_data(fin, signal, N, &data); // Hamming Window hamming_window(signal, window_signal, N); // N-POINT DFT n_dft(window_signal, spec_mag, N); // Copy spec copy_spec(spec_mag, log_spec_mag, N); // Log spec (log|X[k]| + log|H[k]|, log(|X[k]|): High Time, log(|H[k]|): Low Time) log_spec(log_spec_mag, N); // Inverse-N-POINT DFT : Cepstrum inv_n_dft(log_spec_mag, cepstrum, N); // Low-time Liftering : Cepstrum Coefficient lowtime_liftering(cepstrum, low_lifter_cc, N, 15); // High-time Liftering : Cepstrum Coefficient hightime_liftering(cepstrum, high_lifter_cc, N, 15); // Low-time N-POINT DFT n_dft(low_lifter_cc, low_log_mag_spec_env, N); // High-time N-POINT DFT n_dft(high_lifter_cc, high_log_mag_spec_env, N); // Get envelope file get_envlp_file(flow_time_env, low_log_mag_spec_env, N); get_envlp_file(fhigh_time_env, high_log_mag_spec_env, N); get_envlp_file(forigin_spec, spec_mag, N); get_log_env(flog_spec_env, spec_mag, N); get_envlp_file(flow_lifter, low_lifter_cc, N); // File close fclose(fin); fclose(flow_time_env); fclose(fhigh_time_env); fclose(forigin_spec); fclose(flog_spec_env); fclose(flow_lifter); } void frame_number_count(FILE *fp) { if (fp == NULL) printf("Error!!\n"); short fr_data; int count = 0; while (feof(fp) == 0) { fread(&fr_data, 2, 1, fin); count++; } printf("%d\n", count); //-> RESULT: 640 samples -> 0.8s } void read_data(FILE *fp, double* signal, int N_PT, short *data) { for (int i = 0; i < N_PT; i++) { fread(data, 2, 1, fin); signal[i] = (float)*data; // input array } } void hamming_window(double *signal, double* window_signal, int N_PT) { for (int n = 0; n < N_PT; n++) { window_signal[n] = signal[n] * (0.5 - 0.5*cos(2 * PI * n / (float)(N - 1))); } //TEST: for (int n = 0; n < N_PT; n++) printf("window_signal[%d] = %f\n", n, window_signal[n]); } void n_dft(double* signal, double* spec_mag, int N_PT) { double spec_real[N] = { 0.0, }; double spec_imag[N] = { 0.0, }; for (int k = 0; k < N_PT; k++) { spec_real[k] = spec_imag[k] = 0.0; for (int n = 0; n < N_PT; n++) { spec_real[k] = spec_real[k] + signal[n] * cos(2 * PI * k * n / (float)N); // DFT Real spec_imag[k] = spec_imag[k] - signal[n] * sin(2 * PI * k * n / (float)N); // DFT Imainary } spec_mag[k] = sqrt(pow(spec_real[k], 2) + pow(spec_imag[k], 2)); // |spec_mag[k]|^2 = |spec_real[k]|^2 + |spec_imag[k]|^2 // TEST: printf("spec_mag[%d] = %f\n", k, spec_mag[k]); } } void copy_spec(double* spec_mag, double* log_spec_mag, int N_PT) { for (int i = 0; i < N_PT; i++) log_spec_mag[i] = spec_mag[i]; //TEST: for (int n = 0; n < N_PT; n++) printf("log_spec_mag[%d] = %f\n", n, log_spec_mag[n]); } void log_spec(double* log_spec_mag, int N_PT) { double origin_log_spec[N]; for (int i = 0; i < N_PT; i++) origin_log_spec[i] = log_spec_mag[i]; for (int i = 0; i < N_PT; i++) log_spec_mag[i] = log10(origin_log_spec[i]); //TEST: for (int n = 0; n < N_PT; n++) printf("origin[%d] = %f || log_spec_mag[%d] = %f\n",n,origin_log_spec[n], n, log_spec_mag[n]); } void inv_n_dft(double* spec_mag, double* signal, int N_PT) { double sig_real[N] = { 0.0, }; double sig_imag[N] = { 0.0, }; for (int n = 0; n < N_PT; n++) { sig_real[n] = sig_imag[n] = 0.0; for (int k = 0; k < N_PT; k++) { sig_real[n] = sig_real[n] + spec_mag[k] * cos(2 * PI * k * n / (float)N_PT); // IDFT Real sig_imag[n] = sig_imag[n] + spec_mag[k] * sin(2 * PI * k * n / (float)N_PT); // IDFT Imainary } signal[n] = sqrt(pow(sig_real[n], 2) + pow(sig_imag[n], 2)); // |signal[n]|^2 = |sig_real[n]|^2 + |sig_imag[n]|^2 // TEST: printf("signal[%d] = %f\n", n, signal[n]); } } void lowtime_liftering(double* cepstrum, double* low_lifter_cc, int N_PT, int lifter_point) { for (int n = 0; n < N_PT; n++) { if (n < lifter_point || n >= N - lifter_point) low_lifter_cc[n] = cepstrum[n]; else low_lifter_cc[n] = 0.0; } //TEST: for (int n = 0; n < N_PT; n++) printf("low_lifter_cc[%d] = %f\n", n, low_lifter_cc[n]); } void hightime_liftering(double* cepstrum, double* high_lifter_cc, int N_PT, int lifter_point) { for (int n = 0; n < N_PT; n++) { if (N / 2 - lifter_point - 1 < n && n < N / 2 + lifter_point) high_lifter_cc[n] = cepstrum[n]; else high_lifter_cc[n] = 0.0; } //TEST: for (int n = 0; n < N_PT; n++) printf("high_lifter_cc[%d] = %f\n", n, high_lifter_cc[n]); } void get_envlp_file(FILE *fp, double* spec_env, int N_PT) { for (int i = 0; i < N_PT; i++) fprintf(fp, "%10.7f\n", spec_env[i]); } void get_log_env(FILE *fp, double* spec_mag, int N_PT) { for (int i = 0; i < N_PT; i++) { fprintf(fp, "%10.7f\n", log10(spec_mag[i])); } }
C
#ifndef v1beta2_deployment_TEST #define v1beta2_deployment_TEST // the following is to include only the main from the first c file #ifndef TEST_MAIN #define TEST_MAIN #define v1beta2_deployment_MAIN #endif // TEST_MAIN #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdbool.h> #include "../external/cJSON.h" #include "../model/v1beta2_deployment.h" v1beta2_deployment_t* instantiate_v1beta2_deployment(int include_optional); #include "test_v1_object_meta.c" #include "test_v1beta2_deployment_spec.c" #include "test_v1beta2_deployment_status.c" v1beta2_deployment_t* instantiate_v1beta2_deployment(int include_optional) { v1beta2_deployment_t* v1beta2_deployment = NULL; if (include_optional) { v1beta2_deployment = v1beta2_deployment_create( "0", "0", // false, not to have infinite recursion instantiate_v1_object_meta(0), // false, not to have infinite recursion instantiate_v1beta2_deployment_spec(0), // false, not to have infinite recursion instantiate_v1beta2_deployment_status(0) ); } else { v1beta2_deployment = v1beta2_deployment_create( "0", "0", NULL, NULL, NULL ); } return v1beta2_deployment; } #ifdef v1beta2_deployment_MAIN void test_v1beta2_deployment(int include_optional) { v1beta2_deployment_t* v1beta2_deployment_1 = instantiate_v1beta2_deployment(include_optional); cJSON* jsonv1beta2_deployment_1 = v1beta2_deployment_convertToJSON(v1beta2_deployment_1); printf("v1beta2_deployment :\n%s\n", cJSON_Print(jsonv1beta2_deployment_1)); v1beta2_deployment_t* v1beta2_deployment_2 = v1beta2_deployment_parseFromJSON(jsonv1beta2_deployment_1); cJSON* jsonv1beta2_deployment_2 = v1beta2_deployment_convertToJSON(v1beta2_deployment_2); printf("repeating v1beta2_deployment:\n%s\n", cJSON_Print(jsonv1beta2_deployment_2)); } int main() { test_v1beta2_deployment(1); test_v1beta2_deployment(0); printf("Hello world \n"); return 0; } #endif // v1beta2_deployment_MAIN #endif // v1beta2_deployment_TEST
C
/************************************************************************* * Copyright (c) 2004 Altera Corporation, San Jose, California, USA. * * All rights reserved. All use of this software and documentation is * * subject to the License Agreement located at the end of this file below.* ************************************************************************** * Description: * * The following is a simple hello world program running MicroC/OS-II.The * * purpose of the design is to be a very simple application that just * * demonstrates MicroC/OS-II running on NIOS II.The design doesn't account* * for issues such as checking system call return codes. etc. * * * * Requirements: * * -Supported Example Hardware Platforms * * Standard * * Full Featured * * Low Cost * * -Supported Development Boards * * Nios II Development Board, Stratix II Edition * * Nios Development Board, Stratix Professional Edition * * Nios Development Board, Stratix Edition * * Nios Development Board, Cyclone Edition * * -System Library Settings * * RTOS Type - MicroC/OS-II * * Periodic System Timer * * -Know Issues * * If this design is run on the ISS, terminal output will take several* * minutes per iteration. * **************************************************************************/ #include <stdio.h> #include "includes.h" #include <system.h> #include <io.h> #define c4 95565 #define d4 85129 #define e4 75842 #define f4 71585 #define g4 63775 #define a4 56817 #define b4 50619 #define c5 47777 #define d5 42565 #define e5 37920 #define f5 35792 #define g5 31887 #define a5 28408 #define b5 25309 #define silence 1 /* Definition of Task Stacks */ #define TASK_STACKSIZE 2048 OS_STK task1_stk[TASK_STACKSIZE]; OS_STK task2_stk[TASK_STACKSIZE]; OS_STK leds_stk[TASK_STACKSIZE]; /* Definition of Task Priorities */ #define TASK1_PRIORITY 1 #define TASK2_PRIORITY 2 #define LEDS_PRIORITY 3 void play_tone(int nota, int time_ms){ IOWR(DIV_FREQ_BASE,0,nota); OSTimeDlyHMSM(0, 0, 0, time_ms*2); IOWR(DIV_FREQ_BASE,0,silence); OSTimeDlyHMSM(0, 0, 0, 10); } void play_tone1(int nota, int time_ms){ IOWR(DIV_FREQ1_BASE,0,nota); OSTimeDlyHMSM(0, 0, 0, time_ms*2); IOWR(DIV_FREQ1_BASE,0,silence); OSTimeDlyHMSM(0, 0, 0, 10); } /* Prints "Hello World" and sleeps for three seconds */ void task1(void* pdata) { unsigned char counter=0; while (1) { int est= IORD(SW_BASE,0); // counter= IORD(LEDS_BASE,0); if(est==0){ printf("Hola led ++\n"); IOWR(LEDS_BASE,0,counter); counter++; OSTimeDlyHMSM(0, 0, 0, 100); } else{ printf("Hola led --\n"); IOWR(LEDS_BASE,0,counter); counter--; OSTimeDlyHMSM(0, 0, 0, 100); } } } /* Prints "Hello World" and sleeps for three seconds */ void task2(void* pdata) { while (1) { play_tone(b4,400); play_tone(c5,200); play_tone(d5,200); play_tone(d5,200); play_tone(c5,200); play_tone(b4,200); play_tone(a4,200); play_tone(g4,200); play_tone(g4,200); play_tone(a4,200); play_tone(b4,200); play_tone(b4,300); play_tone(a4,100); play_tone(a4,400); play_tone(b4,400); play_tone(c5,200); play_tone(d5,200); play_tone(d5,200); play_tone(c5,200); play_tone(b4,200); play_tone(a4,200); play_tone(g4,200); play_tone(g4,200); play_tone(a4,200); play_tone(b4,200); play_tone(a4,300); play_tone(g4,100); play_tone(g4,400); play_tone(silence,200); play_tone(a4,400); play_tone(b4,200); play_tone(g4,200); play_tone(a4,200); play_tone(b4,100); play_tone(c5,100); play_tone(b4,200); play_tone(g4,200); play_tone(a4,200); play_tone(b4,100); play_tone(c5,100); play_tone(b4,200); play_tone(a4,200); play_tone(g4,200); play_tone(a4,200); play_tone(d4,400); play_tone(b4,400); play_tone(c5,200); play_tone(d5,200); play_tone(d5,200); play_tone(c5,200); play_tone(b4,200); play_tone(a4,200); play_tone(g4,200); play_tone(g4,200); play_tone(a4,200); play_tone(b4,200); play_tone(a4,300); play_tone(g4,100); play_tone(g4,400); play_tone(silence,400); } } void leds_task(void* pdata) { while (1) { play_tone1(c4,400); play_tone1(f4,200); play_tone1(f4,200); play_tone1(f4,600); play_tone1(g4,400); play_tone1(a4,200); play_tone1(a4,200); play_tone1(a4,600); play_tone1(a4,200); play_tone1(g4,200); play_tone1(a4,200); play_tone1(b4,600); play_tone1(e4,400); play_tone1(g4,400); play_tone1(f4,1000); play_tone1(c4,400); play_tone1(f4,200); play_tone1(f4,200); play_tone1(f4,600); play_tone1(g4,400); play_tone1(a4,200); play_tone1(a4,200); play_tone1(a4,600); play_tone1(a4,200); play_tone1(g4,200); play_tone1(a4,200); play_tone1(b4,600); play_tone1(e4,400); play_tone1(g4,400); play_tone1(f4,1000); // play_tone1(c5,200); play_tone1(c5,200); play_tone1(a4,200); play_tone1(d5,400); play_tone1(c5,200); play_tone1(c5,200); play_tone1(b4,200); play_tone1(b4,400); play_tone1(b4,200); play_tone1(b4,200); play_tone1(g4,200); play_tone1(c5,400); play_tone1(b4,200); play_tone1(b4,200); play_tone1(a4,200); play_tone1(a4,400); } } /* The main function creates two task and starts multi-tasking */ int main(void) { OSTaskCreateExt(task1, NULL, (void *)&task1_stk[TASK_STACKSIZE-1], TASK1_PRIORITY, TASK1_PRIORITY, task1_stk, TASK_STACKSIZE, NULL, 0); OSTaskCreateExt(task2, NULL, (void *)&task2_stk[TASK_STACKSIZE-1], TASK2_PRIORITY, TASK2_PRIORITY, task2_stk, TASK_STACKSIZE, NULL, 0); OSTaskCreateExt(leds_task, NULL, (void *)&leds_stk[TASK_STACKSIZE-1], LEDS_PRIORITY, LEDS_PRIORITY, leds_stk, TASK_STACKSIZE, NULL, 0); OSStart(); return 0; } /****************************************************************************** * * * License Agreement * * * * Copyright (c) 2004 Altera Corporation, San Jose, California, USA. * * All rights reserved. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the "Software"), * * to deal in the Software without restriction, including without limitation * * the rights to use, copy, modify, merge, publish, distribute, sublicense, * * and/or sell copies of the Software, and to permit persons to whom the * * Software is furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * * DEALINGS IN THE SOFTWARE. * * * * This agreement shall be governed in all respects by the laws of the State * * of California and by the laws of the United States of America. * * Altera does not recommend, suggest or require that this reference design * * file be used in conjunction or combination with any other product. * ******************************************************************************/
C
#include "types.h" #include "stat.h" #include "user.h" int main(int argc, char *argv[]) { char buf[128]; uint bufsize = sizeof(buf); if(argc != 2){ printf(2, "Usage: ln old new\n"); exit(); } if(readlink(argv[1], buf, bufsize) == 0){ printf(1, "%s\n", buf); } else{ printf(2, "readlink fail\n"); } exit(); }