language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/** * Auteur: Seddar Naïm * Création: 01/12/2020 18:17:34 * Dernière modification: 30/12/2020 12:16:38 * Master 1 Informatique */ #include <signal.h> #include <fcntl.h> #include <stdio.h> #include "../includes/myssh-server.h" #include "../includes/error.h" int sockets[SOMAXCONN]; void signal_callback_handler(int signum) { waitpid(-1, NULL, WNOHANG); } int main() { signal(SIGCHLD, signal_callback_handler); int i = 0; int status; Server daemon = server_create_tcp(); daemon->server_bind(daemon, 1344); if (listen(daemon->socket, SOMAXCONN) == ERR) { exit(EXIT_FAILURE); } for (;;) { pid_t pid; int t = i; sockets[i] = accept(daemon->socket, (struct sockaddr *)&daemon->clientAddr, &daemon->len); if ((pid = fork()) == 0) { close(daemon->socket); char buff[5]; sprintf(buff, "%d", sockets[t]); execl("./myssh-server", "myssh-server", buff, (void *)0); exit(EXIT_SUCCESS); } if (waitpid(-1, &status, WNOHANG) == ERR) { perror("wait"); } i++; } server_destroy(daemon); return 0; }
C
/** * Author: Fateh Karan Singh Sandhu * Collaborators: Saurav Pradhan, Saurav Kushwaha * Date: October 30, 2018 * * This file contains function headings **/ /** * Define a structure for airport */ typedef struct { char *gpsID; char *nameOfAirport; char *typeOfAirport; char *city; char *country; double latitude; double longitude; int elevation; } Airport; /** * A factory function to create a new Airport with the given * attributes. This function should make *deep* copies of each * of the relevant fields and return a pointer to the newly * created Airport structure. */ Airport* createAirport(const char* gpsId, const char* type, const char* name, double latitude, double longitude, int elevationFeet, const char* city, const char* countryAbbrv); /** * This function initializes an existing allocated * Airport structure with the given attributes. */ void initAirport(Airport* airport, const char* gpsId, const char* type, const char* name, double latitude, double longitude, int elevationFeet, const char* city, const char* countryAbbrv); /** * Constructs a new string representation of the given * Airport structure. */ char* airportToString(const Airport* a); /** * Computes the air distance, in kilometers, between * the two Airports using their latitude/longitude */ double getAirDistance(const Airport* origin, const Airport* destination); /** * Computes the estimated travel time (in hours) for a flight * that involves the given stops using the average flight speed * (kilometers per hour) and average layover time (in hours) */ double getEstimatedTravelTime(const Airport* stops, int size, double aveKmsPerHour, double aveLayoverTimeHrs); /** * This function converts degrees into radians. */ double degreesToRadians (double degree); /** * This function gives the air distance between * two places taking in their latitudes and * longitudes */ double getAirDistanceFunction (double latA, double longA, double latB, double longB); /** * This function initializes a new string */ char * initString (const char* string1);
C
#include<stdio.h> #include<string.h> int main() { //get string char s[100]; scanf("%s",s); int n=strlen(s)-1; int c=1; //check whether 7 same charecters are entered next to one another for(int i=0;i<n;i++) { if(s[i]==s[i+1]) c++; else c=1; if(c==7) { printf("YES"); return 0; } } printf("NO"); return 0; }
C
#include <cs50.h> #include <stdio.h> #include <string.h> #include <ctype.h> int main(int argc, string argv[]) { int key = atoi(argv[1]); // here is key entered is converting to integer for (int i=1; i<argc; i++) // here i am indicating that program start analyzing from second argument in a command-line, which is the key. { if (key>25||key<1||argc>2) // here i am breaking the program if key entered is not one integer from 1 to 25. {printf("Sorry, You have to enter the only one key - an integer from 1 to 25. Try again!\n"); return 1;} else // here is a program body in case key entered is OK { printf("Please write the text to be encrypted:\n"); string text = get_string(); //grabbing the text for encrypting printf("Your text encrypted:\n"); for (int j=0, n=strlen(text); j<n; j++) //dividing my text string into separate symbols {if (isalpha (text[j]) && isupper (text[j])) //finding uppercase letters printf("%c", ((((char)text[j]+key)-65)%26)+65); //encrypting uppercase letters else if (isalpha (text[j]) && islower (text[j])) //finding lowercase letters printf("%c", ((((char)text[j]+key)-97)%26)+97); //encrypting lowercase lettes else printf("%c", text[j]);} //leaving all non-alphabetical symbols as it is printf("\n");} } return 0;}
C
/* ARRAY.c * by Tim Müller * * Created: * 28/04/2020, 19:36:38 * Last edited: * 5/24/2020, 3:17:26 PM * Auto updated? * Yes * * Description: * Defines a very simple array class that enhances usage of basic C * arrays. **/ #include <stdio.h> #include <stdlib.h> #include <math.h> #include "Array.h" /***** MEMORY MANAGEMENT *****/ array* create_empty_array(size_t size) { // Allocate the struct array* to_ret = (array*) malloc(sizeof(array) + size * sizeof(double)); if (to_ret == NULL) { fprintf(stderr, "ERROR: create_empty_array: could not allocate memory (%lu bytes).\n", sizeof(array) + size * sizeof(double)); return NULL; } // Set the size and the data pointer to_ret->size = size; to_ret->d = (double*) (((char*) to_ret) + sizeof(array)); // Return return to_ret; } array* create_array(size_t size, double* data) { // Create an empty array array* to_ret = create_empty_array(size); if (to_ret == NULL) { fprintf(stderr, "ERROR: create_array: empty array creation failed.\n"); return NULL; } // Fill it with the data for (size_t i = 0; i < to_ret->size; i++) { to_ret->d[i] = data[i]; } // Return return to_ret; } array* create_linked_array(size_t size, double* data) { // Create an array without place for extra data array* to_ret = (array*) malloc(sizeof(array)); if (to_ret == NULL) { fprintf(stderr, "ERROR: create_linked_array: could not allocate array struct (%lu bytes).\n", sizeof(array)); return NULL; } // Set the size and the data pointer to_ret->size = size; to_ret->d = data; // Return return to_ret; } array* initialize_array(size_t size, array* a) { // Set the size and linked status a->size = size; // Set the data pointer to the continued value a->d = (double*) (((char*) a) + a->size); return a; } array* fill_array(array* a, const double* data) { // Copy all the data and return for (size_t i = 0; i < a->size; i++) { a->d[i] = data[i]; } return a; } array* copy_array(array* target, const array* source) { // Throw an error if not equally sized if (target->size != source->size) { fprintf(stderr, "ERROR: copy_array: target and source array have different lengths (%lu vs %lu).\n", target->size, source->size); return NULL; } // Copy all elements from one to the other fill_array(target, source->d); // Done, return return target; } array* copy_create_array(const array* a) { // Create a new array with the same size array* to_ret = create_empty_array(a->size); if (to_ret == NULL) { fprintf(stderr, "ERROR: copy_create_array: empty array creation failed.\n"); return NULL; } // Use copy_array to copy the data if (copy_array(to_ret, a) == NULL) { fprintf(stderr, "ERROR: copy_create_array: copying data failed.\n"); return NULL; } // Return return to_ret; } void destroy_array(array* a) { // Due to the genius of making the array in one memory space, we can simply call free free(a); } /***** USEFUL FUNCTIONS *****/ double array_sum(const array* a) { double sum = 0; for (size_t i = 0; i < a->size; i++) { sum += a->d[i]; } return sum; } double array_max(const array* a) { double max = -INFINITY; for (size_t i = 0; i < a->size; i++) { if (a->d[i] > max) { max = a->d[i]; } } return max; } /***** DEBUG FUNCTIONS *****/ void array_write(FILE* handle, const array* a) { fprintf(handle, "["); for (size_t i = 0; i < a->size; i++) { if (i > 0) { fprintf(handle, ", "); } fprintf(handle, "%.2f", a->d[i]); } fprintf(handle, "]"); } void array_print(FILE* handle, const array* a) { fprintf(handle, "["); for (size_t i = 0; i < a->size; i++) { if (i > 0) { fprintf(handle, ", "); } fprintf(handle, "%.2f", a->d[i]); } fprintf(handle, "]\n"); } bool array_equals(const array* a1, const array* a2) { // Check if the sizes are equal if (a1->size != a2->size) { return false; } // Check each element for (size_t i = 0; i < a1->size; i++) { if (a1->d[i] != a2->d[i]) { return false; } } // Succes return true; } bool array_equals2(const array* a, const double* data) { // Check each element for (size_t i = 0; i < a->size; i++) { if (a->d[i] != data[i]) { return false; } } // Succes return true; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* julia.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: bdruez <bdruez@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/16 14:54:42 by bdruez #+# #+# */ /* Updated: 2021/09/24 15:07:47 by bdruez ### ########.fr */ /* */ /* ************************************************************************** */ #include "fractol.h" int julia_pixel(int x, int y, t_data *data) { t_complex z; t_complex c; t_complex tmp; int iter; iter = 0; z = get_complex_value(x, y, data->view); c = get_complex_from_angle((data->range / 100) * 2 * M_PI); while (z.rl * z.rl + z.im * z.im < DIV_VAL & iter < MAX_ITER) { tmp.rl = z.rl * z.rl - z.im * z.im + c.rl; tmp.im = 2 * z.rl * z.im + c.im; if (z.rl == tmp.rl && z.im == tmp.im) { iter = MAX_ITER; break ; } z.rl = tmp.rl; z.im = tmp.im; iter++; } return (iter); } void get_julia_view(t_view *view) { view->x_min = -2.0f; view->x_max = 2.0f; view->y_min = -2.0f; view->y_max = 2.0f; } t_color julia_color(int iter) { t_color color; color = init_color(); color.s = 1.0f; color.v = 1.0f; if (iter == MAX_ITER) return (color); if (iter < 1) return (color); color.h = fmod(((double)iter * COLOR_SCALING), 360.0f); hsv_to_trgb(&color); return (color); }
C
#include <stdio.h> #include <math.h> #define OK 0 #define ERROR 1 #define EPS 1e-7 double side_len(double f_x, double s_x, double f_y, double s_y) { return sqrt(pow(s_x - f_x, 2) + pow(s_y - f_y, 2)); } double area(double x1, double y1, double x2, double y2, double x3, double y3) { double len_fs, len_ss, len_ts; double p, s; len_fs = side_len(x1, x2, y1, y2); len_ss = side_len(x2, x3, y2, y3); len_ts = side_len(x3, x1, y3, y1); p = (len_fs + len_ss + len_ts) / 2; s = sqrt(p * (p - len_fs) * (p - len_ss) * (p - len_ts)); return s; } int main(void) { int check_f, check_s, check_t; double x1, y1, x2, y2, x3, y3; double s; printf("Введите координаты (x,y) первой вершины: "); check_f = scanf("%lf%lf", &x1, &y1); printf("Введите координаты (x,y) второй вершины: "); check_s = scanf("%lf%lf", &x2, &y2); printf("Введите координаты (x,y) третьей вершины: "); check_t = scanf("%lf%lf", &x3, &y3); if (check_f == 2 && check_s == 2 && check_t == 2) { s = area(x1, y1, x2, y2, x3, y3); if (s > EPS) { printf("Значение площади: "); printf("%.5f\n", s); return OK; } printf("Исходные данные введены неправильно!"); return ERROR; } printf("Исходные данные введены неправильно!"); return ERROR; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int print_floats(char * string_of_floats) { char * pEnd, * pStart; float f1; pStart = string_of_floats; pEnd = string_of_floats; int len = strlen(string_of_floats); int char_size = sizeof(char); while (1) { printf("Before: %p %p\n",pStart,pEnd); f1 = strtof(pStart,&pEnd); // if no result then pStart == pEnd if (pEnd == pStart) { printf("Breaking, index=%d, length = %d\n",(pEnd - string_of_floats)/char_size,len); return (1); } printf("%0.5f\n",f1); printf("After: %p %p\n\n",pStart,pEnd); pStart = pEnd; // Move the starting position to the end of the last read } } int main(void) { char * str = "334.5 666.5 -123 3.1415926536"; printf("hello, World!\n"); return print_floats(str); }
C
#include <stdio.h> #include <util.h> #include <math.h> #include <stdlib.h> #include "example0.h" #define MEASURE_THRESHOLD 1e7 #define MEASURE_REPETITIONS 15 typedef void (*pointwise_add)(double *x, double* y, double *z, int N); double measure(pointwise_add f, double *x, double *y, double *z, int N) { int runs = 1; int multiplier = 1; uint64_t cycles; double results[MEASURE_REPETITIONS + 1]; do { runs = runs * multiplier; cycles_count_start(); for (int i = 0; i < runs; i += 1) { f(x, y, z, N); } cycles = cycles_count_stop(); multiplier = (int) ceil ( (MEASURE_THRESHOLD * 100.0) / (cycles * 1.0 * runs) + 1.0 ); } while (multiplier > 2); for (int i = 0; i < MEASURE_REPETITIONS; i += 1) { cycles_count_start(); for (int j = 0; j < runs; ++j) { f(x, y, z, N); } cycles = cycles_count_stop(); results[i] = (double) cycles / (double) runs; } qsort(results, MEASURE_REPETITIONS, sizeof(double), cmp_doubles); return results[MEASURE_REPETITIONS / 2]; } int main() { char str_size [1024]; print_compiler_and_system_info(); printf("\n"); printf("=======================================================================================================\n"); printf("= example0\n"); printf("=======================================================================================================\n"); printf("\n"); printf(" N | size | SIMD | SISD \n"); printf("---------------------------------------------------------------------------------------\n"); for (int N = 32; N < 262144; N *= 2) { double * x = (double *) malloc(sizeof(double) * N); double * y = (double *) malloc(sizeof(double) * N); double * z = (double *) malloc(sizeof(double) * N); for (int i = 0; i < N; i += 1) { x[i] = get_random(10); y[i] = get_random(10); } double sisd_cycles = measure(pointwise_add_sisd, x, y, z, N); double simd_cycles = measure(pointwise_add_simd, x, y, z, N); double perf_sisd = (double) N / sisd_cycles; double perf_simd = (double) N / simd_cycles; print_size(3 * N * sizeof(double), str_size); printf(" %7d | %s | %3.2lf F/C %12.2lf cycles | %3.2lf F/C %12.2lf cycles \n", N, str_size, perf_simd, simd_cycles, perf_sisd, sisd_cycles); free(x); free(y); free(z); } printf("\n"); return 0; }
C
/** Relay (2 channels) */ /** Initialize =========1=========2=========3=========4=========5=========6=========7========*/ MyMessage msgA01a( A01a, V_STATUS ); MyMessage msgA01b( A01b, V_STATUS ); /** Setup =========1=========2=========3=========4=========5=========6=========7========*/ void setupA01ab(){ pinMode(pinA01a, OUTPUT); // set relay pin in output mode pinMode(pinA01b, OUTPUT); // set relay pin in output mode //digitalWrite(pinA01a, loadState(A01a) ? 0 : 1); // load state from eeprom //digitalWrite(pinA01b, loadState(A01b) ? 0 : 1); // load state from eeprom } /** Loop =========1=========2=========3=========4=========5=========6=========7========*/ // nothing to loop /** Receive =========1=========2=========3=========4=========5=========6=========7========*/ void receiveA01ab(const MyMessage &message){ if (message.type == V_STATUS) { if (message.sensor == A01a){ digitalWrite(pinA01a, message.getBool() ? 0 : 1); // Toggle relay state //saveState(A01a,message.getBool()); // save state to eeprom Serial.print(F("Toggle - New state of A01a is ")); Serial.println(message.getBool()); } if (message.sensor == A01b){ digitalWrite(pinA01b, message.getBool() ? 0 : 1); // Toggle relay state //saveState(A01b,message.getBool()); // save state to eeprom Serial.print(F("Toggle - New state of A01b is ")); Serial.println(message.getBool()); } } }
C
#include <stdio.h> int main() { int * pt; int valores[100], i, count, tamanho, contador; pt = valores; printf("Digite o tamanho do array: "); scanf("%d", &tamanho); for(i = 0; i < tamanho; i++) { printf("Informe um valor: "); scanf("%d", &valores[i]); } for(i = 0; i < tamanho; i++) { printf("Elementos inseridos %d\n ", valores[i]); } printf("O tamanho do vetor é %d\n", sizeof(pt) * tamanho); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> /* ** clear the buffer to avoid scanf problems */ void clear_buffer(void) { int c; while((c=getchar()) != EOF && c != '\n'); } /* ** Say to the player that the number he chose is bigger or smaller (or same) as the "nombre mystere" ** Also check if the choice is in the good interval */ void verif_choice(signed short p_number_tested, signed short p_number, signed short p_max_value) { if (p_number_tested >= 1 && p_number_tested <= p_max_value) { if (p_number_tested > p_number) printf("Le nombre choisi est trop GRAND !\n"); else if (p_number_tested < p_number) printf("le nombre choisi est trop PETIT !\n"); else printf("Et c'est le GG!\n"); } else printf("ATTENTION ! Entrez un nombre compris entre 1 et %hd !\n", p_max_value); } /* ** Generate a random integer between 1 and p_max_value */ int gen_number(signed short p_max_value) { return (rand() % (p_max_value)) + 1; } /* ** check if the level chose by the player is 1, 2 or 3 and nothing else */ short verif_level(int p_ret_scanf, signed short p_level) { clear_buffer(); if(p_ret_scanf == 1) { switch (p_level) { case 1: case 2: case 3: return (1); break; default: return (0); } } else return(0); } /* ** Just printf the main menu */ void show_menu(void) { printf("\nBienvenue dans le jeu du PLUS OU MOINS !\n"); printf("========================================\n"); printf("Entrez le niveau de difficulte desire:\n"); printf("-------------------------------------\n"); printf("1 - Nombre mystere compris entre 1 et 100\n"); printf("2 - Nombre mystere compris entre 1 et 1000\n"); printf("3 - Nombre mystere compris entre 1 et 10000!!!\n"); printf("C'est a vous: "); } /* ** Just printf the beginning of the game width the level and the interval */ void show_msg_go(signed short p_level) { printf("\n===========================\n"); printf("SUPER ! Allez c'est parti !\n"); printf("===========================\n"); switch(p_level) { case 1: printf("Niveau 1: Facile !\n"); printf("===========================\n"); printf("Intervalle [1;100] !\n"); break; case 2: printf("Niveau 2: Moyen !\n"); printf("===========================\n"); printf("Intervalle [1;1000] !\n"); break; case 3: printf("Niveau 3: HardCore !\n"); printf("===========================\n"); printf("Intervalle [1;10000] !\n"); break; default: printf("Error, probleme dans la fonction show_msg_error\n"); } printf("===========================\n\n"); } /* ** Select the level by the user */ signed short select_level(void) { signed short result_scanf_level; signed short level; do { show_menu(); result_scanf_level = scanf("%hd", &level); } while (verif_level(result_scanf_level, level) != 1); return level; } /* ** return the max value of the "Nombre Mystere" knowing the level */ signed short select_max_value(signed short p_level) { switch(p_level) { case 1: return (100); break; case 2: return (1000); break; case 3: return (10000); break; default: return (0); } } /* ** Do a complete game from generating the mystery number and ask until the player find it */ void game(void) { signed short number; signed short number_tested; signed int count; char *plural; signed short max_value; signed short level; plural = "s"; count = 0; level = select_level(); max_value = select_max_value(level); number = gen_number(max_value); show_msg_go(level); while (number_tested != number) { count++; printf("Entrez un nombre: "); scanf("%hd", &number_tested); getchar(); verif_choice(number_tested, number, max_value); } if (count == 1) plural = ""; printf("Bravo vous avez trouve !\nLe nombre mystere etait %d !\nVous avez trouve en %d essai%s !\n", number, count, plural); printf("Veuillez appuyer sur [ENTREE] pour nous communiquer votre satisfaction !"); } /* ** Ask to the player if he wants a new game, and return the answer */ short ask_continue() { char c_continue; signed short bool_loop; do { clear_buffer(); printf("\n"); printf("Yeah ! Voulez-vous refaire une partie ? (O/N): "); bool_loop = scanf("%c", &c_continue); } while ((bool_loop != 1) || (c_continue != 'O' && c_continue != 'N')); if(c_continue == 'O') return (1); else return (0); } /* ** Main.. */ int main(void) { signed short continue_bool; srand(time(NULL)); continue_bool = 1; while(continue_bool == 1) { game(); continue_bool = ask_continue(); } printf("\n========================================================\n"); printf("Au revoir ! On s'est bien marres ! A Tot-Bien j'espere !"); printf("\n========================================================\n\n"); return (0); }
C
/* =========================================== * Process structure * Keeps process ID, status and exec time * =========================================== */ #ifndef __PROCESS__ #define __PROCESS__ typedef struct _process { int pid; int status; } process; /* ============================================================================= * process_alloc * ============================================================================= */ process* process_alloc(int pid, int status); /* ============================================================================= * process_free * ============================================================================= */ void process_free(process* proc); /* ============================================================================= * process_print * ============================================================================= */ void process_print(process* proc); #endif //__PROCESS__
C
#include <stdio.h> #include <math.h> #define N 7 #define REP(i, n) for (int i = 0; i < (n); ++i) #define REPR(i, n) for (int i = n; i >= 0; --i) #define FOR(i, n, m) for (int i = m; i < n; i++) int main(void) { int n; double a[N][N+1], x[N]; printf("上三角型連立1次方程式の解法\n"); while (1) { printf("未知数の個数 n を入力してください。 (1 < n < 7) n = "); scanf("%d%*c", &n); if (n <= 1 || n >= 7) { continue; } printf("係数と右辺の値を入力してください\n"); REP(i, n) { printf("第%d式:\n", i+1); FOR(j, n+1, i) { if (j == n) { printf("\n\t右辺の値 = "); } else { printf("\tx%dの係数 = ", j+1); } scanf("%lf%*c", &a[i][j]); } } char z; printf("正しく入力しましたか。(y/n)"); scanf("%c%*c", &z); if (z == 'y') break; } /* * 1 -2 3 0.5 * 0 1 -1 0.1 * 0 0 1 -1.1 */ printf("行列\n"); REP(i, n) { REP(j, n+1) { printf("%.2lf ", a[i][j]); } printf("\n"); } REP(i, n) { double p = a[i][i]; // fabs: 浮動小数点の絶対値 if (fabs(p) < 1.0e-6) { printf("一意解をもちません\n"); return 0; } FOR(j, n+1, i) { a[i][j] /= p; } } // 逆進代入 REPR(i, n-1) { // 初期値 n - 1 double s = 0.0; printf("%d行目です。\n", i); FOR(j, n, i+1) { // 初期値 i + 1 printf("s += %lf * %lf\n", a[i][j], x[j]); s += a[i][j] * x[j]; } x[i] = a[i][n] - s; printf("%lf - %lf = %lf\n", a[i][n], s, x[i]); } printf("上三角型連立1次方程式の解\n"); REP(i, n) { printf("\tx%d = %10.6lf\n", i+1, x[i]); } return 0; }
C
#include "server_utils.h" #include "queue.h" #include "dynamic_library_loader.h" int main(){ // // Checking create named socket function if(0!=make_named_socket(8080, 1)) printf("Testcase-1 Passed\n"); else printf("Testcase-1 Failed\n"); // // Check createQueue Function Queue* q = createQueue(5); if(q && q->cap==5) printf("Testcase-2 Passed\n"); else printf("Testcase-2 Failed\n"); int *cli = malloc(sizeof(int)); *cli = 2; char *dll = malloc(64); strcpy(dll, "/lib/x86_64-linux-gnu/libm.so.6"); char *func = malloc(10); strcpy(func, "sin"); char **args = malloc(2); args[0] = malloc(5); args[1] = malloc(5); memset(args[0], 0, sizeof(args[0])); memset(args[1], 0, sizeof(args[1])); strcpy(args[0], "5.0"); strcpy(args[1], "2.0"); Request* req = createRequest(dll, func, args); // Check createRequest function if(!strcmp(req->dll_name, dll) && !(strcmp(req->func_name,func)) && !(strcmp(args[0], req->func_args[0])) && !(strcmp(args[1], req->func_args[1]))) printf("Testcase-3 Passed\n"); else printf("Testcase-3 Failed\n"); Data* d = createData(cli, req); // Check createData function if(d->client_soc==cli && d->req==req) printf("Testcase-4 Passed\n"); else printf("Testcase-4 Failed\n"); int enq = enqueue(q,d); // Check whether enqueue is working if(enq==1) printf("Testcase-5 Passed\n"); else printf("Testcase-5 Failed\n"); for(int i=0; i<5; i++) enq = enqueue(q,d); // Check for max capacity limit of enqueue function if(enq==-1) printf("Testcase-6 Passed\n"); else printf("Testcase-6 Failed\n"); // check working of dequeue function Data* data = dequeue(q); if(data) printf("Testcase-7 Passed\n"); else printf("Testcase-7 Failed\n"); for(int i=0; i<5; i++) data = dequeue(q); // Check for dequeue from empty queue if(data==NULL) printf("Testcase-8 Passed\n"); else printf("Testcase-8 Failed\n"); char* ans = dll_func(dll, func, args, 1); // checking for sin if(strcmp(ans,"-0.95892")==0) printf("Testcase-9 Passed\n"); else printf("Testcase-9 Failed\n"); // checking for cos memset(func, 0, sizeof(func)); strcpy(func, "cos"); ans = dll_func(dll, func, args, 1); if(strcmp(ans,"0.28366")==0) printf("Testcase-10 Passed\n"); else printf("Testcase-10 Failed\n"); // checking for tan memset(func, 0, sizeof(func)); strcpy(func, "tan"); ans = dll_func(dll, func, args, 1); if(strcmp(ans,"-3.3805")==0) printf("Testcase-11 Passed\n"); else printf("Testcase-11 Failed\n"); // checking for pow memset(func, 0, sizeof(func)); strcpy(func, "pow"); ans = dll_func(dll, func, args,1); if(strcmp(ans,"25")==0) printf("Testcase-12 Passed\n"); else printf("Testcase-12 Failed\n"); // checking for sinh memset(func, 0, sizeof(func)); strcpy(func, "sinh"); ans = dll_func(dll, func, args, 1); if(strcmp(ans,"74.203")==0) printf("Testcase-13 Passed\n"); else printf("Testcase-13 Failed\n"); // checking for cosh memset(func, 0, sizeof(func)); strcpy(func, "cosh"); ans = dll_func(dll, func, args, 1); if(strcmp(ans,"74.21")==0) printf("Testcase-14 Passed\n"); else printf("Testcase-14 Failed\n"); // checking for tanh memset(func, 0, sizeof(func)); strcpy(func, "tanh"); ans = dll_func(dll, func, args, 1); if(strcmp(ans,"0.99991")==0) printf("Testcase-15 Passed\n"); else printf("Testcase-15 Failed\n"); // checking for log memset(func, 0, sizeof(func)); strcpy(func, "log"); ans = dll_func(dll, func, args, 1); if(strcmp(ans,"1.6094")==0) printf("Testcase-16 Passed\n"); else printf("Testcase-16 Failed\n"); // checking for exp memset(func, 0, sizeof(func)); strcpy(func, "exp"); ans = dll_func(dll, func, args, 1); if(strcmp(ans,"148.41")==0) printf("Testcase-17 Passed\n"); else printf("Testcase-17 Failed\n"); // checking for sqrt memset(func, 0, sizeof(func)); strcpy(func, "sqrt"); ans = dll_func(dll, func, args, 1); if(strcmp(ans,"2.2361")==0) printf("Testcase-18 Passed\n"); else printf("Testcase-18 Failed\n"); // checking for unsupported function memset(func, 0, sizeof(func)); strcpy(func, "abs"); ans = dll_func(dll, func, args, 1); if(strcmp(ans,"Unsupported dll name or function name")==0) printf("Testcase-19 Passed\n"); else printf("Testcase-19 Failed\n"); // checking for unsupported dll memset(dll, 0, sizeof(dll)); strcpy(dll, "/lib/x86_64-linux-gnu/libm.so.5"); ans = dll_func(dll, func, args, 1); if(strcmp(ans,"DLL not supported")==0) printf("Testcase-20 Passed\n"); else printf("Testcase-20 Failed\n"); // checking for invalid arguments memset(dll, 0, sizeof(dll)); strcpy(dll, "/lib/x86_64-linux-gnu/libm.so.6"); memset(func, 0, sizeof(func)); strcpy(func, "pow"); memset(args[0], 0, sizeof(args[0])); strcpy(args[0], "55ab"); ans = dll_func(dll, func, args, 1); if(strcmp(ans,"Invalid Arguments")==0) printf("Testcase-21 Passed\n"); else printf("Testcase-21 Failed\n"); free(q); free(cli); free(req); free(d); return 0; }
C
/* Nama Kelompok 2: - Stephania Getrudis Inaconta Sadipun (2008561043) - I Made Alit Darma Putra (2008561045) - I Dewa Made Candra Wiguna Marcelino (2008561048) - Maharani Putri Suari (2008561058) Jurusan/Kelas : Informatika/C Informasi Program: - Program merupakan program menentukan graph euler serta lintasan atau circuit euler dengan algoritma fleury. - Dibuat menggunakan sistem operasi Windows, akan ada beberapa syntax yang tidak jalan jika program di jalankan pada sistem operasi berbeda. */ #include <stdio.h> #include <stdlib.h> void title(){ printf(".######.##.....######.##..##.#####..##..##.........####..##......####...####..#####..######.######.##..##.##...##.\n"); printf(".##.....##.....##.....##..##.##..##..####.........##..##.##.....##.....##..##.##..##...##.....##...##..##.###.###.\n"); printf(".####...##.....####...##..##.#####....##..........######.##.....##.###.##..##.#####....##.....##...######.##.#.##.\n"); printf(".##.....##.....##.....##..##.##..##...##..........##..##.##.....##..##.##..##.##..##...##.....##...##..##.##...##.\n"); printf(".##.....######.######..####..##..##...##..........##..##.######..####...####..##..##.######...##...##..##.##...##.\n"); printf("..................................................................................................................\n\n"); } void cetak(int n, int graph[][n]){ printf("\nGraph :\n"); for(int i = 0; i < n; i++){ //mencetak matriks for(int j = 0; j < n; j++){ printf("%d ", graph[i][j]); } printf("\n"); } } void hitung_derajat(int vertex, int graph[][vertex], int derajat[]){ int sum = 0; for(int i = 0; i < vertex; i++){ for(int j = 0; j<vertex; j++){ sum+=graph[i][j]; } derajat[i] = sum; sum = 0; } } int cek_terhubung(int n, int graph[][n]){ int jumlah = 0, func_graph[n][n]; for(int i = 0; i<n; i++){ //menyalin isi graph untuk di proses for(int j = 0; j<n; j++){ func_graph[i][j] = graph[i][j]; } } for(int i = 1; i<n; i++){ for(int j = 0; j<n; j++){ if(func_graph[0][j] == 0 && func_graph [i][j] == 1){ func_graph[0][j] = func_graph[i][j]; } } } for(int i = 0 ; i<n; i++){ //menjumlahkan baris pertama matriks jumlah+=func_graph[0][i]; } if(jumlah == n) return 1; else return 0; } int isEularian(int vertex, int graph[][vertex], int derajat[]){ //Mengecek apakah semua vertex terhubung if(cek_terhubung(vertex, graph) == 0) return 0; //Menghitung banyaknya vertex dengan derajat ganjil int ganjil = 0; for(int i = 0; i<vertex; i++) if(derajat[i] % 2 == 1) ganjil++; if(ganjil > 2) return 0; return (ganjil == 0)? 2:1; } int dfsCount(int vertex, int graph[][vertex], int prev, int visited[]){ visited[prev] = 1; int count = 1; for(int i = 0; i<vertex; i++){ if(graph[prev][i] == 1 && !visited[i]){ count+= dfsCount(vertex, graph, i, visited); } } return count; } void removeEdge(int vertex, int graph[][vertex], int prev, int next){ graph[prev][next] = graph[next][prev] = 0; } void addEdge(int vertex, int graph[][vertex], int prev, int next){ graph[prev][next] = graph[next][prev] = 1; } int isValidNext(int vertex, int graph[][vertex], int prev, int next){ int count = 0; int visited[vertex]; for(int i = 0; i<vertex; i++){ visited[i] = 0; if(graph[prev][i] == 1) count++; } if(count == 0) return 0; else if(count == 1) return 1; int count1 = dfsCount(vertex, graph, prev, visited); removeEdge(vertex, graph, prev, next); for(int i = 0; i<vertex; i++){ visited[i] = 0; } int count2 = dfsCount(vertex, graph, prev, visited); addEdge(vertex, graph, prev, next); return (count1 > count2)? 0:1; } void find_jalan(int vertex, int graph [][vertex], int prev){ for(int i = 0; i<vertex; i++){ if(graph[prev][i] == 1 && isValidNext(vertex, graph, prev, i)){ printf("%d - %d ", prev + 1, i + 1); removeEdge(vertex, graph, prev, i); find_jalan(vertex, graph, i); } } } int main (){ char ulang = 'y'; int vertex, choose_now = 1, vertex_now = 0,sum = 0; do{ system("cls"); title(); printf("Ketik banyaknya vertex: "); scanf("%d%*c", &vertex); int graph[vertex][vertex], derajat[vertex]; //Input graph for(int i = 0; i<vertex; i++){ for(int j = 0; j<vertex; j++){ if(i != j){ printf("Jika vertex %d dan vertex %d berhubungan ketik 1, 0 jika tidak :", i+1, j+1); scanf("%d%*c", &graph[i][j]); }else{ graph[i][j] = 0; } } } cetak(vertex, graph); //Menghitung derajat vertex hitung_derajat(vertex, graph, derajat); //Mengecek jenis graph dengan sifat-sifat yang ada int cek = isEularian(vertex, graph, derajat); if(cek == 0){ printf("\nGraph merupakan graph non-euler\n"); }else{ if(cek == 1){ printf("\nGraph merupakan graph semi-euler\n"); }else{ printf("\nGraph merupakan graph euler\n"); } int start = 0; //Mencari vertex dengan derajat ganjil petama for(int i = 0; i<vertex; i++){ if(derajat[i] % 2 == 1){ start = i; break; } } printf("Edge yang dipilih : "); find_jalan(vertex, graph, start); } printf("\n\nApakah anda ingin mengulang (y/n) :"); scanf("%c%*c", &ulang); }while(ulang == 'y' || ulang == 'Y'); printf("\n\nAkhir dari program\n"); return 0; }
C
/// \file /// A very simple unit test framework. #pragma once #include <signal.h> #include <stdlib.h> #include "util/log.h" #include "util/util.h" /// Exit if \p \_\_EXPR\_\_ evaluates to `false`. #define CHECK(__EXPR__) \ do \ { \ if (UNLIKELY(!(__EXPR__))) \ { \ error("CHECK(%s) failed\n in: %s\n at: %s:%i\n", STR(__EXPR__), __func__, \ __FILE__, __LINE__); \ exit(EXIT_FAILURE); \ } \ } while (0) /// @cond Doxygen_Suppress void unit_test_signal_test_setup(int expected_signal); int unit_test_signal_test_get_seen_signal(); void unit_test_signal_test_reset(); //! @endcond /// Exit if \p expression does not raise \p \_\_signal\_\_. /// \warning Do not execute this macro concurrently. #define CHECK_RAISES(expression, __signal__) \ do \ { \ unit_test_signal_test_setup(__signal__); \ (void)(expression); \ CHECK(unit_test_signal_test_get_seen_signal() == (__signal__)); \ unit_test_signal_test_reset(); \ } while (0)
C
#include <stdio.h> #include <ctype.h> #include <string.h> #include <stdlib.h> #include "command.h" #include "room.h" // build the rooms and return spawn. struct room* initRoom(const char name[21],const char env[21]) { // init our test setup only struct room *spawn = malloc(sizeof(struct room)); if(spawn == NULL) { errAbort("ERROR!"); } spawn->id = 0; strcpy(spawn->env, env); strcpy(spawn->name, name); return spawn; } void connectRoom(struct room *rma, int dira, struct door *dr, struct room *rmb) { dr->nxt = rmb; rma->trans[dira] = dr; } void connectRooms(struct room *rma, int dira, struct door *dra, struct room *rmb, struct door *drb) { int dirb = dira+2; if(dirb>4) { dirb-=4; } if(dirb<0) { dirb+=4; } rma->trans[dira] = dra; dra->nxt = rmb; rmb->trans[dirb] = drb; drb->nxt = rma; } struct door* initDoor(const char name[21], int id, int isLocked, int code) { struct door *door = malloc(sizeof(struct door)); if(door == NULL) { errAbort("ERROR!"); } strcpy(door->name, name); door->code = code; door->isLocked = isLocked; door->id = id; return door; } void addObjectToRoom(struct object *object, struct room *room) { if(room->objsize <4) { room->objs[room->objsize] = object; room->objsize++; } }
C
# include <stdio.h> # include <stdlib.h> int main(){ char c="c"; int i=1; long l=1; printf("&c: %p\n",&c); printf("&c: %ul\n",&c); printf("&i: %p\n",&i); printf("&i: %ul\n",&i); printf("&l: %p\n",&l); printf("&l: %ul\n",&l); char *cp=&c; int *ip=&i; long *lp=&l; printf("cp: %p\n",cp); printf("ip: %p\n",ip); printf("lp: %p\n",lp); *cp="a"; *ip=2; *lp=3; printf("c: %c\n",c); printf("i: %d\n",i); printf("l: %ld\n",l); unsigned int ui=128; int *uip1=&ui; char *uip2=&ui; printf("uip1: %p uip1 points to: %u\n",uip1,*uip1); printf("uip2: %p uip2 points to: %u\n",uip2,*uip2); printf("ui in decimal: %u\n",ui); printf("ui in hexadecimal: %x\n",ui); printf("1st byte:%u\n",*uip2); uip2++; printf("2nd byte:%u\n",*uip2); uip2++; printf("3rd byte:%u\n",*uip2); uip2++; printf("4th byte:%u\n",*uip2); uip2-=3; (*uip2)++; printf("1st byte:%hhu\n",*uip2); uip2++; (*uip2)++; printf("2nd byte:%hhu\n",*uip2); uip2++; (*uip2)++; printf("3rd byte:%hhu\n",*uip2); uip2++; (*uip2)++; printf("4th byte:%hhu\n",*uip2); uip2-=3; *uip2+=16; printf("1st byte:%hhu\n",*uip2); uip2++; *uip2+=16; printf("2nd byte:%hhu\n",*uip2); uip2++; *uip2+=16; printf("3rd byte:%hhu\n",*uip2); uip2++; *uip2+=16; printf("4th byte:%hhu\n",*uip2); printf("modified value after all procedures in decimal: %u\n",*uip1); printf("modified value after all procedures in hexadecimal: %x\n",*uip1); return 0; }
C
//Name: Atharva Mainkar //Group: Alex Jaziel Atharva //Section: Lab 504/Lecture 004 //Problem: Project //Date: 5/5/2020 #include <stdio.h> #include <stdlib.h> #include <string.h> void topupBalance() { FILE *fp; char playerName[100]; char name[20][100]; int i,x, money[20], gain[20], addMoney, a=0; printf("Please enter the player name\n"); scanf("%s",&playerName); printf("How much money do you want to add to your balance?\n"); scanf("%d",&addMoney); fp=fopen("players.txt","r"); if(fp==NULL) { printf("FILE DOES NOT EXIST!"); exit(EXIT_FAILURE); } for(i=0;!feof(fp);i++) { fscanf(fp,"%s %d %d", &name[i], &money[i], &gain[i]); if(strcmp(name[i],playerName)==0) { money[i]=money[i]+addMoney; a=1; } } if(a==0) { printf("The player does not exist.\n"); } fclose(fp); fp=fopen("players.txt","w"); for(x=0;x+1<i;x++) { fprintf(fp,"%s %d %d\n",name[x], money[x], gain[x]); } fclose(fp); } void topPlayersbyBalance() { FILE *fp; char name[20][100]; int i,x, money[20], gain[20], addMoney,q,r,moneycopy[20],temp; fp=fopen("players.txt","r"); if(fp==NULL) { printf("FILE DOES NOT EXIST!"); exit(EXIT_FAILURE); } for(i=0;!feof(fp);i++) { fscanf(fp,"%s %d %d", &name[i], &money[i], &gain[i]); } --i; for(q=0;q<=i;q++) { moneycopy[q]=money[q]; //printf("%s\n",name[q]); } for (q = 0; q < i; q++) { for (r = q + 1; r < i; r++) { if(moneycopy[q] < moneycopy[r]) { temp = moneycopy[q]; moneycopy[q] = moneycopy[r]; moneycopy[r] = temp; } } } for(q=0;q<=4;q++) { for(r=0;r<=i;r++) { if(money[r]==moneycopy[q]) { printf("%s %d %d\n",name[r],money[r],gain[r]); } } } printf("\n"); } void topPlayersbyGain() { FILE *fp; char name[20][100]; int i,x, money[20], gain[20], addMoney,q,r,moneycopy[20],temp; fp=fopen("players.txt","r"); if(fp==NULL) { printf("FILE DOES NOT EXIST!"); exit(EXIT_FAILURE); } for(i=0;!feof(fp);i++) { fscanf(fp,"%s %d %d", &name[i], &money[i], &gain[i]); } --i; for(q=0;q<=i;q++) { moneycopy[q]=gain[q]; //printf("%s\n",name[q]); } for (q = 0; q < i; q++) { for (r = q + 1; r < i; r++) { if(moneycopy[q] < moneycopy[r]) { temp = moneycopy[q]; moneycopy[q] = moneycopy[r]; moneycopy[r] = temp; } } } for(q=0;q<=4;q++) { for(r=0;r<=i;r++) { if(gain[r]==moneycopy[q]) { printf("%s %d %d\n",name[r],money[r],gain[r]); } } } printf("\n"); } void playGame() { FILE *fp; char playerName[100]; char name[20][100]; int i, x, money[20], gain[20], a=0, pos; int dice1, dice2, sum, pointvalue, count, num; fp=fopen("players.txt","r"); if(fp==NULL) { printf("FILE DOES NOT EXIST!"); exit(EXIT_FAILURE); } for(i=0;!feof(fp);i++) { fscanf(fp,"%s %d %d", &name[i], &money[i], &gain[i]); } fclose(fp); printf("Please enter your full name\n"); scanf("%s",playerName); for(x=0;i>x;x++) { if(strcmp(playerName,name[x]) == 0) { a=1; pos=x; } } for(;;) { if(a == 1) { if(money[pos] <= 0) { printf("The given player has an insufficient amount of money to keep playing.\n"); break; } else { printf("Press Enter to Roll the dice.\n"); getchar(); getchar(); dice1=(rand()%6)+1; dice2=(rand()%6)+1; sum = dice1 + dice2; printf("\nThe values of the dices are %d and %d whose sum is %d.\n",dice1,dice2,sum); } if(sum == 7 || sum == 11) { money[pos]+=10; gain[pos]+=10; printf("You win the game. Your current balance is %d.\n",money[pos]); } else if(sum == 2 || sum == 3 || sum == 12) { money[pos]-=1; gain[pos]-=1; printf("You lost the game. Your current balance is %d.\n",money[pos]); } else { pointvalue = sum; for(;;) { printf("Press Enter to Roll the dice.\n"); getchar(); dice1=(rand()%6)+1; dice2=(rand()%6)+1; sum = dice1 + dice2; printf("\nThe values of the dices are %d and %d whose sum is %d.\n",dice1,dice2,sum); if(sum == pointvalue) { money[pos]+=10; gain[pos]+=10; printf("You win the game. Your current balance is %d.\n",money[pos]); break; } else if(sum == 7) { money[pos]-=1; gain[pos]-=1; printf("You lost the game. Your current balance is %d.\n",money[pos]); break; } } } printf("Play another game? 0 for yes/1 for no\n"); scanf("%d",&num); if(num == 0) { continue; } else break; } else { printf("Player does not exist\n"); break; } count++; } fp=fopen("players.txt","w"); for(x=0;x+1<i;x++) { fprintf(fp,"%s %d %d\n",name[x], money[x], gain[x]); } fclose(fp); } int main() { int menuSelect=1; while(menuSelect!=4) { printf("Select one of the following options\n0)Top up balance\n1) play game\n2) top 5 players by balance\n3) top 5 winners by what they have won\n4) exit the game\n"); scanf("%d",&menuSelect); if(menuSelect==0) { topupBalance(); } if(menuSelect==1) { playGame(); } if(menuSelect==2) { topPlayersbyBalance(); } if(menuSelect==3) { topPlayersbyGain(); } } return 0; }
C
/****************************************************************************************** * * Filename: summa.c * Purpose: A paritally implemented program for MSCS6060 HW. Students will complete * the program by adding SUMMA implementation for matrix multiplication C = A * B. * Assumptions: A, B, and C are square matrices n by n; * the total number of processors (np) is a square number (q^2). * To compile, use * mpicc -o summa summa.c * To run, use * mpiexec -n $(NPROCS) ./summa *********************************************************************************************/ #include <stdio.h> #include <time.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "mpi.h" #define min(a, b) ((a < b) ? a : b) // #define SZ 4 //Each matrix of entire A, B, and C is SZ by SZ. Set a small value for testing, and set a large value for collecting experimental data. /** * Allocate space for a two-dimensional array */ double **alloc_2d_double(int n_rows, int n_cols) { int i; double **array; array = (double **)malloc(n_rows * sizeof (double *));//Double pointer to point to rows start array[0] = (double *) malloc(n_rows * n_cols * sizeof(double));//Space allocation for entire matrix for (i=1; i<n_rows; i++) { array[i] = array[0] + i * n_cols;//Defining double pointer start location for 1st index after space alloc. } return array; } /** * Initialize arrays A and B with random numbers, and array C with zeros. * Each array is setup as a square block of blck_sz. **/ void initialize(double **lA, double **lB, double **lC, int blck_sz){ int i, j; double value; // Set random values...technically it is already random and this is redundant printf("\n"); for (i=0; i<blck_sz; i++) { for (j=0; j<blck_sz; j++) { lA[i][j] = (double)rand() / (double)RAND_MAX; lB[i][j] = (double)rand() / (double)RAND_MAX; // printf("%f ", lA[i][j]); lC[i][j] = 0.0; } // printf("\n"); } // printf("\n"); // for (i=0;i<blck_sz;i++) // { // for (j=0;j<blck_sz;j++) // { // printf("%f ", lA[i][j]); // } // printf("\n"); // } } /** * Perform the SUMMA matrix multiplication. * Follow the pseudo code in lecture slides. */ void matmul(double **my_A, double **my_B, double **my_C, int block_sz)//Outer product algo { for (int k=0;k<block_sz;k++) { for (int i=0;i<block_sz;i++) { for (int j=0;j<block_sz;j++) { // printf("%d\n", my_C[i][j]); my_C[i][j]+=(my_A[i][k] * my_B[k][j]); } } } // for (int i=0;i<block_sz;i++) // { // for (int j=0;j<block_sz;j++) // { // printf("%d ", my_A[i][j]); // } // printf("\n"); // } } int main(int argc, char *argv[]) { int world_size, rank; //process rank and total number of processes double t1, t2, time_total; // for timing int block_sz; // Block size length for each processor to handle int proc_grid_sz; // 'q' from the slides int SZ=840*9; srand(time(NULL)); // Seed random numbers /* insert MPI functions to 1) start process, 2) get total number of processors and 3) process rank*/ //Initialize MPI MPI_Init(&argc, &argv); // Get the number of processes MPI_Comm_size(MPI_COMM_WORLD, &world_size); // Get the rank of the process MPI_Comm_rank(MPI_COMM_WORLD, &rank); /* assign values to 1) proc_grid_sz and 2) block_sz*/ proc_grid_sz = (int)sqrt((double)world_size); block_sz=SZ/proc_grid_sz; if (SZ % proc_grid_sz != 0) { printf("Matrix size cannot be evenly split amongst resources!\n"); printf("Quitting....\n"); exit(-1); } // Create the local matrices on each process printf("Station0, process: %d", rank); double **A, **B, **C; A = alloc_2d_double(block_sz, block_sz); B = alloc_2d_double(block_sz, block_sz); C = alloc_2d_double(block_sz, block_sz); int row=0; int col=0; if(rank!=0) { row=proc_grid_sz/rank; col=proc_grid_sz%rank; } initialize(A, B, C, block_sz); double **buff_A=alloc_2d_double(block_sz, block_sz); double **buff_B=alloc_2d_double(block_sz, block_sz); //Dimensional Coordinates MPI_Comm grid_comm, row_comm, col_comm; int dimsizes[2]; int wraparound[2]; int coordinates[2]; int free_coords[2]; int reorder = 1; int my_rank, grid_rank, cart_rank_row, cart_rank_col; int row_test, col_test; int coordinates_row, coordinates_col; dimsizes[0] = dimsizes[1] = proc_grid_sz; wraparound[0] = wraparound[1] = 1; //Create grid comm MPI_Cart_create(MPI_COMM_WORLD, 2, dimsizes, wraparound, reorder, &grid_comm);//int MPI_Cart_create(MPI_Comm comm_old, int ndims, const int dims[],const int periods[], int reorder, MPI_Comm *comm_cart) //Get Rank in grid MPI_Comm_rank(grid_comm, &my_rank); //Get Co-ordinates in grid MPI_Cart_coords(grid_comm, my_rank, 2, coordinates); //Get rank in grid coordinates MPI_Cart_rank(grid_comm, coordinates, &grid_rank); //Free Coordinates for ROW based- multiple columns free_coords[0] = 0;//Disable Rows free_coords[1] = 1;//Enable Columns //Split by rules defined above and define row_comm MPI_Cart_sub(grid_comm, free_coords, &row_comm);//Create Sub Comm MPI_Comm_rank(row_comm, &cart_rank_row); //Rank of Sub Comm MPI_Cart_coords(row_comm, cart_rank_row, 1, &coordinates_row);//Coords of Sub Comm // for (int i=0;i<2;i++) // { // if(coordinates[1] == i)//If it is my column, then send to all other columns in row // { // row_test = my_rank; // printf("*** %d : element %d\n", my_rank, coordinates_row); // } // MPI_Bcast(&row_test, 1, MPI_INT, i, row_comm);//Send to all processes in row // printf("Process %d > coords = (%d, %d), row_test = %d\n", my_rank, coordinates[0], coordinates[1], row_test); // } //Free Coordinates for COL based- multiple rows free_coords[0] = 1;//Enable Rows free_coords[1] = 0;//Disable Columns //Split by rules defined above and define row_comm MPI_Cart_sub(grid_comm, free_coords, &col_comm);//Create Sub Comm MPI_Comm_rank(col_comm, &cart_rank_col); //Rank of Sub Comm MPI_Cart_coords(col_comm, cart_rank_col, 1, &coordinates_col);//Coords of Sub Comm // for (int i=0;i<2;i++) // { // if(coordinates[0] == i)//If it is my row, then send to all other rows in column // { // col_test = my_rank; // printf("*** %d : element %d\n", my_rank, coordinates_col); // } // MPI_Bcast(&col_test, 1, MPI_INT, i, col_comm);//Send to all processes in row // printf("Process %d > coords = (%d, %d), col_test = %d\n", my_rank, coordinates[0], coordinates[1], col_test); // } // Use MPI_Wtime to get the starting time t1 = MPI_Wtime(); int i, j; for ( int k = 0; k < proc_grid_sz; k++) { if(coordinates[1]==k)//Send A to all columns { // buff_A = (double **)malloc(block_sz * sizeof (double *)); // memcpy(buff_A[0], A[0], block_sz * sizeof (double *)*block_sz * block_sz * sizeof(double)); for( i=0;i<block_sz;i++) { memcpy(buff_A[i], A[i], block_sz*sizeof(double)); } // printf("\n"); // for (i=0;i<block_sz;i++) // { // for (j=0;j<block_sz;j++) // { // printf("%f ", buff_A[i][j]); // } // printf("\n"); // } } MPI_Bcast(&buff_A[0][0], block_sz*block_sz, MPI_DOUBLE, k, row_comm); if(coordinates[0]==k)//Send B to all rows { for( i=0;i<block_sz;i++) { memcpy(buff_B[i], B[i], block_sz*sizeof(double)); } // printf("\n"); // for (i=0;i<block_sz;i++) // { // for (j=0;j<block_sz;j++) // { // printf("%f ", buff_B[i][j]); // } // printf("\n"); // } } MPI_Bcast(&buff_B[0][0], block_sz*block_sz, MPI_DOUBLE, k, col_comm); if(coordinates[0]==k && coordinates[1]==k) { printf("SAME, process: %d \n", my_rank); // for (i=0;i<block_sz;i++) // { // for (j=0;j<block_sz;j++) // { // printf("%f ", C[i][j]); // } // printf("\n"); // } matmul(A, B, C, block_sz); // for (i=0;i<block_sz;i++) // { // for (j=0;j<block_sz;j++) // { // printf("%f ", C[i][j]); // } // printf("\n"); // } } else if(coordinates[0]==k) { matmul(buff_A, B, C, block_sz); } else if(coordinates[1]==k) { matmul(A, buff_B, C, block_sz); } else { printf("DIFFERENT, process: %d \n", my_rank); // for (i=0;i<block_sz;i++) // { // for (j=0;j<block_sz;j++) // { // printf("%f ", C[i][j]); // } // printf("\n"); // } matmul(buff_A, buff_B, C, block_sz); // for (i=0;i<block_sz;i++) // { // for (j=0;j<block_sz;j++) // { // printf("%f ", C[i][j]); // } // printf("\n"); // } } } // Use SUMMA algorithm to calculate product C // matmul(rank, proc_grid_sz, block_sz, A, B, C, row, col); // Use MPI_Wtime to get the finishing time t2 = MPI_Wtime(); // Obtain the elapsed time and assign it to total_time time_total=t2-t1; if (rank == 0) { // Print in pseudo csv format for easier results compilation printf("squareMatrixSideLength,%d,numMPICopies,%d,walltime,%lf\n", SZ, world_size, time_total); } // Destroy MPI processes MPI_Finalize(); return 0; }
C
#define F_CPU 1000000 // Snelheid van de CPU, met dit kristal en deze waarde, is het precies 1 seconde #include <avr/io.h> // Laadt de IO library, deze bevat de poorten #include <util/delay.h> // // Laadt de Delay library, nu kan je een delay instellen #include <stdio.h> // Laadt de stdio library, deze vat de meeste nodige onderdelen #include <avr/interrupt.h> // Dit is de library voor de interrupt volatile int roodCount = 255; // startwaarde voor rood volatile int groenCount = 1; // startwaarde voor groen volatile int blauwCount = 128; // startwaarde voor blauw int roodMath = -1; // rood bij elke pulse omlaag int groenMath = 1; // groen bij elke pulse omhoog int blauwMath = 1; // blauw bij elke pulse omhoog uint8_t i = 0; int main() { // Stel CLKRP register in. CLKPR = 0b10000000; // Zet de hoogste bit op 1 CLKPR = 0b00000000; // Zet alle bits op 0 sei(); // Interrupts activeren TCCR0B = 0b00000001; // Timer/Counter voor register B TIMSK0=(1<<TOIE0); // Specifieke interrupt aanzetten DDRD = 0b00000111; // Zet de richting van D0, D1 en D2 op output PORTD = 0b00000111; // Zet de poorten D0, D1 en D2 op hoog while(1) // Doe iets voor altijd { _delay_ms(40); // Wacht 40 miliseconden roodCount+= roodMath; // Doe rood + de waarde van roodMath blauwCount += blauwMath; // Doe blauw + de waarde van blauwMath groenCount += groenMath; // Doe groen + de waarde van groenMath if(roodCount == 0) // Als roodCount gelijk is als 0 { roodMath = 1; // Zet roodMath op 1 } if(roodCount == 255) // Als roodCount gelijk is aan 255 { roodMath = -1; // Zet roodMath op -1 } if(groenCount == 0) // Als groenCount gelijk is als 0 { groenMath = 1; // Zet groenMath op 1 } if(groenCount == 255) // Als groenCount gelijk is aan 255 { groenMath = -1; // Zet groenMath op -1 } if(blauwCount == 0) // Als blauwCount gelijk is als 0 { blauwMath = 1; // Zet blauwMath op 1 } if(blauwCount == 255) // Als blauwCount gelijk is aan 255 { blauwMath = -1; // Zet blauwMath op -1 } } } ISR(TIMER0_OVF_vect) // ISR voor TIMER0 OVERFLOW Interrupt. { if(i == 0) // Als i gelijk is aan 0 { PORTD&=~(1<<PORTD1); // Zet groen aan PORTD&=~(1<<PORTD2); // Zet rood aan PORTD&=~(1<<PORTD0); // Zet blauw aan } if(i == roodCount) // Als i gelijk is aan roodCount { PORTD|=(1<<PORTD2); // Zet rood uit } if(i == blauwCount) // Als i gelijk is aan blauwCount { PORTD|=(1<<PORTD0); // Zet blauw uit } if(i == groenCount) // Als i gelijk is aan groenCount { PORTD|=(1<<PORTD1); // Zet groen uit } i++; // i = i + 1 }
C
#include "matrix.h" #include "nnopti.h" #include "nnactiv.h" #include "neural_network.h" #include <stdio.h> #include <unistd.h> #include <stdlib.h> int main() { int index; int layers[1] = {2}; struct Matrix input; struct Matrix output; struct NeuralNetwork nn; nn = create_feedforward_nn(2, 1, 1, layers, &sigmoid); initialize_weights(&nn); input = create_matrix(1, 2); input.values[0][0] = 0.0; input.values[0][1] = 0.0; // print_matrix(&input); for (index = 0; index < 100000; index++) { output = process_data(&nn, &input); delete_matrix(&output); sleep(1); printf("= %i\n", index+1); } // print_matrix(&output); delete_feedforward_nn(&nn); // delete_matrix(&input); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <signal.h> //doplnte funkciu SignalHandler void SignalHandler(int signal) { printf("Received signal ID: %d\n",signal); } int main() { //vypis PID printf("PID = %d\n", getpid()); //nastavenie signal handlera struct sigaction sa; memset(&sa,0, sizeof(sa)); sa.sa_handler = &SignalHandler; //sigaction(SIGUSR1, &sa, NULL); sigaction(SIGINT, &sa, NULL); //synchronne cakanie na signal sigset_t sigset; sigfillset( &sigset); sigdelset( &sigset, SIGUSR1); printf("pred sigsuspend\n"); sigsuspend( &sigset); printf("za sigsuspend\n"); return EXIT_SUCCESS; }
C
/* Author: Manohar Mukku Date: 17.07.2018 Desc: GeeksforGeeks - Sudo Placement [1.2] - Beautiful pairs Link: https://practice.geeksforgeeks.org/contest-problem/spp-beautiful-pairs/0/ */ #include <stdio.h> #include <stdlib.h> int cmpfunc(const void* a, const void* b) { return (*(int*)a) - (*(int*)b); } int main() { int T; scanf ("%d", &T); while (T--) { int n1; scanf ("%d", &n1); int* arr1 = (int*)malloc(n1 * sizeof (int)); int i; for (i = 0; i < n1; i++) scanf ("%d", &arr1[i]); int n2; scanf ("%d", &n2); int* arr2 = (int*)malloc(n2 * sizeof(int)); for (i = 0; i < n2; i++) scanf ("%d", &arr2[i]); qsort(arr1, n1, sizeof(int), cmpfunc); int j, k; for (i = 0; i < n2; i++) { j = 0, k = n1 - 1; while (j < k) { if (arr1[j] + arr1[k] == arr2[i]) break; else if (arr1[j] + arr1[k] < arr2[i]) j++; else k--; } if (j < k) break; } if (i < n2) printf("1\n"); else printf("0\n"); free(arr1); free(arr2); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "shared.h" #include "hello_tx.h" #include "interface.h" #include "neighbor.h" struct neighbor *alloc_neighbor(void) { struct neighbor *neighbor; neighbor = xzalloc(sizeof(struct neighbor)); neighbor->state = NEIGHBOR_STATE_DOWN; return neighbor; } void interface_add_neighbor(struct interface_data *interface_data, struct neighbor *neighbor) { int ret; ret = list_insert(interface_data->neighbor_list, neighbor); if (ret != SUCCESS) { fprintf(stderr, "Cannot insert neigbor into list\n"); abort(); } } /* it is up to the callee to remove this neighbor out * of any lists */ void free_neighbor(void *a) { struct neighbor *neighbor = a; memset(neighbor, 0, sizeof(struct neighbor)); free(neighbor); } static void neighbor_set_state(struct ospfd *ospfd, struct interface_data *interface_data, struct neighbor *neighbor, int new_state) { neighbor->state = new_state; (void) ospfd; (void) interface_data; } void neighbor_inactive_timer_expired(void *data) { struct inactivity_timer_data *inactivity_timer_data = data; struct ospfd *ospfd = inactivity_timer_data->ospfd; struct neighbor *neighbor = inactivity_timer_data->neighbor; struct interface_data *interface_data = inactivity_timer_data->interface_data; msg(ospfd, DEBUG, "neighbor inactive timer expired (router id: %d)", neighbor->neighbor_id); /* remove neighbor from interface list */ remove_neighbor_from_interface_data_list(ospfd, interface_data, neighbor); free(neighbor->inactivity_timer_data); free(neighbor); } int neighbor_start_inactive_timer(struct ospfd *ospfd, struct interface_data *i, struct neighbor *neighbor) { int ret; struct inactivity_timer_data *inactivity_timer_data; /* FIXME: hardcoded time-out */ struct timespec timespec = { 10, 0 }; struct ev_entry *ev_entry; msg(ospfd, DEBUG, "prepare inactive timer for neighbor"); inactivity_timer_data = xzalloc(sizeof(struct inactivity_timer_data)); inactivity_timer_data->ospfd = ospfd; inactivity_timer_data->neighbor = neighbor; inactivity_timer_data->interface_data = i; neighbor->inactivity_timer_data = inactivity_timer_data; ev_entry = ev_timer_new(&timespec, neighbor_inactive_timer_expired, inactivity_timer_data); if (!ev_entry) { err_msg_die(EXIT_FAILURE, "Cannot initialize a new timer"); } inactivity_timer_data->neighbor->inactive_timer_entry = ev_entry; ret = ev_add(ospfd->ev, ev_entry); if (ret != EV_SUCCESS) { err_msg_die(EXIT_FAILURE, "Cannot add new timer to global event handler"); } return SUCCESS; } int neighbor_cancel_inactive_timer(struct ospfd *ospfd, struct neighbor *neighbor) { assert(ospfd->ev); assert(neighbor); assert(neighbor->inactive_timer_entry); msg(ospfd, DEBUG, "cancel neighbor inactive timer"); ev_timer_cancel(ospfd->ev, neighbor->inactive_timer_entry); free(neighbor->inactivity_timer_data); return SUCCESS; } int neighbor_restart_inactive_timer(struct ospfd *ospfd, struct interface_data *interface_data, struct neighbor *neighbor) { int ret; /* stop running inactivity timer ... */ ret = neighbor_cancel_inactive_timer(ospfd, neighbor); if (ret != SUCCESS) return FAILURE; /* ... and re-arm the timer again! */ ret = neighbor_start_inactive_timer(ospfd, interface_data, neighbor); if (ret != SUCCESS) return FAILURE; return SUCCESS; } /* returns true if the neighbor id is identical * and false in all other cases */ int list_neighbor_id_cmp(const void *a, const void *b) { const struct neighbor *aa = (struct neighbor *)a; const struct neighbor *bb = (struct neighbor *)b; return aa->neighbor_id == bb->neighbor_id; } static int neighbor_id_cmp(void *a, void *b) { struct neighbor *n = (struct neighbor *)a; uint32_t *id = b; return n->neighbor_id == *id; } /* for a given interface data and neighbor id this * function returns the neighbor data structure or * NULL in the cases that these neighbor is not in * the interface data structure */ struct neighbor *neighbor_by_id(struct ospfd *ospfd, struct interface_data *interface_data, uint32_t neighbor_id) { struct neighbor *neighbor; (void) ospfd; neighbor = list_lookup_match(interface_data->neighbor_list, neighbor_id_cmp, &neighbor_id); return neighbor ? neighbor : NULL; } void remove_neighbor_from_interface_data_list(struct ospfd *ospfd, struct interface_data *interface_data, struct neighbor *neighbor) { int ret; (void) ospfd; /* this impliciet calls the compare function of * interface_data->neighbor_list */ ret = list_remove(interface_data->neighbor_list, (void **)&neighbor); if (ret != SUCCESS) { fprintf(stderr, "Cannot remove neigbor from list\n"); abort(); } } int process_state_down_ev_hello_received(struct ospfd *ospfd, struct interface_data *i, struct neighbor *neighbor) { int ret; /* set state to INIT */ neighbor_set_state(ospfd, i, neighbor, NEIGHBOR_STATE_INIT); ret = neighbor_start_inactive_timer(ospfd, i, neighbor); if (ret != SUCCESS) return FAILURE; return SUCCESS; } int process_state_init_ev_hello_received(struct ospfd *o, struct interface_data *i, struct neighbor *n, int new_state) { int ret; (void) new_state; ret = neighbor_restart_inactive_timer(o, i, n); if (ret != SUCCESS) return FAILURE; return SUCCESS; } int process_state_down_to_new_state(struct ospfd *o, struct interface_data *i, struct neighbor *n, int event) { switch (event) { case NEIGHBOR_EV_HELLO_RECEIVED: return process_state_down_ev_hello_received(o, i, n); break; default: err_msg_die(EXIT_FAILURE, "State no handled: %s:%d", __FILE__, __LINE__); break; } /* should not happened - to shut-up gcc warnings */ return FAILURE; } int process_state_init_to_new_state(struct ospfd *o, struct interface_data *i, struct neighbor *n, int s) { switch (s) { case NEIGHBOR_EV_HELLO_RECEIVED: return process_state_init_ev_hello_received(o, i, n, s); break; default: err_msg_die(EXIT_FAILURE, "State no handled: %s:%d", __FILE__, __LINE__); break; } /* should not happened - to shut-up gcc warnings */ return FAILURE; } void process_state_two_way_to_new_state(struct ospfd *ospfd, struct neighbor *neighbor, int new_state) { err_msg_die(EXIT_FAILURE, "State handling not yet implemented: %s:%d", __FILE__, __LINE__); } void process_state_ex_start_to_new_state(struct ospfd *ospfd, struct neighbor *neighbor, int new_state) { err_msg_die(EXIT_FAILURE, "State handling not yet implemented: %s:%d", __FILE__, __LINE__); } void process_state_exchange_to_new_state(struct ospfd *ospfd, struct neighbor *neighbor, int new_state) { err_msg_die(EXIT_FAILURE, "State handling not yet implemented: %s:%d", __FILE__, __LINE__); } void process_state_loading_to_new_state(struct ospfd *ospfd, struct neighbor *neighbor, int new_state) { err_msg_die(EXIT_FAILURE, "State handling not yet implemented: %s:%d", __FILE__, __LINE__); } void process_state_full_to_new_state(struct ospfd *ospfd, struct neighbor *neighbor, int new_state) { err_msg_die(EXIT_FAILURE, "State handling not yet implemented: %s:%d", __FILE__, __LINE__); } int neighbor_process_event(struct ospfd *ospfd, struct interface_data *interface_data, struct neighbor *neighbor, int event) { switch (neighbor->state) { case NEIGHBOR_STATE_DOWN: return process_state_down_to_new_state(ospfd, interface_data, neighbor, event); break; case NEIGHBOR_STATE_INIT: return process_state_init_to_new_state(ospfd, interface_data, neighbor, event); break; case NEIGHBOR_STATE_ATTEMPT: case NEIGHBOR_STATE_TWO_WAY: case NEIGHBOR_STATE_EX_START: case NEIGHBOR_STATE_EXCHANGE: case NEIGHBOR_STATE_LOADING: case NEIGHBOR_STATE_FULL: default: err_msg_die(EXIT_FAILURE, "Programmed error in switch/case statement: " "state (%d) not known or not handled", neighbor->state); break; }; return FAILURE; } /* vim: set tw=78 ts=4 sw=4 sts=4 ff=unix noet: */
C
#include <stdio.h> #include <string.h> char whitespace[] = " \n\r\f\t\v"; unsigned count_word(char *string, const char *word) { unsigned count = 0; char *buff; // strtok with replace separator with NUL, the return the pointer to the // string before separator. // if the first parameter is NULL, strtok with continue the last string for (buff = strtok(string, whitespace); buff != NULL; buff = strtok(NULL, whitespace)) { if (strcmp(buff, word) == 0) count++; } return count; } int main(int argc, char *argv[]) { char buff[101]; unsigned count = 0; while (fgets(buff, 100, stdin)) { count += count_word(buff, "the"); } printf("%u\n", count); return 0; }
C
/** ******************************************************************************* * File : oscode.h * Description : Implementation of a simple shell * Features : History of the last 10 commands, background processes, list of jobs in background output redirection * Author : Felix Dube 260533620 * Version : 1.0.0 * Date : February 2016 ******************************************************************************* */ /* JOB ---------------------------------------------------------------------------*/ // store in a linked list all the jobs in background, along with their PID struct job { char *args[20]; int pid; struct job * next; }; /** * @brief remove a job with a particuliar PID * @param head: pointer to a pointer to the head of linked list of jobs * @param pid: pid of the job to be removed from the linked list * @retval None */ void removejob(struct job ** head, int pid); /** * @brief print all the jobs in back ground and remove the job that are done * @param head: linked list of job to be printed and updated * @retval None */ void printjobs(struct job ** head); /** * @brief add a job to the linked list * @param head: pointer to a pointer to the head of linked list of jobs * @param pid: pid of the job to be added * @param args: command that the job is doing * @retval None */ void pushjob(struct job ** head, int pid, char *args[]); /** * @brief check if a specific job PID exist * @param head: pointer to a pointer to the head of linked list of jobs * @param pid: pid of the job being search for * @retval 1 if the pid is found, 0 otherwise */ int jobexist(struct job * head, int pid); /* HISTORY -----------------------------------------------------------------------*/ // store the command allong with its history ID struct cmd { char *args[20]; int nbr; }; /** * @brief add a specific cmd to the history * @param history: array in which the command need to be added * @param args: command to be added * @param nbr: history ID * @retval void */ void addhistory(struct cmd *history[], char *args[], int nbr); /** * @brief search for a specific history ID in the history * @param history: history array to be search in * @param nbr: history ID being search for * @retval if history ID found it returns the index of the cmd in the history array otherwise return -1 */ int searchhistory(struct cmd *history[], int nbr); /** * @brief verify if a string is a number * @param string: pointer to the string to be verified * @retval 1 if the string is a number, 0 otherwise */ int isnumber (char *string); /** * @brief print all commands in the history * @param history: pointer to the history array * @retval None */ void printhistory(struct cmd *history[]); /** * @brief cast a string to int * @param a: pointer to the string to be cast to int * @retval number that was in the string */ int stringtoint (char* a); /** * @brief check is a cmd is a background cmd * @param args: arguments of the cmd * @retval return the index of the symbol "&" if found, -1 otherwise */ int isbg(char * args[]); /* COMMAND -----------------------------------------------------------------------*/ /** * @brief free the line allocated by getline() * @param line: pointer to the line * @retval None */ void freecmd(char *line); /** * @brief get a command from the user * @param prompt: prompt string to be displayed to the user * @param args: pointer to the array in which the command is saved * @param background: pointer to the value of background * @retval the number of argument in the command */ int getcmd(char *prompt, char *args[], int *background); /** * @brief initialize all the arguments of the command to null * @param args: pointer to the arguments of the command * @retval None */ void initargs(char *args[]); /** * @brief check if a command output is redirected * @param args: pointer to the arguments of the command * @retval the position of the sign ">" in the array, -1 if not found */ int isredirected(char * args[]);
C
/* print the user name in 5 times */ #include <stdio.h> void main() { char n[10]; int i=0; printf("enter the name "); scanf("%s",n); while(5>i) { printf("%s \n",n); i++; } }
C
#include <stdio.h> int main(void) { int x; scanf("%d", &x); if(x % 3 == 0) { printf("能被其中一个数(3)整除\n"); } if(x % 5 == 0) { printf("能被其中一个数(5)整除\n"); } if(x % 7 == 0) { printf("能被其中一个数(7)整除\n"); } return 0; }
C
#pragma once #include<stdio.h> #include<string.h> #include<stdlib.h> #include<errno.h> #define MAX_NAME 10//ֵĴС #define MAX_SEX 5//ԱС #define MAX_TELE 15//绰С #define MAX_ADDR 30//ַС #define DEFAULT_SZ 3 //ͨѶ¼ĬϵĴС enum Option { EXIT, ADD, DEL, SEARCH, MODIFY, SHOW, SORT, SAVE, CLEAR }; struct PeoInfo { char name[MAX_NAME]; int age; char sex[MAX_SEX]; char tele[MAX_TELE]; char addr[MAX_ADDR]; }; //ͨѶ¼ struct Contact { struct PeoInfo* data;//Ϣ int size;//¼ǰѾеԪظ int capacity;//ǰͨѶ¼ }; //ʼͨѶ¼ void InitContact(struct Contact* ps); //ͨѶ¼ void AddContact(struct Contact* ps); //ӡͨѶ¼Ϣ void ShowContact(const struct Contact* ps); //ɾͨѶ¼Ϣ void DelContact(struct Contact* ps); //ͨѶ¼Ϣ void SearchContact(const struct Contact* ps); //޸ָϵ void ModifyContact(struct Contact* ps); // void SortContact(struct Contact* ps); //ͷŶ̬ٵڴ void DestroyContact(struct Contact* ps); //ͨѶ¼ void SaveContact(struct Contact* ps); //ļеϢͨѶ¼ void LoadContact(struct Contact* ps); //ͨѶ¼ void ClearContact(struct Contact* ps);
C
/* ** Created by doom on 17/04/19. */ #ifndef CEEDS_MEMORY_ALLOCATOR_H #define CEEDS_MEMORY_ALLOCATOR_H #include <ceeds/core.h> /** * Memory allocator abstraction, used to build allocator-aware containers */ /** * A handle to an allocator * * Allocator-aware objects should use such a handle in order to manage their memory without caring about * the underlying specific allocator. */ typedef struct memory_allocator *memory_allocator_handle_t; /** * A memory allocator * * Such an object is used only by allocator implementers, and (under the hood) by allocation macros. */ struct memory_allocator { /** * Allocate memory * * @param[in] alloc a pointer to the allocator handle used for this allocation * @param[in] size the amount of bytes to allocate * @param[in] align the minimum alignment required for the allocated memory * @return a pointer to the beginning of the newly allocated memory * * @pre @p align must be a power of 2 */ void *(*allocate)(memory_allocator_handle_t alloc, size_t size, size_t align); /** * Allocate memory, zeroing it * * @param[in] alloc a pointer to the allocator handle used for this allocation * @param[in] size the amount of bytes to allocate * @param[in] align the minimum alignment required for the allocated memory * @return a pointer to the beginning of the newly allocated memory * * @pre @p align must be a power of 2 */ void *(*zero_allocate)(memory_allocator_handle_t alloc, size_t size, size_t align); /** * Deallocate previously allocated memory * * @param[in] alloc a pointer to the allocator handle used for this allocation * @param[in] ptr a pointer to the allocated memory */ void (*deallocate)(memory_allocator_handle_t alloc, void *ptr); /** * Resize a previously allocated memory block, keeping the data * * If @p ptr is NULL, this is equivalent to a regular allocation. * If @p old_size is 0, no data will be kept * If @p new_size is 0, this is equivalent to a regular deallocation * * @param[in] alloc a pointer to the allocator handle used for this allocation * @param[in,out] ptr a pointer to the previously allocated memory * @param[in] old_size the amount of bytes allocated for @p ptr * @param[in] new_size the new amount of bytes to allocated * @param[in] new_align the new minimum alignment required for the allocated memory * @return a pointer to the beginning of the newly allocated memory * * @pre @p ptr must be a pointer to memory previously allocated using @p alloc, or NULL * @pre @p new_align must be a power of 2 */ void *(*reallocate)(memory_allocator_handle_t alloc, void *ptr, size_t old_size, size_t new_size, size_t new_align); }; /** * Allocate memory from a given allocator to hold an object of a given type, with a given alignment * * @param[in] handle a handle to the allocator to use * @param T the type of object to allocate memory for * @param[in] align the minimum alignment required for the allocated memory * @return a pointer to the beginning of the newly allocated memory * * @pre @p align must be a power of 2 */ #define allocator_aligned_new(handle, T, align) ((handle)->allocate((handle), sizeof(T), (align))) /** * Allocate memory from a given allocator to hold an object of a given type, with a given alignment, zeroing it * * @param[in] handle a handle to the allocator to use * @param T the type of object to allocate memory for * @param[in] align the minimum alignment required for the allocated memory * @return a pointer to the beginning of the newly allocated memory * * @pre @p align must be a power of 2 */ #define allocator_aligned_znew(handle, T, align) ((handle)->zero_allocate((handle), sizeof(T), (align))) /** * Allocate memory from a given allocator to hold an array of objects of a given type, with a given alignment * * @param[in] handle a handle to the allocator to use * @param T the type of object to allocate memory for * @param[in] n the number of elements to allocate memory for * @param[in] align the minimum alignment required for the allocated memory * @return a pointer to the beginning of the newly allocated memory * * @pre @p align must be a power of 2 */ #define allocator_aligned_new_array(handle, T, n, align) ((handle)->allocate((handle), sizeof(T) * (n), (align))) /** * Allocate memory from a given allocator to hold an array of objects of a given type, with a given alignment, zeroing it * * @param[in] handle a handle to the allocator to use * @param T the type of object to allocate memory for * @param[in] n the number of elements to allocate memory for * @param[in] align the minimum alignment required for the allocated memory * @return a pointer to the beginning of the newly allocated memory * * @pre @p align must be a power of 2 */ #define allocator_aligned_znew_array(handle, T, n, align) ((handle)->zero_allocate((handle), sizeof(T) * (n), (align))) /** * Change the size of the memory block allocated using a given allocator for a given array, with a given alignment. * Data fitting in the new array will be kept. * * If @p ptr is NULL, this is equivalent to a regular allocation. * If @p old_n is 0, no data will be kept * If @p new_n is 0, this is equivalent to a regular deallocation * * @param[in] handle a handle to the allocator * @param[in,out] ptr a pointer to the allocated memory * @param T the type of object to allocate memory for * @param[in] old_n the number of elements allocated in @p ptr * @param[in] new_n the number of elements to allocate * @param[in] align the minimum alignment required for the memory to allocate * @return a pointer to the beginning of the newly allocated memory * * @pre @p ptr must be a pointer to memory previously allocated using @p handle, or NULL * @pre @p align must be a power of 2 */ #define allocator_aligned_resize_array(handle, ptr, T, old_n, new_n, align) \ ((handle)->reallocate((handle), ptr, sizeof(T) * (old_n), sizeof(T) * (new_n), align)) /** * Allocate memory from a given allocator to hold an object of a given type * * @param[in] handle a handle to the allocator to use * @param T the type of object to allocate memory for * @return a pointer to the beginning of the newly allocated memory */ #define allocator_new(handle, T) allocator_aligned_new(handle, T, alignof(T)) /** * Allocate memory from a given allocator to hold an object of a given type, zeroing it * * @param[in] handle a handle to the allocator to use * @param T the type of object to allocate memory for * @return a pointer to the beginning of the newly allocated memory */ #define allocator_znew(handle, T) allocator_aligned_znew(handle, T, alignof(T)) /** * Allocate memory from a given allocator to hold an array of objects of a given type * * @param[in] handle a handle to the allocator to use * @param T the type of object to allocate memory for * @param[in] n the number of elements to allocate memory for * @return a pointer to the beginning of the newly allocated memory */ #define allocator_new_array(handle, T, n) allocator_aligned_new_array(handle, T, n, alignof(T)) /** * Allocate memory from a given allocator to hold an array of objects of a given type, zeroing it * * @param[in] handle a handle to the allocator to use * @param T the type of object to allocate memory for * @param[in] n the number of elements to allocate memory for * @return a pointer to the beginning of the newly allocated memory */ #define allocator_znew_array(handle, T, n) allocator_aligned_znew_array(handle, T, n, alignof(T)) /** * Change the size of the memory block allocated using a given allocator for a given array * Data fitting in the new array will be kept. * * If @p ptr is NULL, this is equivalent to a regular allocation. * If @p old_n is 0, no data will be kept * If @p new_n is 0, this is equivalent to a regular deallocation * * @param[in] handle a handle to the allocator * @param[in,out] ptr a pointer to the allocated memory * @param T the type of object to allocate memory for * @param[in] old_n the number of elements allocated in @p ptr * @param[in] new_n the number of elements to allocate * @return a pointer to the beginning of the newly allocated memory * * @pre @p ptr must be a pointer to memory previously allocated using @p handle, or NULL */ #define allocator_resize_array(handle, ptr, T, old_n, new_n) \ allocator_aligned_resize_array(handle, ptr, T, old_n, new_n, alignof(T)) /** * Deallocate memory previously allocated from a given allocator * * @param[in] handle a handle to the allocator to use * @param[in] ptr a pointer to the memory to deallocate */ #define allocator_delete(handle, ptr) ((handle)->deallocate((handle), ptr)) #endif /* !CEEDS_MEMORY_ALLOCATOR_H */
C
/* * Copyright (c) 2021 Kevin Townsend (KTOWN) * * SPDX-License-Identifier: Apache-2.0 */ #include <stdlib.h> #include <ctype.h> #include <shell/shell.h> #include <zsl/orientation/orientation.h> #if CONFIG_ZSL_SHELL_ORIENT static int zsl_orient_shell_invalid_arg(const struct shell *shell, char *arg_name) { shell_print(shell, "Error: invalid argument \"%s\"\n", arg_name); return -EINVAL; } static int zsl_orient_shell_missing_arg(const struct shell *shell, char *arg_name) { shell_print(shell, "Error: missing argument: \"%s\"\n", arg_name); return -EINVAL; } static int zsl_orient_shell_rc_code(const struct shell *shell, int rc) { shell_print(shell, "Error: unexpected return code: \"%d\"\n", rc); return -EINVAL; } static int zsl_orient_shell_cmd_lat2g(const struct shell *shell, size_t argc, char **argv) { int rc; zsl_real_t lat = 0.0; zsl_real_t alt = 0.0; zsl_real_t g = 0.0; if ((argc == 1) || (strcmp(argv[1], "help") == 0)) { shell_print(shell, "Latitude and altitude to gravity (m/s^2)"); shell_print(shell, " $ %s <lat> <altitude>\n", argv[0]); shell_print(shell, "Ex. (Barcelona, ES):"); shell_print(shell, " $ %s 41.3851 12.0", argv[0]); shell_print(shell, " 9.794146 m/s^2"); return 0; } /* Missing argument. */ if (argc == 2) { return zsl_orient_shell_missing_arg(shell, "altitude"); } /* Too many arguments. */ if (argc > 3) { return zsl_orient_shell_invalid_arg(shell, argv[3]); } /* Invalid latitude. */ lat = strtof(argv[1], NULL); if (lat <= 0.0) { return zsl_orient_shell_invalid_arg(shell, argv[1]); } /* Invalid altitude. Use sensible Earth limits for validation. */ alt = strtof(argv[2], NULL); if ((alt > 10000.0) || (alt < -500.0)) { return zsl_orient_shell_invalid_arg(shell, argv[2]); } rc = zsl_grav_lat_alt(lat, alt, &g); if (rc) { return zsl_orient_shell_rc_code(shell, rc); } shell_print(shell, "%f m/s^2", g); return 0; } /* Subcommand array for "orient" (level 1). */ SHELL_STATIC_SUBCMD_SET_CREATE( sub_orient, /* 'lat2g' command handler. */ SHELL_CMD_ARG(lat2g, NULL, "Latitude and altitude to gravity", zsl_orient_shell_cmd_lat2g, 1, 4), /* Array terminator. */ SHELL_SUBCMD_SET_END ); /* Root command "orient" (level 0). */ SHELL_CMD_REGISTER(orient, &sub_orient, "Orientation commands", NULL); #endif
C
#include "stdio.h" #include "stm8s.h" #include "uart.h" int putchar (int c) { /* Write a character to the UART1 */ UART1_SendData8(c); /* Loop until the end of transmission */ while (UART1_GetFlagStatus(UART1_FLAG_TXE) == RESET); return (c); } /** * @brief Retargets the C library scanf function to the USART. * @param None * @retval char Character to Read */ int getchar (void) { int c = 0; /* Loop until the Read data register flag is SET */ while (UART1_GetFlagStatus(UART1_FLAG_RXNE) == RESET); c = UART1_ReceiveData8(); return (c); }
C
#include <stdlib.h> #include <unistd.h> #include <string.h> #include "../../../libft.h" void ft_print_result(char const *s, int n) { int i; i = 0; while (i < n) { write(1, &s[i], 1); i++; } } int main(int argc, const char *argv[]) { char *str; if (argc == 1) return (0); if (atoi(argv[1]) == 1) { str = (char *)malloc(sizeof(*str) * 10); if (!str) return (0); memset(str, 'u', 9); str[9] = '\0'; ft_strclr(str); ft_print_result(str, 10); } return (0); }
C
#include<stdio.h> #include<conio.h> #include<string.h> #include<math.h> //DEKLARASI PROSEDUR// void Input_Data(int item[], int jum); void Tampil_Data(int item[], int jum); void Urutan_Profit(int *no, float *weight, float *profit, int *pieces, int c); void Urutan_Density(int *no, float *weight, float *profit, int *pieces, double *density, int c); void Urutan_Weight(int *no, float *weight, float *profit, int *pieces, int c); void Seleksi_Data(int *no, float *weight, float *profit, int *pieces, int c); typedef struct { int b, no; float w, p; double d; //rekaman data yakni berupa bobot, profit, densitas, tersedia, dan nomor// char ket[15]; }item; item item1[100], item2[100]; float ransel; char ulang; int bnyk, k[100], n[100]; double o[100]; float l[100], m[100]; int main() { printf("-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n"); printf("-PENYELESAIAAN OPTIMASI PADA BOUNDED KNAPSACK+\n"); printf("+-+ -+-+\n"); printf("-+-+-+-DENGAN MENGGUNAKAN METODE GREEDY+-+-+-+\n"); printf("-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n"); printf("----------------------------------------------\n"); printf(" by: Nanda Zulhija\n"); printf("----------------------------------------------\n"); printf("\n"); ulang='y'; for(;ulang=='Y' || ulang=='y';) { int X[100]; printf("Ukuran ransel : "); scanf("%f", &ransel); printf("Banyak variasi item : "); scanf("%d", &bnyk); printf("\n"); Input_Data(X,bnyk); //MEMASUKKAN SELURUH DATA KEDALAM PROSEDUR INPUT DATA// Tampil_Data(X,bnyk); //MENAMPILKAN KETERANGAN DATA YANG TELAH DIBUAT// /*TAHAP GREEDY BY PROFIT DIMULAI*/ int i, j, c; float totw, totp; c=0, totw=0, totp=0; for(i=0; i<bnyk; i++) for(j=0; j<item1[i].b; j++) { k[c]=item1[i].no; l[c]=item1[i].w; m[c]=item1[i].p; n[c]=item1[i].b; c++; } Urutan_Profit(k,l,m,n,c); //PROSES PENGURUTAN BERDASARKAN PROFIT// Seleksi_Data(k,l,m,n,c); for(i=0; i<c; i++) { if(strcmp(item2[i].ket, "Take")==0) { totw=totw+item2[i].w; totp=totp+item2[i].p; } } /*HASIL GREEDY BY PROFIT*/ printf("\n"); printf("=================Greedy by Profit==============\n"); printf("Objek weight profit keterangan \n"); printf("-----------------------------------------------\n"); for(i=0; i<c; i++) { printf("%d %10f %10f %10s\n", item2[i].no, item2[i].w, item2[i].p, item2[i].ket); } printf("\n"); printf("Total berat yg diambil : %f\n", totw); printf("Total profit yg diperoleh : %f\n", totp); /*TAHAP GREEDY BY DENSITY DIMULAI*/ float totwd, totpd; c=0, totwd=0, totpd=0; for(i=0; i<bnyk; i++) for(j=0; j<item1[i].b; j++) { k[c]=item1[i].no; l[c]=item1[i].w; m[c]=item1[i].p; n[c]=item1[i].b; o[c]=item1[i].d; c++; } Urutan_Density(k,l,m,n,o,c); Seleksi_Data(k,l,m,n,c); for(i=0; i<c; i++) { if(strcmp(item2[i].ket, "Take")==0) { totwd=totwd+item2[i].w; totpd=totpd+item2[i].p; } } /*HASIL*/ printf("\n"); printf("======================Greedy by Density=================\n"); printf("Objek weight profit keterangan density \n"); printf("--------------------------------------------------------\n"); for(i=0; i<c; i++) { item2[i].d=item2[i].p/item2[i].w; printf("%d %10f %10f %10s %15f\n", item2[i].no, item2[i].w, item2[i].p, item2[i].ket, item2[i].d); } printf("\n"); printf("Total berat yg diambil : %f\n", totwd); printf("Total profit yg diperoleh : %f\n", totpd); printf("\n"); /*TAHAP GREEDY BY WEIGHT*/ float totww, totpw; c=0, totww=0, totpw=0; for(i=0; i<bnyk; i++) for(j=0; j<item1[i].b; j++) { k[c]=item1[i].no; l[c]=item1[i].w; m[c]=item1[i].p; n[c]=item1[i].b; c++; } Urutan_Weight(k,l,m,n,c); Seleksi_Data(k,l,m,n,c); for(i=0; i<c; i++) { if(strcmp(item2[i].ket, "Take")==0) { totww=totww+item2[i].w; totpw=totpw+item2[i].p; } } /*HASIL GREEDY BY WEIGHT*/ printf("\n"); printf("==================Greedy by weight============\n"); printf("Objek weight profit keterangan \n"); printf("----------------------------------------------\n"); for(i=0; i<c; i++) { printf("%d %10f %10f %10s\n", item2[i].no, item2[i].w, item2[i].p, item2[i].ket); } printf("\n"); printf("Total berat yg diambil : %f\n", totww); printf("Total profit yg diperoleh : %f\n", totpw); printf("\n"); printf("\n"); printf("PERBANDINGAN PROFIT HASIL OPTIMASI\n"); printf("==================================\n"); printf("G-Profit G-Density G-Wight\n"); printf("----------------------------------\n"); printf(" %f %10f %10f", totp, totpd, totpw); printf("\n"); //*PERBANDINGAN DARI KETIGA METODE*// float terbaik; char note[40]; terbaik=totp; strcpy(note, "Greedy by Profit"); if(terbaik<totpw){ terbaik=totpw; strcpy(note, "Greedy by Weight"); } if(terbaik<totpd){ terbaik=totpd; strcpy(note, "Greedy by Density"); } printf("\n"); printf("REKOMENDASI : %s dengan KEUNTUNGAN : %f\n", note, terbaik); printf("\n"); printf("\n"); printf("ulang pekerjaan (y\\n) : "); ulang=getche(); printf("\n\n"); } } void Input_Data(int item[], int jum) { int i; for(i=0; i<jum; i++) { printf("Berat objek ke %d : ", i+1); scanf("%f", &item1[i].w); printf("Profit objek ke %d : ", i+1); scanf("%f", &item1[i].p); printf("Jumlah objek ke %d : ", i+1); scanf("%d", &item1[i].b); item1[i].no=i+1; } } void Tampil_Data(int item[], int jum) { int i; printf("\n"); printf("Objek(i) Berat(w) Profit(p) Banyak(b) Density(d)\n"); printf("-------------------------------------------------------------\n"); for(i=0; i<jum; i++) { item1[i].d=item1[i].p/item1[i].w; printf("%2d %12f %12f %12d %12f\n", item1[i].no, item1[i].w, item1[i].p, item1[i].b, item1[i].d); } } void Urutan_Profit(int *no, float *weight, float *profit, int *pieces, int c) { int i, j, sementara; for(i=0; i<c-1; i++) for(j=i; j<c; j++) { if(profit[i]<profit[j]) { sementara=no[i]; no[i]=no[j]; no[j]=sementara; sementara=weight[i]; weight[i]=weight[j]; weight[j]=sementara; sementara=profit[i]; profit[i]=profit[j]; profit[j]=sementara; sementara=pieces[i]; pieces[i]=pieces[j]; pieces[j]=sementara; } } } void Urutan_Density(int *no, float *weight, float *profit, int *pieces, double *density, int c) { int i, j; double temp; for(i=0; i<c-1; i++) for(j=i; j<c; j++) { if(density[i]<density[j]) { temp=no[i]; no[i]=no[j]; no[j]=temp; temp=weight[i]; weight[i]=weight[j]; weight[j]=temp; temp=profit[i]; profit[i]=profit[j]; profit[j]=temp; temp=pieces[i]; pieces[i]=pieces[j]; pieces[j]=temp; temp=density[i]; density[i]=density[j]; density[j]=temp; } } } void Urutan_Weight(int *no, float *weight, float *profit, int *pieces, int c) { int i, j, sementara; for(i=0; i<c-1; i++) for(j=i; j<c; j++) { if(weight[i]>weight[j]) { sementara=no[i]; no[i]=no[j]; no[j]=sementara; sementara=weight[i]; weight[i]=weight[j]; weight[j]=sementara; sementara=profit[i]; profit[i]=profit[j]; profit[j]=sementara; sementara=pieces[i]; pieces[i]=pieces[j]; pieces[j]=sementara; } } } void Seleksi_Data(int *no, float *weight, float *profit, int *pieces, int c) { int i; float acc; acc=0; for(i=0; i<c; i++) { item2[i].no=k[i]; item2[i].w=l[i]; item2[i].p=m[i]; item2[i].b=n[i]; } for(i=0; i<c; i++) { if(acc+item2[i].w<=ransel){ acc=acc+item2[i].w; strcpy(item2[i].ket, "Take"); } else { strcpy(item2[i].ket, "Leave"); } } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> struct juego{ // DEFINIR LAS ESTRUCTURAS EN LAS MATRICES PARA QUE SE PUEDAN COLOCAR TODOS LOS DATOS "" char cobertura; char simbominas; int numminas; int nummarco; int ganador; }; typedef struct juego tipoCasilla; // para no escribir Struct casillas ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// tipoCasilla** armarmatriz(int filas,int cols,tipoCasilla **matriz){ // ESTA FUNCION ME VA A organizar LA MATRIZ int i; for(i=0;i<filas;i++){ matriz[i]=(tipoCasilla *)malloc((cols+2)*sizeof(tipoCasilla)); // por cada fila reserva una columna de memoria } } /////////////////////////////////////////////////////////////////////////777 void rellenar(int filas, int cols,int nminas,tipoCasilla **matriz) { int a,b,i,j,k,l; srand(time(NULL)); for (size_t a = 1; a < filas-1; a++) { for (size_t b = 1; b < cols-1; b++) { matriz[a][b].cobertura='*'; matriz[a][b].ganador=10; /* code */ } /* code */ } for (size_t x = 0; x < filas; x++) { matriz[0][x].nummarco=x; matriz[0][x].numminas=1; if (x==filas-1) { for (size_t y = 0; y < cols; y++) { matriz[y][0].nummarco=y; matriz[y][0].numminas=10; } /* code */ } } for (size_t i = 0; i <nminas; i++) { k=1+(rand()%(filas-2)); l=1+(rand()%(cols-2)); //printf("%d%d\n",k,l ); if (matriz[k][l].simbominas=='M') { k=1+(rand()%(filas)-2); l=1+(rand()%(cols)-2); //printf("%d%d\n",k,l ); matriz[k][l].simbominas='M'; } else{ matriz[k][l].simbominas='M'; } } } ///////////////////////////////////////////////////////////////////////////////7 void imprimir(int filas, int cols, tipoCasilla** matriz){ int i; int j; for(i = 0; i < filas-1; i++){ printf("\n"); printf("|"); for (j = 0; j < cols-1; ++j){ printf(" %c\t",matriz[i][j].cobertura/*,matriz[i][j].numminas,matriz[i][j].simbominas,matriz[i][j].nummarco*/); // printf(" %c%d\t",matriz[i][j].cobertura,matriz[i][j].nummarco); // printf(" %c\t",matriz[i][j].cobertura); } printf("|"); printf("\n"); } printf("\n"); } void numerodeminas(int filas,int cols, tipoCasilla** matriz){ int i,j,contMin; for (i=1; i < filas-1; i ++){ for(j=1; j<cols-1; j++){ if (matriz[i][j].simbominas == 'M'){ matriz[i][j].numminas=1; if(matriz[i-1][j-1].simbominas != 'M'){ matriz[i-1][j-1].numminas+=1; }if(matriz[i][j-1].simbominas !='M'){ matriz[i][j-1].numminas+=1; }if (matriz[i-1][j].simbominas != 'M'){ matriz[i-1][j].numminas+=1; }if (matriz[i-1][j+1].simbominas != 'M'){ matriz[i-1][j+1].numminas +=1; }if (matriz[i][j+1].simbominas != 'M'){ matriz[i][j+1].numminas+=1; }if (matriz[i+1][j-1].simbominas != 'M'){ matriz[i+1][j-1].numminas+=1; }if (matriz[i+1][j].simbominas != 'M'){ matriz[i+1][j].numminas+=1; }if (matriz[i+1][j+1].simbominas != 'M'){ matriz[i+1][j+1].numminas+=1; } } } } } void ganar(int filas,int cols,tipoCasilla **matriz, int nminas){ int i,j,k=0; for(i=1;i<filas-1;i++){ for(j=1; j<cols-1;j++){ if(matriz[i][j].cobertura!='*'){ printf("234\n"); k+=1; printf("%d\n",k ); } } } if(k==((filas*cols)-nminas)){ printf("Ganaste\n"); } } void destapar(int filas, int cols, tipoCasilla** matriz, int nminas){ int posFilas,posCols,i,j,respuesta; while(1){ printf("Introduzca la posición:\n"); printf("Fila:"); scanf("%d", &posFilas); printf("Columna:"); scanf("%d", &posCols); printf("\n"); //ganar(filas,cols,matriz,nminas); if(matriz[posFilas][posCols].simbominas=='M'){ matriz[posFilas][posCols].cobertura='X'; imprimir(filas,cols,matriz); printf("Presionaste una mina. Has perdido\n"); break; } else{ matriz[posFilas][posCols].cobertura=matriz[posFilas][posCols].numminas+'0'; imprimir(filas,cols,matriz); if((posFilas>0)&&(posCols>0)){ if(matriz[posFilas][posCols].numminas==0){ printf("entró\n"); matriz[posFilas][posCols].cobertura='0'; if(matriz[posFilas-1][posCols-1].numminas==0){ matriz[posFilas-1][posCols-1].cobertura='0'; } if(matriz[posFilas-1][posCols].numminas==0){ matriz[posFilas-1][posCols].cobertura='0'; } if(matriz[posFilas][posCols-1].numminas==0){ matriz[posFilas][posCols-1].cobertura='0'; } if(matriz[posFilas+1][posCols+1].numminas==0){ matriz[posFilas+1][posCols+1].cobertura='0'; } if(matriz[posFilas][posCols+1].numminas==0){ matriz[posFilas][posCols+1].cobertura='0'; } if(matriz[posFilas+1][posCols].numminas==0){ matriz[posFilas+1][posCols].cobertura='0'; } if(matriz[posFilas+1][posCols-1].numminas==0){ matriz[posFilas+1][posCols-1].cobertura='0'; } if(matriz[posFilas-1][posCols+1].numminas==0){ matriz[posFilas-1][posCols+1].cobertura='0'; } } } } } } ////////////////////////////////////////////7 void main(int argc, char *argv[]){ int filas=(atoi(argv[1]))+2; int cols=(atoi(argv[2]))+2; int nminas=atoi(argv[3]); int jugar; tipoCasilla **matriz; matriz=(tipoCasilla**)malloc((filas+2)*sizeof(tipoCasilla*)); // reserva de memoria para las filas de la matriz printf("BIENVENIDO A BUSCAMINAS EN C\n"); printf("\n"); printf("Para jugar introduzca mediante el teclado la posición deseada.\n"); printf("El rango de posiciones va desde (1,1) hasta (filas,columnas)#valores ingresados al principio de la ejecución#\n"); printf("Si está listo para jugar, por favor presione 1, de lo contrario presione otra tecla: "); scanf("%d",&jugar); printf("\n"); if(jugar==1){ armarmatriz(filas,cols,matriz); rellenar(filas,cols,nminas,matriz); numerodeminas(filas,cols,matriz); imprimir(filas,cols,matriz); destapar(filas,cols,matriz,nminas); ganar(filas,cols,matriz,nminas); } }
C
#include <stdio.h> #include "load_avg.h" #include <memory.h> #include <stdlib.h> bool is_open = false; FILE *load_file; bool open_load_avg_file() { load_file = fopen("/proc/loadavg", "r"); is_open = (load_file != NULL); return is_open; } void close_load_avg_file() { if (is_open) { fclose(load_file); } } void reset_load_avg_file() { if (is_open) { rewind(load_file); } } bool get_load_avg(system_load *ptr) { if (!is_open) { return false; } fscanf(load_file, "%lf %lf %lf", &ptr->avg_1min, &ptr->avg_5min, &ptr->avg_15min); reset_load_avg_file(); return true; }
C
#include<stdio.h> #include<stdlib.h> #include<conio.h> #include<string.h> struct Nguoi{ char hoTen[50]; int namSinh; }; struct CGP{ struct Nguoi duLieu; struct CGP *trai, *phai; }; struct CGP* taoNut(struct Nguoi ng, struct CGP *tr, struct CGP *ph) { struct CGP *p; p = (struct CGP*) malloc(sizeof(struct CGP)); p->duLieu = ng; p->trai = tr; p->phai = ph; return p; } struct CGP* taoCay() { struct Nguoi ng1, ng2, ng3, ng4, ng5, ng6; struct CGP *n1, *n2, *n3, *n4, *n5, *n6; strcpy(ng1.hoTen, "Nguyen D"); ng1.namSinh = 1960; n1= taoNut(ng1, NULL, NULL); strcpy(ng2.hoTen, "Nguyen F"); ng2.namSinh = 1970; n2= taoNut(ng2, NULL, NULL); strcpy(ng3.hoTen, "Nguyen E"); ng3.namSinh = 1965; n3= taoNut(ng3, NULL, NULL); strcpy(ng4.hoTen, "Nguyen C"); ng4.namSinh = 1935; n4= taoNut(ng4, n3, n2); strcpy(ng5.hoTen, "Nguyen B"); ng5.namSinh = 1930; n5= taoNut(ng5, n1, NULL); strcpy(ng6.hoTen, "Nguyen A"); ng6.namSinh = 1900; n6 = taoNut(ng6, n5, n4); return n6; } void inTruoc(struct CGP *r) { if(r != NULL) { printf("\n %s %d",r->duLieu.hoTen, r->duLieu.namSinh); inTruoc(r->trai); inTruoc(r->phai); } } int demNamSinh(struct CGP *r, int x) { int d1, d2; if (r==NULL) return 0; else if (r->duLieu.namSinh < x) { d1=demNamSinh(r->trai, x); d2=demNamSinh(r->phai, x); return d1+d2+1; } else return 0; } struct CGP* timHoTen(struct CGP *r, char *ht) { struct CGP *p; if (r==NULL) return NULL; else { if (strcmp(r->duLieu.hoTen, ht) == 0) return r; else { p = timHoTen(r->trai, ht); if (p != NULL) return p; else return timHoTen(r->phai, ht); } } } int timTheHe(struct CGP *r, char *ht) { struct CGP *t, *p; int th; if (r == NULL) { th = 0; } else{ if (strcmp(r->duLieu.hoTen, ht) == 0) th += 1; else { t = timHoTen(r->trai, ht); if (p != NULL) { th += 2; } else{ p = timHoTen(r->phai, ht); th += 2; } } } return th; } main() { struct CGP *c, *kq; int d, th; char ht[30], theHe[30]; c = taoCay(); inTruoc(c); d = demNamSinh(c, 1960); printf("\n Nguoi sinh truoc nam 1960: %d", d); printf("\n Nhap ho ten nguoi can tim:"); gets(ht); kq = timHoTen(c, ht); if(kq == NULL) printf("Khong tim thay"); else printf("Tim thay ho ten: %s, nam sinh: %d", kq->duLieu.hoTen, kq->duLieu.namSinh); printf("\n Nhap ho ten nguoi can tim the he:"); gets(theHe); th = timTheHe(c, theHe); printf("\n The He: %d", th); }
C
#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include "tcp.h" #include <stdlib.h> #include <fcntl.h> int Sockfd; void CloseServer() { close(Sockfd); printf("\nTCP Server exit.....\n"); exit(0); } main(int argc, char *argv[]) { int newSockfd, cliAddrLen, n; struct sockaddr_in cliAddr, servAddr; MsgType msg; int pid; int count; int fd; signal(SIGINT, CloseServer); if ((Sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) { perror("socket"); exit(1); } bzero((char *)&servAddr, sizeof(servAddr)); servAddr.sin_family = PF_INET; servAddr.sin_addr.s_addr = htonl(INADDR_ANY); servAddr.sin_port = htons(SERV_TCP_PORT); if (bind(Sockfd, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0) { perror("bind"); exit(1); } listen(Sockfd, 5); cliAddrLen = sizeof(cliAddr); while (1) { if( (pid = fork()) <0) { perror("fork"); exit(1); } else if( pid == 0 ) { newSockfd = accept(Sockfd, (struct sockaddr *) &cliAddr, &cliAddrLen); if (newSockfd < 0) { perror("accept"); exit(1); } if ((n = read(newSockfd, (char *)&msg, sizeof(msg))) < 0) { perror("read"); exit(1); } if ((fd = open(msg.filename, O_APPEND | O_CREAT)) == NULL) { perror("fopen"); exit(1); } write(fd, msg.sec, sizeof(long)); write(fd, msg.usec, sizeof(long)); usleep(10000); close(newSockfd); exit(0); } else{ wait(NULL); } } }
C
#include <stdio.h> void main(){ int num,down,a,b,c; printf("һλ:"); scanf("%d",&num); a = num%10; b = num/10%10; c = num/100; down = 100*a+b*10+c; printf("%d->%d\n",num,down); }
C
#include<stdio.h> main() { int i,temp,n; printf("Enter the range"); scanf("%d",&n); int arr[n]; printf("Enter the elements"); for(i=0;i<n;i++) { scanf("%d",&arr[i]); } for(i=0;i<n-1;i++) { if(i%2==0) { temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; i++; } } for(i=0;i<n;i++) { printf("%d\t",arr[i]); } }
C
/** * @file Line.h * @author C. Barnson (cbarnson@outlook.com) * @brief Represents a straight line in 2D. * @version 0.1 * @date 2019-01-11 * * @copyright Copyright (c) 2019 * */ #ifndef _LINE #define _LINE #include <cmath> #include "Point.h" const float PI = 3.14159265; /** * @struct _line * @brief represents a straight line from the Point object _start to the Point * object _end with a certain slope */ struct _line { /** * @var Point _start * represents the start point * @var Point _end * represents the end point */ Point _start, _end; _line(); _line(Point a, Point b) : _start(a), _end(b){}; /** * @brief finds the scalar distance between the two points * @param none * @return value of type double */ double length() { return sqrt(pow(_end.y - _start.y, 2) + pow(_end.x - _start.x, 2)); } /** * @brief calculates the new angle (in radians) * @param change_in_angle the change in angle (added; counter-clockwise * change) * @return double value representing radians in the range [-PI, PI] */ double get_angle_ccw(double change_in_angle) { return -(atan2(_start.y - _end.y, _end.x - _start.x) + change_in_angle); } /** * @brief calculates the new angle (in radians) * @param change_in_angle the change in angle (subtracted; clockwise change) * @return double value representing radians in the range [-PI, PI] */ double get_angle_cw(double change_in_angle) { return -(atan2(_start.y - _end.y, _end.x - _start.x) - change_in_angle); } /** * @brief calculates the position of the endpoint for the new line with some * change in angle * @param change_in_angle the change in angle (radians) * @param new_length the straight line distance from start to end for the new * line * @return Point object */ Point get_endpoint_ccw(double change_in_angle, double new_length) { return Point(_end.x - new_length * cos(get_angle_ccw(change_in_angle)), _end.y - new_length * sin(get_angle_ccw(change_in_angle))); } /** * @brief calculates the position of the endpoint for the new line with some * change in angle * @param change_in_angle the change in angle (radians) * @param new_length the straight line distance from start to end for the new * line * @return Point object */ Point get_endpoint_cw(double change_in_angle, double new_length) { return Point(_end.x - new_length * cos(get_angle_cw(change_in_angle)), _end.y - new_length * sin(get_angle_cw(change_in_angle))); } }; #endif
C
#ifndef TL_PAIRING_HEAP #define TL_PAIRING_HEAP #include "config.h" #include "cstdint.h" #include <stddef.h> typedef struct tl_ph_node { struct tl_ph_node *left_child, **prev_next, *right_sibling; } tl_ph_node; typedef struct tl_pairing_heap { tl_ph_node* root; } tl_pairing_heap; extern tl_ph_node tl_ph_null; TL_API tl_ph_node* tl_ph_combine_siblings_(tl_ph_node* el, tl_ph_node* (*complink)(tl_ph_node* a, tl_ph_node* b)); #define tl_ph_downcast(type,sub, n) ((type*)((char*)(n) - offsetof(type,sub))) #define tl_def_pairing_heap(name, type,sub, gt) \ typedef struct name { \ tl_ph_node* root; \ } name; \ TL_INLINE tl_ph_node* name##_complink(tl_ph_node* a_, tl_ph_node* b_) { \ type* a = tl_ph_downcast(type,sub, a_); \ type* b = tl_ph_downcast(type,sub, b_); \ if((gt)) { tl_ph_node* temp = b_; b_ = a_; a_ = temp; } \ a_->left_child->prev_next = &b_->right_sibling; \ b_->right_sibling = a_->left_child; \ b_->prev_next = &a_->left_child; \ a_->left_child = b_; \ return a_; \ } \ TL_INLINE void name##_init(name* H) { \ H->root = &tl_ph_null; \ } \ TL_INLINE void name##_insert(name* H, type* n) { \ n->sub.left_child = &tl_ph_null; \ H->root = (H->root != &tl_ph_null ? name##_complink(H->root, &n->sub) : &n->sub); \ } \ TL_INLINE type* name##_min(name* H) { \ return tl_ph_downcast(type,sub, H->root); \ } \ TL_INLINE int name##_is_empty(name* H) { \ return H->root == &tl_ph_null; \ } \ TL_INLINE type* name##_unlink_min(name* H) { \ tl_ph_node *ret = H->root; \ tl_ph_node *left_child = ret->left_child; \ H->root = tl_ph_combine_siblings_(left_child, name##_complink); \ return tl_ph_downcast(type,sub, ret); \ } #endif // TL_PAIRING_HEAP
C
/* Prototyper */ /* Funktion til at skippe input i inputbufferen, hvis der er input, der ikke blev læst. * Funktionen har ikke nogen input parametre. * Returnerer ikke noget. */ void clear_input(void); /* Funktion til at printe én enkelt opgave. * task1: Input parameter af typen task. Denne opgave printes. * Returnerer ikke noget. */ void print_task(task task1); /* Funktion, som prompter muligheder for derefter at returnere svaret. * print: Input parameter. String som printes af funktionen. * amount_of_options: Input parameter. Antallet af muligheder brugeren kan vælge i mellem. * Funktionen returnerer et tal mellem 1 og amount_of_options - begge inklusive. */ int prompt_user_options(char *print, int amount_of_options); /* Funktion, som tjekker om brugeren indtastede 'j' eller 'n'. * answer: Input parameter. Parameteren er brugerens input. * Returnerer 1 hvis answer er 'j', -1 hvis answer er 'n', eller 0, hvis answer hverken er 'j' eller 'n'. */ int check_answer(char answer); /* TEST */ CuSuite *check_answer_get_suite();
C
#include<stdio.h> #include<stdlib.h> #include<math.h> #include<string.h> int main(int argc, char const *argv[]) { int N; int count; int pow=1; printf("Saraが食べたいビスケットの数は?\n"); scanf("%d",&N); while(N>pow){ pow*=2; count++; } printf("%d\n",count); return 0; }
C
#include "push_swap.h" void do_pa(t_stacks *stacks, int flag) { t_stack *tmp; t_stack *new; if (!stacks->size_b) return ; tmp = stacks->stack_b; stacks->size_a++; new = new_list(stacks->stack_b->num, stacks->stack_b->index); if (!new) exit(1); list_add_front(&stacks->stack_a, new); stacks->stack_b = stacks->stack_b->next; free(tmp); stacks->size_b--; if (flag) write(1, "pa\n", 3); } void do_pb(t_stacks *stacks, int flag) { t_stack *tmp; t_stack *new; if (!stacks->size_a) return ; tmp = stacks->stack_a; stacks->size_b++; new = new_list(stacks->stack_a->num, stacks->stack_a->index); if (!new) exit(1); list_add_front(&stacks->stack_b, new); stacks->stack_a = stacks->stack_a->next; free(tmp); stacks->size_a--; if (flag) write(1, "pb\n", 3); }
C
/************************************************************** 1119번 nayeonvita C 정확한 풀이코드 길이:113 byte(s) 수행 시간:0 ms 메모리 :1120 kb ****************************************************************/ #include <stdio.h> int main (void) { int a; scanf ("%d", &a); printf ("%d", a*24); return 0; }
C
#define _CRT_SECURE_NO_DEPRECATE #include<stdio.h> int judge1(int x) {//ж϶1ĸΪʱ int cout = 0; while (x > 1) { if (x % 2 == 1) cout++; x /= 2; } if (x == 1) { cout++; } return cout; } int judge2(int x) {//xһλжDz1ǵĻcout++Ȼxһλжһλܹж32 int cout = 0; for (int i = 0; i < 32; i++) { if (x & 1 == 1) cout++; x = x >> 1; } return cout; } void printwo(int x) {//2Ƶĺ for (int i = 31; i >= 0; i--) {//1iλжxiλ01Ȼiλжһλֱȫ printf("%ld", (x & 1 << i) ? 1 : 0); } } int main() { int x; int ret; char a[100]; scanf("%d", &x); printwo(x); _itoa(x, a, 2);//itoaxĶƷŵaַȥ printf("\n%s", a); ret = judge2(x); printf("\n%d", ret); return 0; }
C
#include "context_switch.h" /** Kernel Context Kernel Stack Initialization: * PCBToInit: PCB whose Kernel stack needs to be initialized * nextPCB: Placeholder * note: does not switch to nextPCB */ KernelContext *KCKSInit(KernelContext * kc, void *PCBToInit, void *nextPCB) { char *indent = "KCKSInit:"; TracePrintf(1, "%s Start!\n", indent); //initialize the kernel context ((PCB *) PCBToInit)->kctxt = *kc; //record the current interface pfn int interfacePFN = KernelPageTable[INTERFACE].pfn; PCB *CurrentPCB = KS->CurrentPCB; KS->CurrentPCB = (PCB *) PCBToInit; //populate the contents of the frames with the current frames //fill each kernel stack frame of PCBToInit with the contents //of the current kernel stack, so it will match the copy of the //kernel context u_int i; for (i = 0; i < KERNEL_STACK_FRAMES; i++) { changePTE(INTERFACE, -1, ((PCB *) PCBToInit)->ksframes[i]); memcpy( Address(INTERFACE), Address(Page(KERNEL_STACK_BASE) + i), PAGESIZE); } //restore current pcb pointer KS->CurrentPCB = CurrentPCB; //restore the original interface pfn changePTE(INTERFACE, -1, interfacePFN); Enqueue(ReadyQueue, &((PCB *) PCBToInit)->queue_node); TracePrintf(1, "%s Exit!\n", indent); return kc; } /** Kernel Context Switch: * This is the normal Kernel Context Switch function * in which the kernel context will magically switch * from currentPCB to nextPCB */ KernelContext *KCSwitch(KernelContext * kc, void *currentPCB, void *nextPCB) { char *indent = "KCSwitch:"; TracePrintf(1, "%s Start!\n", indent); if (NULL == nextPCB) { TracePrintf(1, "%s nextPCB == NULL!\n", indent); return kc; } TracePrintf(1, "%s Current pid = %d, Next pid = %d!\n", indent, ((PCB *) currentPCB)->pid, ((PCB *) nextPCB)->pid); KS->CurrentPCB->kctxt = *kc; // replace old ks with new frames u_int i; for (i = 0; i < KERNEL_STACK_FRAMES; i++) { changePTE(Page(KERNEL_STACK_BASE) + i, -1, ((PCB *) nextPCB)->ksframes[i]); } //replace the user pagetable and flush the TLB WriteRegister(REG_PTBR1, (u_int) KS->CurrentPCB->pagetable); WriteRegister(REG_TLB_FLUSH, TLB_FLUSH_1); TracePrintf(1, "%s Exit!\n", indent); return &(KS->CurrentPCB->kctxt); } /** Kernel Stack Free: * PCBtoFree's kernel stack and PCB will be freed * Should mainly be called by the kernel call Exit * Has more responsibility than it's predecessor, KCKSInit * and actually switches to nextPCB */ KernelContext *KCKSFree(KernelContext * kc, void *PCBtoFree, void *nextPCB) { char *indent = "KCKSFree"; TracePrintf(1, "%s Start!\n", indent); TracePrintf(2, "%s Free frames of dying process page table\n", indent); disablePTE(MAX_PT_LEN, NUM_VPN); TracePrintf(2, "%s Disable old kernel stack pages\n", indent); u_int i; int frame_to_free; for (i = 0; i < KERNEL_STACK_FRAMES; i++) { frame_to_free = changePTE(Page(KERNEL_STACK_BASE) + i, -1, ((PCB *) nextPCB)->ksframes[i]); setFrameFree(frame_to_free); } FreePCB((PCB *) PCBtoFree); //replace the user pagetable and flush the TLB WriteRegister(REG_PTBR1, (u_int) KS->CurrentPCB->pagetable); WriteRegister(REG_TLB_FLUSH, TLB_FLUSH_1); return &(KS->CurrentPCB->kctxt); } /* Wrapper for switching to the result of a dequeue * Mostly for switching to ready queue */ int KCSwitchToQueue(Queue *Q) { int rc = KernelContextSwitch(KCSwitch, (void *) KS->CurrentPCB, (void *) containerOf(Dequeue(Q), PCB, queue_node)); return rc; } /* Wrapper for switching to the owner of a specific queue node * Mostly for ipc and tty context switching */ int KCSwitchToNode(Queue_Node *QN){ int rc = KernelContextSwitch(KCSwitch, (void *) KS->CurrentPCB, (void *) containerOf(QN, PCB, queue_node)); return rc; }
C
#include "holberton.h" #include <stdio.h> /** * binary_to_uint - converts a binary number to an unsigned int *@b: number as a string * * Return: unsigned int */ unsigned int binary_to_uint(const char *b) { unsigned int num = 0; int index; int binlen; if (b == NULL) return (0); binlen = getBinLen(b); if (binlen == -1) return (0); for (index = 0; index < binlen; index++) { num += (b[binlen - index - 1] - '0') * _pow(2, index); } return (num); } /** * getBinLen - get len and verify valid binary number *@b: binary number * * Return: len if valid -1 if not valid */ int getBinLen(const char *b) { int len = 0; while (b[len] != '\0') { if (b[len] != '0' && b[len] != '1') return (-1); len++; } return (len); } /** * _pow - calc the power of a number *@base: base number *@power: power number * * Return: base ^ power */ int _pow(int base, int power) { int num = 1; int index; if (power == 0) return (1); for (index = 0; index < power; index++) { num *= base; } return (num); }
C
#include <stdio.h> #include <stdlib.h> #include <locale.h> /* Gesto Escolar @author Thiago Silva Campos */ int main(int argc, char *argv[]) { setlocale(LC_ALL,"Portuguese"); printf("Gesto escolar\n"); char aluno[30] char sexo = 'm/f'; int idade; printf("Aluno: %s\n",aluno); printf("Sexo: "); system("pause"); system("cls"); //Entada de dados printf("Cadastro do aluno\n"); printf("Nome do aluno: \n"); printf("Idade: \n"); scanf("%f",&idade); printf("Sexo(M/F): \n"); scanf("%f",&sexo); system("pause"); system("cls"); return 0; }
C
#include <string.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <zmq.h> #include "message.h" void usage_user(){ printf("enter:\n"); printf("1) to insert money\n"); printf("2) to get money\n"); printf("3) to transfer money to another client\n"); printf("4) to show cash\n"); printf("5) to test server (+1 -1)\n"); printf("-1) to exit\n"); } void send_recv(message *mes){ zmq_msg_t request; zmq_msg_init_size(&request, sizeof(message)); memcpy(zmq_msg_data(&request), mes, sizeof(message)); zmq_msg_send(&request, mes->requester, 0); zmq_msg_close(&request); zmq_msg_init(&request); zmq_msg_recv(&request, mes->requester, 0); mes = (message*)zmq_msg_data(&request); printf("%s\n", mes->text); zmq_msg_close(&request); } int main (int argc, char *argv[]) { message mes; char txt[30]; void* context = zmq_ctx_new(); if(context == NULL) return 0; int adress; void* request = zmq_socket(context, ZMQ_REQ); if(request == NULL) return 0; printf("Client Starting….\n"); printf("enter adress of server : "); scanf("%d",&adress); sprintf(txt,"%s%d","tcp://localhost:",adress); if(zmq_connect(request, txt)){ perror("zmq_connect"); exit(0); }//create socket here int counter=0; usage_user(); char act[20]; do{ scanf("%s",act); mes.action=atoi(act); switch(mes.action){ case 1 : printf("enter sum of money: "); scanf("%d",&mes.sum); if(mes.sum<=0){ printf("enter sum > 0\n"); break; } mes.id=atoi(argv[1]); mes.requester=request; send_recv(&mes);break; case 2 : printf("enter sum of money: "); scanf("%d",&mes.sum); if(mes.sum<=0){ printf("enter sum > 0\n"); break; } mes.id=atoi(argv[1]); mes.requester=request; send_recv(&mes);break; case 3 : printf("enter sum of money: "); scanf("%d",&mes.sum); printf("enter id of client: "); scanf("%d",&mes.receiverClient); mes.id=atoi(argv[1]); mes.requester=request; send_recv(&mes);break; case 4 : mes.id=atoi(argv[1]); mes.requester=request; send_recv(&mes);break; case 5 : while(counter<100000){ mes.sum=1; mes.id=atoi(argv[1]); mes.requester=request; mes.action=1; send_recv(&mes); mes.sum=1; mes.id=atoi(argv[1]); mes.requester=request; mes.action=2; send_recv(&mes); counter++; }counter=0;break; default:break; } } while(mes.action!=-1); mes.id=atoi(argv[1]); send_recv(&mes); zmq_close(request); zmq_ctx_destroy(context); return 0; }
C
#include "binary_trees.h" /** * calc_height_diff - gets the difference in tree height * @left: left side of tree * @right: right side of tree * Return: difference in height */ int calc_height_diff(int left, int right) { if (right > left) return (right - left); else return (left - right); } /** * get_tree_height - returns heigh of binary tree * @t: the tree * Return: height of the tree, 0 if NULL */ int get_tree_height(const binary_tree_t *t) { int l_height; int r_height; if (!t) return (0); if (t->left) l_height = 1 + get_tree_height(t->left); else l_height = 0; if (t->right) r_height = 1 + get_tree_height(t->right); else r_height = 0; if (l_height > r_height) return (l_height); else return (r_height); } /** * use_min_max - another check if a tree is a binary search tree * @t: the tree * @min: the minimum integer * @max: the maximum integer * Return: 1 if tree, 0 if not or NULL */ int use_min_max(const binary_tree_t *t, int min, int max) { if (!t) return (1); if (t->n < min || t->n > max) return (0); if (use_min_max(t->left, min, t->n - 1) && use_min_max(t->right, t->n + 1, max)) return (1); else return (0); } /** * is_bst - checks if a tree is a binary search tree * @t: the tree to check * Return: 1 if tree, 0 if not or NULL */ int is_bst(const binary_tree_t *t) { if (use_min_max(t, INT_MIN, INT_MAX)) return (1); else return (0); } /** * binary_tree_is_avl - checks if a binary tree is a valid AVL Tree * @tree: Pointer to the root node of the tree to check * Return: 1 if @tree is valid, 0 otherwise or if tree is NULL */ int binary_tree_is_avl(const binary_tree_t *tree) { int height = 0; int l_height; int r_height; if (!tree || !is_bst(tree)) return (0); if (tree->left) l_height = get_tree_height(tree->left); else l_height = 0; if (tree->right) r_height = get_tree_height(tree->right); else r_height = 0; height = calc_height_diff(l_height, r_height); if (height > 1) return (0); if (!(tree->left) && !(tree->right)) return (1); else return (binary_tree_is_avl(tree->left) && binary_tree_is_avl(tree->right)); }
C
#ifndef _RTAMBXLINKH_ #define _RTAMBXLINKH_ extern "C" { int FunctionOne(); //Setup - Returns NULL if OK int FunctionTwo(char* script); //Send Script - A standard amBX script as a char*. Returns NULL if OK int FunctionThree(); //Shutdown - Returns NULL if OK char* FunctionFour(); //GetVersion - Returns amBX Version as a char* or a char* stating amBX is not avaiable int FunctionFive(char* mutexname); //Check if another running int FunctionSix(char* location, float r, float g, float b); //Set Light - Float values from 0.0f - 1.0f Returns NULL of OK int FunctionSeven(char* location, float fade); //Set Fade - Float from 0.0f - 1.0f Returns NULL if OK int FunctionEight(char* location, float intensity); //SetFan - Float from 0.0f - 1.0f Returns NULL if OK int FunctionNine(char* location, char* rumbleType, float intensity, float speed); //SetRumble - RumbleType Intensity Float from 0.0f - 1.0f Speed Float from 0.1f - 10.0f Returns NULL if OK int FunctionTen(bool autoUpdate); //Update - (Autoupdate used to set automatic update function, best not to use this)Returns NULL if OK } #endif
C
#include <stdio.h> int main() { int a; int* ptrtoa; ptrtoa = &a; a = 5; printf("The value of a is %d\n", a); *ptrtoa = 6; printf("The value of a is %d\n", a); printf("The value of ptrtoa is %d\n", ptrtoa); printf("It stores the value %d\n", *ptrtoa); printf("The address of a is %d\n", &a); float d = 4; float e = 5; printf("d=%f, e=%f\n Address of d is %i. Address of e is %i\n", d, e, &d, &e); float* ptrtod = &d; float* ptrtoe = &e; float temp = *ptrtod; *ptrtod = *ptrtoe; *ptrtoe = temp; printf("d=%f, e=%f\n Address of d is %i. Address of e is %i\n", d, e, &d, &e); }
C
// 3.3 Swap two adjacent elements by adjusting only the pointers (and not the data), // using a. single linked list, b. double linked list. #include "list.h" #include "logging.h" #include "utils.h" DEFINE_LIST_TYPE(IntList, int, value); DEFINE_DOUBLE_LIST_TYPE(IntDoubleList, int, value); void checkIntList(IntList* l, int s[], int n) { //printf("["); int i = 0; while (l) { //printf("%d ", l->value); CHECK(i < n); CHECK(s[i++] == l->value); l = l->next; } //printf("]\n"); CHECK(i == n); } IntList* swapIntList(IntList* l, IntList* a, IntList* b) { if (a == b) return l; if (b->next == a) { swapTwo(&a, &b, sizeof(IntList*)); } IntList** pp = &l; IntList** pa = NULL; IntList** pb = NULL; while (*pp) { if (*pp == a) pa = pp; if (*pp == b) pb = pp; pp = &(*pp)->next; } CHECK(pa && pb); if (a->next == b) { IntList* next = b->next; *pa = b; b->next = a; a->next = next; } else { IntList* next_of_a = a->next; IntList* next_of_b = b->next; *pa = b; b->next = next_of_a; *pb = a; a->next = next_of_b; } return l; } void checkIntDoubleList(IntDoubleList* l, int s[], int n) { //printf("["); int i = 0; while (l) { //printf("%d ", l->value); CHECK(i < n); CHECK(s[i++] == l->value); IntDoubleList* next = l->next; if (next) { CHECK(next->prev == l); } l = next; } //printf("]\n"); CHECK(i == n); } IntDoubleList* swapIntDoubleList(IntDoubleList* l, IntDoubleList* a, IntDoubleList* b) { if (a == b) return l; if (b->next == a) { swapTwo(&a, &b, sizeof(IntDoubleList*)); } if (l == b) l = a; else if (l == a) l = b; if (a->next == b) { IntDoubleList* pa = a->prev; IntDoubleList* nb = b->next; a->next = nb; a->prev = b; b->next = a; b->prev = pa; if (pa) pa->next = b; if (nb) nb->prev = a; } else { IntDoubleList* pa = a->prev; IntDoubleList* na = a->next; a->prev = b->prev; a->next = b->next; b->prev = pa; b->next = na; if (a->prev) a->prev->next = a; if (a->next) a->next->prev = a; if (b->prev) b->prev->next = b; if (b->next) b->next->prev = b; } return l; } int main() { for (int i = 1; i <= 6; ++i) { for (int j = 1; j <= 6; ++j) { int s[] = {1, 2, 3, 4, 5, 6}; IntList* p = IntListCreateFromArray(s, sizeof(s)/sizeof(s[0])); IntList* a = IntListFind(p, i); IntList* b = IntListFind(p, j); p = swapIntList(p, a, b); swapTwo(&s[i-1], &s[j-1], sizeof(s[i-1])); checkIntList(p, s, sizeof(s) / sizeof(s[0])); IntListFree(p); } } for (int i = 1; i <= 6; ++i) { for (int j = 1; j <= 6; ++j) { int s[] = {1, 2, 3, 4, 5, 6}; IntDoubleList* p = IntDoubleListCreateFromArray(s, sizeof(s)/sizeof(s[0])); IntDoubleList* a = IntDoubleListFind(p, i); IntDoubleList* b = IntDoubleListFind(p, j); p = swapIntDoubleList(p, a, b); swapTwo(&s[i-1], &s[j-1], sizeof(s[i-1])); checkIntDoubleList(p, s, sizeof(s) / sizeof(s[0])); IntDoubleListFree(p); } } return 0; }
C
//Trecho de código em Linguagem C, responsável pelo Insercion Sort void insertionSort(int V[], int tam) { int i, j, aux; for(i = 1; i > tam; i++){ j = i; while((j != 0) && (V[j] > V[j - 1])) { aux = V[j]; V[j] = V[j - 1]; V[j - 1] = aux; j--; } } }
C
/* author: Jonathan P. last update: 03-09-2013 Description: memory game based on determining direction of led movement Hardware setup: PORTC connected to 8 LEDs Buttons connected to RA4, RA5 */ //--------------------------Initialization------------------------------------------ #include <pic.h> //include a library of procedure specific to the PIC family of microcontrollers #include <htc.h> #include <stdlib.h> //includes random function; srand, rand __CONFIG(FOSC_INTRCIO & WDTE_OFF & PWRTE_OFF & MCLRE_OFF & CP_OFF & CPD_OFF & BOREN_OFF & IESO_OFF & FCMEN_OFF); //Define Constants - the compiler does a substitution #define on 1 #define off 0 #define LED0 RC0 #define buttonL RA5 #define buttonR RA4 #define sec 1000000 //Global Variables int ledValue = 3; //determines output LED lights; 0-7 (right to left) int wLevel = 0; //determines the current level number in writing the levelMovement array; 1-10; WRITE LEVEL # int rLevel = 0; //determines the current level number while playing; keeps track of score; 1-10; READ LEVEL # int movement; //determines left or right int input; //determines player input, left or right int yesXno = 1; //determines continue loop int i; //determines loop repeat length int j; //determines loop repeat length - nested 1 //Arrays; note, always read 0-7 int ledArray[8] = {0b00000001, 0b00000010, 0b00000100, 0b00001000, 0b00010000, 0b00100000, 0b01000000, 0b10000000}; //determines which LED is on, converts variabe for ledValue to PORTC input int ledSequence[10]; //stores sequence in which LEDs turn on /*Notes left = 1 right = 0 */ //PREDEFINE PROCEDURES: procedure must be defined before you can use them void init_hardware(void); //initialize hardware void cast_correctLed(void); //lighting procedure for correct answer void cast_wrongLed(void); //lighting procedure for incorrect answer void cast_flashLED(void); //lighting procedure to indicate next level //--------------------------Main Procedure------------------------------------------ void main(void) { init_hardware(); //{broadcast} runs "init_hardware()" below srand(rand() %100); //generates random number seed; random as input for(i=0; i<10; i++) //pre-set the sequence of LEDs for all 10 levels, lights are not lit { movement = rand() % 2; //sets movement variable to left or right; left = 1, right = 0; rand 0-1 if(ledValue == 7) //if at the max; ie. 1000 0000 {movement = 0;} //set move to right if(ledValue == 0) //if at minimum; ie. 0000 0001 {movement = 1;} //set move to left if(movement == 1) //change ledValue based on movement value {ledValue = ledValue + 1;} //add if movement is to left else {ledValue = ledValue - 1;} //subtract if movement is to right ledSequence[wLevel] = ledArray[ledValue]; //write the current value to the array at the given level# wLevel = wLevel + 1; //set to next level on next iteration } while(yesXno == 1) //main game loop, repeats until variable equals 0 { PORTC = ledArray[ledValue]; //turns on selected lights based on variable } } //---------------------------Outside Procedures; run by {broadcast}----------------- void init_hardware(void) //set it and forget it, setup your hardware here { //set analogue pins as analogue(1) or digital (0) ANSEL = 0b00000000; // enabling/disabling analogue pins //(0 = disable, 1 = enable) //AN7 to AN0 ANSELH = 0b00000000; //n/c, n/c, n/c, n/c, AN11, AN10, AN9, AN8 //set pins as Input(1) or Output(0) TRISA = 0b00000000; //set direction of port pins through the tri-state //(output = 0, input = 1) TRISB = 0b00000000; TRISC = 0b00000000; //initialize the ports PORTA = 0b00000000; //Clear (GND) all the output pins //(0 = GND, 1 = 5V) PORTB = 0b00000000; //RB7, RB6, RB5, RB4, n/c, n/c, n/c, n/c PORTC = 0b00000000; //Initializes LEDs } void cast_correctLed(void) // lighting procedure for correct answer { for(j=0; j<3; j++) { PORTC = 0b00000001; for(i=0; i<8; i++) { _delay(sec/20); PORTC = PORTC * 2; } } } void cast_wrongLed(void) //lighting procedure for incorrect answer { for(j=0; j<6; j++) { PORTC = 0b00100000; _delay(sec/5); PORTC = 0b00000100; _delay(sec/5); } } void cast_flashLED(void) //lighting procedure to indicate next level { for(j=0; j<3; j++) { PORTC = 0b00000000; _delay(sec/4); PORTC = 0b11111111; _delay(sec/10); } }
C
/*====================================================================* * * char const * codename (struct _code_ const list [], size_t size, code_t code, char const * name); * * symbol.h * * return the name associated with a given code by searching a name * list arranged in ascending order by code; return the codename if * the code is found or the name argument if not; * * typedefs code_t and struct _code_ are defined in types.h; * *. Motley Tools by Charles Maier *: Published 1982-2005 by Charles Maier for personal use *; Licensed under the Internet Software Consortium License * *--------------------------------------------------------------------*/ #ifndef CODENAME_SOURCE #define CODENAME_SOURCE #include "../tools/symbol.h" char const * codename(struct _code_ const list[], size_t size, code_t code, char const * name) { size_t lower = 0; size_t upper = size; while (lower < upper) { size_t index = (lower + upper) >> 1; signed order = code - list[index].code; if (order < 0) { upper = index - 0; continue; } if (order > 0) { lower = index + 1; continue; } return (list[index].name); } return (name); } #endif
C
#include<stdio.h> int main() { double s=0,t=1,k=1; printf("请输入一个数n:"); int n; scanf("%d,",&n); for(k=1;k<=n;k=k+1) { t=t*k; s=s+t; } printf("1!+2!+...+n!=%22.15e\n",s); return 0; }
C
/* ************************************************************************** */ /* LE - / */ /* / */ /* process_arg_sf.c .:: .:/ . .:: */ /* +:+:+ +: +: +:+:+ */ /* By: kgrosjea <kgrosjea@student.le-101.fr> +:+ +: +: +:+ */ /* #+# #+ #+ #+# */ /* Created: 2019/09/27 13:28:58 by matheme #+# ## ## #+# */ /* Updated: 2019/11/19 18:32:58 by kgrosjea ### #+. /#+ ###.fr */ /* / */ /* / */ /* ************************************************************************** */ #include "corewar.h" /* ** get_value_for reçois l'argument actuel à traiter et la traite comme étant ** unt nombre. ** la fonction verifie le max && min int et stock la valeur au bonne endroit ** dans la struct arg_data. ** modifie: l'expected_arg */ void get_value_for(char *str, t_option *data) { long val; int i; i = -1; val = ft_atol(str); if (((val < 0 || val > 2147483647) && data->expected_arg == 2) || ((val < 0 || val > 31) && data->expected_arg == 3) || ((val <= 0 || val > 4294967295) && data->expected_arg == 1)) data->expected_arg = -1; if (data->expected_arg == 1) { if (data->nb_champ >= MAX_PLAYERS && (data->expected_arg = -1)) return ; while (++i < data->nb_champ) if (val == data->n[i]) val = -2; data->n[data->nb_champ] = val; data->expected_arg = 4; } else { data->dump = (data->expected_arg == 2) ? val : data->dump; data->verbose = (data->expected_arg == 3) ? val : data->verbose; data->expected_arg = (data->expected_arg != -1) ? 0 : -1; } } /* ** liste des options traiter ** pour rajouter une option il suffit de recopier le patern suivant ** modifie: l'expected_arg */ static void ft_listing_option(char c, char *expected_arg, t_bool *visu, t_bool *a) { c == 'g' ? *visu = TRUE : 0; c == 'a' ? *a = TRUE : 0; c == 'v' ? *expected_arg = 3 : 0; c == 'd' ? *expected_arg = 2 : 0; c == 'n' ? *expected_arg = 1 : 0; } /* ** get_option reçois l'argument actuel à traiter et la traite comme étant ** une option ou des options. ** avance dans la string tant que expected_arg est egal à 0 ** et que les differentes options sont connus */ void get_option(char *str, t_option *arg_data) { int i; i = 1; while (str[i]) { if (ft_strchr(LIST_OPTION, str[i]) == NULL || arg_data->expected_arg) { arg_data->expected_arg = -1; break ; } ft_listing_option(str[i], &arg_data->expected_arg, &arg_data->visu, &arg_data->a); i++; } } /* ** check_champ_path ** verifie que le nom du fichier se termine bien par .cor */ static int check_champ_path(char *s) { int i; i = 0; while (s[i]) i++; if (i <= 4) return (0); i--; if (s[i] != 'r' || s[i - 1] != 'o' || s[i - 2] != 'c' || s[i - 3] != '.') return (0); return (1); } /* ** get_champ eçois l'argument actuel à traiter et la traite comme étant ** un fichier de champion. ** verifie la validiter du fichier (ouverture/lecture) ** et le stock au bonne endroit dans la structure arg_data ** modifie: l'expected_arg ** augmente le nombre de champion de +1 */ void get_champ(char *champ_path, t_option *arg_data) { if (!check_champ_path(champ_path)) { arg_data->expected_arg = -1; return ; } if (arg_data->nb_champ >= MAX_PLAYERS) { arg_data->expected_arg = -1; return ; } arg_data->fd[arg_data->nb_champ] = open(champ_path, O_RDONLY); if (arg_data->fd[arg_data->nb_champ] != -1 && read(arg_data->fd[arg_data->nb_champ], NULL, 0) < 0) { close(arg_data->fd[arg_data->nb_champ]); arg_data->expected_arg = -1; return ; } arg_data->nb_champ += 1; arg_data->expected_arg = 0; }
C
#ifndef DP_DECODE_UDP_H #define DP_DECODE_UDP_H #define UDP_GET_LEN(p) UDP_GET_RAW_LEN(p->udph) #define UDP_GET_SRC_PORT(p) UDP_GET_RAW_SRC_PORT(p->udph) #define UDP_GET_DST_PORT(p) UDP_GET_RAW_DST_PORT(p->udph) #define UDP_GET_SUM(p) UDP_GET_RAW_SUM(p->udph) #define CLEAR_UDP_PACKET(p) do { \ (p)->level4_comp_csum = -1; \ (p)->udph = NULL; \ } while (0) /** * \brief Calculate or valid the checksum for the UDP packet * * \param shdr Pointer to source address field from the IP packet. Used as a * part of the psuedoheader for computing the checksum * \param pkt Pointer to the start of the UDP packet * \param hlen Total length of the UDP packet(header + payload) * \param init For validation this is the UDP checksum, for calculation this * value should be set to 0. * * \retval csum For validation 0 will be returned for success, for calculation * this will be the checksum. */ static __oryx_always_inline__ uint16_t UDPV4Checksum0(uint16_t *shdr, uint16_t *pkt, uint16_t tlen, uint16_t init) { uint16_t pad = 0; uint32_t csum = init; csum += shdr[0] + shdr[1] + shdr[2] + shdr[3] + htons(17) + htons(tlen); csum += pkt[0] + pkt[1] + pkt[2]; tlen -= 8; pkt += 4; while (tlen >= 32) { csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + pkt[7] + pkt[8] + pkt[9] + pkt[10] + pkt[11] + pkt[12] + pkt[13] + pkt[14] + pkt[15]; tlen -= 32; pkt += 16; } while(tlen >= 8) { csum += pkt[0] + pkt[1] + pkt[2] + pkt[3]; tlen -= 8; pkt += 4; } while(tlen >= 4) { csum += pkt[0] + pkt[1]; tlen -= 4; pkt += 2; } while (tlen > 1) { csum += pkt[0]; pkt += 1; tlen -= 2; } if (tlen == 1) { *(uint8_t *)(&pad) = (*(uint8_t *)pkt); csum += pad; } csum = (csum >> 16) + (csum & 0x0000FFFF); csum += (csum >> 16); uint16_t csum_u16 = (uint16_t)~csum; if (init == 0 && csum_u16 == 0) return 0xFFFF; else return csum_u16; } /** * \brief Calculate or valid the checksum for the UDP packet * * \param shdr Pointer to source address field from the IPv6 packet. Used as a * part of the psuedoheader for computing the checksum * \param pkt Pointer to the start of the UDP packet * \param tlen Total length of the UDP packet(header + payload) * \param init For validation this is the UDP checksum, for calculation this * value should be set to 0. * * \retval csum For validation 0 will be returned for success, for calculation * this will be the checksum. */ static __oryx_always_inline__ uint16_t UDPV6Checksum0(uint16_t *shdr, uint16_t *pkt, uint16_t tlen, uint16_t init) { uint16_t pad = 0; uint32_t csum = init; csum += shdr[0] + shdr[1] + shdr[2] + shdr[3] + shdr[4] + shdr[5] + shdr[6] + shdr[7] + shdr[8] + shdr[9] + shdr[10] + shdr[11] + shdr[12] + shdr[13] + shdr[14] + shdr[15] + htons(17) + htons(tlen); csum += pkt[0] + pkt[1] + pkt[2]; tlen -= 8; pkt += 4; while (tlen >= 32) { csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + pkt[7] + pkt[8] + pkt[9] + pkt[10] + pkt[11] + pkt[12] + pkt[13] + pkt[14] + pkt[15]; tlen -= 32; pkt += 16; } while(tlen >= 8) { csum += pkt[0] + pkt[1] + pkt[2] + pkt[3]; tlen -= 8; pkt += 4; } while(tlen >= 4) { csum += pkt[0] + pkt[1]; tlen -= 4; pkt += 2; } while (tlen > 1) { csum += pkt[0]; pkt += 1; tlen -= 2; } if (tlen == 1) { *(uint8_t *)(&pad) = (*(uint8_t *)pkt); csum += pad; } csum = (csum >> 16) + (csum & 0x0000FFFF); csum += (csum >> 16); uint16_t csum_u16 = (uint16_t)~csum; if (init == 0 && csum_u16 == 0) return 0xFFFF; else return csum_u16; } static __oryx_always_inline__ int DecodeUDPPacket(threadvar_ctx_t *t, packet_t *p, uint8_t *pkt, uint16_t len) { if (unlikely(len < UDP_HEADER_LEN)) { ENGINE_SET_INVALID_EVENT(p, UDP_HLEN_TOO_SMALL); return -1; } p->udph = (UDPHdr *)pkt; if (unlikely(len < UDP_GET_LEN(p))) { ENGINE_SET_INVALID_EVENT(p, UDP_PKT_TOO_SMALL); return -1; } if (unlikely(len != UDP_GET_LEN(p))) { ENGINE_SET_INVALID_EVENT(p, UDP_HLEN_INVALID); return -1; } SET_UDP_SRC_PORT(p,&p->sp); SET_UDP_DST_PORT(p,&p->dp); p->payload = pkt + UDP_HEADER_LEN; p->payload_len = len - UDP_HEADER_LEN; p->proto = IPPROTO_UDP; return 0; } static __oryx_always_inline__ int DecodeUDP0(threadvar_ctx_t *tv, decode_threadvar_ctx_t *dtv, packet_t *p, uint8_t *pkt, uint16_t len, pq_t *pq) { oryx_logd("UDP"); oryx_counter_inc(&tv->perf_private_ctx0, dtv->counter_udp); if (unlikely(DecodeUDPPacket(tv, p,pkt,len) < 0)) { p->udph = NULL; return TM_ECODE_FAILED; } oryx_logd("UDP sp: %" PRIu32 " -> dp: %" PRIu32 " - HLEN: %" PRIu32 " LEN: %" PRIu32 "", UDP_GET_SRC_PORT(p), UDP_GET_DST_PORT(p), UDP_HEADER_LEN, p->payload_len); #if defined(HAVE_TEREDO_DECODE) if (unlikely(DecodeTeredo(tv, dtv, p, p->payload, p->payload_len, pq) == TM_ECODE_OK)) { /* Here we have a Teredo packet and don't need to handle app * layer */ FlowSetupPacket(p); return TM_ECODE_OK; } #endif FlowSetupPacket(p); return TM_ECODE_OK; } #endif
C
// // Created by YDiamond on 03.11.2020. // #include <stdio.h> #include <malloc.h> #include "linkedList.h" llist_node* llist_create(int number){ llist_node *tmp = malloc(sizeof(llist_node)); tmp->prev = NULL; tmp->value = number; tmp->next = NULL; return tmp; } llist_node* list_add_front (llist_node** llist, int number){ llist_node* front = llist_create(number); if(*llist == NULL){ *llist = front; } else{ front->next = *llist; (*llist)->prev = front; *llist = front; } return *llist; } llist_node* list_add_back (llist_node** llist, int number){ llist_node* back = llist_create(number); if(*llist == NULL){ *llist = back; } else{ llist_node* iter = *llist; while (iter->next != NULL) iter = iter->next; iter->next = back; back->prev = iter; } return back; } llist_node* llist_at(llist_node* llist, int at, int* error){ if(length(llist)==0 || at<0){ *error = 1; return NULL; } llist_node* iter = llist; for(; at >= 0 ; --at, iter = iter->next){ if(iter == NULL){ *error = 1; return NULL; } } return iter; } int list_get (llist_node* list, int index, int* error){ llist_node* at = llist_at(list, index, error); if(*error == 1){ return 0; } return at->value; } int length(llist_node* llist){ int length = 0; for(;llist != NULL; llist = llist->next) length++; return length; } static void print_int(int number){ printf("%d ", number); } int sum(llist_node* iter){ int sum = 0; for(;iter != NULL; iter = iter->next) { sum += iter->value; } return sum; } void llist_free (llist_node* llist){ while(llist != NULL){ llist_node* next = llist->next; free(llist); llist = next; } }
C
#include <stdlib.h> #include <unistd.h> #include <string.h> #include "libft.h" #include <stdio.h> #include <ctype.h> static void check_tolower(int start, int end) { int c; while (start <= end) { c = ft_tolower(start); write(1, &c, 1); start++; } } static void check_tolowertrue(int start, int end) { int c; while (start <= end) { c = tolower(start); write(1, &c, 1); start++; } } int main(void) { printf("============================================================================================\n"); printf("============================================================================================\n"); printf("\n"); printf(" FT_TOLOWER\n"); printf("\n"); printf("============================================================================================\n"); printf("============================================================================================\n"); printf("\n\nTEST 1 :\n"); printf("0 to 47\n"); check_tolower(0, 47); printf("\nTest 1 tolower() :\n"); check_tolowertrue(0, 47); printf("\n"); printf("\n\nTEST 2 :\n"); printf("'0' to '9'\n"); check_tolower('0', '9'); printf("\nTest 2 tolower() :\n"); check_tolowertrue('0', '9'); printf("\n"); printf("\n\nTEST 3 :\n"); printf("58 to 64\n"); check_tolower(58, 64); printf("\nTest 3 tolower() :\n"); check_tolowertrue(58, 64); printf("\n"); printf("\n\nTEST 4 :\n"); printf("'A' to 'Z'\n"); check_tolower('A', 'Z'); printf("\nTest 4 tolower() :\n"); check_tolowertrue('A', 'Z'); printf("\n"); printf("\n\nTEST 5 :\n"); printf("91 to 96\n"); check_tolower(91, 96); printf("\nTest 5 tolower() :\n"); check_tolowertrue(91, 96); printf("\n"); printf("\n\nTEST 6 :\n"); printf("'a' to 'z'\n"); check_tolower('a', 'z'); printf("\nTest 6 tolower() :\n"); check_tolowertrue('a', 'z'); printf("\n"); printf("\n\nTEST 7 :\n"); printf("123 to 127\n"); check_tolower(123, 127); printf("\nTest 7 tolower() :\n"); check_tolowertrue(123, 127); printf("\n\n\n"); return (0); }
C
// newton raphson // floating point support // support for math function fabs int printf(char s[20],float a); int printf1(char s[20],float a,float b,float c,float d); int printf2(char s[20],int b); float fabs(float a); // x^3-x^2+2 float func(float x){ return x*x*x - x*x + 2; } float deriv(float x){ return 3*x*x - 2*x; } float newton_raphson(float x,float epsilon,int max_itr){ int i; for(i = 0;i<max_itr;i++){ float h = func(x)/deriv(x); if(fabs(h)<epsilon){ return x; } x = x - h; } return x; } int main(){ printf("root: %.3f\n",newton_raphson(-20,0.001,100)); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* pixel_colors.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: anieto <anieto@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/05/25 17:54:30 by anieto #+# #+# */ /* Updated: 2017/05/25 19:44:55 by anieto ### ########.fr */ /* */ /* ************************************************************************** */ #include "./fractol.h" void ptoi_4(int x, int y, t_window *win, unsigned int i) { int j; int c[5]; j = (4 * x) + (y * win->lsize); c[0] = 0xFF0000; c[1] = 0x0000FF; c[2] = 0x00FF00; c[3] = 0xFFFF00; c[4] = 0xFFAA00; if (i < win->max_iter) { win->pixels[j] = (i * ((c[win->c % 5] >> 16) & 0xFF)) / win->max_iter; win->pixels[++j] = (i * ((c[win->c % 5] >> 8) & 0xFF)) / win->max_iter; win->pixels[++j] = (i * ((c[win->c % 5]) & 0xFF)) / win->max_iter; } else { win->pixels[j] = 0x00; win->pixels[++j] = 0x00; win->pixels[++j] = 0x00; } } void ptoi_3(int x, int y, t_window *win, unsigned int iter) { int i; i = (4 * x) + (y * win->lsize); if (iter < win->max_iter) { win->pixels[i] = 0x42 + iter; win->pixels[i + 1] = 0x00 + iter; win->pixels[i + 2] = 0x00 + iter; } else { win->pixels[i] = 0x00; win->pixels[i + 1] = 0x00; win->pixels[i + 2] = 0x00; } } void ptoi_2(int x, int y, t_window *win, unsigned int iter) { int i; i = (4 * x) + (y * win->lsize); if (iter < win->max_iter) { win->pixels[i] = (sin(iter + win->c / M_PI) + 1) * 255; win->pixels[i + 1] = (-cos(iter + win->c / M_PI) + 1) * 255; win->pixels[i + 2] = (-sin(iter + win->c / M_PI) + 1) * 255; } else { win->pixels[i] = 0x00; win->pixels[i + 1] = 0x00; win->pixels[i + 2] = 0x00; } } void ptoi(int x, int y, t_window *win, unsigned int iter) { int i; i = (4 * x) + (y * win->lsize); if (iter < win->max_iter) { win->pixels[i] = sin((float)iter / 6.0) * 100; win->pixels[i + 1] = -cos((float)iter / 9.0) * 100; win->pixels[i + 2] = cos((float)iter / 2.0 + 3.14 / 2.0) * 100; } else { win->pixels[i] = 0x00; win->pixels[i + 1] = 0x00; win->pixels[i + 2] = 0x00; } }
C
#include<stdio.h> #include<string.h> #define N strlen(g) char t[128],cs[128],g[] = "10001000000100001"; int a,e,c; void xor() { for(c=1;c<N;c++) cs[c] = ((cs[c] == g[c])?'0':'1'); } void crc() { for(e=0;e<N;e++) cs[e] = t[e]; do { if(cs[0] == '1')xor(); for(c=0;c<N-1;c++) cs[c] = cs[c+1]; cs[c] = t[e++]; } while(e<=a+N-1); } int main() { printf("\n empty poly: "); scanf("%s",t); printf(" generating polynomial is: %s",g); a = strlen(t); for(e=1;e<a+N-1;e++) t[e]='0'; printf("\n modified t[u] is: %s",t); crc(); printf("\n checksum is : %s",cs); for(e=a;e<a+N-1;e++) t[e]=cs[e-a]; printf("\n final codeword is : %s",t); printf("\n test error detection 0(yes) 1(no)?:"); scanf("%d",&e); if(e==0) { printf("enter position where error is to be inserted: "); scanf("%d",&e); t[e] = (t[e]=='0')?'1':'0'; printf("erronous data: %s\n",t); } crc(); for(e=0;((e<N-1)&&(cs[e]!='1'));e++); if(e<N-1) printf("error detected"); else printf("no error detected"); return 0; }
C
#include "elenco.h" void elenco_HardcodeElenco(eElenco* listE,int lenElenco) { int i; int codActor[]= {0,12,14,2,5,17,19,8,9,12}; float valorContrato[]= {30000,2000,500000,9000,20000,10000,30000,2000,500000,9000}; int codPelicula[]= {12,10,12,7,8,4,10,8,4,7}; for(i=0; i<lenElenco; i++) { listE[i].codigoDeActor=codActor[i]; listE[i].codigoDePelicula=codPelicula[i]; listE[i].valorContrato=valorContrato[i]; listE[i].estado=OCUPADO; } } int elenco_AltaElenco(eElenco* listE,int lenElenco,eActor* listaA,int lenA,ePais* listPais,int lenPais,ePelicula* listP,int lenP,eGenero* listG,int lenG) { int retorno=-1; int iElenco; int generolist; ePelicula auxPelicula; eGenero auxGenero; eActor auxActor; printf("%30s","Generar Elenco"); iElenco=elenco_BuscarLibre(listE,lenElenco); if(iElenco!=-1) { auxPelicula=pelicula_ElejirPelicula(listP,lenP,listG,lenG); generolist=genero_BuscarGenero(listG,lenG,auxPelicula.idGenero); auxGenero=listG[generolist]; borrar(); auxActor=actor_ElejitActor(listaA,lenA,listPais,lenPais); borrar(); if(elenco_BuscarIgualdad(listE,lenElenco,auxActor,auxPelicula)!=-1) { getValidFloat("Ingrese el valor del contrato: ","Error solo numeros",0,10000000000,&listE[iElenco].valorContrato); borrar(); printf("***********************************************************************************************************\n"); elenco_MostrarUnElenco(listE[iElenco],auxActor,auxPelicula,auxGenero); printf("***********************************************************************************************************\n"); if(verifyConformity("esta seguro que desea crear este elenco?[Si/No]: ","Error, solo [Si/No]")==1) { retorno=0; listE[iElenco].codigoDeActor=auxActor.codigo; listE[iElenco].codigoDePelicula=auxPelicula.codigo; listE[iElenco].estado=OCUPADO; } else { retorno=1; } } else { retorno=-2; } } return retorno; } int elenco_InicializarElenco(eElenco* list,int lenElenco) { int retorno=-1; int i; if(list!=NULL && lenElenco!=0) { retorno=0; for(i=0; i<lenElenco; i++) { list[i].estado=LIBRE; } } return retorno; } int elenco_BuscarLibre(eElenco* list,int lenElenco) { int retorno=-1; int i; if(list!=NULL && lenElenco!=0) { for(i=0; i<lenElenco; i++) { if(list[i].estado==LIBRE) { retorno=i; break; } } } return retorno; } void elenco_menu(eElenco* listE,int lenElenco,eActor* listaA,int lenA,ePais* listPais,int lenPais,ePelicula* listP,int lenP,eGenero* listG,int lenG) { int opcion; int respuesta; do { elenco_ActorNoEncontrado(listE,lenElenco,listaA,lenA); getValidInt("1. Alta Elenco\n2. Mostrar Elencos\n3. Salir\nElija una opcion: ","Error, solo numeros[1-3]",1,3,&opcion); switch(opcion) { case 1: borrar(); respuesta =elenco_AltaElenco(listE,lenElenco,listaA,lenA,listPais,lenPais,listP,lenP,listG,lenG); switch(respuesta) { case -2: borrar(); printf("Ya existe la Pelicula con el Actor\n"); pausa(); break; case -1: borrar(); printf("No hay espacio disponible\n"); pausa(); break; case 0: borrar(); printf("Elenco Cargado\n"); pausa(); break; case 1: borrar(); printf("Accion cancelada por el usuario\n"); pausa(); break; } break; case 2: borrar(); printf("%50s\n","ELENCOS"); elenco_MostarElencos(listE,lenElenco,listaA,lenA,listP,lenP,listG,lenG); pausa(); borrar(); printf("%50s\n","ELENCOS ORDENADOS"); elenco_OrdenarPorPeliculaActor(listE,lenElenco,listaA,lenA,listP,lenP); elenco_MostarElencos(listE,lenElenco,listaA,lenA,listP,lenP,listG,lenG); pausa(); borrar(); break; case 3: break; } borrar(); } while(opcion!=3); printf("ADIOS VUELVA PRONTOS\n"); } void elenco_MostarElencos(eElenco* listE,int lenElenco,eActor* listaA,int lenA,ePelicula* listP,int lenP,eGenero* listG,int lenG) { int i; ePelicula auxPelicula; eActor auxActor; eGenero auxGenero; if(listE!=NULL && lenElenco!=0 && listaA!=NULL && lenA!=0 && listP!=NULL && lenP!=0 && listG!=NULL && lenG!=0) { printf("***********************************************************************************************************\n"); printf("%30s %20s %25s %20s\n","Pelicula","Genero","Nombre y Apellido","Valor Contrato"); printf("***********************************************************************************************************\n"); for(i=0; i<lenElenco; i++) { if(listE[i].estado==OCUPADO) { auxActor=actor_ObtenerActor(listaA,lenA,listE[i].codigoDeActor); auxPelicula=pelicula_ObtenerPelicula(listP,lenP,listE[i].codigoDePelicula); auxGenero=genero_ObtenerGenero(listG,lenG,auxPelicula.idGenero); elenco_MostrarUnElenco(listE[i],auxActor,auxPelicula,auxGenero); } } printf("***********************************************************************************************************\n"); } } void elenco_MostrarUnElenco(eElenco unElenco,eActor unActor,ePelicula unaPelicula,eGenero unGenero) { printf("%35s %15s %15s %10s %15.2f\n\n",unaPelicula.descripcion,unGenero.descripcion,unActor.nombre,unActor.apellido,unElenco.valorContrato); } int elenco_BuscarIgualdad(eElenco* listE,int lenElenco,eActor elActor,ePelicula laPelicula) { int i; int retorno=0; for(i=0; i<lenElenco; i++) { if(listE[i].estado==OCUPADO) { if(listE[i].codigoDeActor==elActor.codigo && listE[i].codigoDePelicula==laPelicula.codigo) { retorno=-1; } } } return retorno; } void elenco_OrdenarPorPeliculaActor(eElenco* listE,int lenElenco,eActor* listaA,int lenA,ePelicula* listP,int lenP) { int i,j; eElenco auxElenco; ePelicula auxPelicula; ePelicula auxPelicula2; eActor auxActor; eActor auxActor2; for(i=0; i<lenElenco-1; i++) { for(j=i+1; j<lenElenco; j++) { auxPelicula=pelicula_ObtenerPelicula(listP,lenP,listE[i].codigoDePelicula); auxPelicula2=pelicula_ObtenerPelicula(listP,lenP,listE[j].codigoDePelicula); if(strcmp(auxPelicula.descripcion,auxPelicula2.descripcion)>0) { auxElenco=listE[i]; listE[i]=listE[j]; listE[j]=auxElenco; } else { if(strcmp(auxPelicula.descripcion,auxPelicula2.descripcion)==0) { auxActor=actor_ObtenerActor(listaA,lenA,listE[i].codigoDeActor); auxActor2=actor_ObtenerActor(listaA,lenA,listE[j].codigoDeActor); if(strcmp(auxActor.nombre,auxActor2.nombre)>0) { auxElenco=listE[i]; listE[i]=listE[j]; listE[j]=auxElenco; } } } } } } void elenco_ActorNoEncontrado(eElenco* listE,int lenElenco,eActor* listA,int lenA) { int i; int auxActor; for(i=0; i<lenElenco; i++) { auxActor=actor_BuscarCodigo(listA,lenA,listE[i].codigoDeActor); if(auxActor==-1) { listE[i].estado=LIBRE; } } } void elenco_Informes(eElenco* listE,int lenElenco,eActor* listaA,int lenA,ePais* listPais,int lenPais,ePelicula* listP,int lenP,eGenero* listG,int lenG) { int opcion; do { getValidInt("1- Peliculas de terror cuyo ano de estreno sea despues del 2002\n2- Peliculas en donde haya participado un actor argentino\n3- Mostrar las peliculas en las que participo un actor seleccionado.\n4- Actor cuanto ha recaudado en todas las peliculas romanticas\n5- Listar los actores que no participaron en ninguna pelicula\n6- Salir\nElija una Opcion: ","Eror, solo numeros",1,6,&opcion); switch(opcion) { case 1: borrar(); elenco_PterrorMayor2002(listE,lenElenco,listaA,lenA,listP,lenP,listG,lenG); pausa(); break; case 2: borrar(); elenco_ActorArgentino(listE,lenElenco,listaA,lenA,listPais,lenPais,listP,lenP,listG,lenG); pausa(); break; case 3: borrar(); elenco_ActorSelecionado(listE,lenElenco,listaA,lenA,listPais,lenPais,listP,lenP,listG,lenG); pausa(); break; case 4: borrar(); elenco_ActorRecaudado(listE,lenElenco,listaA,lenA,listPais,lenPais,listP,lenP,listG,lenG); pausa(); break; case 5: borrar(); elenco_ActorNingunaPeli(listE,lenElenco,listaA,lenA,listPais,lenPais,listP,lenP,listG,lenG); pausa(); break; case 6: borrar(); break; } borrar(); } while(opcion!=6); } void elenco_PterrorMayor2002(eElenco* listE,int lenElenco,eActor* listaA,int lenA,ePelicula* listP,int lenP,eGenero* listG,int lenG) { int j; eActor auxActor; ePelicula auxPelicula; eGenero auxGenero; auxGenero=genero_ObtenerGenero(listG,lenG,101); printf("***********************************************************************************************************\n"); printf("%50s\n",auxGenero.descripcion); for(j=0; j<lenElenco; j++) { if(listE[j].estado==OCUPADO) { auxPelicula=pelicula_ObtenerPelicula(listP,lenP,listE[j].codigoDePelicula); if(auxGenero.id==auxPelicula.idGenero) { if(auxPelicula.fechaEstreno.year>2002) { auxActor=actor_ObtenerActor(listaA,lenA,listE[j].codigoDeActor); elenco_MostrarUnElenco(listE[j],auxActor,auxPelicula,auxGenero); } } } } printf("***********************************************************************************************************\n"); } void elenco_ActorArgentino(eElenco* listE,int lenElenco,eActor* listaA,int lenA,ePais* listPais,int lenPais,ePelicula* listP,int lenP,eGenero* listG,int lenG) { int i; eActor auxActor; ePelicula auxPelicula; eGenero auxGenero; ePais auxPais; printf("***********************************************************************************************************\n"); for(i=0; i<lenElenco; i++) { if(listE[i].estado==OCUPADO) { auxActor=actor_ObtenerActor(listaA,lenA,listE[i].codigoDeActor); auxPais=pais_BuscarPaisid(listPais,lenPais,1); if(auxActor.paisOrigen==auxPais.id) { auxPelicula=pelicula_ObtenerPelicula(listP,lenP,listE[i].codigoDePelicula); auxGenero=genero_ObtenerGenero(listG,lenG,auxPelicula.idGenero); elenco_MostrarUnElenco(listE[i],auxActor,auxPelicula,auxGenero); } } } printf("***********************************************************************************************************\n"); } void elenco_ActorSelecionado(eElenco* listE,int lenElenco,eActor* listaA,int lenA,ePais* listPais,int lenPais,ePelicula* listP,int lenP,eGenero* listG,int lenG) { int i; eActor auxActor; ePelicula auxPelicula; eGenero auxGenero; ePais auxPais; int flag=0; auxActor=actor_ElejitActor(listaA,lenA,listPais,lenPais); auxPais=pais_BuscarPaisid(listPais,lenPais,auxActor.paisOrigen); borrar(); printf("***********************************************************************************************************\n"); actor_MostrarUnActor(auxActor,auxPais); printf("***********************************************************************************************************\n"); for(i=0; i<lenElenco; i++) { if(listE[i].estado==OCUPADO) { if(listE[i].codigoDeActor==auxActor.codigo) { auxPelicula=pelicula_ObtenerPelicula(listP,lenP,listE[i].codigoDePelicula); auxGenero=genero_ObtenerGenero(listG,lenG,auxPelicula.idGenero); elenco_MostrarUnElenco(listE[i],auxActor,auxPelicula,auxGenero); flag=1; } } } if(flag==0) { printf("El Actor seleccionado no ha realizado ninguna Pelicula\n"); } printf("***********************************************************************************************************\n"); } void elenco_ActorRecaudado(eElenco* listE,int lenElenco,eActor* listaA,int lenA,ePais* listPais,int lenPais,ePelicula* listP,int lenP,eGenero* listG,int lenG) { int i; eActor auxActor; eGenero auxGenero; ePais auxPais; ePelicula auxPelicula; int sumador=0; auxActor=actor_ElejitActor(listaA,lenA,listPais,lenPais); auxPais=pais_BuscarPaisid(listPais,lenPais,auxActor.paisOrigen); borrar(); printf("***********************************************************************************************************\n"); actor_MostrarUnActor(auxActor,auxPais); printf("***********************************************************************************************************\n"); for(i=0; i<lenElenco; i++) { if(listE[i].estado==OCUPADO) { if(auxActor.codigo==listE[i].codigoDeActor) { auxGenero=genero_ObtenerGenero(listG,lenG,102); auxPelicula=pelicula_ObtenerPelicula(listP,lenP,listE[i].codigoDePelicula); if(auxPelicula.idGenero==auxGenero.id) { sumador+=listE[i].valorContrato; } } } } if(sumador!=0) { printf("\nEl Actor ha recaudado en todas las peliculas romanticas en las que participo: %d\n",sumador); } else { printf("\nEl Actor NO ha recaudado nada en las peliculas romanticas\n"); } printf("***********************************************************************************************************\n"); } void elenco_ActorNingunaPeli(eElenco* listE,int lenElenco,eActor* listaA,int lenA,ePais* listPais,int lenPais,ePelicula* listP,int lenP,eGenero* listG,int lenG) { int i,j; eActor auxActor; ePais auxPais; int contador=0; for(i=0; i<lenA; i++) { if(listaA[i].estado==OCUPADO) { for(j=0; j<lenElenco; j++) { if(listE[j].estado==OCUPADO) { auxActor=actor_ObtenerActor(listaA,lenA,listaA[i].codigo); if(listE[j].codigoDeActor==auxActor.codigo) { contador++; } } } if(contador==0) { auxPais=pais_BuscarPaisid(listPais,lenPais,auxActor.paisOrigen); actor_MostrarUnActor(auxActor,auxPais); } contador=0; } } }
C
/*************************************************************************** util.c - description ------------------- begin : Fri Sep 26 2003 copyright : (C) 2003 by Hiroyuki Kuwahara email : kuwahara@cs.utah.edu ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #if defined(DEBUG) #undef DEBUG #endif #include "util.h" /* #define UTIL_FILE_NAME_SIZE 256 #define UTIL_FILE_EXTENSION_SIZE 8 #define UTIL_DIRECTORY_SIZE 512 static char _fileName[UTIL_FILE_NAME_SIZE]; static char _fileExtension[UTIL_FILE_EXTENSION_SIZE]; static char _directory[UTIL_DIRECTORY_SIZE]; */ DLLSCOPE char * STDCALL GetFileName( char *path, char *buf, int offset, int len ) { char *start = NULL; char *target = NULL; START_FUNCTION("GetFileName"); start = strrchr( path, FILE_SEPARATOR ); if( start == NULL ) { start = path; } else { start += 1; } if( *start == '\0' ) { END_FUNCTION("GetFileName", SUCCESS ); return NULL; } target = buf + offset; strncpy( target, start, len ); target[len - 1] = '\0'; END_FUNCTION("GetFileName", SUCCESS ); return target; } DLLSCOPE char * STDCALL GetFileNameWithoutExtension( char *path, char *buf, int offset, int len ) { int i = 0; int size = 0; char *p = NULL; char *target = NULL; char *end = NULL; START_FUNCTION("GetFileNameWithoutExtension"); p = strrchr( path, FILE_SEPARATOR ); if( p == NULL ) { p = path; } else { p += 1; } if( *p == '\0' ) { END_FUNCTION("GetFileName", SUCCESS ); return NULL; } end = strrchr( p, '.' ); if( end == NULL ) { end = p + strlen(p); } else { } target = buf + offset; size = len - 1; for( i = 0; i < size; i++, p++ ) { if( p == end ) { break; } target[i] = *p; } target[i] = '\0'; END_FUNCTION("GetFileNameWithoutExtension", SUCCESS ); return target; } DLLSCOPE char * STDCALL GetFileExtension( char *path, char *buf, int offset, int len ) { char *start = NULL; char *target = NULL; START_FUNCTION("GetFileExtension"); start = strrchr( path, '.' ); if( start == NULL ) { END_FUNCTION("GetFileExtension", SUCCESS ); return NULL; } start++; target = buf + offset; strncpy( target, start, len ); target[len - 1] = '\0'; END_FUNCTION("GetFileExtension", SUCCESS ); return target; } DLLSCOPE char * STDCALL GetDirectory( char *path, char *buf, int offset, int len ) { int i = 0; int size = 0; char *p = NULL; char *end = NULL; char *target = NULL; START_FUNCTION("GetDirectory"); target = buf + offset; end = strrchr( path, FILE_SEPARATOR ); if( end == NULL ) { END_FUNCTION("GetDirectory", SUCCESS ); return NULL; } p = &path[0]; size = len - 2; for( i = 0; i < size; i++, p++ ) { target[i] = *p; if( p == end ) { break; } } target[i+1] = '\0'; END_FUNCTION("GetDirectory", SUCCESS ); return target; } DLLSCOPE STRING * STDCALL CreateEmptyString() { STRING *string = NULL; START_FUNCTION("CreateEmptyString"); string = (STRING*)CALLOC( 1, sizeof(STRING) ); if( string == NULL ) { END_FUNCTION("CreateEmptyString", FAILING ); return NULL; } END_FUNCTION("CreateEmptyString", SUCCESS ); return string; } DLLSCOPE STRING * STDCALL CreateString( char *str ) { STRING *string = NULL; START_FUNCTION("CreateString"); #if 1 if( str == NULL ) { TRACE_0("trying to create a empty string from null"); END_FUNCTION("CreateString", FAILING ); return NULL; } #endif string = (STRING*)MALLOC( sizeof(STRING) ); if( string == NULL ) { END_FUNCTION("CreateString", FAILING ); return NULL; } string->length = strlen( str ); string->charArray = (char*)MALLOC( string->length + 1 ); if( string->charArray == NULL ) { FREE( string ); END_FUNCTION("CreateString", FAILING ); return NULL; } strcpy( string->charArray, str ); string->charArray[string->length] = '\0'; END_FUNCTION("CreateString", SUCCESS ); return string; } UINT GetStringLength( STRING *string ) { START_FUNCTION("GetStringLength"); END_FUNCTION("GetStringLength", SUCCESS ); return (string == NULL ? (UINT)0 : string->length ); } DLLSCOPE char * STDCALL GetCharArrayOfString( STRING *string ) { START_FUNCTION("GetCharArrayOfString"); END_FUNCTION("GetCharArrayOfString", SUCCESS ); return (string == NULL ? NULL : string->charArray ); } DLLSCOPE int STDCALL CompareString( STRING *s1, STRING *s2 ) { int result = 0; START_FUNCTION("CompareString"); result = strcmp( s1->charArray, s2->charArray ); END_FUNCTION("CompareString", SUCCESS ); return result; } DLLSCOPE STRING * STDCALL AppendString( STRING *string, STRING *suffix ) { STRING *appended = NULL; int len1 = 0; int len2 = 0; int len = 0; char *charArray = NULL; START_FUNCTION("AppendString"); len1 = GetStringLength( string ); len2 = GetStringLength( suffix ); len = len1 + len2; if( ( charArray = (char*)MALLOC( len + 1 ) ) == NULL ) { END_FUNCTION("AppendString", FAILING ); return NULL; } if( len1 > 0 ) { strcpy( charArray, string->charArray ); } if( len2 > 0 ) { strcpy( charArray + len1, suffix->charArray ); } charArray[len] = '\0'; if( ( appended = CreateString( charArray ) ) == NULL ) { END_FUNCTION("AppendString", FAILING ); return NULL; } FREE( charArray ); END_FUNCTION("AppendString", SUCCESS ); return appended; } DLLSCOPE STRING * STDCALL CloneString( STRING *from ) { STRING *string = NULL; START_FUNCTION("CloneString"); if( ( string = CreateString( from->charArray ) ) == NULL ) { END_FUNCTION("CloneString", FAILING ); return NULL; } END_FUNCTION("CloneString", SUCCESS ); return string; } DLLSCOPE void STDCALL FreeString( STRING **string ) { START_FUNCTION("FreeString"); if( *string != NULL ) { FREE( (*string)->charArray ); FREE( *string ); } END_FUNCTION("FreeString", SUCCESS ); } typedef struct { char *key; char *value; } PROPERTIES_ENTRY; static RET_VAL STDCALL _Properties_Load( PROPERTIES *properties, char *path ); static char * STDCALL _Properties_GetPath( PROPERTIES *properties ); static char * STDCALL _Properties_GetProperty( PROPERTIES *properties, char *key ); static RET_VAL STDCALL _Properties_SetProperty( PROPERTIES *properties, char *key, char *value ); static RET_VAL STDCALL _Properties_RemoveProperty( PROPERTIES *properties, char *key ); static RET_VAL STDCALL _Properties_Free( PROPERTIES *properties ); static RET_VAL STDCALL _Properties_ReadLine( FILE *file, char *buf, int size ); static RET_VAL STDCALL _Properties_Parse( PROPERTIES *properties, char *buf, int size ); DLLSCOPE PROPERTIES * STDCALL CreateProperties( char *path ) { PROPERTIES *properties = NULL; START_FUNCTION("CreateProperties"); if( ( properties = (PROPERTIES*)MALLOC( sizeof(PROPERTIES) ) ) == NULL ) { END_FUNCTION("CreateProperties", FAILING ); return NULL; } if( ( properties->table = CreateHashTable( 256 ) ) == NULL ) { END_FUNCTION("CreateProperties", FAILING ); return NULL; } properties->path = NULL; properties->GetPath = _Properties_GetPath; properties->GetProperty = _Properties_GetProperty; properties->SetProperty = _Properties_SetProperty; properties->RemoveProperty = _Properties_RemoveProperty; properties->Free = _Properties_Free; if( IS_FAILED( _Properties_Load( properties, path ) ) ) { _Properties_Free( properties ); END_FUNCTION("CreateProperties", FAILING ); return NULL; } END_FUNCTION("CreateProperties", SUCCESS ); return properties; } DLLSCOPE PROPERTIES * STDCALL CreateEmptyProperties( ) { PROPERTIES *properties = NULL; START_FUNCTION("CreateEmptyProperties"); if( ( properties = (PROPERTIES*)MALLOC( sizeof(PROPERTIES) ) ) == NULL ) { END_FUNCTION("CreateEmptyProperties", FAILING ); return NULL; } if( ( properties->table = CreateHashTable( 256 ) ) == NULL ) { END_FUNCTION("CreateEmptyProperties", FAILING ); return NULL; } properties->path = NULL; properties->GetPath = _Properties_GetPath; properties->GetProperty = _Properties_GetProperty; properties->SetProperty = _Properties_SetProperty; properties->RemoveProperty = _Properties_RemoveProperty; properties->Free = _Properties_Free; END_FUNCTION("CreateEmptyProperties", SUCCESS ); return properties; } static RET_VAL STDCALL _Properties_Load( PROPERTIES *properties, char *path ) { RET_VAL ret = SUCCESS; char buf[4096+1]; char *newPath = NULL; FILE *file = NULL; START_FUNCTION("_Properties_Load"); if( ( newPath = (char*)MALLOC( strlen( path ) + 1 ) ) == NULL ) { return ErrorReport( FAILING, "_Properties_Load", "could not allocate memory for %s", path ); } properties->path = newPath; if( ( file = fopen( path, "r" ) ) == NULL ) { return ErrorReport( FAILING, "_Properties_Load", "file %s could not be opened" ); } while( !feof( file ) ) { if( ferror( file ) ) { return ErrorReport( FAILING, "_Properties_Load", "file error in %s", path ); } if( IS_FAILED( ( ret = _Properties_ReadLine( file, buf, sizeof( buf ) ) ) ) ) { if( ret == ( E_NODATA | E_END_OF_FILE ) ) { if( buf[0] != '\0' ) { TRACE_1("read line is: %s", buf ); if( IS_FAILED( ( ret = _Properties_Parse( properties, buf, strlen( buf ) ) ) ) ) { END_FUNCTION("_Properties_Load", ret ); return ret; } } TRACE_0("end of file" ); END_FUNCTION("_Properties_Load", SUCCESS ); return SUCCESS; } END_FUNCTION("_Properties_Load", ret ); return ret; } TRACE_1("read line is: %s", buf ); if( IS_FAILED( ( ret = _Properties_Parse( properties, buf, strlen( buf ) ) ) ) ) { END_FUNCTION("_Properties_Load", ret ); return ret; } } END_FUNCTION("_Properties_Load", SUCCESS ); return ret; } static RET_VAL STDCALL _Properties_ReadLine( FILE *file, char *buf, int size ) { int i = 0; int len = 0; int remainingSize = 0; char *head = NULL; START_FUNCTION("_Properties_ReadLine"); remainingSize = size; head = buf; head[0] = '\0'; while( !ferror( file ) ){ if( feof( file ) ) { if( head[0] == '\\' ) { head[0] = '\0'; } END_FUNCTION("_Properties_ReadLine", SUCCESS ); return E_NODATA | E_END_OF_FILE; } if( fgets( head, remainingSize, file ) == NULL ) { if( feof( file ) ) { END_FUNCTION("_Properties_ReadLine", SUCCESS ); return E_NODATA | E_END_OF_FILE; } END_FUNCTION("_Properties_ReadLine", FAILING ); return FAILING; } if( head[0] == '#' ) { continue; } len = strlen( head ); for( i = 0; i < len; i++ ) { if( !isspace( head[i] ) ) { break; } } if( i == len ) { head[0] = '\0'; if( head != buf ) { END_FUNCTION("_Properties_ReadLine", SUCCESS ); return SUCCESS; } continue; } i = len - 1; while( isspace( head[i] ) ) { i--; } if( head[i] == '\\' ) { head += i; remainingSize -= i; } else { head[i+1] = '\0'; END_FUNCTION("_Properties_ReadLine", SUCCESS ); return SUCCESS; } } END_FUNCTION("_Properties_ReadLine", SUCCESS ); return SUCCESS; } static RET_VAL STDCALL _Properties_Parse( PROPERTIES *properties, char *buf, int size ) { RET_VAL ret = SUCCESS; char c = 0; int i = 0; int j = 0; char *key = NULL; char *value = NULL; START_FUNCTION("_Properties_Parse"); for( i = 0; i < size; i++ ) { if( !isspace( buf[i] ) ) { break; } } if( i == size ) { return ErrorReport( FAILING, "_Properties_Parse", "line %s is not a valid property entry", buf ); } key = buf + i; for( ; i < size; i++ ) { c = buf[i]; if( c == '=' ) { j = i - 1; while( isspace( buf[j] ) ) { j--; } buf[j+1] = '\0'; if( (i + 1) >= size ) { return ErrorReport( FAILING, "_Properties_Parse", "line %s is not a valid property entry", buf ); } for( i = i + 1; i < size; i++ ) { if( !isspace( buf[i] ) ) { break; } } if( i == size ) { return ErrorReport( FAILING, "_Properties_Parse", "line %s is not a valid property entry", buf ); } value = buf + i; break; } } if( i == size ) { return ErrorReport( FAILING, "_Properties_Parse", "line %s is not a valid property entry", buf ); } i = size - 1; while( isspace( buf[i] ) ) { i--; } buf[i + 1] = '\0'; if( IS_FAILED( ( ret = _Properties_SetProperty( properties, key, value ) ) ) ) { END_FUNCTION("_Properties_Parse", ret ); return ret; } END_FUNCTION("_Properties_Parse", SUCCESS ); return ret; } static char * STDCALL _Properties_GetPath( PROPERTIES *properties ) { START_FUNCTION("_Properties_GetPath"); END_FUNCTION("_Properties_GetPath", SUCCESS ); return properties->path; } static char * STDCALL _Properties_GetProperty( PROPERTIES *properties, char *key ) { PROPERTIES_ENTRY *entry = NULL; HASH_TABLE *table = NULL; START_FUNCTION("_Properties_GetProperty"); table = properties->table; entry = (PROPERTIES_ENTRY*)GetValueFromHashTable( key, strlen( key ), table ); if( entry == NULL ) { END_FUNCTION("_Properties_GetProperty", FAILING ); return NULL; } END_FUNCTION("_Properties_GetProperty", SUCCESS ); return entry->value; } static RET_VAL STDCALL _Properties_SetProperty( PROPERTIES *properties, char *key, char *value ) { UINT32 len = 0; RET_VAL ret = SUCCESS; PROPERTIES_ENTRY *entry = NULL; HASH_TABLE *table = NULL; START_FUNCTION("_Properties_SetProperty"); _Properties_RemoveProperty( properties, key ); if( ( entry = (PROPERTIES_ENTRY*)MALLOC( sizeof(PROPERTIES_ENTRY) ) ) == NULL ) { return ErrorReport( FAILING, "_Properties_SetProperty", "failed to allocate properties entry for %s and %s", key, value ); } len = strlen(key); if( ( entry->key = (char*)MALLOC( len + 1 ) ) == NULL ) { return ErrorReport( FAILING, "_Properties_SetProperty", "failed to allocate properties entry key for %s", key ); } strcpy( entry->key, key ); if( ( entry->value = (char*)MALLOC( strlen(value) + 1 ) ) == NULL ) { return ErrorReport( FAILING, "_Properties_SetProperty", "failed to allocate properties entry value for %s", value ); } strcpy( entry->value, value ); table = properties->table; TRACE_2( "putting key %s and value %s in the properties", entry->key, entry->value ); if( IS_FAILED( ( ret = PutInHashTable( entry->key, len, entry, table ) ) ) ) { END_FUNCTION("_Properties_SetProperty", ret ); return ret; } END_FUNCTION("_Properties_SetProperty", SUCCESS ); return ret; } static RET_VAL STDCALL _Properties_RemoveProperty( PROPERTIES *properties, char *key ) { RET_VAL ret = SUCCESS; UINT32 len = 0; PROPERTIES_ENTRY *entry = NULL; HASH_TABLE *table = NULL; START_FUNCTION("_Properties_RemoveProperty"); len = strlen( key ); table = properties->table; if( ( entry = (PROPERTIES_ENTRY*)GetValueFromHashTable( key, len, table ) ) == NULL ) { TRACE_1("key %s is not in properties", key ); END_FUNCTION("_Properties_RemoveProperty", SUCCESS ); return ret; } if( IS_FAILED( ( ret = RemoveFromHashTable( key, len, table ) ) ) ) { END_FUNCTION("_Properties_RemoveProperty", ret ); return ret; } TRACE_2( "key %s and value %s are removed from the properties", entry->key, entry->value ); FREE( entry->key ); FREE( entry->value ); FREE( entry ); END_FUNCTION("_Properties_RemoveProperty", SUCCESS ); return ret; } static RET_VAL STDCALL _Properties_Free( PROPERTIES *properties ) { RET_VAL ret = SUCCESS; PROPERTIES_ENTRY *entry = NULL; LINKED_LIST *list = NULL; HASH_TABLE *table = NULL; START_FUNCTION("_Properties_Free"); table = properties->table; if( ( list = GenerateValueList( table ) ) == NULL ) { return ErrorReport( FAILING, "_Properties_Free", "failed to create a list to delete properties" ); } ResetCurrentElement( list ); while( ( entry = (PROPERTIES_ENTRY*)GetNextFromLinkedList( list ) ) != NULL ) { FREE( entry->key ); FREE( entry->value ); FREE( entry ); } DeleteLinkedList( &list ); DeleteHashTable( &table ); if( properties->path != NULL ) { FREE( properties->path ); } BZERO( properties, sizeof(PROPERTIES) ); END_FUNCTION("_Properties_Free", SUCCESS ); return ret; }
C
/** * 作者:chenda * 时间:2019/7/10:13:26 * 邮箱: * 说明: */ #ifndef CORENOTE_DULLINKLIST_H #define CORENOTE_DULLINKLIST_H //泛型循环双链表,带头节点,节点下标从0开始,头节点不计入下标值 typedef struct node{ void *data; //数据域指针 struct node *pre; struct node *next; }Node; struct list{ struct node *head; int data_size; //数据域所占内存大小 int length; }; //定义结点指针 node *为List类型的迭代器 typedef struct node *DlIterator; //List类型的定义 typedef struct list *List; //初始化链表 int initList(List *list,int data_size); //把data的数据内容插入到链表的list末尾 //assign指定数据data间的赋值方法 int insertLast(List list, void *data, void (*assign)(void *, const void *)); //返回index位置的迭代器 DlIterator getIterator(List list, int index); void* getData(DlIterator iterator); //删除index位置的元素 int remove(List list, int index); //查找链表startIndex到endIndex的最大值 //int (*large)(const void*,const void*) 定义data域大小比较的函数,返回1,代表参数值1大于参数值2;返回0,就是小于 //返回最大值的下标 int getMax(List list,int startIndex,int endIndex,int (*large)(const void*,const void*),void* max); #endif //CORENOTE_DULLINKLIST_H
C
#include <stdint.h> #include <string.h> #include "qc/error.h" #include "qc/random.h" #include "qc/tests.h" int main(void) { qc_rnd rnd; qc_err* err = qc_err_new(); qc_assert(qc_rnd_init(&rnd, err) == QC_SUCCESS, "qc_rnd_init has failed: %s", qc_err_get(err)); qc_err_free(err); uint8_t buf[32] = {0}; qc_rnd_buf(&rnd, 20, &buf[2]); qc_assert(memcmp(&buf[2], (uint8_t[20]){0}, 20) != 0, "qc_rnd_buf() does not write random"); qc_assert(memcmp(&buf[0], (uint8_t[2]){0}, 2) == 0 && memcmp(&buf[22], (uint8_t[10]){0}, 10) == 0, "qc_rnd_buf() writes out of bounds"); }
C
#include <stdio.h> #include <locale.h> #include <stdlib.h> #include <string.h> /* Faca um programa que leia um vetor com dados de 5 livros: tıtulo (maximo 30 letras), autor (maximo 15 letras) e ano. Procure um livro por tıtulo, perguntando ao usuario qual tıtulo deseja buscar. Mostre os dados de todos os livros encontrados */ struct Livro { char titulo[30], autor[15]; int ano; struct Livro *prox; }; void print(struct Livro *atual) { printf("Titulo: %s\n", atual->titulo); printf("Autor: %s\n", atual->autor); printf("Ano: %d\n", atual->ano); } int main() { setlocale(LC_ALL, "portuguese"); struct Livro *inicio, *atual; char titulo[30]; inicio = malloc(sizeof(struct Livro)); atual = inicio; atual->prox = NULL; for (int i=0; i<5; i++) { printf("Titulo: "); fflush(stdin); gets(atual->titulo); printf("Autor: "); fflush(stdin); gets(atual->autor); printf("Ano: "); scanf("%d", &atual->ano); printf("\n"); atual->prox = malloc(sizeof(struct Livro)); atual = atual->prox; } printf("\n\nQual título deseja buscar? "); fflush(stdin); gets(titulo); atual = inicio; while (atual->prox != NULL) { if (strcmpi(atual->titulo, titulo) == 0) print(atual); atual = atual->prox; printf("\n"); } return 0; }
C
#include <stdio.h> int main(void) { int i; char arr[10] = {0, }; for(i = 0; i < 10; i++) { if(arr[i] == 0) printf("null "); else printf("%d ", arr[i]); } printf("\n"); return 0; }
C
#include <sys/types.h> /* basic system data types */ #include <sys/socket.h> /* basic socket definitions */ #include <netinet/in.h> /* sockaddr_in{} and other Internet defns */ #include <arpa/inet.h> /* inet(3) functions */ #include <errno.h> #include <fcntl.h> #include <netdb.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/uio.h> #include <unistd.h> #include <sys/wait.h> #include <sys/un.h> #define MYPORT "4950" // port to be opened on server #define SERVERPORT "4950" // the port users will be connecting to #define MAXBUFLEN 550 // get sockaddr, IPv4 or IPv6: #define MAX_READ_LEN 512 // maximum data size that can be sent on one packet #define MAX_FILENAME_LEN 100 // maximum length of file name supported #define MAX_PACKETS 99 // maximum number of file packets #define MAX_TRIES 3 // maximum number of tries if packet times out #define TIME_OUT 5 // in seconds // converts block number to length-2 string void s_to_i(char *f, int n){ if(n==0){ f[0] = '0', f[1] = '0', f[2] = '\0'; } else if(n%10 > 0 && n/10 == 0){ char c = n+'0'; f[0] = '0', f[1] = c, f[2] = '\0'; } else if(n%100 > 0 && n/100 == 0){ char c2 = (n%10)+'0'; char c1 = (n/10)+'0'; f[0] = c1, f[1] = c2, f[2] = '\0'; } else { f[0] = '9', f[1] = '9', f[2] = '\0'; } } // makes RRQ packet char* make_rrq(char *filename){ char *packet; packet = malloc(2+strlen(filename)); memset(packet, 0, sizeof packet); strcat(packet, "01");//opcode strcat(packet, filename); return packet; } // makes WRQ packet char* make_wrq(char *filename){ char *packet; packet = malloc(2+strlen(filename)); memset(packet, 0, sizeof(packet)); strcat(packet, "02");//opcode strcat(packet, filename); return packet; } // makes data packet char* make_data_pack(int block, char *data){ char *packet; char temp[3]; s_to_i(temp, block); packet = malloc(4+strlen(data)); memset(packet, 0, sizeof packet); strcat(packet, "03");//opcode strcat(packet, temp); strcat(packet, data); return packet; } // makes ACK packet char* make_ack(char* block){ char *packet; packet = malloc(2+strlen(block)); memset(packet, 0, sizeof packet); strcat(packet, "04");//opcode strcat(packet, block); return packet; } // makes ERR packet char* make_err(char *errcode, char* errmsg){ char *packet; packet = malloc(4+strlen(errmsg)); memset(packet, 0, sizeof(packet)); strcat(packet, "05");//opcode strcat(packet, errcode); strcat(packet, errmsg); return packet; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* 2-0-inter3.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gachan <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/01/24 16:19:30 by gachan #+# #+# */ /* Updated: 2019/01/24 16:57:43 by gachan ### ########.fr */ /* */ /* ************************************************************************** */ // Write a program that takes 2 strings // // example: // padinton :w // paqefwtdjetyiytjneytjoeyjnejeyj // output: padinto // // ddf6vewg64f gtwthgdwthdwfteewhrtag6h4ffdhsd // df6ewg4 // // "rien" "cette phrase ne cache rien" // rien // // // letter in both strings are output // ZZ #include <unistd.h> //write int main(int argc, char **argv) { //declarations int vf[128]; // buffer int i; int j; char *str1 = argv[1]; char *str2 = argv[2]; i = 0; j = 0; while (i <= 128) { vf[i] = 0; i++; } if (argc != 3) { write(1, "\n", 1); return (0); } if (argc == 3) { i = 0; while (str2[i]) { if(vf[(int)str2[i]] == 0) vf[(int)str2[i]] = 1; i++; } i = 0; while (str1[i]) { if(vf[(int)str1[i]] == 1) vf[(int)str1[i]] = 2; i++; } i = 0; while(str1[i]) // iterate thru to print str1 { if(vf[(int)str1[i]] == 2) { write(1, &str1[i], 1); vf[(int)str1[i]] = 1; // decrement, so char prints only once. } i++; // iterate through each char } } return (0); }
C
struct obj_test_t { int val; char* name; size_t len; }; /* constructor */ int obj_test_Ctor(struct obj_test_t** obj, const char* name, size_t len, int val); /* destructor */ void obj_test_Dtor(struct obj_test_t** obj); /* getters */ char* obj_test_get_name(struct obj_test_t* obj); int obj_test_get_val(struct obj_test_t* obj); /* setters */ void obj_test_set_name(struct obj_test_t* obj, const char* name, size_t len); void obj_test_set_val(struct obj_test_t* obj, int val);
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* redir_struct_utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sesnowbi <sesnowbi@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/16 22:08:41 by sesnowbi #+# #+# */ /* Updated: 2021/09/16 22:10:08 by sesnowbi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../../includes/minishell.h" t_els *last_el(t_els *el) { if (el) { while (el->next) el = el->next; return (el); } return (NULL); } t_redir *ft_rednew(void *content) { t_redir *elem; elem = NULL; elem = (t_redir *)malloc(sizeof(t_redir)); if (!elem) return (NULL); elem->r_type = 0; if (((t_red *)content)->type == 0) elem->r_type = 3; if (((t_red *)content)->type == 1) elem->r_type = 4; if (((t_red *)content)->type == 2) elem->r_type = 1; if (((t_red *)content)->type == 3) elem->r_type = 2; elem->file = ft_strdup(((t_red *)content)->word); elem->heredoc_fds[0] = -1; elem->heredoc_fds[1] = -1; elem->next = NULL; return (elem); } t_redir *ft_redlast(t_redir *lst) { if (lst) { while (lst->next) lst = lst->next; return (lst); } return (NULL); } void ft_redadd_back(t_redir **lst, t_redir *neww) { t_redir *el; el = NULL; if (lst && neww) { if (*lst) { el = ft_redlast(*lst); el->next = neww; neww->next = NULL; } else { *lst = neww; neww->next = NULL; } } } void copy_redirs(t_els *els, t_list *red_list) { while (red_list) { ft_redadd_back(&(els->redir), ft_rednew(red_list->content)); red_list = red_list->next; } }
C
/** sebu petrik * prikald vystupu * * [50%] Building C object CMakeFiles/slova.dir/slova.c.o [100%] Linking C executable slova [100%] Built target slova Kededi jinedu ki hawi volebi.Fi dedu lasusi bepomi womewe he nu. Dukeve niwozu topepe pu caki hicuhu ca site.Le duju wine zavefu jefomo na wido. Buso vefoki lapore gevuko vegu ma ronu.Gabuxu biga kareli zara.Juga rivo vusimu xohosi voga bi kega. Li sisi xasoco pufa joze pa zu vime juto.Vawu vovufu wekota.Hewa no hata. **/ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <ctype.h> const char SPOLUHLASKY[] = "bcdfghjklmnprstvwxz"; const char SAMOHLASKY[] = "aeiou"; const size_t SAM_SIZE = sizeof(SAMOHLASKY); const size_t SPO_SIZE = sizeof(SPOLUHLASKY); char randSpoluhlaska() { return SPOLUHLASKY[rand() % (SPO_SIZE-1)]; } char randSamohlaska() { return SAMOHLASKY[rand() % (SAM_SIZE-1)]; } char * randSlovo(int pocetHlasok) { static char * slovo; slovo = malloc(pocetHlasok * sizeof(char)); for (int i = 0; i < pocetHlasok*2; i += 2) { slovo[i] = randSpoluhlaska(); slovo[i+1] = randSamohlaska(); } return slovo; } char * randVeta(int pocetSlov) { static char * veta; int velkostSlov[pocetSlov]; int velkostVety = 0; // vypocet velkosti vety a slov for (int i = 0; i < pocetSlov; i++) { velkostSlov[i] = ((rand() % 3)+1)*2; // iba parne velkosti velkostVety += velkostSlov[i]; // pridaj velkost slova velkostVety += 1; // 1 znak za medzeru } // alokovanie pamati pre vetu veta = malloc(velkostVety*sizeof(char)); // vytvorenie a prekopirovanie slov do vety for (int i = 0; i < pocetSlov; i++) { char * slovo = randSlovo(velkostSlov[i]/2); if (i == 0) { slovo[0] = toupper(slovo[0]); } strcat(veta, slovo); if (i == pocetSlov-1) { strcat(veta, "."); } else { strcat(veta, " "); } } return veta; } char * randSlohovyUtvar(int pocetViet) { static char *sloh; size_t slohSize = 0; char *vety[pocetViet]; // array pointerov na char, medzery su akoby samostatne vety s pointerom // vytvaranie viet for (int i = 0; i < pocetViet; i++) { vety[i] = randVeta((rand() % 7) + 3); // medzi 3 a 10 slovami slohSize += strlen(vety[i]); // velkost viet } slohSize += 1; // terminator na koniec sloh = malloc(slohSize * sizeof(char)); for (int i = 0; i < pocetViet; i++) { strcat(sloh, vety[i]); } return sloh; } int main() { srand(time(NULL)); char *utvar = randSlohovyUtvar(10); printf("%s\n", utvar); }
C
#include <stdio.h> int main(void) { int m, d, y, mm, md, my; printf("Enter a date (mm/dd/yy): "); scanf("%d/%d/%d", &mm, &md, &my); while (1){ if (mm==0 && md==0 && my==0) break; printf("Enter a date (mm/dd/yy): "); scanf("%d/%d/%d", &m, &d, &y); if (m==0 && d==0 && y==0) break; else if (y > my) continue; else if (y == my && m > mm) continue; else if (m == mm && d > md) continue; else {mm = m; md = d; my =y;} } printf("%d/%d/%d is the earliest date\n", mm, md, my); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "HDDsimugrad.netid.h" int main () { //createtherequests int requests[]; requests = createRequests(); for (int i = 0; i < NUM_REQUESTS; ++i) { addToQueue(requests[i]); } //servicetherequests int r; r = getNextRequest(); while (r >= 0) { r = getNextRequest(); } } //--------------------------------------------- // insert value at end int addRequest(IORequestNode **listP, int trackNum) { DListNode *currNode, *prevNode, *newNode; newNode = (DListNode *) malloc(sizeof(DListNode)); newNode->value = trackNum; newNode->next = *listP; newNode->prev = NULL; if (*listP != NULL) (*listP)->prev = newNode; *listP = newNode; return(0); } //===================================================================== int printList(IORequestNode *list) { IORequestNode *node; if (list == NULL) printf("[empty]\n"); else { printf("[ "); node = list; while (node != NULL) { printf("%d ", node->trackNum); node = node->next; } printf("]\n"); } return(0); } //===================================================================== // find and return the first instance of the matching value; if it's // not found, then return -1; if it is found, return 0; int find(DListNode *list, int value) { DListNode *currNode; if (list == NULL) return(-1); currNode = list; while (currNode != NULL) { if (currNode->value == value) return(0); else currNode = currNode->next; } return(-1); } //===================================================================== // delete ALL instances of the matching value // if at least one instance was found, return 0; else return 1 int serviceNextRequest(IORequestNode **listP, int *headPosition, int *headDirection, SchedulerType schedType, int *displacement) { DListNode *currNode, *prevNode, *nextNode; int rtnval; if (*listP == NULL) return(1); rtnval = 1; prevNode = NULL; currNode = *listP; while (currNode != NULL) { nextNode = currNode->next; if (currNode->value == displacement) { // delete currNode rtnval = 0; if (prevNode != NULL) { prevNode->next = currNode->next; if (currNode->next != NULL) currNode->next->prev = prevNode; } else { *listP = currNode->next; } free(currNode); } else { prevNode = currNode; } currNode = nextNode; } return(rtnval); } #define MAX_TEST_LENGTH 16 #define LINELEN 256 int getInputs(long *seed, SchedulerType *schedType) { char line[LINELEN]; int i, seedOK, schedTypeOK, numvals; seedOK = 0; schedTypeOK = 0; while ( ! seedOK ) { printf("seed (integer value): "); fgets(line, LINELEN, stdin); line[strlen(line)-1] = '\0'; // chop off the newline char for (i=0; i<strlen(line); ++i) // convert to lower-case line[i] = tolower(line[i]); if (strlen(line) > 0) { numvals = sscanf(line, "%ld", seed); if (numvals != 1) { printf("seed must be an integer value\n"); } else { seedOK = 1; } } } while ( ! schedTypeOK ) { printf("scheduler (FCFS, SCAN, or SSTF): "); fgets(line, LINELEN, stdin); line[strlen(line)-1] = '\0'; // chop off the newline char for (i=0; i<strlen(line); ++i) // convert to lower-case line[i] = tolower(line[i]); if (strlen(line) > 0) { if ( !strcmp(line, "fcfs") ) { schedTypeOK = 1; *schedType = SCHEDULER_FCFS; } else if ( !strcmp(line, "sstf") ) { schedTypeOK = 1; *schedType = SCHEDULER_SSTF; } else if ( !strcmp(line, "scan") ) { schedTypeOK = 1; *schedType = SCHEDULER_SCAN; } else { printf("scheduler must be 'FCFS' or 'SCAN' or 'SSTF'\n"); } } } return(0); } int testRandomRequests(SchedulerType schedType, int numRequests, int maxRequest, long seed) { IORequestNode *requestQueue; int i, trackNum; double r, meandpr; int displacementTotal; int headPosition, headDirection, displacement; srand48(seed); requestQueue = NULL; displacementTotal = 0; for (i=0; i<numRequests; ++i) { r = drand48(); trackNum = (int) maxRequest * r; addRequest(&requestQueue, trackNum); } printRequestQueue(requestQueue); headPosition = maxRequest / 2; headDirection = 1; printf("["); trackNum = serviceNextRequest(&requestQueue, &headPosition, &headDirection, schedType, &displacement); while (trackNum >= 0) { printf(" %d", trackNum); displacementTotal = displacementTotal + displacement; // printf("next request: %d; displacement = %d; pos = %d dir = %d\n", // trackNum, displacement, headPosition, headDirection); trackNum = serviceNextRequest(&requestQueue, &headPosition, &headDirection, schedType, &displacement); } printf(" ]\n"); meandpr = (double) displacementTotal / numRequests; printf("%d requests; mean displacement per request = %.2f\n", numRequests, meandpr); }
C
#include <include.h> static bool playerCheck(char color) { // Horizontal check for (int y = 0; y < size; y++) { int count = 0; for (int x = 0; x < size; x++) if (fields[y * size + x] == color) { if (count < winReq) trace[count] = (Pos) { .x = x, .y = y }; count++; } else { if (count == winReq) return true; count = 0; } } // Vertical check for (int x = 0; x < size; x++) { int count = 0; for (int y = 0; y < size; y++) if (fields[y * size + x] == color) { if (count < winReq) trace[count] = (Pos) { .x = x, .y = y }; count++; } else { if (count == winReq) return true; count = 0; } } // 135 degree diagonal check for (int o = -size; o < size; o++) { int count = 0; for (int x = 0; x < size; x++) { int y = o + x; if (y > 0 && fields[y * size + x] == color) { if (count < winReq) trace[count] = (Pos) { .x = x, .y = y }; count++; } else { if (count == winReq) return true; count = 0; } } } // 45 degree diagonal check for (int o = 2 * size; o >= 0; o--) { int count = 0; for (int y = 0; y < 15; y++) { int x = o - y; if (x < size && fields[y * size + x] == color) { if (count < winReq) trace[count] = (Pos) { .x = x, .y = y }; count++; } else { if (count == winReq) return true; count = 0; } } } nullize(trace); return false; } void gameCheck() { bool fullBoard = true; for (int y = 0; y < size; y++) { for (int x = 0; x < size; x++) { if (fields[y * size + x] == '0') { fullBoard = false; break; } } } char* file = (player == BLACK) ? file_blackDump : file_whiteDump; if (fullBoard) { UISetLabelText(ui_status, txt_endFull); tlkSend(file, "full"); gameOver('f'); } if (playerCheck(BLACK)) { UISetLabelText(ui_status, (player == BLACK ? txt_endWin : txt_endLoose)); tlkSend(file, "black"); gameOver('b'); } if (playerCheck(WHITE)) { UISetLabelText(ui_status, (player == WHITE ? txt_endWin : txt_endLoose)); tlkSend(file, "white"); gameOver('w'); } }
C
#include "threadlist.h" extern ptrListaThread listaThread; extern HANDLE listMutex; void imprimeLista(ptrListaThread ptr) { if (ptr == NULL) printf("(Vacia)\r\n\r\n"); else { printf("La lista es:\r\n"); while (ptr != NULL) { printf("Request %d -> ", ptr->info.socket); ptr = ptr->sgte; } printf("NULL\r\n\r\n"); } } int EliminarThread(SOCKET cli) { ptrListaThread ptrA = listaThread; ptrListaThread ptrAnt = NULL; /*Se busca el cliente en lista*/ while (ptrA->info.socket != cli && ptrA != NULL) { ptrAnt = ptrA; ptrA = ptrA->sgte; } if (ptrA == listaThread) { WaitForSingleObject(listMutex, INFINITE); listaThread = listaThread->sgte; ReleaseMutex(listMutex); } else ptrAnt->sgte = ptrA->sgte; if (ptrA == NULL) return -1; /*closesocket(ptrA->info.socket);*/ if (ptrA->info.threadHandle != 0) CloseHandle(ptrA->info.threadHandle); ptrA->sgte = NULL; HeapFree (GetProcessHeap(), 0, ptrA); ptrA = NULL; return 0; } int AgregarThread(ptrListaThread *ths, SOCKET socket, SOCKADDR_IN dirCliente, msgGet getInfo) { ptrListaThread nuevo, actual, anterior; if (socket == INVALID_SOCKET) { printf("Error en _beginthreadex(): %d\r\n", GetLastError()); return -1; } if ( (nuevo = HeapAlloc(GetProcessHeap(), 0, sizeof (struct nodoListaThread))) == NULL) return -1; nuevo->info.threadHandle = 0; nuevo->info.socket = socket; nuevo->info.direccion = dirCliente; nuevo->info.threadID = 0; nuevo->info.estado = ESPERA; nuevo->info.bytesEnviados = 0; nuevo->info.getInfo = getInfo; nuevo->info.arrival = GetTickCount(); nuevo->sgte = NULL; anterior = NULL; actual = *ths; while (actual != NULL) { WaitForSingleObject(listMutex, INFINITE); anterior = actual; actual = actual->sgte; ReleaseMutex(listMutex); } if (anterior == NULL) { WaitForSingleObject(listMutex, INFINITE); nuevo->sgte = *ths; *ths = nuevo; ReleaseMutex(listMutex); } else { WaitForSingleObject(listMutex, INFINITE); anterior->sgte = nuevo; nuevo->sgte = actual; ReleaseMutex(listMutex); } return 0; } int listaVacia(ptrListaThread listaThread) { int boolean; if (listaThread == NULL) boolean = 1; else boolean = 0; return boolean; } unsigned cantidadThreadsLista(ptrListaThread listaThread, int mode) { ptrListaThread ptrAux = listaThread; int contador = 0; while (ptrAux != NULL) { if (ptrAux->info.estado == mode) contador++; ptrAux = ptrAux->sgte; } return contador; } ptrListaThread BuscarThreadxId(ptrListaThread listaThread, DWORD threadId) { ptrListaThread ptr = listaThread; while (ptr != NULL && ptr->info.threadID != threadId) ptr = ptr->sgte; return ptr; } ptrListaThread BuscarThread(ptrListaThread listaThread, SOCKET sockfd) { ptrListaThread ptr = listaThread; while (ptr != NULL) { if (ptr->info.socket == sockfd && ptr->info.estado != ATENDIDO) break; ptr = ptr->sgte; } return ptr; } ptrListaThread BuscarProximoThread(ptrListaThread listaThread) { ptrListaThread ptr = listaThread; while (ptr != NULL && ptr->info.estado != ESPERA) ptr = ptr->sgte; return ptr; }
C
/* * This file defines and implements the Global descriptor tables. */ #include <ganoid/types.h> #include <string.h> #include <gdt.h> #include <kernel.h> #include <timer.h> void gdt_flush(void); // allocate space for the GDT struct segment_descriptor GDT[DEFAULT_GDT_SIZE] __attribute__ ((aligned(8))); struct GDTR_val GDTR_val; void init_GDT(void) { //struct GDTR_val cur_gdtr_val; // clear the global descriptor table. memset(GDT, 0, (sizeof(struct segment_descriptor) * DEFAULT_GDT_SIZE)); // keep first entry (entry 0) empty) // code segment add_gdt_entry(1, 0, 0xFFFFF, CODE_NO_CONFIRMING_NO_R, DESC_CODEDATA, DESC_SVC, GBL_DESC_DEFAULT_OPERATION_SIZE_32BIT, GBL_DESC_GRANULARITY_4KB); // data segment add_gdt_entry(2, 0, 0xFFFFF, DATA_EXPAND_UP_RW, DESC_CODEDATA, DESC_SVC, GBL_DESC_DEFAULT_OPERATION_SIZE_32BIT, GBL_DESC_GRANULARITY_4KB); /* // stack segment add_gdt_entry (3, 0xFFFFFFFF, 0xFFFFF, DATA_EXPAND_DOWN_RW, DESC_CODEDATA, DESC_SVC, GBL_DESC_DEFAULT_OPERATION_SIZE_32BIT, GBL_DESC_GRANULARITY_4KB); */ GDTR_val.table_limit = (sizeof(struct segment_descriptor) * DEFAULT_GDT_SIZE); GDTR_val.table_base_addr = (unsigned)&GDT; gdt_flush(); /* // test asm volatile ("sgdt %0": :"m"(cur_gdtr_val)); print_global_desc_table (&cur_gdtr_val); while (1); */ } /* * Encode the given information and create descriptor in memory. * Activate it immediately. */ void add_gdt_entry(int gdt_index, unsigned seg_base, unsigned seg_limit, unsigned seg_type, unsigned desc_type, unsigned desc_priv_level, unsigned default_operation_size, unsigned granularity) { GDT[gdt_index].seg_limit_low = (seg_limit & 0xFFFF); GDT[gdt_index].base_addr_low = (seg_base & 0xFFFF); GDT[gdt_index].base_addr_middle = (unsigned char)((seg_base & 0x00FF0000) >> 16); GDT[gdt_index].flags_1 = (unsigned char)((GBL_DESC_SEGMENT_PRESENT) | (desc_priv_level << 5) | (desc_type << 4) | (seg_type)); GDT[gdt_index].flags_2 = (unsigned char)(granularity | default_operation_size | (u32) ((seg_limit & 0x000F0000) >> 16)); GDT[gdt_index].base_addr_high = (unsigned char)((seg_base & 0xFF000000) >> 24); } void print_global_desc_table(const struct GDTR_val *GDTR_value) { int i; struct segment_descriptor *seg_desc = (struct segment_descriptor *)GDTR_value->table_base_addr; unsigned int segment_base_address; unsigned int segment_limit; // test code /* unsigned char *ptr; */ /* ptr = (unsigned char*)seg_desc; */ /* for (i = 0; i <= GDTR_value->table_limit; i++){ printk ("%2x ", *ptr); ptr++; if (!((i+1)%4)) printk ("\n"); //delay (1000000); } */ // seg_desc points to the first segment descriptor for (i = 0; i < GDTR_value->table_limit; i += 8, seg_desc += 1) { printk("\nSegment Descriptor No.: %d\n", i / 8); printk("Descriptor Address: %x\n", seg_desc); printk("DWord_H: %8x\n", *(unsigned int *)((unsigned int *)seg_desc + 1)); printk("DWord_L: %8x\n", *(unsigned int *)seg_desc); segment_base_address = ((unsigned int)seg_desc-> base_addr_high) << 24 | ((unsigned int)seg_desc-> base_addr_middle) << 16 | ((unsigned int)seg_desc->base_addr_low); segment_limit = ((((unsigned int)(seg_desc-> flags_2)) & 0x0F) << 16) | (unsigned int) seg_desc->seg_limit_low; printk("Segment Base Address: %8x\n", segment_base_address); printk("Segment Limit: %8x\n", segment_limit); delay(18000000); } }
C
#include<stdio.h> #include<ctype.h> #include<stdlib.h> #include<string.h> int gcd(int a, int b) { int g,i; for(i=1; i <= a && i <= b; ++i) { if(a%i==0 && b%i==0) g = i; } return g; } void main() { int p,q,N,Q,e,d; printf("Enter the value of first prime no. "); scanf("%d",&p); printf("Enter the value of second prime no. "); scanf("%d",&q); N=p*q; Q=(p-1)*(q-1); for(e=2;e<Q;e++){ if(gcd(e,Q)==1) break; } for(d=rand()%100000;;d++){ if(d!=1 && (d*e)%Q==1){ break; } } crypto(e,d,N); //printf("The possible values for e and d are\n p= %d, q= %d",e,d); } void crypto(int e, int d, int N) { char a[1000]; int p,i; printf("Enter the message you want to encrypt:\n"); fflush(stdin); gets(a); printf("Your encrypted message will be:\n"); for(i=0;i<strlen(a);i++){ if(a[i]>='A' && a[i]<='Z'){ p=((a[i]-'A')^e)%N; printf("%c",p+'A'); } else if(a[i]>='a' && a[i]<='z'){ p=((a[i]-'a')^e)%N; printf("%c",p+'a'); } else printf("%c",a[i]); } }
C
//#include <avr/io.h> //#include <avr/interrupt.h> //#include <stdlib.h> //#define PUFFER_GROESSE 50 //Puffergre in Byte #include "uart.h" unsigned char puffer[PUFFER_GROESSE]; unsigned char* lesezeiger; unsigned char* schreibzeiger; FILE uart_stdout = FDEV_SETUP_STREAM(uart_putchar, NULL, _FDEV_SETUP_WRITE); //======================================================================= //Serielle Schnittstelle mit 8 Bit, no parity, 1 Stoppbit initialisieren //Den Datenempfang erledigt eine Interrupt-Service-Routine. //======================================================================= void usart_init_intr(){ //void usart_init_intr(uint16_t baud){ /* UART-Init: Berechnung des Wertes fr das Baudratenregister aus Taktrate und gewnschter Baudrate */ #ifndef F_CPU /* In neueren Version der WinAVR/Mfile Makefile-Vorlage kann F_CPU im Makefile definiert werden, eine nochmalige Definition hier wuerde zu einer Compilerwarnung fuehren. Daher "Schutz" durch #ifndef/#endif Dieser "Schutz" kann zu Debugsessions fhren, wenn AVRStudio verwendet wird und dort eine andere, nicht zur Hardware passende Taktrate eingestellt ist: Dann wird die folgende Definition nicht verwendet, sondern stattdessen der Defaultwert (8 MHz?) von AVRStudio - daher Ausgabe einer Warnung falls F_CPU noch nicht definiert: */ #warning "F_CPU war noch nicht definiert, wird nun nachgeholt mit 8000000" #define F_CPU 8000000UL // Systemtakt in Hz - Definition als unsigned long beachten // Ohne ergeben sich unten Fehler in der Berechnung #endif //#define BAUD 38400UL // Baudrate // Berechnungen #define UBRR_VAL ((F_CPU+BAUD*8)/(BAUD*16)-1) // clever runden #define BAUD_REAL (F_CPU/(16*(UBRR_VAL+1))) // Reale Baudrate #define BAUD_ERROR ((BAUD_REAL*1000)/BAUD) // Fehler in Promille, 1000 = kein Fehler. #if ((BAUD_ERROR<990) || (BAUD_ERROR>1010)) #error Systematischer Fehler der Baudrate grsser 1% und damit zu hoch! #endif //const uint32_t fosz=16000000L; //uint16_t baud_wert; lesezeiger=puffer; schreibzeiger=puffer; ////Baudrate einstellen //baud_wert=fosz/(baud*16L)-1; //UBRRH=(uint8_t)(baud_wert>>8); //UBRRL=(uint8_t)baud_wert; UBRR0H = UBRR_VAL >> 8; UBRR0L = UBRR_VAL & 0xFF; //8N1 Daten UCSR0C|=(1<<UCSZ00)|(1<<UCSZ01); //Empfangen und Senden und Empfangsinterrupt aktivieren UCSR0B=(1<<RXEN0)|(1<<TXEN0)|(1<<RXCIE0); } //============================================================= // Interrupt-Service-Routine //============================================================= ISR (USART_RX_vect){ //Automatisch empfangene Daten in den Puffer schreiben: *schreibzeiger=UDR0; schreibzeiger++; if(schreibzeiger==puffer+PUFFER_GROESSE) schreibzeiger=puffer; } //============================================================= //Funktionen fr den interrupt-gesteuerten Datenempfang //============================================================= uint8_t usart_byte_avail_intr(void){ //Prft, ob ein Datenbyte im Puffer vorhanden ist // 1 = vorhanden, 0 = nicht vorhanden _delay_ms(10); //warten10ms(); if(schreibzeiger!=lesezeiger) return 1; else return 0; } //-------------------------------------------------------------- uint8_t usart_string_avail_intr(void){ //Hilfsfunktion fr die Funktion usart_gets_intr //Prfen, ob ein kompletter String im Puffer verfgbar ist. //Rckgabewert 1 = verfgbar, 0 = nicht verfgbar uint8_t avail=0; uint8_t *r=lesezeiger; while(r!=schreibzeiger){ if(*r==0) avail=1; r++; if(r==puffer+PUFFER_GROESSE) r=puffer; } return avail; } //-------------------------------------------------------------- uint8_t usart_getc_intr(void){ //Liest ein Byte aus dem Puffer //Nur aufrufen, wenn usart_byte_avail_intr() vorher aufgerufen wurde und //eine 1 lieferte. uint8_t datenbyte=0; if(schreibzeiger!=lesezeiger){ datenbyte=*lesezeiger; lesezeiger++; if(lesezeiger==puffer+PUFFER_GROESSE) lesezeiger=puffer; } return datenbyte; } //-------------------------------------------------------------- uint8_t usart_gets_intr(char *s){ //Liest eine Zeichenkette aus dem Puffer //einschlielich Endmarke 0 in die Stringvariable s //Wenn der Rckgabewert ok = 1 ist, war das Lesen erfolgreich, //bei ok = 0 nicht erfolgreich. char c; uint8_t ok=0; if(usart_string_avail_intr()){ ok=1; do{ c = usart_getc_intr(); *s=c; s++; }while(c!=0); } return ok; } // //Hinweise zum Empfang Zahlen (int, long, foat und double) //-------------------------------------------------------- // Zahlen werden vor dem Senden in Zeichenketten umgewandelt. // Sie mssen deshalb mit der obigen Funktion usart_gets_intr als // Zeichenketten empfangen werden. // // Die Rckumwandung dieser Zeichenkette in Zahlen kann dann mit // den Funktionen aus <stdlib.h> erfolgen: // // int atoi(const char* s); => Umwandlung in int // long atol(const char* s); => Umwandlung in long // double atof(const char* s); => Umwandlung in double oder float // //============================================================= //Die nachfolgenden Sendefunktionen sind nicht interrupt-gesteuert //============================================================= void usart_putc(uint8_t byte){ //Ein Byte senden while(!(UCSR0A&(1<<UDRE0)));//warten auf Datenregister empty UDR0=byte; } //-------------------------------------------------------------- void usart_puts(char *s) //Einen String mit Endmarke 0 senden { while (*s!=0) { usart_putc(*s); s++; } //usart_putc(0); //Endmarke 0 wird bertragen! } //--------------------------------------------------------------- void usart_puti(int zahl, int sges){ //Senden der Integerzahl zahl als Zeichenkette formatiert mit sges Stellen //als Zeichenkette char buffer[16]; uint8_t l=0,n; char *z=buffer; itoa(zahl,buffer,10); while(*z!=0){l++; z++;}//Bufferlnge l for(n=l;n<sges;n++) usart_putc(' '); usart_puts(buffer); } //-------------------------------------------------------------- void usart_putf(float zahl, int sges, int snach){ //Senden einer Fliekommazahl als Zeichenkette mit sges Gesamtstellen //als Zeichenkette //Hiervon sind snach Nachkommastellen. //Die Nachkollastellen werden gerundet. char buffer[16]; dtostrf(zahl,sges,snach,buffer); usart_puts(buffer); } //-------------------------------------------------------------- void usart_putui(unsigned int zahl, int sges){ //Senden der Integerzahl zahl als Zeichenkette formatiert mit sges Stellen //als Zeichenkette char buffer[16]; uint8_t l=0,n; char *z=buffer; utoa(zahl,buffer,10); while(*z!=0){l++; z++;}//Bufferlnge l for(n=l;n<sges;n++) usart_putc(' '); usart_puts(buffer); } //-------------------------------------------------------------- void usart_putui_0(unsigned int zahl, int sges){ //Senden der Integerzahl zahl als Zeichenkette formatiert mit sges Stellen //als zeichekette //Leerstellen werden mit 0 aufgefllt (TSC) char buffer[16]; uint8_t l=0,n; char *z=buffer; utoa(zahl,buffer,10); while(*z!=0){l++; z++;}//Bufferlnge l for(n=l;n<sges;n++) usart_putc('0'); usart_puts(buffer); } //-------------------------------------------------------------- void usart_putui_hex(unsigned int zahl, int sges){ //Senden der nur-positiven Integerzahl zahl als Zeichenkette formatiert mit sges Stellen // das Ausgabeformat ist hex (TSC) char buffer[17]; uint8_t l=0,n; char *z=buffer; utoa(zahl,buffer,16); while(*z!=0){l++; z++;}//Bufferlnge l for(n=l;n<sges;n++) usart_putc(' '); usart_puts(buffer); } //-------------------------------------------------------------- void usart_putui_bin(unsigned int zahl, int sges){ //Senden der Integerzahl zahl als Zeichenkette formatiert mit sges Stellen // Das Ausgabeformat ist binr. Leerstellen werden mit 0 aufgefllt. char buffer[17]; uint8_t l=0,n; char *z=buffer; utoa(zahl,buffer,2); while(*z!=0){l++; z++;}//Bufferlnge l for(n=l;n<sges;n++) usart_putc('0'); usart_puts(buffer); } //-------------------------------------------------------------- void usart_putb(uint8_t a){ //Senden einer 8-Bit-Zahl binr(TSC) usart_putui_bin(a,8); } int uart_putchar(char c, FILE *stream) // // bindet printf() ein { usart_putc(c); //UART return 0; } FILE* uart_file_stream(){ return &uart_stdout; }
C
#include "stack_linked_list.h" Node* push_front(Node* node, const int data) { Node* new_node = malloc(sizeof(Node)); new_node->data = data; new_node->next = node; return new_node; } Node* pop_front(Node* node, int* data) { *data = node->data; Node* next_node = node->next; free(node); return next_node; } void clear_node(Node* node) { int trash; while (node) { node = pop_front(node, &trash); } }
C
//Write a program to display the class according to //marks scored by students. The marks scored is taken //as input and class is displayed according to the range : //70-100 Distinction(A) //60-69 First Class(B) //50-59 Second Class(C) //40-49 Pass Class(D) //0-39 Fail(F) //Subjects are : //Physics //Maths //Biology //Chemistry //Computer #include <stdio.h> int main() { float phy=0,chem=0,math=0,bio=0, comp=0, total=0, percent=0; printf("Enter the marks of:\n"); printf("1.Physics\n"); scanf("%f",&phy); printf("2.Chemistry\n"); scanf("%f",&chem); printf("3.Maths\n"); scanf("%f",&math); printf("4.Computer\n"); scanf("%f",&comp); printf("5.Biology\n"); scanf("%f",&bio); total = phy+chem+math+comp+bio; percent=total/5; if(percent>=70) { printf("Class: Distinction\n"); printf("Grade: A\n"); } else if(percent<70&&percent>=60) { printf("Class: First Class\n"); printf("Grade: B\n"); } else if(percent<60&&percent>=50) { printf("Class: Second Class\n"); printf("Grade: C\n"); } else if(percent<50&&percent>=40) { printf("Class: Pass\n"); printf("Grade: D\n"); } else { printf("Class: Fail\n"); printf("Grade: F\n"); } printf("%f", percent); }
C
#include <stdio.h> #include <cs50.h> #include <string.h> #include <ctype.h> #include <stdlib.h> int main(int argc, string argv[]) { if (argc != 2) { printf("Usage: ./vigenere k"); return 1; } string key = argv[1]; int len_key = strlen(key); for(int i = 0; i < len_key; i++) { if(isalpha(key[i])== false) { printf("%c sage: ./vigenere k!",key[i]); return 1; } } string pt,ct; pt = get_string("plaintext:"); ct = pt; int j = 0; for(int i = 0, n = strlen(pt); i < n; i++) { int key_num; if (islower(key[(j % len_key)])) { key_num = key[(j % len_key)] - 'a'; } else { key_num = key[(j % len_key)] - 'A'; } if (islower(pt[i])) { if (pt[i] + key_num> 'z') { ct[i] = pt[i] + key_num -26; } else { ct[i] = pt[i] + key_num; } j++; } else if (isupper(pt[i])) { if (pt[i] + key_num > 'Z') { ct[i] = pt[i] + key_num - 26; } else { ct[i] = pt[i] +key_num; } j++; } else { ct[i] = pt[i]; } } printf("ciphertext: %s\n", ct); }
C
#include <stdio.h> #include <malloc.h> #include <string.h> #define MAX_LENGTH 200 int main() { char* input; input = malloc(MAX_LENGTH); printf("Please enter your string"); scanf("%[^\n]", input); for(int i=strlen(input);i>=0;i--) printf("%c", input[i]); printf("\n"); free(input); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* print_f.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: stross <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/11/22 17:57:22 by stross #+# #+# */ /* Updated: 2019/11/22 21:38:54 by stross ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" void print_lf_help1(double x, int len, char *str) { if (g_pf_flags.flag_plus && x > 0) { ft_putchar_g('+'); len++; } if (!g_pf_flags.flag_plus && g_pf_flags.flag_space && x > 0) { ft_putchar_g(' '); len++; } ft_putstr_g(str); if (g_pf_flags.dot && g_pf_flags.precision == 0 && g_pf_flags.flag_hash) ft_putchar_g('.'); while (g_pf_flags.width > len) { ft_putchar_g(' '); g_pf_flags.width--; } } void print_lf_help3(double x, int len, char *str) { if (x < 0) { ft_putchar_g('-'); str++; } if (x > 0 && g_pf_flags.flag_plus) { ft_putchar_g('+'); len++; } if (g_pf_flags.flag_space && g_pf_flags.width > len && x >= 0) { ft_putchar_g(' '); g_pf_flags.width--; } while (g_pf_flags.width > len) { ft_putchar_g('0'); g_pf_flags.width--; } ft_putstr_g(str); if (g_pf_flags.dot && g_pf_flags.precision == 0 && g_pf_flags.flag_hash) ft_putchar_g('.'); } void print_lf_help2(double x, int len, char *str) { if (g_pf_flags.flag_zero && g_pf_flags.width > len) print_lf_help3(x, len, str); else { if (g_pf_flags.flag_space && g_pf_flags.width <= len && !g_pf_flags.flag_plus && x > 0) { ft_putchar_g(' '); len++; } if (g_pf_flags.flag_plus) { if (x > 0) len++; } while (g_pf_flags.width > len) print_lf_help10(); if (g_pf_flags.flag_plus && x > 0) ft_putchar_g('+'); ft_putstr_g(str); if (g_pf_flags.dot && g_pf_flags.precision == 0 && g_pf_flags.flag_hash) ft_putchar_g('.'); } } void print_lf(va_list arg) { double x; char *str; char *to_free; int len; x = va_arg(arg, double); str = ft_float(x, (g_pf_flags.precision == 0 ? 6 : g_pf_flags.precision)); if (g_pf_flags.dot && g_pf_flags.precision == 0) { free(str); str = ft_float(x, 0); } len = ft_strlen(str); if (g_pf_flags.dot && g_pf_flags.precision == 0 && g_pf_flags.flag_hash) len++; to_free = str; if (g_pf_flags.flag_minus) print_lf_help1(x, len, str); else print_lf_help2(x, len, str); free(to_free); }
C
/* Eratosthenes sieve -- method of finding the prime numbers. This example shows loops and conditions work correctly. */ #include <stdio.h> #include <stdlib.h> typedef unsigned long UL; int main() { #ifdef JUDGE UL n = 10000; #else UL n; scanf("%lu", &n); #endif char *p = malloc(n + 1); if (!p) { puts("Out of memory."); return 1; } p[0] = p[1] = 0; for (UL i = 2; i <= n; ++i) { p[i] = 1; } for (UL i = 2; i <= n; ++i) { if (p[i]) { if (i * i <= n) { for (UL j = i * i; j <= n; j += i) { p[j] = 0; } } printf("%lu\n", i); } } }
C
#include <stdlib.h> char* duplicate(char* letters, int* digits) //Dubles letters by the number that is in the corsponding cell in digits { int size = 1, i, j; char* str_res = (char*)malloc(1 * sizeof(char)); //Creates a one cell char int lenLet = strlen(letters); for (i = 0; i < lenLet; i++) { if (letters[i] >= 'a' && letters[i] <= 'z' || letters[i] >= 'A' && letters[i] <= 'Z' || letters[i] == ' ') { for (j = 0; j < digits[i]; j++) { str_res[size - 1] = letters[i]; size++; str_res = (char*)realloc(str_res, size * sizeof(char)); } } else { return NULL; } } str_res[size - 1] = '\0'; return str_res; } int main() //Added for running { char letters[] = "cTest"; int digits[] = { 2,1,4,2,3 }; duplicate(letters, digits); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include <allegro5/allegro_native_dialog.h> #include "baralho.h" #include "jogo.h" #include "save.h" void writeToLog(char *str) { FILE *logfile = fopen(LOG_FILE, "a"); if(!logfile) return; fprintf(logfile, "* %s\n", str); fclose(logfile); } int iniciaMontes(Baralho baralho, Monte bp[], Monte bd[], Monte bc[]) { Monte monteAux = geraMonte(baralho, 2); int i; for(i = 0; i < 4; i++) { bp[i] = geraMonteVazio(); bd[i] = geraMonteVazio(); bc[i] = geraMonteVazio(); } for(; i < 16; i++) bp[i] = geraMonteVazio(); monteAux = geraMonte(baralho, 2); for(i = 0; i < NAIPES; i++) { char *naipes = "PECO"; if(!removeCarta(&monteAux, 'A', naipes[i]) || !removeCarta(&monteAux, 'K', naipes[i])) return 0; insereCarta(&(bd[i]), getCarta(naipes[i], 'K', baralho)); insereCarta(&(bc[i]), getCarta(naipes[i], 'A', baralho)); } embaralha(monteAux); i = 0; while(getMonteSize(monteAux)) { insereCarta(&(bp[i++]), tiraCarta(&monteAux, baralho)); if(i >= 16) i = 0; } free(monteAux); for(i = 0; i < 4; i++) { embaralha(bc[i]); embaralha(bd[i]); embaralha(bp[i]); } for(; i < 16; i++) embaralha(bp[i]); return 1; } void printMesa(Monte bp[], Monte bd[], Monte bc[]) { int i, j; printf("%10c", ' '); for(i = 5; i < 13; i++) printf(" %2d ", i); printf("\n%10c", ' '); for(i = 4; i < 12; i++) { if(getMonteSize(bp[i])) { printf("[%c-%c] ", bp[i][0][0], bp[i][0][1]); } else { printf("[ ] "); } } printf("\n\n"); for(i = 4; i > 0; i--) { if(getMonteSize(bp[i-1])) { printf("%2d [%c-%c]%14c", i, bp[i-1][0][0], bp[i-1][0][1], ' '); } else { printf("%2d [ ]%14c", i, ' '); } for(j = 0; j < 4; j++) { switch(i) { case 4: case 1: printf(" %2d ", j+1); break; case 2: // Crescente if(getMonteSize(bc[j])) { printf("[%c-%c] ", bc[j][0][0], bc[j][0][1]); } else { printf("[ ] "); } break; case 3: // Decrescente if(getMonteSize(bd[j])) { printf("[%c-%c] ", bd[j][0][0], bd[j][0][1]); } else { printf("[ ] "); } break; } } if(getMonteSize(bp[j])) { printf("%14c[%c-%c] %2d", ' ', bp[16-i][0][0], bp[16-i][0][1], 17-i); } else { printf("%14c[ ] %2d", ' ', 17-i); } printf("\n"); } } unsigned long jogar(int load, int mode, Baralho baralho) { unsigned long sTime, lTime; if(mode == 1) { //Contra o tempo int tmp = 0; printf("* Insira o limite de tempo, em minutos: "); do { scanf("%d", &tmp); } while (tmp <= 0); lTime = tmp * 60; while(getchar() != '\n'); } printf("\n\n"); char result[200]; int i, running=1, reshuffles=5; if(!(baralho = geraBaralho(baralho))) return 0; Monte blocoPeriferico[16], blocoDecrescente[4], blocoCrescente[4]; sTime = time(NULL); if(!load) { if(!iniciaMontes(baralho, blocoPeriferico, blocoDecrescente, blocoCrescente)) return 0; } else { // TODO Dialogo gráfico char arquivo[100]; printf("Insira o nome do jogo salvo: "); fgets(arquivo, 100, stdin); arquivo[strlen(arquivo)-1]='\0'; for(i = 0; i < 4; i++) { blocoPeriferico[i] = geraMonteVazio(); blocoCrescente[i] = geraMonteVazio(); blocoDecrescente[i] = geraMonteVazio(); } for(i = 4; i < 16; i++) blocoPeriferico[i] = geraMonteVazio(); if(!loadState(arquivo, blocoPeriferico, blocoDecrescente, blocoCrescente, &reshuffles, &sTime, &lTime, &mode)) { fputs("*** Erro: Não foi possível carregar o jogo.\n", stderr); return 0; } printf("* Jogo carregado com sucesso.\n"); } do { char cmd; int arg[2]; printMesa(blocoPeriferico, blocoDecrescente, blocoCrescente); printf("\n[M] Mover uma carta.\n[R] Reembaralhar os montes periféricos (%d restantes).\n" "[D] Desistir.\n[S] Salvar jogo\nOpção: ", reshuffles); cmd = getchar(); if(cmd != '\n') while(getchar() != '\n'); // Limpar buffer de entrada. switch(cmd) { case 'S': case 's': printf("* Escolha o nome do save: "); char file[30], continuar; scanf("%s", file); while(getchar() != '\n'); if(!saveState(file, blocoPeriferico, blocoDecrescente, blocoCrescente, reshuffles, sTime, lTime, mode)) fputs("*** Erro: Não foi possível salvar.\n", stderr); else printf("* Salvo em %s com sucesso!\n", file); printf("* Deseja continuar jogando [S/n]? "); do { continuar = getchar(); } while(continuar == '\n'); while(getchar() != '\n'); if(continuar == 'n' || continuar == 'N') return 0; break; case 'M': case 'm': printf("* Insira o bloco de origem [1-16]: "); scanf("%d", &arg[0]); if(--arg[0] < 0 || arg[0] > 15) { fputs("*** Erro: Entrada inválida - bloco inexistente.\n", stderr); break; } if(!getMonteSize(blocoPeriferico[arg[0]])) { fputs("*** Erro: Esse bloco não possui cartas.\n", stderr); break; } printf("* Qual o destino da carta?\n[1] Bloco Periférico\n[2] Bloco Central Crescente\n[3] Bloco Central Decrescente.\nDestino: "); scanf("%d", &arg[1]); switch(arg[1]) { case 1: printf("* Insira o bloco de destino [1-16]: "); scanf("%d", &arg[1]); if(--arg[1] < 0 || arg[1] > 15) { fputs("*** Erro: Entrada inválida - bloco inexistente.\n", stderr); break; } Carta origem, destino; // Talvez eu devesse ter implementado uma função na biblioteca para isso... if(getMonteSize(blocoPeriferico[arg[1]])) { origem = getCarta(blocoPeriferico[arg[0]][0][1], blocoPeriferico[arg[0]][0][0], baralho); destino = getCarta(blocoPeriferico[arg[1]][0][1], blocoPeriferico[arg[1]][0][0], baralho); if(!isNextCard(origem, destino) && !isNextCard(destino, origem)) { fputs("*** Erro: Movimento inválido.\n", stderr); break; } } insereCarta(&blocoPeriferico[arg[1]], tiraCarta(&blocoPeriferico[arg[0]], baralho)); break; case 2: printf("* Insira o bloco de destino [1-4]: "); scanf("%d", &arg[1]); if(--arg[1] < 0 || arg[1] > 3) { fputs("*** Erro: Entrada inválida - bloco inexistente.\n", stderr); break; } if(getMonteSize(blocoCrescente[arg[1]])) { origem = getCarta(blocoPeriferico[arg[0]][0][1], blocoPeriferico[arg[0]][0][0], baralho); destino = getCarta(blocoCrescente[arg[1]][0][1], blocoCrescente[arg[1]][0][0], baralho); if(!isNextCard(destino, origem)) { fputs("*** Erro: Movimento inválido.\n", stderr); break; } } insereCarta(&blocoCrescente[arg[1]], tiraCarta(&blocoPeriferico[arg[0]], baralho)); break; case 3: printf("* Insira o bloco de destino [1-4]: "); scanf("%d", &arg[1]); if(--arg[1] < 0 || arg[1] > 3) { fputs("*** Erro: Entrada inválida - bloco inexistente.\n", stderr); break; } if(getMonteSize(blocoDecrescente[arg[1]])) { origem = getCarta(blocoPeriferico[arg[0]][0][1], blocoPeriferico[arg[0]][0][0], baralho); destino = getCarta(blocoDecrescente[arg[1]][0][1], blocoDecrescente[arg[1]][0][0], baralho); if(!isNextCard(origem, destino)) { fputs("*** Erro: Movimento inválido.\n", stderr); break; } } insereCarta(&blocoDecrescente[arg[1]], tiraCarta(&blocoPeriferico[arg[0]], baralho)); break; } while(getchar() != '\n'); break; case 'R': case 'r': if(reshuffles > 0) { for(i = 0; i < 16; i++) embaralha(blocoPeriferico[i]); reshuffles--; } else { fputs("*** Erro: Você não possui embaralhamentos restantes.\n", stderr); } break; case 'D': case 'd': sTime = time(NULL) - sTime; sprintf(result, "Jogo no modo %s. Duração: %ld minutos e %ld segundos. Derrota (desistiu).", (mode == 0) ? "\"Melhor Tempo\"" : "\"Contra o relógio\"", sTime/60, sTime%60); writeToLog(result); return 0; default: fputs("* Comando não encontrando.\n", stderr); } printf("\n"); if(time(NULL) - sTime > lTime) running = 0; if(running) { running = 0; for(i = 0; !running && i < 16; i++) { if(getMonteSize(blocoPeriferico[i])) running = 1; } } } while(running); sTime = time(NULL) - sTime; if(mode == 1 && sTime > lTime) { sprintf(result, "Jogo no modo Contra o Relógio. Duração: %ld minutos e %ld segundos. Derrota (Tempo).", sTime/60, sTime%60); writeToLog(result); return 0; } sprintf(result, "Jogo no modo %s. Duração: %ld minutos e %ld segundos. Vitória.", (mode == 0) ? "\"Melhor Tempo\"" : "\"Contra o relógio\"", sTime/60, sTime%60); writeToLog(result); return sTime; } void parseConfig(FILE *config, char *filename, char *naipes, char *first, int *cw, int *ch, int *bordas, unsigned long *bestTime) { fgets(filename, SIZEFILENAME, config); filename[strlen(filename)-1] = '\0'; fscanf(config, "%d %d", cw, ch); fseek(config, 1, SEEK_CUR); // Pula nova linha *first = fgetc(config); fseek(config, 1, SEEK_CUR); // Pula nova linha char tmpNaipes[6]; fgets(tmpNaipes, 6, config); tmpNaipes[4] = '\0'; strcpy(naipes, tmpNaipes); fscanf(config, "%ld", bestTime); int i; for(i = 0; i < 4; i++) fscanf(config, "%d", &bordas[i]); fclose(config); } void writeConfig(FILE *config, char *filename, char *naipes, char first, int cw, int ch, int *bordas, unsigned long bestTime) { fprintf(config, "%s\n%d %d\n%c\n%s\n%ld\n", filename, cw, ch, first, naipes, bestTime); int i; for(i = 0; i < 4; i++) fprintf(config, "%d ", bordas[i]); fseek(config, -1, SEEK_END); fprintf(config, "\n"); }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> /**** Lista de Exercícios - Funções e Ponteiros em C */ //... /**TODO: Escreva os cabeçalhos (protótipos) das funcoeses aqui **/ void incrementa(int *n, int num); void swap(int *a, int *b); void calc(int x, int y, int *soma); int eqSegundoGrau(float a, float b, float c, float *x1, float *x2); void testaIncrementa(); void testaSwap(); void testaCalc(); void testaEqSegundoGrau(); /**TODO: Definicoes das funcoes**/ // funcao para incrementar N de um valor num void incrementa(int *n, int num){ *n = *n + num; return; } /* funcao que realiza um swap, ou seja, troca os valores das variáveis A e B*/ void swap(int *a, int *b){ int aux = *a; *a = *b; *b = aux; return; } // funcao calc deve colocar em soma o valor da soma de x e y. void calc(int x, int y, int *soma){ *soma = x + y; return; } int eqSegundoGrau(float a, float b, float c, float *x1, float *x2){ float delta = 0; delta = (b) * (b) - (4 * a * c); if(delta < 0){ return -1; }else if(delta == 0){ *x1 = (-b) + sqrt(delta)/2 *a; //*x2 = (-b) - sqrt(delta)/2 *a; return 0; }else{ *x1 = (-b) + sqrt(delta)/2*a; *x2 = (-b) - sqrt(delta)/2*a; return 1; } } /**Funcoes de teste **/ /*definição de funções de teste */ void testaIncrementa(){ printf("<funcao incrementa>\n"); int a=2,b=3,c=10; /*teste 1*/ incrementa(&a,b); if(a == 5){ printf(" teste 1: ok.\n"); }else{ printf(" teste 1: not ok.\n"); } /*teste 2*/ incrementa(&a,c); if(a == 15){ printf(" teste 2: ok.\n"); }else{ printf(" teste 2: not ok.\n"); } } void testaSwap(){ printf("<funcao swap1>\n"); int a=1,b=2,c=6,d=7; swap(&a,&b); if(a == 2 && b == 1){ printf(" teste 1: ok.\n"); }else{ printf(" teste 1: not ok.\n"); } swap(&c,&d); if(c == 7 && d == 6){ printf(" teste 2: ok.\n"); }else{ printf(" teste 2: not ok.\n"); } } void testaCalc(){ printf("<funcao calc>\n"); int soma; int x=10,y=20; calc(x,y,&soma); if(soma == 30){ printf(" teste 1: ok.\n"); }else{ printf(" teste 1: not ok.\n"); } x=24;y=100; calc(x,y,&soma); if(soma == 124){ printf(" teste 2: ok.\n"); }else{ printf(" teste 2: not ok.\n"); } } void testaEqSegundoGrau(){ float a, b, c, x1, x2; printf("<funcao EqSegundoGrau>\n"); /*eq. sem raizes*/ a = 1, b = -1, c = 5; if(eqSegundoGrau(a,b,c, &x1, &x2) == -1){ printf(" teste 1 (sem raizes): ok.\n"); }else{ printf(" teste 1 (sem raizes): not ok.\n"); } /*eq. com uma raiz*/ a = 4, b = 4, c = 1; if(eqSegundoGrau(a,b,c, &x1, &x2) == 0){ printf(" teste 2 (uma raiz = %.2f): ok.\n", x1); }else{ printf(" teste 2 (uma raiz): not ok.\n"); } /*eq. com duas raizes*/ a = 1, b = 5, c = 6; if(eqSegundoGrau(a,b,c, &x1, &x2) == 1){ printf(" teste 3 (duas raizes = %.2f e %.2f): ok.\n", x1, x2); }else{ printf(" teste 3 (duas raizes): not ok.\n"); } } /**Função principal**/ int main() { testaIncrementa(); testaSwap(); testaCalc(); testaEqSegundoGrau(); return 0; }
C
#include <stdio.h> /** Macro used to define a command ID based on the service ID and function number. */ #define TZ_SYSCALL_CREATE_CMD_ID(s, f) \ ((int)(((s & 0x3ff) << 10) | (f & 0x3ff))) #define tzt_fastcall_tz3(xxid) \ ((int)((xxid << 12) | 3)) int createSysCall() { int s = 0x1; int f = 0xb; int test_s = 255; int test_f = 1; printf("\nSysCall with test_s = %x, test_f= %x := %x",s,f,(TZ_SYSCALL_CREATE_CMD_ID(s,f))); printf("\nSysCall with test_s = %x, test_f= %x := %x",test_s,test_f,(TZ_SYSCALL_CREATE_CMD_ID(test_s,test_f))); printf("\nFastCall: %x", tzt_fastcall_tz3((TZ_SYSCALL_CREATE_CMD_ID(test_s,test_f)))); return 0; }
C
#include "calc.h" #include <stdio.h> #define FLAG_1 0x1 #define FLAG_2 0x2 #define FLAG_3 0x4 int is_flag_on (struct calc *c, int flag); int set_flag (struct calc *c, int flag, int on); #define assert_equal(first, second) \ if (first == second) \ printf ("%s: OK\n", __func__); \ else \ printf ("%s: %d != %d\n", __func__, first, second); void test_flags (void) { CALC_NEW (c); c.flags = 0; assert_equal (set_flag (&c, FLAG_1, 1), 0); assert_equal (is_flag_on (&c, FLAG_1), 1); assert_equal (c.flags, FLAG_1); assert_equal (set_flag (&c, FLAG_1, 0), 1); assert_equal (is_flag_on (&c, FLAG_1), 0); assert_equal (c.flags, 0); assert_equal (set_flag (&c, FLAG_1, 1), 0); assert_equal (set_flag (&c, FLAG_2, 1), 0); assert_equal (set_flag (&c, FLAG_3, 1), 0); assert_equal (c.flags, (FLAG_1 | FLAG_2 | FLAG_3)); } void test_input_append (void) { struct calc c; calc_init (&c); assert_equal (calc_process_cmd (&c, '1'), 1); assert_equal (calc_process_cmd (&c, '2'), 12); assert_equal (calc_process_cmd (&c, '3'), 123); assert_equal (calc_process_cmd (&c, '='), 123); assert_equal (calc_process_cmd (&c, '3'), 3); assert_equal (calc_process_cmd (&c, '2'), 32); assert_equal (calc_process_cmd (&c, '1'), 321); } void test_input_zero (void) { struct calc c; calc_init (&c); assert_equal (calc_process_cmd (&c, '0'), 0); assert_equal (calc_process_cmd (&c, '0'), 0); assert_equal (calc_process_cmd (&c, '0'), 0); } void test_plus1 (void) { CALC_NEW (c); assert_equal (calc_process_line (&c, "2+"), 2); } void test_plus2 (void) { CALC_NEW (c); assert_equal (calc_process_line (&c, "+2"), 2); } void test_plus3 (void) { CALC_NEW (c); assert_equal (calc_process_line (&c, "1+2="), 3); } void test_plus4 (void) { CALC_NEW (c); assert_equal (calc_process_line (&c, "1+5+10="), 16); } void test_plus5 (void) { CALC_NEW (c); assert_equal (calc_process_line (&c, "1+5=10="), 15); } void test_plus6 (void) { CALC_NEW (c); assert_equal (calc_process_line (&c, "1+5+10=20="), 30); assert_equal (calc_process_cmd (&c, '='), 40); assert_equal (calc_process_cmd (&c, '='), 50); } void test_mult1 (void) { struct calc c; calc_init (&c); assert_equal (calc_process_line (&c, "*2="), 0); } void test_mult2 (void) { struct calc c; calc_init (&c); assert_equal (calc_process_line (&c, "2*="), 4); } void test_mult3 (void) { CALC_NEW (c); assert_equal (calc_process_line (&c, "2*3="), 6); } void test_mult4 (void) { CALC_NEW (c); assert_equal (calc_process_line (&c, "2*3*"), 6); assert_equal (calc_process_line (&c, "="), 36); assert_equal (calc_process_line (&c, "="), 216); } void test_mult5 (void) { CALC_NEW (c); assert_equal (calc_process_line (&c, "1*2*"), 2); assert_equal (calc_process_line (&c, "3*"), 6); assert_equal (calc_process_line (&c, "4*"), 24); assert_equal (calc_process_line (&c, "5*"), 120); assert_equal (calc_process_line (&c, "6*"), 720); assert_equal (calc_process_line (&c, "="), 518400); } void test_minus1 () { CALC_NEW (c); assert_equal (calc_process_cmd (&c, '-'), 0); assert_equal (calc_process_line (&c, "123"), 123); assert_equal (calc_process_cmd (&c, '='), -123); assert_equal (calc_process_cmd (&c, '='), -246); assert_equal (calc_process_cmd (&c, '='), -369); } void test_minus2 () { CALC_NEW (c); assert_equal (calc_process_line (&c, "5-1="), 4); assert_equal (calc_process_cmd (&c, '='), 3); assert_equal (calc_process_cmd (&c, '='), 2); assert_equal (calc_process_cmd (&c, '='), 1); assert_equal (calc_process_cmd (&c, '='), 0); assert_equal (calc_process_cmd (&c, '='), -1); } void test_minus3 () { CALC_NEW (c); assert_equal (calc_process_line (&c, "10-5-1="), 4); assert_equal (calc_process_cmd (&c, '='), 3); assert_equal (calc_process_cmd (&c, '='), 2); assert_equal (calc_process_line (&c, "20="), 19); } void test_minus4 () { CALC_NEW (c); assert_equal (calc_process_line (&c, "10-50="), -40); assert_equal (calc_process_line (&c, "="), -90); assert_equal (calc_process_line (&c, "="), -140); } void test_minus5 () { CALC_NEW (c); assert_equal (calc_process_line (&c, "123-="), -123); } void test_div1 () { CALC_NEW (c); assert_equal (calc_process_line (&c, "/20="), 0); assert_equal (calc_process_cmd (&c, '='), 0); } void test_div2 () { CALC_NEW (c); assert_equal (calc_process_line (&c, "256/2="), 128); assert_equal (calc_process_cmd (&c, '='), 64); assert_equal (calc_process_cmd (&c, '='), 32); } void test_div3 () { CALC_NEW (c); assert_equal (calc_process_line (&c, "256/2="), 128); assert_equal (calc_process_line (&c, "/="), 0); /* 2 / 256 */ } void test_all1 () { CALC_NEW (c); assert_equal (calc_process_line (&c, "123*32-66*-+100="), 3970); } void test_all2 () { CALC_NEW (c); } int main () { test_flags(); test_input_append (); test_input_zero (); test_plus1 (); test_plus2 (); test_plus3 (); test_plus4 (); test_plus5 (); test_plus6 (); test_mult1 (); test_mult2 (); test_mult3 (); test_mult4 (); test_mult5 (); test_minus1 (); test_minus2 (); test_minus3 (); test_minus4 (); test_minus5 (); test_div1 (); test_div2 (); test_div3 (); test_all1 (); test_all2 (); return 0; }
C
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/pem.h> #include <openssl/rsa.h> #include <openssl/err.h> #define ID_EN_FILE_PATH "/home/lele/Template/id_en_file" #define USR_PRV_PATH "/home/lele/Template/usr_prv.key" #define MFR_PRV_PATH "/home/lele/Template/mfr_prv.key" #define LISCENCE_EN_PATH "/home/lele/Template/liscence_en_file" #define SIZE 128 char *usr_prv_de(FILE *id_en_file, char *usr_prv_path) { char *id_en; id_en = (char *)malloc(SIZE); memset(id_en, '\0', SIZE); int ret = 0; if((ret = fread(id_en, 1, SIZE, id_en_file)) == 0) { perror("fread"); return NULL; } fclose(id_en_file); FILE *usr_prv_file; if((usr_prv_file = fopen(usr_prv_path, "r")) == NULL) { printf("open usr_prv.key failed\n"); return NULL; } RSA *usr_prv; if((usr_prv = PEM_read_RSAPrivateKey(usr_prv_file, NULL, NULL, NULL)) == NULL) { ERR_print_errors_fp(stdout); return NULL; } char *id_de; id_de = (char *)malloc(RSA_size(usr_prv)); memset(id_de, '\0', RSA_size(usr_prv)); if(RSA_private_decrypt(RSA_size(usr_prv), (u_char *)id_en, (u_char *)id_de, usr_prv, RSA_NO_PADDING) < 0) return NULL; free(usr_prv); fclose(usr_prv_file); //printf("id_de is: %s\n", id_de); return id_de; } char *mfr_prv_en(char *liscence, char *mfr_prv_path) { FILE *mfr_prv_file; if((mfr_prv_file = fopen(mfr_prv_path, "r")) == NULL) { printf("open mfr_prv.key failed\n"); return NULL; } RSA *mfr_prv; if((mfr_prv = PEM_read_RSAPrivateKey(mfr_prv_file, NULL, NULL, NULL)) == NULL) { ERR_print_errors_fp(stdout); return NULL; } char *liscence_en; liscence_en = (char *)malloc(RSA_size(mfr_prv)); memset(liscence_en, '\0', RSA_size(mfr_prv)); if(RSA_private_encrypt(RSA_size(mfr_prv), (u_char *)liscence, (u_char *)liscence_en, mfr_prv, RSA_NO_PADDING) < 0) return NULL; fclose(mfr_prv_file); //printf("liscence_en is %x \n",liscence_en); FILE *liscence_en_file; if((liscence_en_file = fopen(LISCENCE_EN_PATH, "w")) == NULL) { printf("creating liscence_en_file failed\n"); return NULL; } fwrite(liscence_en, 1, RSA_size(mfr_prv), liscence_en_file); fclose(liscence_en_file); free(mfr_prv); return liscence_en; } int main(void) { char *id_de = NULL; FILE *id_en_file; id_en_file = fopen(ID_EN_FILE_PATH, "r"); if(id_en_file == NULL) { printf("No id_en_file found: "); return -1; } else { id_de = usr_prv_de(id_en_file, USR_PRV_PATH); char *date; date = (char *)malloc(10); memset(date, '\0', 10); printf("set an authoried period (e.g. 20250101):\n"); scanf("%s", date); printf("authoried date set to %s\n", date); char *liscence_temp; liscence_temp = (char *)malloc(strlen(date) + strlen(id_de) + 1); memset(liscence_temp, '\0', strlen(date) + strlen(id_de) + 1); char *liscence = liscence_temp; while(*date != '\0') *liscence_temp++ = *date++; while(*id_de != '\0') *liscence_temp++ = *id_de++; //printf("liscence is %s\n", liscence); mfr_prv_en(liscence, MFR_PRV_PATH); } return 0; }
C
#include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/file.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/errno.h> #include <signal.h> #include <fcntl.h> #include "../libpfs/pfs.h" #include "../pfsd/pfsd.h" int pfsd_bootstrap (const char * root_path) { char * log_path; int fd; uint32_t zero = 0; if (root_path[strlen (root_path) - 1] != '/') { log_path = (char *) malloc (strlen (root_path) + strlen (PFSD_LOG_PATH) + 2); sprintf (log_path, "%s/%s", root_path, PFSD_LOG_PATH); } else { log_path = (char *) malloc (strlen (root_path) + strlen (PFSD_LOG_PATH) + 2); sprintf (log_path, "%s%s", root_path, PFSD_LOG_PATH); } fd = open (log_path, O_WRONLY|O_TRUNC|O_APPEND|O_CREAT); fchmod (fd, S_IRUSR | S_IWUSR); write (fd, &zero, sizeof (uint32_t)); close (fd); return 0; } int main (int argc, char ** argv) { char root_path [PFS_NAME_LEN]; char sd_owner [PFS_NAME_LEN]; char sd_name [PFS_NAME_LEN]; if (argc != 4) { printf ("usage : ./pfs_init root_path sd_owner sd_name\n"); exit (-1); } strncpy (root_path, argv[1], PFS_NAME_LEN); strncpy (sd_owner, argv[2], PFS_NAME_LEN); strncpy (sd_name, argv[3], PFS_NAME_LEN); printf ("Initiating %s.%s in dir %s\n", sd_owner, sd_name, root_path); pfs_bootstrap (root_path, sd_owner, sd_name); pfsd_bootstrap (root_path); exit (0); }
C
/* * myMath_matrix3.c * * Created on: Aug 20, 2013 * Author: Jure */ #include "stm32f4xx.h" #include "arm_math.h" #include "allinclude.h" #include "myMath_typedefs.h" #include "myMath.h" #include "myMath_vec3.h" #include "myMath_matrix3.h" // Create and initialize new 3x3 matrix // if identity == 0, init matrix with all zeroes // if identity == 1, init identity matrix ErrorStatus matrix3_init(int identity, Matrixf * mat) { mat->a.x = 0; mat->a.y = 0; mat->a.z = 0; mat->b.x = 0; mat->b.y = 0; mat->b.z = 0; mat->c.x = 0; mat->c.y = 0; mat->c.z = 0; if(0 != identity) { mat->a.x = 1; mat->b.y = 1; mat->c.z = 1; } return SUCCESS; } ErrorStatus matrix3_vectorMultiply(Matrixf * mat, Vectorf * vecIn, Vectorf * vecOut) { ErrorStatus status = ERROR; // Set FPU exception bit to 0 FPU_EXCEPTION = 0; float32_t a = 0; float32_t b = 0; float32_t c = 0; // Calculate vector by multiplying given vector with given matrix a = mat->a.x * vecIn->x; b = mat->a.y * vecIn->y; c = mat->a.z * vecIn->z; vecOut->x = a + b + c; a = mat->b.x * vecIn->x; b = mat->b.y * vecIn->y; c = mat->b.z * vecIn->z; vecOut->y = a + b + c; a = mat->c.x * vecIn->x; b = mat->c.y * vecIn->y; c = mat->c.z * vecIn->z; vecOut->z = a + b + c; // Check if FPU result is OK if(!FPU_EXCEPTION) { status = SUCCESS; } return status; } ErrorStatus matrix3_transposeVectorMultiply(Matrixf * mat, Vectorf * vecIn, Vectorf * vecOut) { ErrorStatus status = ERROR; // Set FPU exception bit to 0 FPU_EXCEPTION = 0; float32_t a = 0; float32_t b = 0; float32_t c = 0; // Calculate vector by multiplying given vector with given matrix transpose a = mat->a.x * vecIn->x; b = mat->b.x * vecIn->y; c = mat->c.x * vecIn->z; vecOut->x = a + b + c; a = mat->a.y * vecIn->x; b = mat->b.y * vecIn->y; c = mat->c.y * vecIn->z; vecOut->y = a + b + c; a = mat->a.z * vecIn->x; b = mat->b.z * vecIn->y; c = mat->c.z * vecIn->z; vecOut->z = a + b + c; // Check if FPU result is OK if(!FPU_EXCEPTION) { status = SUCCESS; } return status; } // Multiply matrices A and B into matrix C ErrorStatus matrix3_MatrixMultiply(Matrixf * matA, Matrixf * matB, Matrixf * matC) { ErrorStatus status = ERROR; // Set FPU exception bit to 0 FPU_EXCEPTION = 0; float32_t a = 0; float32_t b = 0; float32_t c = 0; // Calculate resulting matrix by multiplying matrices A and B // Row A.a, col B.x a = matA->a.x * matB->a.x; b = matA->a.y * matB->b.x; c = matA->a.z * matB->c.x; matC->a.x = a + b + c; a = matA->a.x * matB->a.y; b = matA->a.y * matB->b.y; c = matA->a.z * matB->c.y; matC->a.y = a + b + c; a = matA->a.x * matB->a.z; b = matA->a.y * matB->b.z; c = matA->a.z * matB->c.z; matC->a.z = a + b + c; a = matA->b.x * matB->a.x; b = matA->b.y * matB->b.x; c = matA->b.z * matB->c.x; matC->b.x = a + b + c; a = matA->b.x * matB->a.y; b = matA->b.y * matB->b.y; c = matA->b.z * matB->c.y; matC->b.y = a + b + c; a = matA->b.x * matB->a.z; b = matA->b.y * matB->b.z; c = matA->b.z * matB->c.z; matC->b.z = a + b + c; a = matA->c.x * matB->a.x; b = matA->c.y * matB->b.x; c = matA->c.z * matB->c.x; matC->c.x = a + b + c; a = matA->c.x * matB->a.y; b = matA->c.y * matB->b.y; c = matA->c.z * matB->c.y; matC->c.y = a + b + c; a = matA->c.x * matB->a.z; b = matA->c.y * matB->b.z; c = matA->c.z * matB->c.z; matC->c.z = a + b + c; // Check if FPU result is OK if(!FPU_EXCEPTION) { status = SUCCESS; } return status; } ErrorStatus matrix3_transpose(Matrixf * matA, Matrixf * matB) { matA->a.x = matB->a.x; matA->a.y = matB->b.x; matA->a.z = matB->c.x; matA->b.x = matB->a.y; matA->b.y = matB->b.y; matA->b.z = matB->c.y; matA->c.x = matB->a.z; matA->c.y = matB->b.z; matA->c.z = matB->c.z; return SUCCESS; } ErrorStatus matrix3_copy(Matrixf * matA, Matrixf * matB) { matA->a.x = matB->a.x; matA->a.y = matB->a.y; matA->a.z = matB->a.z; matA->b.x = matB->b.x; matA->b.y = matB->b.y; matA->b.z = matB->b.z; matA->c.x = matB->c.x; matA->c.y = matB->c.y; matA->c.z = matB->c.z; return SUCCESS; } // Make matrix orthogonal and normalized ErrorStatus matrix3_normalizeOrthogonalizeMatrix(Matrixf * rotMatrix, float32_t maxError) { ErrorStatus status = SUCCESS; // Set FPU exception bit to 0 FPU_EXCEPTION = 0; float32_t error = 0; Vectorf tempVector = vectorf_init(0); Vectorf tempVector1 = vectorf_init(0); // Calculate error = X.Y status = vectorf_dotProduct(&rotMatrix->a, &rotMatrix->b, &error); // If error is larger than we permit, return ERROR if(maxError < error) { return ERROR; } // Add half error to X, half to Y error = error / 2; status = vectorf_scalarProduct(&rotMatrix->a, error, &tempVector); status = vectorf_scalarProduct(&rotMatrix->b, error, &tempVector1); status = vectorf_substract(&rotMatrix->a, &tempVector1, &rotMatrix->a); status = vectorf_substract(&rotMatrix->b, &tempVector, &rotMatrix->b); // Normalize a status = vectorf_dotProduct(&rotMatrix->a, &rotMatrix->a, &error); error = 3 - error; error = error / 2; // If error is larger than we permit, return ERROR if(maxError < error) { return ERROR; } status = vectorf_scalarProduct(&rotMatrix->a, error, &rotMatrix->a); // Normalize b status = vectorf_dotProduct(&rotMatrix->b, &rotMatrix->b, &error); error = 3 - error; error = error / 2; // If error is larger than we permit, return ERROR if(maxError < error) { return ERROR; } status = vectorf_scalarProduct(&rotMatrix->b, error, &rotMatrix->b); // Calculate Z as cross product of X and Y status = vectorf_crossProduct(&rotMatrix->a, &rotMatrix->b, &rotMatrix->c); // Normalize c status = vectorf_dotProduct(&rotMatrix->c, &rotMatrix->c, &error); error = 3 - error; error = error / 2; // If error is larger than we permit, return ERROR if(maxError < error) { return ERROR; } status = vectorf_scalarProduct(&rotMatrix->c, error, &rotMatrix->c); // Check if FPU result is OK if(!FPU_EXCEPTION) { status = SUCCESS; } return status; }