language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include "holberton.h" /** * _isalpha - alpha * @c: this is about the alphabet * description: alphabet * Return: 1, 0 */ int _isalpha(int c) { if ((('a' <= c) && (c <= 'z')) || (('A' <= c) && (c <= 'Z'))) { return (1); } else { return (0); } }
C
inherit VERB_OB; int get_floor(object living); int get_ceiling(object living); void drain_target(object living); void concentration(object living); void do_steallife_liv(object living) { object this_body = this_body(); if (this_body->query_guild_level("jedi")) { if (this_body->is_body() && !this_body->has_learned_skill("steal life")) { write("You have not learned how to drain someone's life through the force.\n"); } else if (this_body->has_skill_delay()) { write("You are too busy to concentrate on draining someone's life.\n"); } else if (this_body->query_health() >= this_body->query_max_health()) { write("You are already at full health.\n"); } else { if (living->is_adversary()) { if (living != this_body) { int alignment = this_body->query_jedi_alignment(); this_body->adjust_jedi_alignment(alignment < 0 ? -5 : this_body->has_buff("/d/buffs/force_focus") ? -15 : -10); concentration(living); } else { write("Just being alive is enough of a drain on yourself.\n"); } } else { write("You could find someone whose life is actually worth draining.\n"); } } } else { write("Only Jedi know how to drain someone's life through the Force.\n"); } } void do_steallife() { object target = this_body()->get_target(); if (!this_body()->is_body()) { concentration(target); return; } if (target) { do_steallife_liv(target); } else { write("Drain whose life?\n"); } } void drain_target(object living) { object this_body = this_body(); int floor = get_floor(living); int ceiling = get_ceiling(living); int amount = floor + random(ceiling - floor + 1); this_body->simple_action("$N can steal life from " + floor + " to " + ceiling + ", and had a roll of " + amount + ".\n"); this_body->targetted_action("$N $vdrain some of $p1 life energy, adding it to $p own.\n", living); amount = living->weaken_us(amount); if (amount > 0) { this_body->heal_us(amount); } else { tell(this_body, "You discover that " + living->short() + " is nearly lifeless.\n"); } this_body->initiate_combat(living); this_body->handle_events(); } int get_floor(object living) { object this_body = this_body(); int force = this_body->query_for(); int living_force = living->query_for(); int level = this_body->query_guild_level("jedi"); int rank = this_body->query_skill("steal life") / 100; int spec = this_body->query_guild_specialization_rank("jedi", "affliction"); int amount = to_int((rank * 0.2) * ((force / 5) + (level / 5) + spec)); if (force < (living_force - (spec * 3))) { amount -= ((living_force - (spec * 3)) - force); } return (amount > 0 ? amount : 1); } int get_ceiling(object living) { object this_body = this_body(); int force = this_body->query_for(); int living_force = living->query_for(); int level = this_body->query_guild_level("jedi"); int rank = this_body->query_skill("steal life") / 100; int spec = this_body->query_guild_specialization_rank("jedi", "affliction"); int amount = to_int((rank * 0.1) * (20 + ((force / 5) * 2) + (level * 2) + (spec * 4))); if (force < (living_force - (spec * 3))) { amount -= ((living_force - (spec * 3)) - force); } return (amount > 0 ? amount : force / 5); } void concentration(object living) { object this_body = this_body(); int alignment = this_body->query_jedi_alignment(); if (this_body->test_skill("steal life", (alignment * -15))) { drain_target(living); } else { this_body->targetted_action("$N $vattempt to drain some of $p1 life energy, and $vfail.\n", living); } this_body->add_skill_delay(12); } void create() { add_rules( ({ "", "LIV" }) ); }
C
// 123 = 1 + 2 + 3 = 6 // 852 = 8 + 5 + 2 = 15 #include <stdio.h> int main() { int num, rem = 0, sum = 0, temp; printf("Enter a number: "); scanf("%d", &num); temp = num; while (num != 0) { rem = num % 10; num = num / 10; sum = sum + rem; } printf("Sum of %d is %d", temp, sum); }
C
#include <assert.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include "forces.h" #include "scene.h" #include "sdl_wrapper.h" #include "shapes.h" #include "color.h" #define WIDTH 1000 #define HEIGHT 500 #define NUM_BODIES 100 #define NUM_SIDES 10 #define RADIUS 10 #define MASS 20000000 #define GRAVITY 1e-3 const Vector min = {.x = 0, .y = 0}; const Vector max = {.x = WIDTH, .y = HEIGHT}; const RGBColor red = {.r = 1, .g = 0, .b = 0}; // Return random location as a vector on the screen Vector random_location() { double x = rand() % (WIDTH + 1); double y = rand() % (HEIGHT + 1); return (Vector) {.x = x, .y = y}; } int main(int argc, char *argv[]) { sdl_init(min, max); Scene *scene = scene_init(); size_t i, j; double dt; for (i = 0; i < NUM_BODIES; i++) { scene_add_body(scene, n_polygon_shape(NUM_SIDES, RADIUS, MASS, random_color(), random_location())); } for (i = 0; i < NUM_BODIES -1; i++) { for (j = i + 1; j < NUM_BODIES; j++) { create_newtonian_gravity(scene, GRAVITY, scene_get_body(scene, i), scene_get_body(scene, j)); } } while (!sdl_is_done()) { dt = time_since_last_tick(); scene_tick(scene, dt); sdl_render_scene(scene); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <mpi.h> // Creates an array of random numbers. int *create_random_array(int num_elements, int max_value) { int *arr = (int *)malloc(sizeof(int) * num_elements); for (int i = 0; i < num_elements; i++) { arr[i] = (rand() % max_value); } return arr; } int count_multiple(int *array, int size, int filter_num) { int count = 0; for (int i = 0; i < size; i++) { if ((array[i] % filter_num) == 0) count++; } return count; } int *filter_array(int *array, int size, int filter_num, int out_size) { int *out_array = (int *)malloc(sizeof(int) * out_size); int j = 0; for (int i = 0; i < size; i++) { if ((array[i] % filter_num) == 0) out_array[j++] = array[i]; } return out_array; } void send_results(int *array, int size, int filter_num, int my_rank) { int multiple_count = count_multiple(array, size, filter_num); MPI_Send(&multiple_count, 1, MPI_INT, 0, 0, MPI_COMM_WORLD); printf("Node %d count result %d\n", my_rank, multiple_count); if (multiple_count > 0) { int *result_array = filter_array(array, size, filter_num, multiple_count); MPI_Send(result_array, multiple_count, MPI_INT, 0, 0, MPI_COMM_WORLD); free(result_array); } } int *receive_result(int world_size, int *out_size) { int num_procc_with_result = 0; *out_size = 0; int *result = NULL; for (int procID = 1; procID < world_size; procID++) { int count_result; MPI_Recv(&count_result, 1, MPI_INT, procID, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE); (*out_size) += count_result; if (count_result > 0) num_procc_with_result++; } if (*out_size == 0) return result; result = (int *)malloc(sizeof(int) * (*out_size)); printf("Master out size %d results\n", *out_size); int fill_index = 0; for (int i = 0; i < num_procc_with_result; i++) { MPI_Status status; MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); int count; MPI_Get_count(&status, MPI_INT, &count); MPI_Recv(&result[fill_index], count, MPI_INT, status.MPI_SOURCE, status.MPI_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE); fill_index += count; } return result; } // Process 0 selects a number num. // All other processes have an array that they filter to only keep the elements // that are multiples of num. // Process 0 collects the filtered arrays and print them. int main(int argc, char **argv) { // Maximum value for each element in the arrays const int max_val = 100; // Number of elements for each processor int num_elements_per_proc = 50; // Number to filter by int num_to_filter_by = 2; if (argc > 1) { num_elements_per_proc = atoi(argv[1]); } // Init random number generator srand(time(NULL)); MPI_Init(NULL, NULL); int my_rank, world_size; MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); MPI_Comm_size(MPI_COMM_WORLD, &world_size); // Process 0 selects the num int num; int *local_array; if (my_rank == 0) { num = num_to_filter_by; } else { local_array = create_random_array(num_elements_per_proc, max_val); } MPI_Bcast(&num, 1, MPI_INT, 0, MPI_COMM_WORLD); if (my_rank > 0) { send_results(local_array, num_elements_per_proc, num, my_rank); } else { int result_size; int *results = receive_result(world_size, &result_size); printf("Received %d results\n", result_size); printf("Results: \n"); for (int i = 0; i < result_size; i++) { printf("%d\t", results[i]); } if (result_size > 0) { printf("\n"); free(results); } if (my_rank > 0) free(local_array); } MPI_Barrier(MPI_COMM_WORLD); MPI_Finalize(); }
C
/* Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: Input: 121 Output: true Example 2: Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Example 3: Input: 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #define MAX_DIGITS 0xFFFFFFFF int max_digits(){ int digits=0; long num = 0xFFFFFFFF - 1; digits = 1; while ( num > 0 ) { num = num/10; digits++; } return digits; } bool isPalindrome(int x){ bool ret=false; int tmp = 0, i=0, j=0, noDigits=0, decimalDigits=0; char *digits=NULL; if ( x < 0 ) return false; decimalDigits = max_digits(); printf("max. digits=%d\n", decimalDigits); digits = malloc( sizeof (char) * decimalDigits ); if ( digits ) { tmp = x; i = 0; while ( tmp > 9 ) { digits[i] = tmp % 10; i++; tmp = tmp/10; printf("tmp=%d\n", tmp); if ( tmp < 10 ) { digits[i] = tmp; i++; break; } } noDigits = i; printf("%d has %d digits\n", x, noDigits); if ( noDigits < 2 ) { ret = true; goto free_m; } i = 0; j = noDigits - 1; ret = true; while ( i != j ) { printf("%d : %d\n", digits[i] , digits[j]); if ( digits[i] != digits[j] ) { ret = false; break; } i++; j--; if ( j == 0 ) break; } } free_m: if (digits) free(digits); return ret; } int main(){ int num=-121; printf("%d(0x %x)\n", num, num); if ( isPalindrome(num) ) printf("%d is Palindrome\n", num); else printf("%d is Not Palindrome\n", num); }
C
#include "libmx.h" int mx_sqrt(int x) { long root = 1; if (x < 0) return 0; for (; root*root < x; root++); if (root*root == x) { return (int)root; } return 0; } // double mx_sqrt(double x) { // // - algorithm for real numbers: // double root = x / 2; // double scale_factor = 2.0; // if (root < 0) return 0; // for (int i = 0; i < 1000; i++, scale_factor *= 1.05) { // double squared_root = root*root; // if (squared_root == x) { // return root; // } else if (squared_root > x) { // root -= (root / scale_factor); // } else { // root += (root / scale_factor); // } // } // return root; // }
C
#include <stdio.h> #include <stdlib.h> int main() { return 0; } void baja( ePersona pers[] , int cantidad ) { int auxId, i , flag = 0; char respuesta; printf("Ingrese id: "); scanf( "%d" , &auxId ); for( i = 0 ; i < cantidad ; i++ ) { if( auxId == pers[i].id ) { printf(""); muestro los datos de lo que encontro do { printf(" Esta seguro que desea darlo de baja ? s/n"); scanf( "%c" , &respuesta ); } while (respuesta != 's' && respuesta != 'n'); if(respuesta == 's') { pers[i].isEmpty = 1; flag = 1; break; } else { printf("El registro no se dio de baja"); } } } if( flag == 0 ) { printf("El dato no existe"); } } void modificacion( ePersona pers[] , int cantidad ) { int auxId, menuMod, i , flag = 0; char respuesta; printf("Ingrese id: "); scanf( "%d" , &auxId ); for( i = 0 ; i < cantidad ; i++ ) { if( auxId == pers[i].id ) { printf(""); muestro los datos de lo que encontro do { printf(" Esta seguro que desea modificar el campo ? s/n"); scanf( "%c" , &respuesta ); } while (respuesta != 's' && respuesta != 'n'); if(respuesta == 's') { do { menuMod = menuModificacion(); switch( idMenu ) { case 1: printf("\nNombre: "); fflush(stdin); scanf("%s", pers[i].nombre); break; case 2: printf("\nApellido: "); fflush(stdin); scanf("%s", pers[i].apellido); break; case 3: printf("\nEdad: "); fflush(stdin); scanf("%d", pers[i].edad); break; case 4: break; } } while ( menuMod != 5 ); } else { printf("El registro no se dio de baja"); } } } if( flag == 0 ) { printf("El dato no existe"); } } int menuModificacion() { int menu; printf("\n1) Nombre. "); printf("\n2) Apellido. "); printf("\n3) Edad. "); printf("\n4) Salir."); printf("\nSeleccionar una opcion <1-4>: "); scanf( "%d" , &menu ); return menu; }
C
/* * a MinHeap ADT Header * Ref: www.geeksforgeeks.org/greedy-algorithms-set-3-huffman-coding * Written by Tianpeng Chen z5176343 for COMP9319 assignment 1 * Destroy method added * Table transfer function added */ // a huffman tree node structure typedef struct MinHeapNode { unsigned char data; unsigned freq; struct MinHeapNode *left, *right; int valid; // 1 for data node, 0 for internal node } MinHeapNode; // a huffman tree structure typedef struct MinHeapST { unsigned size; unsigned capacity; MinHeapNode **array; } MinHeap; // code table unsigned char* table[256]; // to destroy MinHeap* globalMinHeapPtr; MinHeapNode* newNode(unsigned char data, unsigned freq, int valid); MinHeap* createMinHeap(unsigned capacity); void swapMinHeapNode(MinHeapNode** a, MinHeapNode** b); void minHeapify(MinHeap* minHeap, int index); int isSizeOne(MinHeap* minHeap); MinHeapNode* getMin(MinHeap* minHeap); void insertMinHeap(MinHeap* minHeap, MinHeapNode* minHeapNode); void buildMinHeap(MinHeap* minHeap); void printArray(unsigned char array[], unsigned n); int isLeaf(MinHeapNode* root); MinHeap* createAndBuildMinHeap(unsigned char data[], unsigned freq[], int size); MinHeapNode* buildHuffmanTree(unsigned char data[], unsigned freq[], int size); void printHuffman(MinHeapNode* root, unsigned char arrry[], unsigned top); // expose huffmantree pointer to outside unsigned char** huffmanCodes(MinHeapNode** tree, unsigned char data[], unsigned freq[], int size); // int* getCode(unsigned char token); // HuffmanTable* initTable(int size); void transferToTable(MinHeapNode* root, unsigned char array[], unsigned top, unsigned char* table[]); void printTable(unsigned char* table[]); void destroyMinHeap(); void destroyHuffmanTree(MinHeapNode* tree); // expose root pointer outside, move this function to huffman.c // void getunsigned char(MinHeapNode* root, unsigned char* code[], int* cur, int* n, unsigned char* decoded[], unsigned char* rest[]);
C
/** \archivo sh.c \descripcion Este archivo representa al proceso sh que funge como shell o interpretador de comandos, en este caso solo puede aceptar comandos con un solo argumento, el comando EXIT, sale de sesion y el comando SHUTDOWN, cierra todos los procesos \autores Jose Andres Hernandez Hernandez Andrea Miriam Perez Huizar \fecha 12/Feb/20 */ /* Librerias*/ #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/wait.h> /* Macros*/ #define LENGTH_TEXT 30 /* Longitud de los strings */ #define ASCII_SPACE 32 /* Codigo ASCII de espacio */ int main(void) { char *argv[3] = {NULL,NULL,NULL}; /* Arreglo de strings para comandos y parametros*/ char command[LENGTH_TEXT] = {0}; /* String donde se guardara el comando introducido*/ char temp1[LENGTH_TEXT] = {0}; /* Variable temporal para comando*/ char temp2[LENGTH_TEXT] = {0}; /* Variable temporal para argumentos de comandos*/ int counter1; /* Contador para identificar comando*/ int counter2; /* Contador para identificar argumentos*/ int len_cmd; /* Longitud de comandos con sus argumentos*/ int flag_space; /* Bandera que indica la existencia de espacios*/ const char amp[LENGTH_TEXT] = "&"; /* Constante que almacena al amperson*/ /* Ciclo infinito ya que este siempre estara pidiendo comandos al usuario*/ for(;;) { printf("sh > "); fgets(temp1,LENGTH_TEXT,stdin); /* Peticion de comando a usuario*/ memcpy(command,temp1,strlen(temp1)-1); /* Almacenamiento en string comando*/ memset(temp1,0,strlen(temp1)); /* Vaciado total de variable temporal*/ len_cmd = strlen(command); /* Longitud del comando ingresado*/ flag_space = 0; /* Inicializacion de bandera de espacio*/ /* Deteccion de espacio en comando, que indica que tiene argumentos*/ for(counter1 = 0; counter1 <= len_cmd; counter1++) { if(command[counter1] == ASCII_SPACE) flag_space = 1; /* Si hay espacio, la bandera se activa*/ } /* Si existe espacio se ejecuta la siguiente rutina para obtener argumentos*/ if(flag_space) { /* Se guarda el comando en la variable temporal 1*/ for(counter1 = 0; command[counter1] != ASCII_SPACE; counter1++) temp1[counter1] = command[counter1]; counter1++; /* Se aumenta 1 para evitar tomar el espacio*/ counter2 = 0; /* Se inicializa el contador 2*/ /* El contador 1 continua con lo ingresado por el usuario*/ for(;counter1 <= len_cmd; counter1++) { temp2[counter2] = command[counter1]; /* Se guarda el argumento*/ counter2++; /* Guarda en el siguiente espacio*/ } memset(command,0,strlen(command)); /* Vaciado en cero de comando*/ memcpy(command,temp1,strlen(temp1)); /* Asignacion de comando separado*/ argv[1] = temp2; /* Asignacion de argumento separado*/ } if(strcmp(command,"exit") == 0) /* Comparacion con comando EXIT*/ { execlp("./getty","getty",NULL); /* Regresa a proceso getty*/ }else if(strcmp(command,"shutdown") == 0) /* Comparacion con comando SHUTDOWN*/ { /* Se elimina todo los procesos*/ execl("/usr/bin/killall","killall","./init","./getty","./sh","/usr/bin/xterm",NULL); }else { argv[0] = command; /* Primer string de argumentos es el comando*/ if(fork() == 0) execvp(command,argv); /* Se ejecuta lo pedido por el comando*/ else if(strcmp(temp2, amp)) /* Si en los argumentos existe &, entonces no espera*/ wait(NULL); /* Solo se espera en primer plano*/ } argv[0] = NULL; /* Vaciado de primer string de argumentos*/ argv[1] = NULL; /* Vaciado de segundo string de argumentos*/ memset(temp1,0,strlen(temp1)); /* Vaciado de variable temporal 1*/ memset(temp2,0,strlen(temp2)); /* Vaciado de variable temporal 2*/ memset(command,0,strlen(command)); /* Vaciado de variale comando */ } return 0; }
C
/* * Daniel Goncalves > [email protected] * ARQCP - Turma 2DK * * same_word.h */ #include <stdio.h> /* * Compares words in the string address with the word received * * returns 1 or 0 depending if a word matches with a word in the given string or not. */ int same_word(char *word, char *str){ while(*str != ' ' && *str != '\0'){ if(*word != *str){ return 0; } word++; str++; } return 1; }
C
#include<stdio.h> main() { int a[50],i,n,large,small; printf("enter the number of elements in an array:\n"); scanf("%d",&n); printf("enter the elements in an array\n"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } large=small=a[0]; for(i=1;i<n;i++) { if(a[i]>large) large=a[i]; if(a[i]<small)33 small=a[i]; } printf("the largest number is %d",large); printf("the smallest number is %d",small); }
C
// list/list.h // // Interface definition for linked list. // // <Daniel> #include <stdbool.h> /* Defines the node structure. Each node contains its key and value, and points to the * next node in the list. The last element in the list should have NULL as its * next pointer. */ struct node { char* key; char* value; struct node *next; }; typedef struct node node_t; /* Defines the list structure, which simply points to the first node in the * list. */ struct list { node_t *head; }; typedef struct list list_t; /* Functions for allocating and freeing lists. By using only these functions, * the user should be able to allocate and free all the memory required for * this linked list library. */ list_t *list_alloc(); void list_free(list_t *l); /* Prints the list in some format. */ void list_print(list_t *l, char* buffer); /* Methods for adding to the list. */ void list_add_to_front(list_t *l, char* key, char* value); /* Checks to see if the given element exists in the list. */ bool list_is_in(list_t *l, char* key); void list_put(list_t *l, char* key, char* value); /* Returns the value at particularly key. */ char* list_get_value_of_key(list_t *l, char* key);
C
#include <stdio.h> #include "calculadora.h" #define TAMANHO_VETOR 10 int main(void) { // Declarando variáveis int resultado, vetor1[TAMANHO_VETOR] = {0,0,0,0,0,0,0,0,0,0}, vetor2[TAMANHO_VETOR] = {0,0,0,0,0,0,0,0,0,0}; // Menu interativo printf("Calculadora de Vetores [versão 1.0]\n\n"); printf("Crie o primeiro vetor, você deve digitar 10 números:\n"); // Recebendo valores do vetor 1 preencher_vetor(vetor1); // Menu interativo printf("Crie o segundo vetor, você deve digitar 10 números:\n"); // Recebendo vetor 2 preencher_vetor(vetor2); // Repetir operações char comando = ' '; do { // Retornando Vetores printf("\nVetor 1 = ["); for(int i=0; i<TAMANHO_VETOR-1; i++) { printf("%d, ", vetor1[i]); } printf("%d]\n", vetor1[TAMANHO_VETOR-1]); printf("Vetor 2 = ["); for(int i=0; i<TAMANHO_VETOR-1; i++) { printf("%d, ", vetor2[i]); } printf("%d]\n", vetor2[TAMANHO_VETOR-1]); // Gerenciando operações char operacao = ' '; printf("Digite '+' para soma\n"); printf("Digite '-' para subtração\n"); printf("Digite '*' para multiplicação\n"); do { printf("\nEscolha uma operação: "); scanf(" %c", &operacao); if(operacao == '+') { resultado = soma(vetor1, vetor2); } else if (operacao == '-') { resultado = subtracao(vetor1, vetor2); } else if (operacao == '*') { resultado = multiplicacao(vetor1, vetor2); } else { printf("Operação inválida\n"); } } while(operacao != '+' && operacao != '-' && operacao != '*'); // Resultado printf("Resultado: %d\n", resultado); // Defenir repetição printf("\nPara finalizar o programa digite 'x'\n"); do { printf("Você deseja realisar outra operação com os mesmos vetores (s/n)? "); scanf(" %c", &comando); if (comando == 's') { continue; } else if (comando == 'n'){ printf("Qual vetor você deseja alterar? Digite 'u' para o vetor 1, 'd' para o vetor 2 e 'a' para ambos... "); scanf(" %c", &comando); if (comando == 'u') { printf("Digite os valores do primeiro vetor:\n"); preencher_vetor(vetor1); comando = 's'; } else if (comando == 'd') { printf("Digite os valores do segundo vetor:\n"); preencher_vetor(vetor2); comando = 's'; } else if (comando == 'a') { printf("Digite os valores do primeiro vetor:\n"); preencher_vetor(vetor1); printf("Digite os valores do segundo vetor:\n"); preencher_vetor(vetor2); comando = 's'; } else { printf("Comando inválido\n"); } } else if (comando == 'x') { break; } else { printf("Comando inválido\n"); } } while(comando != 's' && comando != 'n' && comando != 'x'); } while(comando != 'x'); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_putnbr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mschneid <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/09/08 10:21:35 by mschneid #+# #+# */ /* Updated: 2017/09/11 17:55:38 by mschneid ### ########.fr */ /* */ /* ************************************************************************** */ void ft_putchar(char c); int ft_putnbr_nbrofdigits(int nb) { int count; count = 0; while (nb != 0) { nb /= 10; count++; } return (count); } int ft_putnbr_extractdigit(int nb, int digitnb) { int i; char arr[ft_putnbr_nbrofdigits(nb)]; int nb2; i = ft_putnbr_nbrofdigits(nb); while (i--) { nb2 = nb; nb = nb / 10; arr[i] = nb2 - nb * 10; } return (arr[digitnb]); } void ft_putnbr_convertprint(int digit) { char c; c = digit + '0'; ft_putchar(c); } void ft_putnbr(int nb) { int i; int intmin; i = 0; intmin = 0; if (nb == 0) ft_putchar('0'); if (nb < 0) { ft_putchar('-'); nb = nb * -1; } if (nb == -2147483648) { intmin = 1; nb = 214748364; } while (i < ft_putnbr_nbrofdigits(nb)) { ft_putnbr_convertprint(ft_putnbr_extractdigit(nb, i)); i++; } if (intmin) ft_putchar('8'); }
C
#include <stdio.h> int main(){ int metre,nbre_foliole; scanf("%d\n%d",&metre,&nbre_foliole); if(metre<=5 && nbre_foliole>=8) printf("Tinuviel\n"); if(metre>=10 && nbre_foliole>=10) printf("Calaelen\n"); if(metre<=8 && nbre_foliole<=5) printf("Falarion\n"); if(metre>=12 && nbre_foliole<=7) printf("Dorthonion\n"); }
C
#include<stdio.h> #include<SDL2/SDL.h> #include<SDL2/SDL_image.h> /*Declarando variáveis globais*/ SDL_Window* janela = NULL; SDL_Renderer* renderizador = NULL; SDL_Texture* fundo = NULL; /*Função usada para carregar as imagens para variáveis tipo textura*/ SDL_Texture* carrega_textura(char *caminho_img) { SDL_Texture* textura = NULL; SDL_Surface* imagem = IMG_Load(caminho_img); textura = SDL_CreateTextureFromSurface(renderizador, imagem); if(!imagem || !textura){ printf("Nao foi possivel carregar a seguinte imagem: \n%s\nErro: %s\n", caminho_img, IMG_GetError()); SDL_DestroyTexture(textura); SDL_FreeSurface(imagem); return 0; } return textura; } /*----- Função que gera a janela inicial de menu ----- */ SDL_Window* menu() { /*Criando janela principal*/ janela = SDL_CreateWindow("LaunchPad+ Beats 1.0", SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,SCREEN_WIDTH,SCREEN_HEIGHT,SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); if(!janela) { printf("Ocorreu um erro ao abrir a janela!\nErro: %s\n",SDL_GetError()); return 0; } /*Inicializando o renderizador na janela criada*/ renderizador = SDL_CreateRenderer(janela,-1,SDL_RENDERER_ACCELERATED); if(!renderizador) { printf("Ocorreu um erro ao iniciar o renderizador!\nErro: %s\n",SDL_GetError()); return 0; } SDL_SetRendererDrawColor(renderizador, 255,0,0,255); /*Inicializando suporte para os formatos de imagens a serem usados. (PNG e JPEG)*/ int img_flags = IMG_INIT_JPG | IMG_INIT_PNG; if(IMG_Init(img_flags) != img_flags){ printf("O programa não conseguiu suporte para os formatos de imagem JPG e/ou PNG\nErro: %s\n", IMG_GetError() ); return 0; } }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <math.h> #include <time.h> #define tam 1000000000 void exectime(int time_s){ clock_t time_e = clock(); double execution = (double) (time_e - time_s) / CLOCKS_PER_SEC; printf("\tTempo de execucao: %f\n", execution); } void main(){ int i, j, k, nprimos=2; static bool primos[tam]; clock_t time_s = clock(); primos[2]=true; primos[3]=true; for(i=4; i<tam; i+=2) primos[i]=false; for(i=5; i<tam; i+=2) primos[i]=true; printf("Vetor setado para true."); exectime(time_s); /* for(j=4; j<tam; j+=2) primos[j] = false; */ for(j=9; j<tam; j+=6) primos[j] = false; for(i=6; i*i<=tam; i+=6){ if(primos[i-1]){ for(j=((i-1)*(i-1)); j<tam; j+=(i+i-2)) primos[j]=false; } if(primos[i+1]){ for(j=((i+1)*(i+1)); j<tam; j+=(i+i+2)) primos[j]=false; } } printf("Primos descobertos."); exectime(time_s); for(i=6; i<tam; i+=6){ if(primos[i-1]) nprimos++; if(primos[i+1]) nprimos++; } printf("O numero de numeros primos e %d.", nprimos); exectime(time_s); int *primoss = (int *) malloc(nprimos * sizeof(int)); j=2; primoss[0] = 2; primoss[1] = 3; for(i=6; i<tam; i+=6){ if(primos[i-1]) primoss[j++]=i-1; if(primos[i+1]) primoss[j++]=i+1; } printf("Maior primo em %d: %d", tam, primoss[nprimos-1]); exectime(time_s); /* for(i=0; i<nprimos; i++) printf("%d ", primoss[i]); */ }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "List.h" void printStringArray(FILE *out, char **array, List L, int count); int main(int argc, char *argv[]) { int count = 0, i, j; int *lineLength; int *indexArray; char c = '0'; char **input; // char *buffer; FILE *in, *out; // -------------condition check-------------- if (argc <= 1) { fprintf(stderr, "USAGE: ./<Program name> + <input file name>\n"); exit(EXIT_FAILURE); } // open input file for reading if ((in = fopen(argv[1], "r")) == NULL) { printf("Unable to read from file %s\n", argv[1]); exit(EXIT_FAILURE); } // open output file for writing if ((out = fopen(argv[2], "w")) == NULL) { printf("Unable to write to file %s\n", argv[2]); exit(EXIT_FAILURE); } // read in m lines from input file for (c = getc(in); c != EOF; c = getc(in)) if (c == '\n') // Increment count if this character is newline count = count + 1; // printf("The input file has %d words\n", count); rewind(in); // read in the length for each line lineLength = calloc(count, sizeof(int)); i = 0; for (c = getc(in); c != EOF; c = getc(in)) { lineLength[i] += 1; if (c == '\n') { // Increment count if this character is newline // printf("line %d has %d cahracters\n", i, lineLength[i]); i = i + 1; } } rewind(in); // integrate List according to line counts // List output = newList(); // for (i = 0; i < count; i++) // { // append(output, i); // } // printList(stdout, output); // printf("\n"); indexArray = calloc(count, sizeof(int)); for (i = 0; i < count; i++) { indexArray[i] = i; } for (i = 0; i < count; i++) { // printf("%d ", indexArray[i]); } // printf("\n"); List output = newList(); // allocate backup storage for input file by using the length obtained earlier input = malloc((count + 1) * sizeof(char *)); c = 0; for (i = 0; i < count + 1; i++) { if (i < count) { input[i] = calloc(lineLength[i] + 1, sizeof(char)); // while (c != '\n') // { // c = getc(in); // } fgets(input[i], lineLength[i] + 1, in); // printf("%s is stored\n", input[i]); } else if (i == count) input[i] = NULL; } int key; for (i = 1; i < count; i++) { key = indexArray[i]; j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && strcmp(input[indexArray[j]], input[key]) > 0) { indexArray[j + 1] = indexArray[j]; j = j - 1; } indexArray[j + 1] = key; } for (i = 0; i < count; i++) { // printf("%d ", indexArray[i]); append(output, indexArray[i]); } // printf("\n"); printStringArray(out, input, output, count); for (i = 0; i <= count; i++) { if (input[i] != NULL) { free(input[i]); input[i] = NULL; } } free(input); free(lineLength); free(indexArray); lineLength = NULL; indexArray = NULL; input = NULL; fclose(in); fclose(out); freeList(&output); } void printStringArray(FILE *out, char **array, List L, int count) { int i; moveFront(L); // for (i = 0; array[i] != NULL; i++) // { // printf("%s", array[i]); // } for (i = 0; i < count; i++) { fprintf(out, "%s", array[get(L)]); // printf("%s", array[get(L)]); moveNext(L); } }
C
/* * This file is part of KONNEKTING Device Library. * * The KONNEKTING Device Library is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // File : SAMD21G18_Reset.h // Author: Alexander Christian <info(at)root1.de> // Description : Code to reset an SAMD21G18 microcontroller, inspired by http://forum.arduino.cc/index.php?topic=366836.0 #ifndef SAMD21G18_RESET_H #define SAMD21G18_RESET_H #include <Arduino.h> // keep system alive while wdt is enabled void resetWDT() { // reset the WDT watchdog timer. // this must be called before the WDT resets the system WDT->CLEAR.reg= 0xA5; // reset the WDT while (WDT->STATUS.bit.SYNCBUSY == 1); //Just wait till WDT is free } void systemReset() { // use the WDT watchdog timer to force a system reset. // WDT MUST be running for this to work WDT->CLEAR.reg= 0x00; // system reset via WDT while (WDT->STATUS.bit.SYNCBUSY == 1); //Just wait till WDT is free } /* *initializes WDT period, * valid values: 0x0 to 0xB (0-11) * see 17.18.2 and Table 17-5 in Atmel SAM D21G Datasheet */ void setupWDT( uint8_t period) { // initialize the WDT watchdog timer WDT->CTRL.reg = 0; // disable watchdog while (WDT->STATUS.bit.SYNCBUSY == 1); //Just wait till WDT is free WDT->CONFIG.reg = min(period,11); // see Table 17-5 Timeout Period (valid values 0-11) WDT->CTRL.reg = WDT_CTRL_ENABLE; //enable watchdog while (WDT->STATUS.bit.SYNCBUSY == 1); //Just wait till WDT is free } void disableWDT() { WDT->CTRL.reg = 0; // disable watchdog } #endif // SAMD21G18_RESET_H
C
#include <stdio.h> unsigned int power(unsigned int p, unsigned int k) { if (k == 0) { return 1; } else if (k % 2 == 0) { return power(p * p, k / 2); } else { return p * power(p * p, (k - 1) / 2); } } int main() { printf("%d\n", power(3, 2)); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include "simplehash.h" // 初始化 hashtable table * init_hash_table() { int i; table *t = (table *)malloc(sizeof(table)); if (t == NULL) { printf("init hash table is failed!\n"); return NULL; } t->cap = MAX_ENTRY_NUMS; t->count = 0; for (i = 0; i < MAX_ENTRY_NUMS; i ++) { t->table = (entry *)malloc(MAX_ENTRY_NUMS * sizeof(entry)); if (t->table != NULL) { memset(t->table, 0, MAX_ENTRY_NUMS * sizeof(entry)); } } for (i = 0; i < MAX_ENTRY_NUMS; i ++) { data_table[i] = malloc(MAX_STR_LEN); memset(data_table[i], 0, MAX_STR_LEN); } return t; } // 从 hashtable 查询数据 int find_hash_table(table *t) { } // 向 hashtable 插入数据 int insert_hash_table(table *t, int key, char *value, int len) { int index, pos; if (NULL == t) { return 0; } if (t->count >= MAX_ENTRY_NUMS) { printf("hash table is full!\n"); return 0; } index = hash_key(key); if (t->table[index].key == key) { printf("index: %d, key is exit!, orikey: %d, nowkey: %d\n", index, t->table[index].key, key); return 0; } pos = index; while (t->table[pos].flag == 1) { pos = (++ pos) % MAX_ENTRY_NUMS; } t->table[pos].key = key; memcpy(data_table[pos], value, len); t->table[pos].value = data_table[pos]; t->table[pos].flag = 1; t->count ++; return 1; } // 计算 hash key int hash_key(int key) { return (key % MAX_ENTRY_NUMS); } void print_hash(table *t, int len) { int i; printf("count: %d\n", t->count); for (i = 0; i <= len; i ++) { printf("key: %d, value: %s\n", t->table[i].key, t->table[i].value); } printf("table:\n"); for (i = 0; i <= len; i ++) { printf("value: %s\n", data_table[i]); } } int main(void) { int i; table *t = init_hash_table(); //print_hash(t, 5); char *value[5] = {"ab", "bc", "cd", "de", "ef"}; for (i = 1; i <= 5; i ++) { insert_hash_table(t, i, value[i-1], 2); } print_hash(t, 5); return 0; }
C
/* * File Name: arithcl.c * version: 1.0 * Author: William Collins * Date: 2/14/2012 * Assignment: Assignment 1 * Course: Real Time Programming * Code: CST8244 * Professor: Saif Terai * Due Date: 2/17/2012 * Submission * Type: Email Submission * Destination * Address: [email protected] * Subject Line: CST 8244, F11, Asgn 1 * Description: Reads a file, sending operations to the server to be completed * and returned with results. */ #include <stdio.h> #include <stdlib.h> #include <sys/iofunc.h> #include <sys/dispatch.h> #include "arith.h" //function declarations void *snd_stmt(void*); //globals char ops[] = { '+', '-', '/', '*' }; pthread_mutex_t filemutex; //mutex for the log file FILE *flog; //The log file that the threads will write to /******************************************************************************************** * Function Name main() * Version 1.0 * Author William Collins * Purpose * Inputs command line arguments * Outputs Returns an integer, '0' on successful completion, '1' if an error * occurred. *********************************************************************************************/ int main(int argc, char *argv[]) { pthread_t t_add, t_sub, t_div, t_mult; // a place to hold the thread ID's pthread_attr_t attrib; // scheduling attributes struct sched_param param; // for setting priority int policy; //Get the file ready to write to flog = fopen("arith.log", "w"); if (flog == NULL){ perror("Log File"); exit(EXIT_FAILURE); } pthread_getschedparam( pthread_self(), &policy, &param ); pthread_attr_init (&attrib); pthread_attr_setinheritsched (&attrib, PTHREAD_EXPLICIT_SCHED); pthread_attr_setschedpolicy (&attrib, SCHED_RR); param.sched_priority = 10; // default priority pthread_attr_setschedparam (&attrib, &param); //Get the mutex ready to use pthread_mutex_init(&filemutex, NULL); //My name, for I am the chosen one fprintf(flog, "Student Name: William Collins\n"); //Launch each thread pthread_create(&t_add, &attrib, snd_stmt, &ops[0]); pthread_create(&t_sub, &attrib, snd_stmt, &ops[1]); pthread_create(&t_div, &attrib, snd_stmt, &ops[2]); pthread_create(&t_mult, &attrib, snd_stmt, &ops[3]); //Wait for each thread to finish pthread_join(t_add, NULL); pthread_join(t_sub, NULL); pthread_join(t_div, NULL); pthread_join(t_mult, NULL); printf("All threads have successfully completed!"); //Clean up resources fclose(flog); pthread_mutex_destroy(&filemutex); return EXIT_SUCCESS; } /******************************************************************************************** * Function Name snd_stmt() * Version 1.0 * Author William Collins * Purpose Sends arithmetic statements to the server * Inputs The operation to be performed on the data * Outputs NULL *********************************************************************************************/ void *snd_stmt(void *op){ int coid; //connection id int status; //return status arith stmt; //arithmetic statement to send //Open the data file for reading FILE *data = fopen("arith_data.txt", "r"); if (data == NULL){ perror("Data File"); exit(EXIT_FAILURE); } //Connect to the server coid = name_open(SERVER_NAME, 0); //Determine if the connection was successful if(-1 == coid) { perror("ConnectAttach"); exit(EXIT_FAILURE); } int scan; int line = 0; //Read the entire file sending values on each line while (!feof(data)){ scan = fscanf(data, "%lf,%lf", &stmt.operand1, &stmt.operand2); line++; //Only perform the operation if scan returned properly if (scan == 2) { stmt.operator = *(char*)op; //Send the message to server and get the reply status = MsgSend(coid, &stmt, sizeof stmt, &stmt, sizeof stmt); //Check for communication errors if(status == -1) { perror("MsgSend"); exit(EXIT_FAILURE); } //Write to log file when able pthread_mutex_lock(&filemutex); fprintf(flog, "line %d: op1 = %.2lf, op2 = %.2lf, op = '%c', result = %.3lf\n", line, stmt.operand1, stmt.operand2, stmt.operator,stmt.result ); pthread_mutex_unlock(&filemutex); } } fclose(data); name_close(coid); return NULL; } //eof: arithcl.c
C
/* ** EPITECH PROJECT, 2018 ** 42sh ** File description: ** Functions to tokenize the cut command */ #include "list.h" #include "lexer.h" #include "tools.h" #include "str_manip.h" /* Always put the doubly separator at the top */ static const token_type_list_t TYPES[] = { {"||", OR}, {">>", D_SUP}, {"<<", D_INF}, {"&&", AND}, {"|", PIPE}, {">", SUP}, {"<", INF}, {";", SEMI_COLON}, {"", COMMAND} }; static enum tnode_type get_token_type(char *str) { int it = 0; while (it < (int)ARRAY_SIZE(TYPES)) { if (!(strncmp(str, TYPES[it].str, strlen(TYPES[it].str)))) { return (TYPES[it].type); } ++it; } return (COMMAND); } static token_t *create_token(char **value, enum tnode_type type) { token_t *token = malloc(sizeof(*token)); if (!(token)) { return (NULL); } token->value = value; token->type = type; return (token); } static int process(llist_t *tokens, enum tnode_type type, char **value) { token_t *token = create_token(NULL, type); if (!(token)) { return (false); } if (type == COMMAND && value) { token->value = value; if (!(list_push_tail(token, tokens))) { free(token); return (false); } return (true); } else if (type == COMMAND && !(value)) { free(token); return (true); } return (list_push_tail(token, tokens)); } static int check_process(llist_t *tokens, enum tnode_type type, char **value) { if (!(process(tokens, COMMAND, value))) { return (false); } if (!(process(tokens, type, NULL))) { return (false); } return (true); } llist_t *tokenize_command(char **command) { llist_t *tokens = list_init(&destroy_token); enum tnode_type type; char **value = NULL; while (command && *command) { type = get_token_type(*(command)); if (type == COMMAND) { value = add_line(value, *(command)); ++command; continue; } else if (!(check_process(tokens, type, value))) { list_destroy(tokens); return (NULL); } value = NULL; ++command; free(*(command - 1)); } return ((process(tokens, COMMAND, value) ? tokens : NULL)); }
C
#ifndef __HIDRANTE_H #define __HIDRANTE_H typedef void* Hidrante; /* Cria um hidrante Pré: Atributos do hidrante (id, x e y) Pós: Retorna o endereço do hidrante */ Hidrante criaHidrante(char* id, float x, float y); //Setters /* Define algum atributo do hidrante Pré: Atributo do hidrante referente deseja definir Pós: nenhum */ void hidranteSetId(Hidrante hidrante, char* id); void hidranteSetX(Hidrante hidrante, float x); void hidranteSetY(Hidrante hidrante, float y); //Getters /*Obtém algum atributo do hidrante Pre: Hidrante Pós: Retorna o atributo em questão */ char* hidranteGetId(Hidrante hidrante); float hidranteGetX(Hidrante hidrante); float hidranteGetY(Hidrante hidrante); #endif
C
#include<stdio.h> #defline INT_SIZE sizeof(int)*8 int main() { int num,zero=0,one=0; intn,m,a[20][20],k,i,j,temp; prinf("size of matrix\n"); scanf("%d%d",&m,&n); printf("enter the elements of matrix\n"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { scanf("%d",&a[i][j]); if (a[i][j]==0) { zero ++; } else { one ++; } } } printf("the number of zero's are:%d\n",zero); printf("the number of one's are:%d\n",one); }
C
/* ** EPITECH PROJECT, 2021 ** B-CPE-110-RUN-1-1-antman-alexis.picard ** File description: ** my_memset */ #include "my.h" #include <stdio.h> char *my_memset(void *s, char data, size_t n) { char *s_ptr = (char *)s; for (int i = 0; i < n; i++) s_ptr[i] = data; return s; }
C
/** * Driver for LED Panel - 8 LEDs * Model: KingBright DC-10EWA * * @author Tyler Thompson * @date 3/26/2018 * @note LED panel has 10 LEDs, but this driver only uses 8 */ /* Includes ------------------------------------------------------------------*/ #include "LED_Panel_X8.h" /** * @brief Initialize the LEDS * @param None * @retval None */ void led_init(void) { GPIO_InitTypeDef GPIO_InitStructure; /* GPIO clock enable */ RCC_AHB1PeriphClockCmd(LED_GPIO_CLK, ENABLE); /* GPIO Configuration */ GPIO_InitStructure.GPIO_Pin = LED_GPIO_PINS; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP ; GPIO_Init(LED_GPIO_PORT, &GPIO_InitStructure); led_set_all(0xff); // initalize all leds off delay_init(); // initialize delays for blink } /** * @brief Set the state of an LED * @param led_number - the number of the LED to work with * @param state - the state to put the LED in * @retval None */ void led_set_state(uint8_t led_number, uint8_t state) { uint16_t port_number = LED_GPIO_PIN0; switch(led_number) { case 0 : port_number = LED_GPIO_PIN0; break; case 1 : port_number = LED_GPIO_PIN1; break; case 2 : port_number = LED_GPIO_PIN2; break; case 3 : port_number = LED_GPIO_PIN3; break; case 4 : port_number = LED_GPIO_PIN4; break; case 5 : port_number = LED_GPIO_PIN5; break; case 6 : port_number = LED_GPIO_PIN6; break; case 7 : port_number = LED_GPIO_PIN7; break; default: port_number = LED_GPIO_PIN0; } if ( state == 0 ) { GPIO_SetBits(LED_GPIO_PORT, port_number); } else { GPIO_ResetBits(LED_GPIO_PORT, port_number); } } /** * @brief Set the state of all LEDs * @param states - The states of a LEDs to set * @retval None */ void led_set_all(uint16_t states) { LED_GPIO_PORT->ODR = (states << LED_GPIO_ALIGN); } /** * @brief Blink and LED a specified number of times with a specified delay * @param led_number - Which LED to work with * @param times - Number of times to blink * @param delay - number of milliseconds to delay between blinks * @retval None */ void led_blink(uint8_t led_number, uint32_t times, uint32_t delay_time) { for(uint8_t i = 0; i < times; i++) { led_set_state(led_number, 1); delay(delay_time / 2); led_set_state(led_number, 0); delay(delay_time / 2); } }
C
/********Software Analysis - FY2013*************/ /* * File Name: data_overflow.c * Defect Classification * --------------------- * Defect Type: Numerical defects * Defect Sub-type: Data overflow * Description: Defect Code to identify defects in data overflow in static declaration */ static int sink; #include "HeaderFile.h" int rand (void); /* * Types of defects: overflow * Complexity: Overflow in char + 1 Constant */ void data_overflow_001 () { char max = 0x7f; char ret; ret = max + 1;/*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ sink = ret; } /* * Types of defects: overflow * Complexity: Overflow in short + 1 Constant */ void data_overflow_002 () { short max = 0x7fff; short ret; ret = max + 1;/*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ sink = ret; } /* * Types of defects: overflow * Complexity: Overflow in int + 1 Constant */ void data_overflow_003 () { int max = 0x7fffffff; int ret; ret = max + 1;/*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ sink = ret; } /* * Types of defects: overflow * Complexity: Overflow in long + 1 Constant */ void data_overflow_004 () { long max = 0x7fffffffffffffff; long ret; ret = max + 1;/*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ sink = ret; } /* * Types of defects: overflow * Complexity: Overflow in unsigned char + 1 Constant */ void data_overflow_005 () { unsigned char max = 0xff; unsigned char ret; ret = max + 1;/*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ sink = ret; } /* * Types of defects: overflow * Complexity: Overflow in unsigned short + 1 Constant */ void data_overflow_006 () { unsigned short max = 0xffff; unsigned short ret; ret = max + 1;/*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ sink = ret; } /* * Types of defects: overflow * Complexity: Overflow in unsigned int + 1 Constant */ void data_overflow_007 () { unsigned int max = 0xffffffff; unsigned int ret; ret = max + 1;/*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ sink = ret; } /* * Types of defects: overflow * Complexity: Overflow in unsigned long + 1 Constant */ void data_overflow_008 () { unsigned long max = 0xffffffffffffffff; unsigned long ret; ret = max + 1;/*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ sink = ret; } /* * Types of defects: overflow * Complexity: overflow in constant (signed) +1 bit field */ typedef struct { signed int max : 5; signed int ret : 5; } data_overflow_009_s_001; void data_overflow_009 () { data_overflow_009_s_001 s; s.max = 0x0f; s.ret = s.max + 1;/*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ } /* * Types of defects: overflow * Complexity: overflow in constant (unsigned) +1 bit field */ typedef struct { unsigned int max : 5; unsigned int ret : 5; } data_overflow_010_s_001; void data_overflow_010 () { data_overflow_010_s_001 s; s.max = 0x1f; s.ret = s.max + 1;/*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ } /* * Types of defects: overflow * Complexity: int Increment ++ operator */ void data_overflow_011 () { int max = 0x7fffffff; int ret; max ++; ret = max;/*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ sink = ret; } /* * Types of defects: overflow * Complexity: int Overflow + 128 Constant */ void data_overflow_012 () { int max = 0x7fffff80; int ret; ret = max + 128;/*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ sink = ret; } /* * Types of defects: overflow * Complexity: int That overflow in multiplication Constant */ void data_overflow_013 () { int max = 0x40000000; int ret; ret = max * 2;/*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ sink = ret; } /* * Types of defects: overflow * Complexity: int Overflow at + 1 Variable */ void data_overflow_014 () { int max = 0x7fffffff; int d = 1; int ret; ret = max + d;/*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ sink = ret; } /* * Types of defects: overflow * Complexity: int Overflow at Value of random variable + 1 */ void data_overflow_015 () { int max = 0x7fffffff; int d; int ret; d = rand(); ret = max + d; /*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ sink = ret; } /* * Types of defects: overflow * Complexity: int Overflow at Linear equation */ void data_overflow_016 () { int max = 429496729; int ret; ret = (5 * max) + 3; /*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ sink = ret; } /* * Types of defects: overflow * Complexity: int Overflow at Nonlinear equation */ void data_overflow_017 () { int max = 46340; int ret; ret = (max * max) + 88048; /*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ sink = ret; } /* * Types of defects: overflow * Complexity: int Overflow at The return value of the function */ int data_overflow_018_func_001 () { return 1; } void data_overflow_018 () { int max = 0x7fffffff; int ret; ret = max + data_overflow_018_func_001(); /*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ sink = ret; } /* * Types of defects: overflow * Complexity: int Overflow at Function arguments */ void data_overflow_019_func_001 (int d) { int max = 0x7fffffff; int ret; ret = max + d; /*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ sink = ret; } void data_overflow_019 () { data_overflow_019_func_001(1); } /* * Types of defects: overflow * Complexity: int Overflow at An array of element values */ void data_overflow_020 () { int max = 0x7fffffff; int dlist[4] = {0, 1, -2, -1}; int ret; ret = max + dlist[1]; /*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ sink = ret; } /* * Types of defects: overflow * Complexity: int Overflow at Alias for 1 weight */ void data_overflow_021 () { int max = 0x7fffffff; int d = 1; int d1; int ret; d1 = d; ret = max + d1; /*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ sink = ret; } /* * Types of defects: overflow * Complexity: int Overflow at Also known as double */ void data_overflow_022 () { int max = 0x7fffffff; int d = 1; int d1; int d2; int ret; d1 = d; d2 = d1; ret = max + d2; /*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ sink = ret; } /* * Types of defects: overflow * Complexity: the operands is a constant */ void data_overflow_023 () { int ret; ret = 0x7fffffff + 1; /*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ sink = ret; } /* * Types of defects: overflow * Complexity: floating point overflow (double) */ void data_overflow_024 () { float ret; /* 0 11111110 11111111111111111111111 */ float max = 3.40282347e+38F; /* 0 11100111 00000000000000000000000 */ ret = max + 2.02824096e+31F; /*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ sink = ret; } /* * Types of defects: overflow * Complexity: floating point overflow (double) */ void data_overflow_025 () { double ret; /* 0 11111111110 1111111111111111111111111111111111111111111111111111 */ double max = 1.7976931348623157e+308; /* 0 11111001010 0000000000000000000000000000000000000000000000000000 */ ret = max + 1.9958403095347198e+292; /*Tool should detect this line as error*/ /*ERROR:Data Overflow*/ sink = ret; } /* * */ extern volatile int vflag; void data_overflow_main () { if (vflag ==1 || vflag ==888) { data_overflow_001(); } if (vflag ==2 || vflag ==888) { data_overflow_002(); } if (vflag ==3 || vflag ==888) { data_overflow_003(); } if (vflag ==4 || vflag ==888) { data_overflow_004(); } if (vflag ==5 || vflag ==888) { data_overflow_005(); } if (vflag ==6 || vflag ==888) { data_overflow_006(); } if (vflag ==7 || vflag ==888) { data_overflow_007(); } if (vflag ==8 || vflag ==888) { data_overflow_008(); } if (vflag ==9 || vflag ==888) { data_overflow_009(); } if (vflag ==10 || vflag ==888) { data_overflow_010(); } if (vflag ==11 || vflag ==888) { data_overflow_011(); } if (vflag ==12 || vflag ==888) { data_overflow_012(); } if (vflag ==13 || vflag ==888) { data_overflow_013(); } if (vflag ==14 || vflag ==888) { data_overflow_014(); } if (vflag ==15 || vflag ==888) { data_overflow_015(); } if (vflag ==16 || vflag ==888) { data_overflow_016(); } if (vflag ==17 || vflag ==888) { data_overflow_017(); } if (vflag ==18 || vflag ==888) { data_overflow_018(); } if (vflag ==19 || vflag ==888) { data_overflow_019(); } if (vflag ==20 || vflag ==888) { data_overflow_020(); } if (vflag ==21 || vflag ==888) { data_overflow_021(); } if (vflag ==22 || vflag ==888) { data_overflow_022(); } if (vflag ==23 || vflag ==888) { data_overflow_023(); } if (vflag ==24 || vflag ==888) { data_overflow_024(); } if (vflag ==25 || vflag ==888) { data_overflow_025(); } }
C
/* Author: daddinuz email: [email protected] Copyright (c) 2018 Davide Di Carlo Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <text.h> #include <stdio.h> int main() { Text text = Text_fromLiteral("\t \tHello world!\t \t"); Text_trim(text); Text_eraseRange(text, sizeof("Hello") - 1, Text_length(text) - 1); text = Text_quote(&text); printf("Text(content='%s', length=%zu, capacity=%zu)", text, Text_length(text), Text_capacity(text)); Text_delete(text); return 0; }
C
#include <stdio.h> int main() { int matriz1[4][7]; int i; int j; //leer matriz for(i = 0;i<4;i++) { for(j=0;j<7;j++) { scanf("%d",&matriz1[i][j]); } } //imprimir matriz for(i = 0;i<4;i++) { for(j=0;j<7;j++) { printf("%3d ",matriz1[i][j]); } printf("\n"); } getchar(); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <ctype.h> #include <time.h> #include "SDL2/SDL.h" #include "SDL2/SDL_image.h" #define lebar_layar 1080 #define tinggi_layar 720 #define phi 3.14159265358979323846 typedef struct { int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z; }tombuol; /*typedef struct { int player, map; }tembak;*/ typedef struct { SDL_Renderer *renderer; SDL_Window *window; int atas, bawah, kiri, kanan, spasi; //tembak tembakan; int tombal[37]; tombuol tombol; }control; typedef struct { int x, y; float sudut; SDL_Texture *texture; } Entity; control app; int i; void initSDL(void) { int rendererFlags, windowFlags; rendererFlags = SDL_RENDERER_ACCELERATED; windowFlags = 0; if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("Couldn't initialize SDL: %s\n", SDL_GetError()); exit(1); } app.window = SDL_CreateWindow("PROYEK PROGLAN CUK!", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, lebar_layar, tinggi_layar, windowFlags); if (!app.window) { printf("Failed to open %d x %d window: %s\n", lebar_layar, tinggi_layar, SDL_GetError()); exit(1); } SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear"); app.renderer = SDL_CreateRenderer(app.window, -1, rendererFlags); if (!app.renderer) { printf("Failed to create renderer: %s\n", SDL_GetError()); exit(1); } IMG_Init(IMG_INIT_PNG | IMG_INIT_JPG); } void cleanup(void){ SDL_DestroyRenderer(app.renderer); SDL_DestroyWindow(app.window); SDL_Quit(); } SDL_Texture *loadTexture(char *filename){ SDL_Texture *texture; SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, "Loading %s", filename); texture = IMG_LoadTexture(app.renderer, filename); return texture; } void blit(SDL_Texture *texture, int x, int y, int sudut){ //SDL Rect isinya -> x buat posisi x, y posisi y, w tinggi gambar, h lebar gambar SDL_Rect dest; dest.x = x; dest.y = y; //query texture buat ambil berapa tinggi dan lebar gambarnya SDL_QueryTexture(texture, NULL, NULL, &dest.w, &dest.h); SDL_RenderCopyEx(app.renderer, texture, NULL, &dest, sudut, NULL, SDL_FLIP_NONE); //SDL_RenderCopy(app.renderer, texture, NULL, &dest); } void dipencet(SDL_KeyboardEvent *pencetan){ if (pencetan->repeat == 0){ //printf("= %d\n", pencetan->keysym.scancode); //a itu adalah 4, dst if (pencetan->keysym.scancode == SDL_SCANCODE_UP){ app.atas = 1; } if (pencetan->keysym.scancode == SDL_SCANCODE_DOWN){ app.bawah = 1; } if (pencetan->keysym.scancode == SDL_SCANCODE_LEFT){ app.kiri = 1; } if (pencetan->keysym.scancode == SDL_SCANCODE_RIGHT){ app.kanan = 1; } if (pencetan->keysym.scancode == SDL_SCANCODE_W){ app.tombol.w = 1; } if (pencetan->keysym.scancode == SDL_SCANCODE_A){ app.tombol.a = 1; } if (pencetan->keysym.scancode == SDL_SCANCODE_S){ app.tombol.s = 1; } if (pencetan->keysym.scancode == SDL_SCANCODE_D){ app.tombol.d = 1; } if (pencetan->keysym.scancode == SDL_SCANCODE_SPACE){ app.spasi = 1; app.tombal[36]=1; } for(i=4; i<40; i++){ if (pencetan->keysym.scancode == i){ app.tombal[pencetan->keysym.scancode-4] = 1; } } /*for(i=0; i<36; i++){ printf("tombal %d\n", app.tombal[i]); }*/ } } void dilepas(SDL_KeyboardEvent *pencetan){ if (pencetan->repeat == 0){ if (pencetan->keysym.scancode == SDL_SCANCODE_UP){ app.atas = 0; } if (pencetan->keysym.scancode == SDL_SCANCODE_DOWN){ app.bawah = 0; } if (pencetan->keysym.scancode == SDL_SCANCODE_LEFT){ app.kiri = 0; } if (pencetan->keysym.scancode == SDL_SCANCODE_RIGHT){ app.kanan = 0; } if (pencetan->keysym.scancode == SDL_SCANCODE_W){ app.tombol.w = 0; } if (pencetan->keysym.scancode == SDL_SCANCODE_A){ app.tombol.a = 0; } if (pencetan->keysym.scancode == SDL_SCANCODE_S){ app.tombol.s = 0; } if (pencetan->keysym.scancode == SDL_SCANCODE_D){ app.tombol.d = 0; } if (pencetan->keysym.scancode == SDL_SCANCODE_SPACE){ app.spasi = 0; app.tombal[36]=0; } for(i=4; i<40; i++){ if (pencetan->keysym.scancode == i){ app.tombal[pencetan->keysym.scancode-4] = 0; } } } } int main(int argc, char *argv[]){ //ayok bantu mama buat jadi lebih pinter dengan cara meminjam buku, yuk pinjam buku sebanyak2nya untuk mendapat reward yang besar Entity player, map, mulai_tulisan, mulai_gambar, tulisan_pencetlanjut; memset(&app, 0, sizeof(control)); memset(&player, 0, sizeof(Entity)); initSDL(); map.texture = loadTexture("img/mario.png"); map.x = 0; map.y = tinggi_layar-720; map.sudut = 0; player.texture = loadTexture("img/emak_main.png"); player.x = 10; player.y = tinggi_layar-97; player.sudut = 0; mulai_tulisan.texture = loadTexture("img/super_makmak_kecil.png"); mulai_tulisan.x = 35; mulai_tulisan.y = tinggi_layar-565; mulai_tulisan.sudut = 0; mulai_gambar.texture = loadTexture("img/emaaakkk_kecil.png"); mulai_gambar.x = -235; mulai_gambar.y = tinggi_layar-325; mulai_gambar.sudut = 0; /*tulisan_pencetlanjut.x = 100; tulisan_pencetlanjut.y = 300; mulai_gambar.texture = loadTexture("img/continue.png");*/ atexit(cleanup); int lompat=0, x=0; //int awal=1, game=0, game1=0; int awal=1, game=0, game1=0; int r=170, g=134, b=95, a=255; char teks[100]={}; int tek=0, flag=-1, count_flag=0; //teks = (char*)malloc(0*sizeof(char)); while (1){ //prepareScene(); //nerima input SDL_Event pencetan; SDL_SetRenderDrawColor(app.renderer, r, g, b, a); SDL_RenderClear(app.renderer); if(awal){ blit(mulai_tulisan.texture, mulai_tulisan.x, mulai_tulisan.y, mulai_tulisan.sudut); blit(mulai_gambar.texture, mulai_gambar.x, mulai_gambar.y, mulai_gambar.sudut); if(mulai_gambar.x<100){ mulai_gambar.x+=3; if(mulai_gambar.x%5==0){ mulai_gambar.y--; } mulai_gambar.sudut-=0.3; } else{ while (SDL_PollEvent(&pencetan)){ switch(pencetan.type){ case SDL_KEYDOWN: awal=0; game=1; break; } } } } while (SDL_PollEvent(&pencetan)) { switch (pencetan.type) { case SDL_QUIT: exit(0); break; //case SDL_TEXTINPUT: /* Add new text onto the end of our text */ //strcat(teks, pencetan.text.text); //break; //kalo lagi dipencet case SDL_KEYDOWN: dipencet(&pencetan.key); //printf("player 1 -> x = %d, y = %d.....player 2 -> x = %d, y = %d\n", player.x, player.y, map.x, map.y); break; //kalo lagi gak dipencet case SDL_KEYUP: dilepas(&pencetan.key); break; default: break; } } //main game if(game){ if(app.spasi){ lompat=1; } if(lompat){ int skala = 100, sudut=45; int lama_waktu=25; //dalam satuan x if(x<=lama_waktu){ //printf("woy %f\n", skala*(cos(((2*x*phi)/skala)+phi)+1)/2); player.y = tinggi_layar-97-(skala*(cos((2*x*phi/lama_waktu)+phi)+1)/2); player.sudut = (sudut*cos((2*x*phi/lama_waktu)+(phi/2))/2); x++; } else{ lompat=0; x=0; } } //batas maju player adalah batas karakter maju dan gantian sama layarnya int batas_maju_player = 100; if(app.tombol.a){ if(player.x>10){ player.x-=5; } else{ if(map.x<0){ map.x+=5; } else{ map.x=0; } } } if(app.tombol.d){ if(player.x<batas_maju_player){ player.x+=5; } else{ if(game1){ } else{ if(map.x>1280-3840-batas_maju_player){ map.x-=5; } else{ map.x=1280-3840-batas_maju_player; if(player.x<lebar_layar-48){ player.x+=5; } else{ player.x=lebar_layar-48; } } } } } //scene 2 char tambol[37]={"abcdefghijklmnopqrstuvwxyz1234567890 "}; if(game1){ SDL_DestroyTexture(map.texture); SDL_DestroyTexture(player.texture); if(flag==-1){ for(i=0; i<37; i++){ if(app.tombal[i]){ teks[tek]=tambol[i]; tek++; a-=15; //teks = (char*)realloc(teks, tek*sizeof(char)); flag=i; //strcat(teks, tambol[i]); printf("%d %s\n", a, teks); } } } else{ if(app.tombal[flag]==0){ flag=-1; } /*if(count_flag<5){ count_flag++; } else{ count_flag=0; flag=1; }*/ } //printf("%s", teks); //strcat(teks, ); //SDL_StartTextInput(); //r=0; g=0; b=0; a=0; } //scene 1 else{ if(app.tombol.w){ if(map.x==1280-3840-batas_maju_player){ if(player.x>=890&&player.x<=1000){ game1=1; } } } blit(map.texture, map.x, map.y, map.sudut); blit(player.texture, player.x, player.y, player.sudut); r=170; g=255; b=100; a=255; } } SDL_RenderPresent(app.renderer); SDL_Delay(16); } return 0; }
C
/* * trans.c - Matrix transpose B = A^T * * Each transpose function must have a prototype of the form: * void trans(int M, int N, int A[N][M], int B[M][N]); * * A transpose function is evaluated by counting the number of misses * on a 1KB direct mapped cache with a block size of 32 bytes. */ #include <stdio.h> #include "cachelab.h" int is_transpose(int M, int N, int A[N][M], int B[M][N]); /* * transpose_submit - This is the solution transpose function that you * will be graded on for Part B of the assignment. Do not change * the description string "Transpose submission", as the driver * searches for that string to identify the transpose function to * be graded. */ char transpose_submit_desc[] = "Transpose submission"; void transpose_submit(int M, int N, int A[N][M], int B[M][N]) { // cache: 8 int per block // read and write 8 int per row in A if (M == 32){ int a1, a2, a3, a4, a5, a6, a7, a8; int i, j; for (i = 0; i < N; i+=8) { for (j = 0; j < M; j++) { a1 = A[j][i]; a2 = A[j][i+1]; a3 = A[j][i+2]; a4 = A[j][i+3]; a5 = A[j][i+4]; a6 = A[j][i+5]; a7 = A[j][i+6]; a8 = A[j][i+7]; B[i ][j] = a1; B[i+1][j] = a2; B[i+2][j] = a3; B[i+3][j] = a4; B[i+4][j] = a5; B[i+5][j] = a6; B[i+6][j] = a7; B[i+7][j] = a8; } } return; } else if (M == 64){ int a1, a2, a3, a4, a5, a6, a7, a8; int i, j, k; for(i=0;i<64;i+=8){ for(j=0;j<64;j+=8){ for(k=j;k<j+4;k++){ a1=A[k][i]; a2=A[k][i+1]; a3=A[k][i+2]; a4=A[k][i+3]; a5=A[k][i+4]; a6=A[k][i+5]; a7=A[k][i+6]; a8=A[k][i+7]; B[i][k]=a1; B[i+1][k]=a2; B[i+2][k]=a3; B[i+3][k]=a4; B[i][k+4]=a5; B[i+1][k+4]=a6; B[i+2][k+4]=a7; B[i+3][k+4]=a8; } for(k=i;k<i+4;k++){ a1=B[k][j+4]; a2=B[k][j+5]; a3=B[k][j+6]; a4=B[k][j+7]; a5=A[j+4][k]; a6=A[j+5][k]; a7=A[j+6][k]; a8=A[j+7][k]; B[k][j+4]=a5; B[k][j+5]=a6; B[k][j+6]=a7; B[k][j+7]=a8; B[k+4][j]=a1; B[k+4][j+1]=a2; B[k+4][j+2]=a3; B[k+4][j+3]=a4; } for(k=i+4;k<i+8;k++){ a1=A[j+4][k]; a2=A[j+5][k]; a3=A[j+6][k]; a4=A[j+7][k]; B[k][j+4]=a1; B[k][j+5]=a2; B[k][j+6]=a3; B[k][j+7]=a4; } } } return; } int i, j, m, n; int block = 16; for (i = 0; i < N; i+=block) { for (j = 0; j < M; j+=block) { for (m = i; m < i+block && m < N; m++) { for (n = j;n< j+block && n < M; n++) { B[n][m] = A[m][n]; } } } } } /* * You can define additional transpose functions below. We've defined * a simple one below to help you get started. */ /* * trans - A simple baseline transpose function, not optimized for the cache. */ char trans_desc[] = "Simple row-wise scan transpose"; void trans(int M, int N, int A[N][M], int B[M][N]) { int i, j, tmp; for (i = 0; i < N; i++) { for (j = 0; j < M; j++) { tmp = A[i][j]; B[j][i] = tmp; } } } /* * registerFunctions - This function registers your transpose * functions with the driver. At runtime, the driver will * evaluate each of the registered functions and summarize their * performance. This is a handy way to experiment with different * transpose strategies. */ void registerFunctions() { /* Register your solution function */ registerTransFunction(transpose_submit, transpose_submit_desc); /* Register any additional transpose functions */ registerTransFunction(trans, trans_desc); } /* * is_transpose - This helper function checks if B is the transpose of * A. You can check the correctness of your transpose by calling * it before returning from the transpose function. */ int is_transpose(int M, int N, int A[N][M], int B[M][N]) { int i, j; for (i = 0; i < N; i++) { for (j = 0; j < M; ++j) { if (A[i][j] != B[j][i]) { return 0; } } } return 1; }
C
/* *PPM.C *A 16 Bit PWM module is used to gennerate the PPM train *The PWM actually gennerates an inverted CPPM __|_|_|_|_|_|_|_|_|___|_|_|_|_|_|_|_|_|___|_ *this has the advantage that the pulse width can stay constant, only the periode has to be changed *on everey compare match interrupt the periode value for the next chanel is loaded *the last chanal value has an extra large value and is used to gennerate the sync gap *the fist ppm train after power up is wrong so dynamic reconfiguration is used to disconect the PWM from the output PIN *this mecanism is also used the start / stop the PPM output loading a 1 to ppm_Run will output one pulse train *between the last pulse and the sync pulse an IO interrupt on rising edge is enabled , in the interrupt rotine *of this ppm_Run is cleared and the PWM is disdonected from the PIN, the PWM will stay in state PPM_PULSE_COUNT+1 * and wait that the main program will set ppm_Run again, that will start the next cycle */ #include <m8c.h> // part specific constants and macros #include "PSoCAPI.h" // PSoC API definitions for all User Modules #include "ppm.h" volatile WORD ppm_Data[PPM_PULSE_COUNT]; //the pulse len valune for the chanales volatile BYTE ppm_Nr=0;//the chanal counter volatile BOOL ppm_Run=0;//start one pulse train //initialize PPM output void ppm_Init(void ) { int n; //Init PPM_DATA array for (n=0;n<PPM_PULSE_COUNT;n++) { //set to center ppm_Data[n]=PPM_OUT_CENTER_LEN; } //enable glogal interrupts M8C_EnableGInt; //enable compare match interrupt of the PWM PWM16_1_EnableInt(); //enable GPOI Interrupts //we need that to trigger on falling egde of "compare true" M8C_EnableIntMask(INT_MSK0, INT_MSK0_GPIO); //pulse widht is actually the small gap between the PPM pulses PWM16_1_WritePulseWidth(PPM_OUT_PULSE_GAP_LEN_US); //disable IRQ on Port Pin, we do nt need iot jet Port_0_4_IntEn_ADDR&=~(1<<4); //disconnect the PIN from the PWM and set the pin to High RDI0LT0|=0x3; //init pulse counter, will loop thru the canales ppm_Nr=0; //set a initial pulse len, just to have somthing in ther will be change in the interrupt service PWM16_1_WritePeriod(PPM_OUT_SYNC_PULSE_LEN); //start the PWM Module PWM16_1_Start(); }//END OFF ppm_Init /*inerrupt service routine for the PWM module *will be called on compare match *-load pulse len of the next PPM pulse *- increase pulse counter *-after the last pulse (before the sync pulse is outputed enable GPOI interrupt on rising egde *-when done wait for ppm_Run to go on again, stay in a small loop for that time */ #pragma interrupt_handler PWM16_1_CMP_ISR void PWM16_1_CMP_ISR(void ) { //if we are done wait for start (ppm_Run==1) if (ppm_Nr==PPM_PULSE_COUNT+1) { if (ppm_Run) { //continue with next Block of pulses RDI0LT0&=~0x3; //reconect i/O PIN to PWM ppm_Nr=1;//reset counter PWM16_1_WritePeriod(ppm_Data[0]);//load pulse len of first chanal } else//continue waiting PWM16_1_WritePeriod(PPM_OUT_PULSE_GAP_LEN_US+10); //continue waiting } //load pulse len of next chanal else { //check if that is the last chanal is done if(ppm_Nr==PPM_PULSE_COUNT) { ppm_Nr++; PWM16_1_WritePeriod(PPM_OUT_SYNC_PULSE_LEN); Port_0_4_IntEn_ADDR|=(1<<4); //enable pin irq } else { PWM16_1_WritePeriod(ppm_Data[ppm_Nr++]); } } }//END OFF PWM16_1_CMP_ISR //called on a GPIO interrupt #pragma interrupt_handler PPM_GPIO_ISR void PPM_GPIO_ISR(void ) { if (PRT0DR&(1<<4)) //Check if PPM output pin went high { //we are done ppm_Run=0; //signal that we are done Port_0_4_IntEn_ADDR&=~(1<<4); //disable pin irq RDI0LT0|=0x3; //disconect IO pin from PWM and set to High } }
C
#include <stdio.h> #include <stdlib.h> int flag_a = 0; int flag_b = 0; int flag_c = 0; /* * We use a fully instantiated manifest. * * The Config Prime engine should remove everthing except the only * possible execution. * * EXPECTED: all strings "You should NOT see this message" are removed * in the bitcode. */ void get_opt(int argc, char **argv) { // assigning a literal value 1 to each flag unsigned iter; for(iter = 1; iter < argc; iter++){ if(argv[iter][0] == '-' && argv[iter][1]){ switch(argv[iter][1]){ case 'a': flag_a = 1; break; case 'b': flag_b = 1; break; case 'c': flag_c = 1; break; default: break; } } } } void use_flags() { if (flag_b) { printf("You should see this message\n"); } if (flag_a) { printf("You should NOT see this message\n"); } if (flag_c) { printf("You should NOT see this message\n"); } } int main (int argc, char **argv){ get_opt(argc, argv); use_flags(); return 0; }
C
#include <stdio.h> int main(void) { int myIntArray [10] = {100, 100, 100, 100, 100, 100, 100, 100, 100, 100}; float myFloatArray [5] = {1, 2, 3, 4, 5}; char myCharArray [256] = {0}; printf("%d \n", myIntArray[2]); printf("%f \n", myFloatArray[2]); printf("%c \n\n", myCharArray[2]); myIntArray [0] = (0 + 1) * 10; myIntArray [1] = (1 + 1) * 10; myIntArray [2] = (2 + 1) * 10; myIntArray [3] = (3 + 1) * 10; myIntArray [4] = (4 + 1) * 10; myIntArray [5] = (5 + 1) * 10; myIntArray [6] = (6 + 1) * 10; myIntArray [7] = (7 + 1) * 10; myIntArray [8] = (8 + 1) * 10; myIntArray [9] = (9 + 1) * 10; myFloatArray [0] = myFloatArray [0] * 1.1; myFloatArray [1] = myFloatArray [1] * 1.1; myFloatArray [2] = myFloatArray [2] * 1.1; myFloatArray [3] = myFloatArray [3] * 1.1; myFloatArray [4] = myFloatArray [4] * 1.1; myCharArray [0] = 'S'; myCharArray [1] = 'M'; myCharArray [2] = 'I'; myCharArray [3] = 'T'; myCharArray [4] = 'H'; printf("%d \n", myIntArray[2]); printf("%f \n", myFloatArray[2]); printf("%c \n\n", myCharArray[2]); printf("my last name is %s \n", myCharArray); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* range_comb.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kmurray <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/10/07 15:21:01 by kmurray #+# #+# */ /* Updated: 2017/10/09 17:29:55 by kmurray ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include <unistd.h> #include <string.h> int g = 0; typedef struct s_tree { int *arr; int size; struct s_tree *left; struct s_tree *right; } t_tree; void insert_node(t_tree **root, t_tree *new) { if (!*root) *root = new; else { int i = -1; int value = 0; while (++i <= new->size && !value) value = (*root)->arr[i] - new->arr[i]; insert_node((value > 0) ? &(*root)->left : &(*root)->right, new); } } void destroy_tree(t_tree *root) { if (root) { destroy_tree(root->left); destroy_tree(root->right); free(root); } } void add_to_array(t_tree *root, int **rc) { if (root) { add_to_array(root->left, rc); rc[g++] = root->arr; add_to_array(root->right, rc); } } void swap(int *a, int l, int i) { int tmp = a[l]; a[l] = a[i]; a[i] = tmp; } void permute(int *a, int l, int r, t_tree **root) { int i = l - 1; t_tree *new; if (l == r) { i = -1; new = (t_tree *)malloc(sizeof(t_tree)); new->arr = (int *)malloc(sizeof(int) * (r + 1)); new->arr = (int *)memcpy(new->arr, a, sizeof(int) * (r + 1)); new->size = r; new->left = NULL; new->right = NULL; insert_node(root, new); } else { while (++i <= r) { swap(a, l, i); permute(a, l + 1, r, root); swap(a, l, i); } } } int factorial(int n) { if (n > 1) n *= factorial(n - 1); return (n); } int **range_comb(int n) { int err = 0; int f = factorial(n); t_tree *root = NULL; if (0 >= n || n >= 13) { err = 1; f = 1; } int **rc = (int **)malloc(sizeof(int *) * (f + 1)); rc[f] = NULL; if (err) { rc[0] = (int *)malloc(sizeof(int)); rc[0][0] = -1; return (rc); } int i = -1; int dummy[n - 1]; i = -1; while (++i < n) dummy[i] = i; permute(dummy, 0, n - 1, &root); add_to_array(root, rc); destroy_tree(root); return (rc); }
C
#include <idt.h> #include <isr.h> #include <irq.h> #include <tty.h> #include <kb.h> #include <timer.h> #include <memory.h> #include <stdint.h> #include <stddef.h> #include <string.h> #include <stdio.h> #include <paging.h> #include <malloc.h> /* This is only a test entry point */ void dummy_entry(){ } static char * get_name(void); void kmain() { tty_init(); // initate the terminal interface printf("TTY ... [done]\n"); idt_install(); printf("IDT ... [done]\n"); isr_install(); printf("ISR ... [done]\n"); irq_install(); printf("IRQ .. [done]\n"); keyboard_install(); printf("Keyboard ... [done]\n"); paging_init(); printf("Paging ... [done]\n"); malloc_init(); printf("Heap ... [done]\n"); __asm__ __volatile__ ("sti"); printf("Core functionality installed\n"); printf("Welcome to ChaosOS\n"); char *msg = get_name(); printf("This is written by: %s\n", msg); } static char * get_name(void) { char *msg = malloc(8); msg[0] = 'C'; msg[1] = 'h'; msg[2] = 'a'; msg[3] = 'r'; msg[4] = 'l'; msg[5] = 'i'; msg[6] = 'e'; msg[7] = '\0'; return msg; }
C
/****************************************************************************** * Unit Test 2 * Checks to see if player has 5 cards at start * Primary tested function: numHandCards() ******************************************************************************/ #include <stdio.h> #include "assert.h" #include "../dominion.h" int main(int argc, char *argv[]){ // Game init variables int numPlayers = 2; int kingdomCards[] = {smithy,adventurer,gardens,embargo,cutpurse,mine, ambassador,outpost,baron,tribute}; int seed = 1234; struct gameState g1; struct gameState *game1 = &g1; // Init unshuffled and unshuffled game initializeGame(numPlayers, kingdomCards, seed, game1); // Check player hand at start int result = numHandCards(game1); myAssertTrue((result == 5), "Player has 5 cards at start."); checkAsserts(); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* parsing_memory.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: thflahau <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/05/23 12:20:22 by thflahau #+# #+# */ /* Updated: 2019/05/26 15:09:13 by thflahau ### ########.fr */ /* */ /* ************************************************************************** */ #include <lem_in_list.h> #include <lem_in_parsing.h> #include <lem_in_compiler.h> #include <stdlib.h> #include "../libft/libft.h" /* ** Cast the t_listhead pointer of the t_input structure out to the ** containing structure. Works just like the `container_of` macro from ** the Linux kernel, file `include/linux/kernel.h` L.968 */ inline t_input *ft_input_entry(t_listhead *ptr) { return ((t_input *)((char *)ptr - __builtin_offsetof(t_input, list))); } inline t_input *ft_make_node(char *buffer) { t_input *node; if (UNLIKELY((node = (t_input *)malloc(sizeof(t_input))) == NULL)) return (NULL); node->buffer = buffer; return (node); } inline uint8_t ft_parsing_panic(t_listhead *head, char const *str) { t_input *ptr; t_listhead *node; t_listhead *next; if (LIKELY(str != NULL)) free((void *)str); node = head->next; next = node->next; while (node != head) { if (LIKELY((ptr = ft_input_entry(node)) != NULL)) { free((void *)ptr->buffer); free((void *)ptr); } node = next; next = node->next; } return (EXIT_FAILURE); } inline void ft_safe_print_and_free(t_listhead *head) { t_input *ptr; t_listhead *node; t_listhead *next; node = head->next; next = node->next; while (node != head) { if (LIKELY((ptr = ft_input_entry(node)) != NULL)) { ft_putstr_endl_free(ptr->buffer); free((void *)ptr); } node = next; next = node->next; } }
C
#include <stdio.h> #include <string.h> #include <stdio.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/un.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <stdlib.h> struct sockaddr_un *local; static void die(const char *msg) { perror(msg); exit(EXIT_FAILURE); } static int socket_create() { int sd; sd = socket(AF_UNIX, SOCK_STREAM, 0); if (sd < 0) die("cannot create socket"); local->sun_family = AF_UNIX; strcpy(local->sun_path, getenv("HOME")); strcat(local->sun_path, "/victim.sock"); unlink(local->sun_path); if (bind(sd, (struct sockaddr *)local, sizeof(struct sockaddr_un)) != 0) die("bind failed"); if (listen(sd, 5) != 0) die("listen failed"); return sd; } static void socket_destroy(int sd) { close(sd); unlink(local->sun_path); } static void heartbeat_respond(int sd, char *str, int len) { char heartbeat[16], *c, *h; for (c = str, h = heartbeat; *c != '\n'; h++, c++) *h = *c; write(sd, heartbeat, len); } static void do_client(int sd) { int len; char sbuf[512], *str, lbuf[32], *len_s; FILE *fl; fl = fdopen(sd, "rb+"); if (!fl) { perror("opening FILE interface for socket failed"); return; } while (1) { if ((str = fgets(sbuf, sizeof(sbuf), fl)) == NULL) break; if ((len_s = fgets(lbuf, sizeof(lbuf), fl)) == NULL) break; len = atoi(len_s); heartbeat_respond(sd, str, len); } } int main(int argc, const char **argv) { int serv_sd, cli_sd; socklen_t slen; struct sockaddr_un remote; local = mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (local == MAP_FAILED) die("mmap failed"); serv_sd = socket_create(); if (mprotect(local, 4096, PROT_READ) != 0) die("mprotect failed"); while (1) { cli_sd = accept(serv_sd, (struct sockaddr *)&remote, &slen); if (cli_sd < 0) { perror("accepting socket failed"); break; } do_client(cli_sd); close(cli_sd); } socket_destroy(serv_sd); return 0xc35a; /* A gift */ }
C
#include "spi.h" #include "usart_u.h" /** * SPI2 ʼ * **/ void SPI2_Init(void) { GPIO_InitTypeDef GPIO_InitStructure; SPI_InitTypeDef SPI_InitStructure; RCC_APB1PeriphClockCmd( RCC_APB1Periph_SPI2, ENABLE );//SPI2ʱʹ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13 | GPIO_Pin_15; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOB, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(GPIOB, &GPIO_InitStructure); SPI_Cmd(SPI2, DISABLE); SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex; SPI_InitStructure.SPI_Mode = SPI_Mode_Master; SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b; SPI_InitStructure.SPI_CPOL = SPI_CPOL_High; //CPOL =1 SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge; //CPHA = 1 SPI_InitStructure.SPI_NSS = SPI_NSS_Soft; SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_32; //ADISͨʲܳ2M˴36/64 = 0.625 SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; SPI_InitStructure.SPI_CRCPolynomial = 7; SPI_Init(SPI2, &SPI_InitStructure); SPI_Cmd(SPI2, ENABLE); SPI2_ReadWriteByte(0xff); } /** * SPIٶ * ΪƵϵ * * ע⣬burstģʽʱСƵϵΪ64SPIٶȲɳ1M * ֶȡĴǣƵϵɳ32SPIٶȲܳ2M **/ void SPI2_SetSpeed(u8 SPI_BaudRatePrescaler){ assert_param(IS_SPI_BAUDRATE_PRESCALER(SPI_BaudRatePrescaler)); SPI2->CR1&=0XFFC7; SPI2->CR1|=SPI_BaudRatePrescaler; SPI_Cmd(SPI2,ENABLE); } /** * spiд * Ҫдӻֵ * ֵӻдֵʱӻλĴص */ u8 SPI2_ReadWriteByte(u8 TxData){ u8 retry=0; while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET){ retry++; if(retry>200){ uprintf(USART1 , "error while waiting TX Flag\n"); return 0; } } SPI_I2S_SendData(SPI2, TxData); retry=0; while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == RESET){ retry++; if(retry>200){ uprintf(USART1 , "error while waiting RX Flag\n"); return 0; } } return SPI_I2S_ReceiveData(SPI2); }
C
#include <stdio.h> #include "./drivers/inc/LEDs.h" #include "./drivers/inc/slider_switches.h" #include "./drivers/inc/pushbuttons.h" #include "./drivers/inc/HEX_displays.h" int main() { while (1) { int readInteger = read_slider_switches_ASM(); int toHEXDisplays = read_PB_data_ASM() & 0x0000000F; // 0b1111 char readChar = (char)(readInteger & 0x0000000F); int isClear = readInteger & 0x00000200; // 0b1000000000 if (isClear) { HEX_clear_ASM(HEX0 | HEX1 | HEX2 | HEX3 | HEX4 | HEX5); // 0b111111 } else { HEX_flood_ASM(HEX4 | HEX5); HEX_write_ASM(toHEXDisplays, readChar); } write_LEDs_ASM(readInteger); } return 0; }
C
#include "inodes.h" // void locate_inode(int inode_number, int inodes_per_group, int* inode_group, int* inode_offset){ // *inode_group = (inode_number -1)/inodes_per_group; // *inode_offset = (inode_number -1)%inodes_per_group; // } int is_dir(uint16 i_mode){ if(i_mode >= 0x4000 && i_mode < 0x5000) return 1; return 0; } int is_file(uint16 i_mode){ if(i_mode >= 0x8000 && i_mode < 0x9000) return 1; return 0; }
C
/** * File: str.h * Author: AWTK Develop Team * Brief: string * * Copyright (c) 2018 - 2019 Guangzhou ZHIYUAN Electronics Co.,Ltd. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * License file for more details. * */ /** * History: * ================================================================ * 2018-04-30 Li XianJing <[email protected]> adapt from uclib * */ #ifndef TK_STR_H #define TK_STR_H #include "tkc/value.h" #include "tkc/types_def.h" BEGIN_C_DECLS /** * @class str_t * 可变长度的UTF8字符串。 * * 示例: * * ```c * str_t s; * str_init(&s, 0); * * str_append(&s, "abc"); * str_append(&s, "123"); * * str_reset(&s); * ``` * * > 先调str\_init进行初始化,最后调用str\_reset释放内存。 * */ typedef struct _str_t { /** * @property {uint32_t} size * @annotation ["readable"] * 长度。 */ uint32_t size; /** * @property {uint32_t} capacity * @annotation ["readable"] * 容量。 */ uint32_t capacity; /** * @property {char*} str * @annotation ["readable"] * 字符串。 */ char* str; } str_t; /** * @method str_init * 初始化字符串对象。 * @annotation ["constructor"] * @param {str_t*} str str对象。 * @param {uint32_t} capacity 初始容量。 * * @return {str_t*} str对象本身。 */ str_t* str_init(str_t* str, uint32_t capacity); /** * @method str_extend * 扩展字符串到指定的容量。 * @annotation ["constructor"] * @param {str_t*} str str对象。 * @param {uint32_t} capacity 初始容量。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_extend(str_t* str, uint32_t capacity); /** * @method str_eq * 判断两个字符串是否相等。 * @param {str_t*} str str对象。 * @param {char*} text 待比较的字符串。 * * @return {bool_t} 返回是否相等。 */ bool_t str_eq(str_t* str, const char* text); /** * @method str_set * 设置字符串。 * @param {str_t*} str str对象。 * @param {char*} text 要设置的字符串。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_set(str_t* str, const char* text); /** * @method str_clear * 清除字符串内容。 * @param {str_t*} str str对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_clear(str_t* str); /** * @method str_set_with_len * 设置字符串。 * @param {str_t*} str str对象。 * @param {char*} text 要设置的字符串。 * @param {uint32_t} len 字符串长度。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_set_with_len(str_t* str, const char* text, uint32_t len); /** * @method str_append * 追加字符串。 * @param {str_t*} str str对象。 * @param {char*} text 要追加的字符串。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append(str_t* str, const char* text); /** * @method str_append_with_len * 追加字符串。 * @param {str_t*} str str对象。 * @param {char*} text 要追加的字符串。 * @param {uint32_t} len 字符串长度。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append_with_len(str_t* str, const char* text, uint32_t len); /** * @method str_insert * 插入子字符串。 * @param {str_t*} str str对象。 * @param {uint32_t} offset 偏移量。 * @param {char*} text 要插入的字符串。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_insert(str_t* str, uint32_t offset, const char* text); /** * @method str_insert_with_len * 插入子字符串。 * @param {str_t*} str str对象。 * @param {uint32_t} offset 偏移量。 * @param {char*} text 要插入的字符串。 * @param {uint32_t} len 字符串长度。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_insert_with_len(str_t* str, uint32_t offset, const char* text, uint32_t len); /** * @method str_remove * 删除子字符串。 * @param {str_t*} str str对象。 * @param {uint32_t} offset 偏移量。 * @param {uint32_t} len 长度。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_remove(str_t* str, uint32_t offset, uint32_t len); /** * @method str_append_char * 追加一个字符。 * @param {str_t*} str str对象。 * @param {char} c 要追加的字符。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append_char(str_t* str, char c); /** * @method str_append_int * 追加一个整数。 * @param {str_t*} str str对象。 * @param {int32_t} value 要追加的整数。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_append_int(str_t* str, int32_t value); /** * @method str_pop * 删除最后一个字符。 * @param {str_t*} str str对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_pop(str_t* str); /** * @method str_unescape * 对字符串进行反转义。如:把"\n"转换成'\n'。 * @param {str_t*} str str对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_unescape(str_t* str); /** * @method str_decode_xml_entity * 对XML基本的entity进行解码,目前仅支持&lt;&gt;&quota;&amp;。 * @param {str_t*} str str对象。 * @param {char*} text 要解码的XML文本。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_decode_xml_entity(str_t* str, const char* text); /** * @method str_decode_xml_entity_with_len * 对XML基本的entity进行解码,目前仅支持&lt;&gt;&quota;&amp;。 * @param {str_t*} str str对象。 * @param {char*} text 要解码的XML文本。 * @param {uint32_t} len 字符串长度。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_decode_xml_entity_with_len(str_t* str, const char* text, uint32_t len); /** * @method str_from_int * 用整数初始化字符串。 * @param {str_t*} str str对象。 * @param {int32_t} v 整数。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_from_int(str_t* str, int32_t v); /** * @method str_from_float * 用浮点数初始化字符串。 * @param {str_t*} str str对象。 * @param {double} v 浮点数。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_from_float(str_t* str, double v); /** * @method str_from_value * 用value初始化字符串。 * @param {str_t*} str str对象。 * @param {value_t} v value。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_from_value(str_t* str, const value_t* v); /** * @method str_from_wstr * 用value初始化字符串。 * @param {str_t*} str str对象。 * @param {wchar_t*} wstr wstr。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_from_wstr(str_t* str, const wchar_t* wstr); /** * @method str_to_int * 将字符串转成整数。 * @param {str_t*} str str对象。 * @param {int32_t*} v 用于返回整数。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_to_int(str_t* str, int32_t* v); /** * @method str_to_float * 将字符串转成浮点数。 * @param {str_t*} str str对象。 * @param {double*} v 用于返回浮点数。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_to_float(str_t* str, double* v); /** * @method str_end_with * 判断字符串是否以指定的子串结尾。 * @param {str_t*} str str对象。 * @param {char*} text 子字符串。 * * @return {bool_t} 返回是否以指定的子串结尾。 */ bool_t str_end_with(str_t* str, const char* text); /** * @method str_start_with * 判断字符串是否以指定的子串开头。 * @param {str_t*} str str对象。 * @param {char*} text 子字符串。 * * @return {bool_t} 返回是否以指定的子串开头。 */ bool_t str_start_with(str_t* str, const char* text); /** * @method str_trim * 去除首尾指定的字符。 * @param {str_t*} str str对象。 * @param {char*} text 要去除的字符集合。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_trim(str_t* str, const char* text); /** * @method str_trim_left * 去除首部指定的字符。 * @param {str_t*} str str对象。 * @param {char*} text 要去除的字符集合。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_trim_left(str_t* str, const char* text); /** * @method str_trim_right * 去除尾部指定的字符。 * @param {str_t*} str str对象。 * @param {char*} text 要去除的字符集合。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_trim_right(str_t* str, const char* text); /** * @method str_replace * 字符串替换。 * @param {str_t*} str str对象。 * @param {char*} text 待替换的子串。 * @param {char*} new_text 将替换成的子串。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_replace(str_t* str, const char* text, const char* new_text); /** * @method str_to_lower * 将字符串转成小写。 * @param {str_t*} str str对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_to_lower(str_t* str); /** * @method str_to_upper * 将字符串转成大写。 * @param {str_t*} str str对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_to_upper(str_t* str); /** * @method str_expand_vars * 将字符串中的变量展开为obj中对应的属性值。 * * 变量的格式为${xxx}: * * * xxx为变量名时,${xxx}被展开为obj的属性xxx的值。 * * xxx为表达式时,${xxx}被展开为表达式的值,表达式中可以用变量,$为变量的前缀,如${$x+$y}。 * * xxx为变量名时,而不存在obj的属性时,${xxx}被移出。 * * @param {str_t*} str str对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_expand_vars(str_t* str, const char* src, const object_t* obj); /** * @method str_reset * 重置字符串为空。 * @param {str_t*} str str对象。 * * @return {ret_t} 返回RET_OK表示成功,否则表示失败。 */ ret_t str_reset(str_t* str); END_C_DECLS #endif /*TK_STR_H*/
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <ctype.h> int isolateExp(unsigned int hex, unsigned int nExp, unsigned int nFrac); //Prototype for function to isolate the exponent bits double calculateExp(unsigned int iExp); //Prototype for function to calculate the exponent int isolateFrac(unsigned int hex, unsigned int iExp); //Prototype for function to isolate the fraction bits double calculateFrac(unsigned int iFrac, unsigned int nFrac); //Prototype for function to calculate the fraction int isolateSign(unsigned int hex, unsigned int nExp, unsigned int nFrac); //Prototype for function to isolate the sign bit double calculateIeee(double exp, double fraction, unsigned int nExp, unsigned int sign, double bias); //Prototype for function to calculate the IEEE floating point number int main(int argc, char * argv[]) { char * ptr = NULL; unsigned int check = 0; /* Check one and check 2 used to check for string inputs */ unsigned int check2 = 0; unsigned int nFrac, nExp, hex = 0; //Number of fraction bits, exponent bits, and hex all passed by command line unsigned int iFrac, iExp, sign = 0; //Isolated fraction bits, exponent bits, and sign bits double fraction = 0; //Fraction calculated using fraction bits double exp = 0; //Exponent calculated using exponent bits double base = 2; //Base of 2 used for calculations double bias = 0; //Bias used for IEEE calculation double iEEE = 0; //IEEE representation for(int i = 0; i < strlen(argv[3]); i++) { if(!isxdigit(argv[3][i])) { printf("A string was detected\n"); exit(0); } } sscanf(argv[1], "%d", &nFrac); //Sscanf used to convert string into ints sscanf(argv[2], "%d", &nExp); sscanf(argv[3], "%x", &hex); if(nFrac < 2 || nFrac > 10) //Checking fraction bits for correct input { printf("The fraction field is out of range, enter a number between 2 - 10\n"); return(0); } if(nExp < 3 || nExp > 5) //Cheching exponent bits for correct input { printf("The exponent field is out of range, enter a number between 3 - 5\n"); return(0); } bias = pow(base, (nExp - 1)) - 1; //Calculating bias using base and number of exponent bits iFrac = isolateFrac(hex, nFrac); //Function call to isolateFrac to isolate fraction bits iExp = isolateExp(hex, nExp, nFrac); //Function call to isolateExp to isolate exponent bits sign = isolateSign(hex, nExp, nExp); //Function call to isolateSign to isolate sign bits fraction = calculateFrac(iFrac, nFrac); //Function call to calculateFrac to calculate fraction taking in iFrac and nFrac exp = calculateExp(iExp); //Function call to calculateExp to calculate exponent bits taking in iExp iEEE = calculateIeee(exp, fraction, nExp, sign, bias); //Funtion call to calculateIeee to calculate the IEEE floating point number, taking in the exponent, fraction, number of exponent bits, sign, and bias printf("Fraction Bits: %d ", iFrac); //Printing out all variable and the final IEEE floating point number printf("Fraction: %f ", fraction); printf("Exponent Bits: %d ", iExp); printf("Exponent: %f ", exp); printf("Sign Bits: %d \n", sign); printf("IEEE Number: %f \n", iEEE); return(0); } int isolateExp(unsigned int hex, unsigned int nExp, unsigned int nFrac) { unsigned int iExp = hex << (32 - (nFrac + nExp)) >> (32 - nExp); //Bit shifting the hex value to isolate the exponent bits return iExp; } double calculateExp(unsigned int iExp) //Uses isolated exponent bits and math to calculate the exponent representation { unsigned int eMask = 1; double base = 2; double exp = 0; double eCount = 0; while(eMask <= 16) { if(eMask & iExp) { if(!exp) exp = pow(base, eCount); else exp += pow(base, eCount); } eCount += 1; eMask <<= 1; } return exp; } int isolateFrac(unsigned int hex, unsigned int nFrac) { unsigned int iFrac = hex << (32 - nFrac) >> (32 - nFrac); //Bit shifting to isolate the fraction bits return iFrac; } double calculateFrac(unsigned int iFrac, unsigned int nFrac) //Uses isolated fraction bits and math to calculate the fraction { unsigned int fMask = 0x80000000; double fraction = 0; double base = 2; double fCount = 1; fMask >>= (32 - nFrac); while(fMask >= 1) { if(fMask & iFrac) { if(!fraction) fraction = 1/(pow(base, fCount)); else fraction += 1/(pow(base, fCount)); } fCount += 1; fMask >>= 1; } return fraction; } int isolateSign(unsigned int hex, unsigned int nExp, unsigned int nFrac) { unsigned int sign = hex >> nFrac + nExp; //Uses bit shifting to isolate the sign bit return sign; } double calculateIeee(double exp, double fraction, unsigned int nExp, unsigned int sign, double bias) //Uses fraction, exponent, number of exponentbits, sign bits, and bias to calculate the final IEEE floating point number { double iEEE = 0; double M = 0; double E = 0; int check = (1 << nExp) - 1; if(check == exp) { if(fraction == 0) { if(sign) printf("-infinity\n"); else printf("+infinity\n"); exit(0); } else{ printf("NaN\n"); exit(0); } } if(exp == 0) { E = 1 - bias; M = fraction; } else{ E = exp - bias; M = fraction + 1; } iEEE = pow(-1, sign) * M * pow(2, E); return iEEE; }
C
/** ************************************************************ * @file usart.c * @brief * @author Javid * @date 2019-02-20 * @version 1.0 * ***********************************************************/ #include "sys.h" #include "usart.h" /*****************ڳʼ******************/ void uart_init(u32 bound) { //GPIO˿ GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE); //ʹUSART1GPIOAʱ //USART1_TX GPIOA.9 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //PA.9 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; // GPIO_Init(GPIOA, &GPIO_InitStructure);//ʼGPIOA.9 //USART1_RX GPIOA.10ʼ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;//PA10 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;// GPIO_Init(GPIOA, &GPIO_InitStructure);//ʼGPIOA.10 //USART ʼ USART_InitStructure.USART_BaudRate = bound;//ڲ USART_InitStructure.USART_WordLength = USART_WordLength_8b;//ֳΪ8λݸʽ USART_InitStructure.USART_StopBits = USART_StopBits_1;//һֹͣλ USART_InitStructure.USART_Parity = USART_Parity_No;//żУλ USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//Ӳ USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //շģʽ USART_Init(USART1, &USART_InitStructure); //ʼ1 USART_Cmd(USART1, ENABLE); //ʹܴ1 }
C
/* * reference: https://www.cnblogs.com/wangcq/p/3520400.html */ #include <sys/socket.h> #include <stdio.h> #include <stdlib.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <netinet/in.h> #include <unistd.h> int socket_fd; void socket_init() { int ret = socket_fd = socket(AF_INET, SOCK_STREAM, 0); if (ret < 0) { perror("create socket failed!"); exit(-1); } } void socket_close() { close(socket_fd); } int main(int argc, char **argv) { short port = 4096; int client_sockfd; char ip[32] = "127.0.0.1"; struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr(ip); // Host to Network Short, reference: https://blog.csdn.net/zhuguorong11/article/details/52300680 // https://blog.csdn.net/z_ryan/article/details/79134980 addr.sin_port = htons(port); // bind socket and address int ret = bind(socket_fd, (struct sockaddr *)&addr, sizeof(addr)); if (ret < 0) { perror("bind address failed!"); exit(-1); } listen(socket_fd, 100); while (1) { struct sockaddr_in client_address; int client_len = sizeof(client_address); client_sockfd = accept(socket_fd, (struct sockaddr*)&client_address, (socklen_t *)&client_len); if (client_sockfd < 0) { perror("connection error!"); } else { int keepAlive = 1; setsockopt(socket_fd, SOL_SOCKET, SO_KEEPALIVE, (void*)&keepAlive, sizeof(keepAlive)); int keepIdle = 5; int keepInterval = 5; int keepCount = 5; setsockopt(socket_fd, SOL_TCP, TCP_KEEPIDLE, (void *)&keepIdle, sizeof(keepIdle)); setsockopt(socket_fd, SOL_TCP,TCP_KEEPINTVL, (void *)&keepInterval, sizeof(keepInterval)); setsockopt(socket_fd,SOL_TCP, TCP_KEEPCNT, (void *)&keepCount, sizeof(keepCount)); } } return 0; }
C
/******************************** * OS Lab 1 Part 1a * * * * Usage: * * ./part1a.exe * * * * Spawns a child process * ******************************** * For: Professor Megherbi * * By: David Tyler * * ID: 00952042 * * * * 9/22/14 * * *****************************/ #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { int pid; int child_pid; for(;;) { sleep(1); child_pid = fork(); if (child_pid > 0) { //wait for child wait(child_pid); } else if (child_pid == 0) { //we are now in the child code printf("Child Running\n\0"); exit(1); } } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef enum { FALSE, TRUE } BOOL; typedef struct Element { int row; int column; int element; struct Element *line; struct Element *col; } Element; typedef struct SparseMatrix { int row; int column; Element **line; //Pointer Vector Element **col; //Pointer Vector } SparseMatrix; char *getSubstring(char *first, int idx, int len) { char *subStr = (char*)malloc(sizeof(char) * (len+1)); memcpy(subStr, &first[idx], len); subStr[len] = '\0'; //printf("substr = %s\n", subStr); return subStr; } void printIntMatrix(int **m, int r, int c) { int i, j; printf("---- Matrix:\n"); for(i=0; i<r; i++) { for(j=0; j<c; j++) { printf("%d ", m[i][j]); } printf("\n"); } printf("---- ---- ----\n"); } Element *createElement(int line, int column, int element) { Element *e = NULL; e = (Element *)calloc(1, sizeof(Element)); e->row = line; e->column = column; e->element = element; return e; } Element **createVectorElement(int n) { Element **vector = NULL; vector = (Element**)calloc(n, sizeof(Element*)); return vector; } SparseMatrix *createSparseMatrix(int row, int column) { SparseMatrix *matrix = NULL; matrix = (SparseMatrix*)calloc(1, sizeof(SparseMatrix)); matrix->row = row; matrix->column = column; matrix->line = createVectorElement(row); matrix->col = createVectorElement(column); return matrix; } void printSparseMatrix(SparseMatrix *matrix) { int **m = NULL; int i = 0, j = 0; Element *aux = NULL; m = (int**)calloc(matrix->row, sizeof(int*)); for(i=0; i<matrix->row; i++) { m[i] = (int*)calloc(matrix->column, sizeof(int)); } for(i=0; i<matrix->row; i++) { aux = matrix->line[i]; while(aux != NULL) { m[aux->row][aux->column] = aux->element; aux = aux->line; } } printf("---- Matrix:\n"); for(i=0; i<matrix->row; i++) { for(j=0; j<matrix->column; j++) { printf("%d ", m[i][j]); } printf("\n"); } printf("---- ---- ----\n"); } int **getIntMatrix(SparseMatrix *matrix) { int **m = NULL; int i = 0; Element *aux = NULL; m = (int**)calloc(matrix->row, sizeof(int*)); for(i=0; i<matrix->row; i++) { m[i] = (int*)calloc(matrix->column, sizeof(int)); } for(i=0; i<matrix->row; i++) { aux = matrix->line[i]; while(aux != NULL) { m[aux->row][aux->column] = aux->element; aux = aux->line; } } return m; } void fillSparseMatrix(SparseMatrix **matrix, int line, int column, int element) { Element *e = NULL; Element *aux1 = NULL; Element *aux2 = NULL; BOOL insert = FALSE; e = createElement(line, column, element); //printf("Matrix->Row [%d] Matrix->Col [%d]\n", (*matrix)->row, (*matrix)->column); //printf("line [%d] column [%d]\n", line, column); if(line > (*matrix)->row || column > (*matrix)->column) exit(0); //Insert on line //printf("fillSparseMatrix:: Insert on line\n"); if((*matrix)->line[line] == NULL) { (*matrix)->line[line] = e; } else { aux1 = (*matrix)->line[line]; aux2 = (*matrix)->line[line]; while(aux1 != NULL) { if(aux1->row > line) { aux2 = e; e->line = aux1; insert = TRUE; break; } aux2 = aux1; aux1 = aux1->line; } if(insert == TRUE) { aux1 = e; e->line = NULL; } } insert = FALSE; //Insert on column //printf("fillSparseMatrix:: Insert on column\n"); if((*matrix)->col[column] == NULL) { (*matrix)->col[column] = e; } else { aux1 = (*matrix)->col[column]; aux2 = (*matrix)->col[column]; while(aux1 != NULL) { if(aux1->column > column) { aux2->col = e; e->col = aux1; insert = TRUE; break; } aux2 = aux1; aux1 = aux1->col; } if(insert == TRUE) { aux1 = e; e->col = NULL; } } } void freeSparseMatrix(SparseMatrix *matrix) { } SparseMatrix *convertInMatrixToSparseMatrix(int **m, int r, int c) { SparseMatrix *matrix = NULL; int i = 0, j = 0; matrix = createSparseMatrix(r, c); for(i=0; i<r; i++) { for(j=0; j<c; j++) { if(m[i][j] != 0) { fillSparseMatrix(&matrix, i, j, m[i][j]); } } } return matrix; } void printInMatrixToSparseMatrix(int **m, int r, int c) { int i = 0, j = 0; printf("-1 %d %d\n", r, c); for(i=0; i<r; i++) { for(j=0; j<c; j++) { if(m[i][j] != 0) { printf("%d %d %d\n", i, j, m[i][j]); } } } } SparseMatrix *multiplyMatrices(SparseMatrix *first, SparseMatrix *second) { int **firstM = NULL; int **secondM = NULL; int **result = NULL; SparseMatrix *matrix = NULL; int i, j, k; //printf("multiplyMatrices::ENTER\n"); result = (int **)malloc(sizeof(int*) * first->row); for(i=0; i<first->row; i++) result[i] = (int*)calloc(second->column, sizeof(int)); //printf("multiplyMatrices::first->column[%d] second->row[%d]\n", first->column, second->row); if(first->column != second->row) exit(0); //printf("multiplyMatrices::FIRST\n"); firstM = getIntMatrix(first); //printIntMatrix(firstM, first->row, first->column); //printf("multiplyMatrices::SECOND\n"); secondM = getIntMatrix(second); //printIntMatrix(secondM, second->row, second->column); for(i=0; i<first->row; i++) { for(j=0; j<second->column; j++) { for(k=0; k<first->column; k++) { result[i][j] += firstM[i][k] * secondM[k][j]; } } } //printIntMatrix(result, first->row, second->column); matrix = convertInMatrixToSparseMatrix(result, first->row, second->column); printInMatrixToSparseMatrix(result, first->row, second->column); return matrix; } SparseMatrix *addMatrices(SparseMatrix *first, SparseMatrix *second) { int **firstM = NULL; int **secondM = NULL; int **result = NULL; SparseMatrix *matrix = NULL; int i, j; result = (int **)malloc(sizeof(int*) * first->row); for(i=0; i<first->row; i++) result[i] = (int*)calloc(first->column, sizeof(int)); if(first->row != second->row) exit(0); if(first->column != second->column) exit(0); firstM = getIntMatrix(first); secondM = getIntMatrix(second); for(i=0; i<first->row; i++) { for(j=0; j<second->column; j++) { result[i][j] = firstM[i][j] + secondM[i][j]; } } //printIntMatrix(result, first->row, first->column); matrix = convertInMatrixToSparseMatrix(result, first->row, first->column); printInMatrixToSparseMatrix(result, first->row, first->column); return matrix; } int main() { char op; int row = 0, column = 0, value = 0; SparseMatrix *first = NULL; SparseMatrix *second = NULL; //Get Operation scanf("%c", &op); //printf("op [%c]\n", op); //Reading Data FIRST scanf("%d %d %d", &value, &row, &column); first = createSparseMatrix(row, column); while(scanf("%d %d %d", &row, &column, &value) && row != -1){ fillSparseMatrix(&first, row, column, value); } //printf("First Matrix:\n"); //printSparseMatrix(first); //Reading Data SECOND second = createSparseMatrix(column, value); while(scanf("%d %d %d", &row, &column, &value) != EOF) { //while (scanf("%d %d %d", &row, &column, &value) && row != -1){ fillSparseMatrix(&second, row, column, value); } //printf("Second Matrix:\n"); //printSparseMatrix(second); if(op == 'A') { //printf("ADD MATRICES\n"); addMatrices(first, second); } else if(op == 'M') { //printf("MULTIPLY MATRICES\n"); multiplyMatrices(first, second); } return 0; }
C
#include <stdio.h> // #include <ctype.h> // #include <conio.h> int main(){ char ch; printf("Enter ch: "); ch = getchar(); if( (ch>='A' && ch<='Z') || (ch>='a' && ch<='z') ) // if( isalpha(ch) ) printf("%c is an alphabet\n", ch); else if( ch>='0' && ch<='9' ) // else if( isdigit(ch) ) printf("%c is a digit\n", ch); else printf("%c is a special character\n", ch); // getch(); // clrscr(); return 0; } /* Console Enter ch: A A is an alphabet Enter ch: 9 9 is a digit Enter ch: * * is a special character */
C
#include "test.h" #include "symbol_set.h" #include "chain.h" static void header(const char * text) { printf("---------------- %s ---------------\n", text); } static void print_chain(GhBrain * gh, bool back) { for (size_t i = 0; i <= gh->chain_mask; i++) { GhChain * chain = gh->chains[i]; while (chain != NULL) { printf("'%s', '%s', '%s', '%s' (%d)\n", chain->q.a->data, chain->q.b->data, chain->q.c->data, chain->q.d->data, chain->usage); GhSetIterator it = gh_sset_iterator(back ? &chain->back : &chain->forw); GhSymbol * s; size_t usage; while ((s = gh_sset_nextu(&it, &usage)) != NULL) printf(" '%s' (%zu)\n", s->data, usage); printf("\n"); chain = chain->next; } } } static void print_symbols(GhBrain * gh, bool pointers) { for (size_t i = 0; i <= gh->symbol_mask; i++) { GhSymbol * symbol = gh->symbols[i]; while (symbol != NULL) { printf("%s (%d)\n", symbol->data, symbol->usage); if (gh_symbol_isword(symbol) && pointers) { for (size_t j = 0; j <= symbol->chp_mask; j++) { GhChain * chain = symbol->chp[j]; if (chain != NULL) { printf(" ('%s', '%s', '%s', '%s')\n", chain->q.a->data, chain->q.b->data, chain->q.c->data, chain->q.d->data); } } } symbol = symbol->next; } } } int main(int argc, const char * argv[]) { if (argc <= 1) { printf("Usage: debug_data [fbsp]\n"); printf(" f - print chains with forward symbols\n"); printf(" b - print chains with backward symbols\n"); printf(" s - print list of symbols \n"); printf(" p - print list of symbols with chain pointers (implies s)\n"); exit(0); } printf("\n"); const char * options = argv[1]; GhBrain * gh = gh_new_brain(); gh_input_no_reply(gh, "This is test sentence number one."); gh_input_no_reply(gh, "Different sentence to provide additional input"); if (strchr(options, 'f')) { header("Forward chain"); print_chain(gh, false); printf("\n"); } if (strchr(options, 'b')) { header("Backward chain"); print_chain(gh, true); printf("\n"); } if (strchr(options, 's') || strchr(options, 'p')) { header("Symbols"); print_symbols(gh, strchr(options, 'p')); printf("\n"); } }
C
/* ** EPITECH PROJECT, 2017 ** my_strcat.c ** File description: ** my_strcat.c */ #include "my.h" char *my_strcat(char *dest, char const *src) { int len = my_strlen(src) + my_strlen(dest) + 1; char *temp = malloc(sizeof(char) * len); int i = 0; int j = 0; for (; src[i] != '\0'; i++, j++) temp[j] = src[i]; for (i = 0; dest[i] != '\0'; i++, j++) temp[j] = dest[i]; temp[j] = '\0'; return (temp); }
C
#include <stdio.h> #define MAXLINE 1000 // maximum input line length /*if these two are declared after print_longest_line_for_stdin, gcc will give warning*/ /*another solution is put print_longest_line_for_stdin function at last*/ int getline_for_me(char s[], int lim); void copy_for_me(char to[], char from[]); int print_longest_line_for_stdin() { int len; // current line length int max; // maximum length seen so far char line[MAXLINE]; // current input line char longest[MAXLINE]; // longest line saved here max = 0; while ((len = getline_for_me(line, MAXLINE)) > 0) if (len > max) { max = len; copy_for_me(longest, line); } if (max > 0) // there was a line printf("%s", longest); return 0; } /*getline_for_me: read a line into s, return length*/ int getline_for_me(char s[], int lim) { int c, i; for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i) s[i] = c; if (c == '\n') { s[i] = c; ++i; } /*getline puts the character '\0' (the null character, whose value is zero) at the end of the array it is creating, to mark the end of the string of characters.*/ s[i] = '\0'; return i; } /*copy: copy 'from' into 'to'; assume to is big enough*/ void copy_for_me(char to[], char from[]) { int i; i = 0; while ((to[i] = from[i]) != '\0') ++i; }
C
#ifndef __COMMON_H__ #define __COMMON_H__ #include <tina_log.h> /*---------------------------------------------------------------------- | result codes +---------------------------------------------------------------------*/ /** Result indicating that the operation or call succeeded */ #define SUCCESS 0 /** Result indicating an unspecififed failure condition */ #define FAILURE (-1) #include <assert.h> #define ASSERT(x) assert(x) /*---------------------------------------------------------------------- | error code +---------------------------------------------------------------------*/ #if !defined(ERROR_BASE) #define ERROR_BASE -20000 #endif // general errors #define INVALID_PARAMETERS (ERROR_BASE - 0) #define PERMISSION_DENIED (ERROR_BASE - 1) #define OUT_OF_MEMORY (ERROR_BASE - 2) #define NO_SUCH_NAME (ERROR_BASE - 3) #define NO_SUCH_PROPERTY (ERROR_BASE - 4) #define NO_SUCH_ITEM (ERROR_BASE - 5) #define NO_SUCH_CLASS (ERROR_BASE - 6) #define OVERFLOW (ERROR_BASE - 7) #define INTERNAL (ERROR_BASE - 8) #define INVALID_STATE (ERROR_BASE - 9) #define INVALID_FORMAT (ERROR_BASE - 10) #define INVALID_SYNTAX (ERROR_BASE - 11) #define NOT_IMPLEMENTED (ERROR_BASE - 12) #define NOT_SUPPORTED (ERROR_BASE - 13) #define TIMEOUT (ERROR_BASE - 14) #define WOULD_BLOCK (ERROR_BASE - 15) #define TERMINATED (ERROR_BASE - 16) #define OUT_OF_RANGE (ERROR_BASE - 17) #define OUT_OF_RESOURCES (ERROR_BASE - 18) #define NOT_ENOUGH_SPACE (ERROR_BASE - 19) #define INTERRUPTED (ERROR_BASE - 20) #define CANCELLED (ERROR_BASE - 21) const char* ResultText(int result); #define CHECK(_x) \ do { \ int _result = (_x); \ if (_result != SUCCESS) { \ TLOGE("%s(%d): @@@ CHECK failed, result=%d (%s)\n", __FILE__, __LINE__, _result, ResultText(_result)); \ return _result; \ } \ } while(0) #define CHECK_POINTER(_p) \ do { \ if ((_p) == NULL) { \ TLOGE("%s(%d): @@@ NULL pointer parameter\n", __FILE__, __LINE__); \ return INVALID_PARAMETERS; \ } \ } while(0) #define DELETE_POINTER(_p) \ do{ \ if((_p) != NULL){ \ TLOGD("delete: %p",_p); \ delete _p; \ _p = NULL; \ } \ }while(0) #endif /*__COMMON_H__*/
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ typedef int u_int ; struct timeval {scalar_t__ tv_sec; int tv_usec; } ; /* Variables and functions */ int EINVAL ; scalar_t__ tick ; int itimerfix(struct timeval *tv) { if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000) return (EINVAL); if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < (u_int)tick / 16) tv->tv_usec = (u_int)tick / 16; return (0); }
C
#ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <stdio.h> #include <WINGs/WINGs.h> void showSelectedColor(void *self, void *cdata) { WMColorPanel *panel = (WMColorPanel *) self; printf("Selected Color: %s\n", WMGetColorRGBDescription(WMGetColorPanelColor(panel))); } int main(int argc, char **argv) { Display *dpy; WMScreen *scr; WMInitializeApplication("wmcolorpick", &argc, argv); dpy = XOpenDisplay(""); if (!dpy) { printf("could not open display\n"); exit(1); } scr = WMCreateScreen(dpy, DefaultScreen(dpy)); { WMColorPanel *panel = WMGetColorPanel(scr); WMSetColorPanelAction(panel, showSelectedColor, NULL); WMShowColorPanel(panel); } WMScreenMainLoop(scr); return 0; }
C
/* Program : KelerengMudah_MuhammadFauzanLubis.c Deskripsi : Menapilkan warna kelereng Nama /Author : Muhammad Fauzan Lubis Tanggal/versi : 24 Oktober 2019/1.0 Compiler : gcc (tdm64-1) 5.1.0 Pertanyaan : Terdapat sejumlah kelereng berwarna Merah (M), kelereng berwana Biru (B) dan kelereng berwarna Kuning (K), dalam sebuah wadah (W) dengan jumlah 5 kelereng. Buatlah Program untuk menentukan warna dari setiap kelereng yang terdapat di dalam wadah tersebut. ======================================*/ #include <stdio.h> #include <string.h> int main() { //Declaration char input[6], temp[10]; int i; //Process scanf("%[^\n]", &input); for (i = 0; i < 5; i++) { switch (input[i]) { case 'M': strcpy(temp, "Merah"); break; case 'B': strcpy(temp, "Biru"); break; case 'K': strcpy(temp, "Kuning"); break; default: break; } if (i != 4) { printf("%s ", temp); } else { printf("%s\n", temp); } } return 0; }
C
#include<stdio.h> struct COUNTRY { double achiv[3]; int rank[4]; int firank[2]; double gp; double medalp; /* data */ }; int main() { int m,n; while(scanf("%d%d",&m,&n)!=EOF) { int opc[n]; struct COUNTRY country[m]; for (int i = 0; i < m; ++i) { for (int j = 0; j < 3; ++j) scanf("%lf",&country[i].achiv[j]); country[i].gp=country[i].achiv[0]/country[i].achiv[2]; country[i].medalp=country[i].achiv[1]/country[i].achiv[2]; } for (int i = 0; i < n; ++i) scanf("%d",&opc[i]); for (int i = 0; i < n; ++i) { int temp[4]={0}; for(int j=0;j<n;j++) { if(country[opc[i]].achiv[0]<country[opc[j]].achiv[0]) temp[0]++; if(country[opc[i]].achiv[1]<country[opc[j]].achiv[1]) temp[1]++; if(country[opc[i]].gp<country[opc[j]].gp) temp[2]++; if(country[opc[i]].medalp<country[opc[j]].medalp) temp[3]++; } for(int z=0;z<4;z++){ country[opc[i]].rank[z]=temp[z]+1; } country[opc[i]].firank[0]=country[opc[i]].rank[0]; country[opc[i]].firank[1]=1; for(int j=0;j<4;j++){ if(country[opc[i]].rank[j]<country[opc[i]].firank[0]) { country[opc[i]].firank[0]=country[opc[i]].rank[j]; country[opc[i]].firank[1]=j+1; } } } for (int i = 0; i < n; ++i) printf("%d:%d\n", country[opc[i]].firank[0],country[opc[i]].firank[1]); printf("\n"); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: brjorgen <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/23 05:13:59 by brjorgen #+# #+# */ /* Updated: 2020/12/18 17:29:51 by brjorgen ### ########.fr */ /* */ /* ************************************************************************** */ #include "lang.h" #include <stdio.h> void ft_augment_size(char **original_container, size_t *size) { char *tmp_container; size_t size_to_augment; size_to_augment = *size * 2; if (!(tmp_container = (char *)malloc(sizeof(char) * (size_to_augment)))) { free((void **)original_container); return ; } memcpy(tmp_container, *original_container, *size); free((void **)original_container); *original_container = tmp_container; *size = size_to_augment; } int ft_get(const int fd, char *c) { static t_getc_vars t_getv; if (c == NULL) { t_getv.len = 0; t_getv.i = 0; return (0); } if (t_getv.i == t_getv.len) { t_getv.len = read(fd, t_getv.tmp, BUFF_SIZE); t_getv.i = 0; } if (t_getv.len != 0) *c = t_getv.tmp[t_getv.i++]; else *c = 0; return (t_getv.len); } void manage_line(char **line) { free((void **)*line); *line = NULL; ft_get(0, NULL); } int init_gnl(t_vars *vr, const int fd, char **line) { if (fd < 0 || line == NULL) return (-1); vr->buf = 0; vr->len = 128; return (1); } int get_next_line(const int fd, char **line) { t_vars vr; if (init_gnl(&vr, fd, line) < 0) return (-1); if (!(*line = (char *)malloc(sizeof(char) * vr.len))) return (-1); while (vr.buf < vr.len) { if ((vr.ret = ft_get(fd, &vr.c)) < 0 || (vr.ret == 0 && vr.buf == 0)) { if (**line != '\0') { manage_line(line); } return (0); } if (vr.ret == 0 || vr.c == '\n') { line[0][vr.buf] = '\0'; return (1); } line[0][vr.buf++] = vr.c; vr.buf >= vr.len ? ft_augment_size(line, &vr.len) : 0; } return (-1); }
C
// // Home Presence Detector // AlanFromJapan http://kalshagar.wikispaces.com/ // // includes #include <avr/io.h> #include <util/delay.h> #include <avr/interrupt.h> //use this trick to ""adjust"" the timer1 and subscale it #define TIMER_DIVIDER 2 volatile uint16_t mTimerCounter = 0; volatile unsigned char mPinDIn; ISR(TIMER1_OVF_vect){ mTimerCounter++; if (mTimerCounter >= TIMER_DIVIDER){ //first thing, reset mTimerCounter = 0; //then do the interrupt job //read input on PB7, and light or stop D port mPinDIn = PIND; if (!(mPinDIn & 0x01)){ //movement detected! PORTB |= 0x80; } else { //movement off PORTB &= 0x7F; } } } //inits timer 1 to do interrupt on overflow (calls ISR(TIMER1_OVF_vect)) void init_timer1_OVF() { //timer 1 prescaler : makes clock / 64 -> tick every 1/4 sec roughly TCCR1B=0x03; //trigger the interrupt vector TIMER1_OVF_vect when timer 1 is overflow TIMSK = 0x80; //sets the interruptions to enabled sei(); } //Inits timer 0 to do PWM on pin B2 void init_timer0_PWM() { /* Set Fast PWM mode. */ TCCR0A |= (1<<WGM00) | (1<<WGM01); /* Clear 0C0A on compare. */ TCCR0A |= (1<<COM0A1); /* Start timer, no prescaling. */ TCCR0B |= (1<<CS00); /* Duty cycle 0% */ OCR0A = 0; } // // main function // int main(void) { //factory settings is to divide internal clock 8MHz by 8. //don't, and just run at 8 MHz (set the clock divider to 1 so no effect) CLKPR = (1<<CLKPCE); CLKPR = 0; // Divide by 1 //ports of bank D goes Mixed : PD0 in (movement detected on low), others out DDRD = 0xFE; //all ports of bank B goes output PB6~0 is output DDRB = 0xFF; //will be used to re-divide the TIMER1 (too fast) mTimerCounter = 0; //init for PWM init_timer0_PWM(); //init for timer interrupt init_timer1_OVF(); unsigned char vIn; while (1){ //read input on PB7, and light or stop D port vIn = PIND; if (!(vIn & 0x01)){ //movement detected! PORTB |= 0x80; } else { //movement off PORTB &= 0x7F; } /* //pulse led unsigned char i ; for(i=0; i < 255; i++) { OCR0A = i; _delay_ms(10); } for(i=255; i > 0; i--) { OCR0A = i; _delay_ms(10); } OCR0A = 0; */ _delay_ms(50); } /* //test : blink the port D PORTD = 0x7F; while (1){ PORTD ^= 0x7F; _delay_ms(3000); } */ } ////////////////////////////////////////////////////////////
C
/* * maze.h - header file for 'maze.c' module * * A maze contains a 2D array of objects that will be shared and updated * by all the avatars. The avatar will make use of this maze to update walls * and check for any existing walls. See object.h for details on each * object in the array. * * CS50 Winter 2020 */ /* Object types: 1 is a blank tile 2 is a horizontal wall 3 is a vertical wall 4 is a corner 5 is an avatar */ #include <stdio.h> #include <stdlib.h> #include "amazing.h" #include "object.h" typedef struct maze maze_t; /**************** maze_new ****************/ /* Create a new maze and initialize array * * Caller provides: * width and height of maze * We return: * the maze after initialization * We do: * Allocate memory for the maze * Initialize 2D Array * Initialize outer edges of the array */ maze_t *maze_new(const int width, const int height); /**************** getTile ****************/ /* Returns the integer type of a desired tile * * Caller provides: * maze and X Y position of desired tile * We return: * integer type of the desired tile */ int getTile(maze_t *mz, int x, int y); /**************** setObj ****************/ /* Sets the integer type of a desired tile * * Caller provides: * maze, X Y position of desired tile, and desired type * We do: * Set tile in the 2D array to desired type */ void setObj(maze_t *mz, int x, int y, int type); /* Helper functions to get maze's width and height */ int getMazeWidth(maze_t *mz); int getMazeHeight(maze_t *mz); /* Helper functions to delete and print the maze */ void maze_delete(maze_t *mz); void maze_print(maze_t* mz);
C
/* * RangeSumQueryImmutable2.c * * Created on: Sep 28, 2016 * Author: xinsu * * Dynamic programming, O(n) space */ /* Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. Example: Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3 Note: You may assume that the array does not change. There are many calls to sumRange function. */ #include <stdio.h> #include <stdlib.h> struct NumArray { int *sums; }; /** Initialize your data structure here. */ struct NumArray* NumArrayCreate(int* nums, int numsSize) { if (nums == NULL || numsSize < 0) { return NULL; } struct NumArray *numArray = (struct NumArray *) calloc(1, sizeof(struct NumArray)); numArray->sums = (int *) calloc(numsSize, sizeof(int)); numArray->sums[0] = nums[0]; for (int i = 1; i < numsSize; i++) { numArray->sums[i] = numArray->sums[i - 1] + nums[i]; } return numArray; } int sumRange(struct NumArray* numArray, int i, int j) { if (numArray == NULL || i > j) { return 0; } return numArray->sums[j] - numArray->sums[i - 1]; } /** Deallocates memory previously allocated for the data structure. */ void NumArrayFree(struct NumArray* numArray) { if (numArray->sums != NULL) { free(numArray->sums); } free(numArray); } // Your NumArray object will be instantiated and called as such: // struct NumArray* numArray = NumArrayCreate(nums, numsSize); // sumRange(numArray, 0, 1); // sumRange(numArray, 1, 2); // NumArrayFree(numArray);
C
void sorty() { double array_size=5; const Double_t aray[5] = { 3, 1, 7, 9, 2 }; const int index[5]; aray= TMath::Sort(5,aray,index,0); for(int i=0;i<5;i++){ cout << aray[i] << " "; } cout << endl; for(int i=0;i<5;i++){ cout << index[i] << " " << aray[index[i]] << endl; } cout << endl; }
C
#ifndef FUNCTION_H_INCLUDED #define FUNCTION_H_INCLUDED #define PI 3.1415926 //ԲPIĺ궨塣 #ifdef __cplusplus extern "C"{ #endif //Ŀ꺯 double f(double x); /********************************************************************************* data˫ȸ飻 keyֵ left_indexʼ±ꣻ right_indexֹ±ꣻ ܣŴ㷨dataдkey򷵻keyڵ±꣬ 򷵻-1򷵻ֹ±ꡣ *********************************************************************************/ int GA_binary_search(double *data, double key, int left_index, int right_index) ; /******************************************************************************** from->, to->, digit_num->Сλ; ܣ ע⣺ 1). digit_numĴССfromtoСλfrom=0.005, to=0.01ʱ, digit_num>=3 ***********************************************************************************/ double random_with_digit(double from, double to, int digit_num); /********************************************************************************** from->, to->; ܣСλfromtoλ 磺 double rand = 0; double from = 2.33; //λС double to = 3.898878 //λС rand = random(from, to); //randλС ע⣺˺ҪСλδ֪ ***********************************************************************************/ double random(double from, double to); #ifdef __cplusplus } #endif #endif
C
#include <stdio.h> #include <syscall.h> #include "threads/malloc.h" int main (int argc, char **argv) { int i; printf("Hello pINTOS\n"); for (i = 0; i < argc; i++) printf ("%s hello", argv[i]); printf ("\n"); /* for(i =0; i<10000;i++){ malloc(400); printf("malloc...."); } */ return EXIT_SUCCESS; }
C
#include "sequence_list.h" #include <stdlib.h> /* *ܣӡԱ * */ void Display_Sq(SqList *L) { int i; for (i = 0;i < L->length;i++) { printf("L %d elem is %d \n",(i + 1),L->elem[i]); } } /* *ܴԱ */ Status InitList_Sq(SqList *L) { //һյԱL if (0 == (L->elem = (ElemType*) malloc ( LIST_INIT_SIZE * sizeof(ElemType))) ) { return -1; } L->length = 0; L->listsize = LIST_INIT_SIZE; return OK; } /* *:˳ԱLеiλòµԪe */ Status ListInsert_Sq(SqList *L,int i,ElemType e) { if(i < 1 || i > (L->length + 1)) { return ERROR; } if(L->length >= L->listsize) { ElemType *new_base_addr; new_base_addr = (ElemType *)realloc(L->elem,(L->listsize + LISTINCREMENT)*sizeof(ElemType)); if(!new_base_addr) { return OVERFLOW; } L->elem = new_base_addr; L->listsize += LISTINCREMENT; } ElemType *q = &(L->elem[i-1]); //qΪeҪλ ElemType *p; for(p = (&L->elem[L->length] - 1); p >= q; --p) { *(p + 1) = *p; //qλúԪض } *q = e; L->length++; return OK; } /* *:ɾ˳LеĵiԪأe */ Status ListDelete_Sq(SqList *L,int i,ElemType *e) { if(L->length < 1 || i > L->length) { return ERROR; } ElemType *q = &(L->elem[i-1]); //qΪҪɾλ *e = *q; for (;q < (L->elem + L->length - 1);q++) { *q = *(q + 1); } L->length--; return OK; } /* *;һeȵֵ,չıȽϹϵ */ Status LocateElem_Sq(SqList *L,ElemType e) { int i = 0; ElemType *p = L->elem; while(++i <= L->length && e != *p++ ); return (i <= L->length) ? i : 0; } /* *:˳ϲ2˳ԱLaLb.洢Lc */ Status MergeList_Sq(SqList *La,SqList *Lb,SqList *Lc) { ElemType *pa = La->elem, *pb = Lb->elem,*pc; ElemType *pa_last = La->elem + La->length - 1; ElemType *pb_last = Lb->elem + Lb->length - 1; Lc->length = La->length + Lb->length; pc = Lc->elem = (ElemType *)malloc(Lc->length*sizeof(ElemType)); if (!Lc->elem) { return OVERFLOW; } while(pa <= pa_last && pb <= pb_last)//鲢 { *pc++ = (*pa <= *pb) ? *pa++ : *pb++; } while(pa <= pa_last)//LaʣԪ { *pc++ = *pa++; } while(pb <= pb_last)//LbʣԪ { *pc++ = *pb++; } return OK; } /* *: ڵеõiԪأظe */ Status GetElem_L(LNode *L,int i, ElemType *e) { LNode *p = L->next; int j = 1; while(j < i && p) { j++; p = p->next; } if(!p && j > i) { return ERROR; } *e = p->data; return OK; } Status LinkInsert_L(LNode *L,int i, ElemType e) { LNode *p = L->next; LNode *s; int j = 1; while(j < i && p) { j++; p = p->next; } if(!p && j > i) { return ERROR; } s = (LNode *)malloc(sizeof(LNode)); s->next = p->next; p->next = s; s->data = e; return OK; } Status LinkDelete_L(LNode *L,int i, ElemType *e) { LNode *p = L; LNode *q; int j = 1; while(j < i && p->next) { j++; p = p->next; } if(!(p->next) && j > i) { return ERROR; } q = p->next; p->next = q->next; *e = q->data; free(q); return OK; } /* *nڵĵ */ void CreateList_L(LNode *L,int n) { int i; LNode *p; L = (LNode *)malloc(sizeof(LNode)); L->next = NULL; for (i = n;i > 0;i--) { p = (LNode *)malloc(sizeof(LNode)); scanf("%d",&p->data); p->next = L->next; L->next = p; } } /* *ϲΪһ */ void MergeList_L(LNode *La,LNode *Lb,LNode *Lc) { LNode *pa,*pb,*pc; pa = La->next; pb = Lb->next; Lc = pc = (LNode *)malloc(sizeof(LNode)); pc->next = NULL; while(pa && pb) { if(pa->data <= pb->data) { pc->next = pa; pc = pa; pa = pa->next; } else { pc->next = pb; pc = pb; pb = pb->next; } } pc->next = pa ? pa : pb; } void Sq_Test(void) { LNode *L; CreateList_L(L,3); }
C
#include <stdio.h> #include <string.h> //请编写一个函数void fun(char a[],char b[],int n),其功能是:删除以各字符串中指定下标的字符。其中,a指向原字符串,删除后的字符串存放在b所指的数组中,n中存放指定的下标。 void fun(char a[], char b[], int n) { a[n] = '\0'; strcpy(b, &a[0]); strcat(b, &a[n+1]); } int main(void) { int n = 0; char a[256] = {'\0'}; char b[256] = {'\0'}; printf("Please input the string you want to process:\n"); scanf("%s", a); printf("Please input nth element to remove:\n"); scanf("%d", &n); fun(a, b, n - 1); puts(b); return 0; }
C
/**************************************** > File Name: text.c > Author: Lanotte > Mail: [email protected] > Created Time: 2015年01月27日 星期二 14时22分40秒 > Function: *****************************************/ #include <stdio.h> int main() { printf("Helo"); return 0; }
C
#include <stdio.h> #include <stdbool.h> #include <math.h> #include <unistd.h> #include <time.h> const long long N = 600851475143; /** * This program shows an approach with three functions to the 3rd problem of * project euler. By further abstracting this logic, the steps of this * problem get easier. There's still a problem, the function takes too long */ /** * isDivisble - checks if a long long i is divisble by a long long j * @i: i will be divided by j * @j: j divides i * Return: true or false */ bool isDivisible(long long i, long long j) { if (i % j == 0) { return (true); } return (false); } /** * isPrime - determines if a number is prime * @i: potential prime * Return: true or false */ bool isPrime(long long i) { // for every j up to i for (long long j = 2; j < i; j++) { // if i is divisible by j it's not prime if (isDivisible(i, j)) { // return false return (false); } } // return true return (true); } /** * getLargestPrimeFactor - gets the largest prime factor up to long long int N * @N: Target Number of prime factorization * Return: Largest Prime Factor or 1 */ long long getLargestPrimeFactor(long long N) { // Container for largest prime factor long long int largest = 1; // for every number [2-N] // allow the largest prime factor to be set to largest for (long long i = 2; i < N; i++) { // if i is a factor and prime, if (isDivisible(N, i) && isPrime(i)) { // set largest to the other factor. largest = i; } } // return the largest prime factor or 1 return (largest); } /** * main - Entry Point * Description: Will find the largest prime number of N and print it to console * Return: void */ int main(void) { // Useful for timing functions time_t begin = time(NULL); // Given N const long long N = 600851475143; // a container for the largest prime factor long long largestPrimeFactor = getLargestPrimeFactor(N) printf("Largest Prime Factor of %llu is %llu\n", N, largest); time_t end = time(NULL); printf("The elapsed time is %ld seconds\n", (end - begin)); return (0); }
C
#include "civyobjectqueue.h" #define Q_IS_EMPTY(q) (q->head == NULL) typedef struct _cvobjectqueueentry { CVCoroutine *routine; CVObjectQEntry *previous; CVObjectQEntry *next; } CVObjectQEntry; struct _cvobjectqueue { CVObjectQEntry *head; CVObjectQEntry *tail; }; static void cv_init_object_queue(CVObjectQ *self) { self->head = self->tail = NULL; } static int cv_object_queue_push(CVObjectQ *self, CVCoroutine *coro) { /* We're gonna borrow some of python's internals for a little bit */ CVObjectQEntry *new_entry = (CVObjectQEntry *)PyObject_Malloc(sizeof(_cvobjectqueueentry)); if (new_entry == NULL) { PyErr_NoMemory(); return -1; } new_entry->routine = coro; new_entry->previous = self->tail; new_entry->next = NULL; switch(self->tail == NULL) { case 0: self->tail = self->tail->next = new_entry; break; case 1: self->head = self->tail = new_entry; break; } return 0; } static CVCoroutine* cv_object_queue_pop(CVObjectQ *self) { CVCoroutine *coro; CVObjectQEntry *entry; if (Q_IS_EMPTY(self)) { return NULL; } entry = self->head; coro = entry->routine; self->head = entry->next; switch(self->head == NULL) { case 0: self->head->previous = NULL; break; case 1: self->tail = self->head; break; } PyObject_Free(entry); return coro; } static void cv_dealloc_object_queue(CVObjectQ *self) { CVCoroutine *c = cv_object_queue_pop(self); while (c != NULL) { cv_dealloc_coroutine(c); c = cv_object_queue_pop(self); } }
C
#include <stdio.h> #include <stdlib.h> #include "compearth.h" /*! * @brief Decomposes a general moment tensor into its isotropic and * deviatoric components. * * @param[in] n Number of moment tensors. * @param[in] M [6 x n] general moment tensors. The leading dimension * is 6. * @param[out] Miso [6 x n] isotropic moment tensors. The leading dimension * is 6. * @param[out] Mdev [6 x n] deviatoric moment tensors. The leading dimension * is 6. * @param[out] trM If NULL then this will not be accessed. Otherwise, this * is the trace(M) and is an array of dimension [n]. * * @result 0 indicates success. * * @copyright MIT * */ int compearth_CMTdecomIso(const int n, const double *__restrict__ M, double *__restrict__ Miso, double *__restrict__ Mdev, double *__restrict__ trM) { double traceM; int i; bool lwantTrM; const double third = 1.0/3.0; if (n < 1 || M == NULL || Miso == NULL || Mdev == NULL) { if (n < 1){fprintf(stderr, "%s: No moment tensors\n", __func__);} if (M == NULL){fprintf(stderr, "%s: M is NULL\n", __func__);} if (Miso == NULL){fprintf(stderr, "%s: Miso is NULL\n", __func__);} if (Mdev == NULL){fprintf(stderr, "%s: Mdev is NULL\n", __func__);} if (trM == NULL){fprintf(stderr, "%s: trM is NULL\n", __func__);} return -1; } lwantTrM = false; if (trM != NULL){lwantTrM = true;} for (i=0; i<n; i++) { traceM = M[6*i] + M[6*i+1] + M[6*i+2]; Miso[6*i+0] = third*traceM; //trM[i]; Miso[6*i+1] = third*traceM; //trM[i]; Miso[6*i+2] = third*traceM; //trM[i]; Miso[6*i+3] = 0.0; Miso[6*i+4] = 0.0; Miso[6*i+5] = 0.0; if (lwantTrM){trM[i] = traceM;} } for (i=0; i<6*n; i++) { Mdev[i] = M[i] - Miso[i]; } return 0; }
C
#ifndef MY_IO_UTILS_H #define MY_IO_UTILS_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <limits.h> #define BF_SIZE 8 #define MAX_NUM 100 #define NUM_OF_LINE 8 void genRandArray(int* buffer, int dataSize) { // seed srand(time(NULL)); for (int counter = 0; counter < dataSize; counter++) { buffer[counter] = rand() % MAX_NUM; } } int exists(int* data, int size, int target) { for (int idx = 0; idx < size; idx++) { if (data[idx] == target) return 1; } return 0; } void genNoDupRandomArray(int* buffer, int dataSize) { // seed srand(time(NULL)); for (int counter = 0; counter < dataSize; counter++) { int candidate = rand() % MAX_NUM; if (!exists(buffer, counter, candidate)) { buffer[counter] = candidate; } else { // printf("dup!!!\n"); counter--; } } } void genData(int** buffers, int* sizes, int* types, int validSize) { for (int idx = 0; idx < validSize; idx++) { buffers[idx] = (int*) malloc(sizes[idx] * sizeof(int)); if (types[idx] == 0) { genRandArray(buffers[idx], sizes[idx]); } else { genNoDupRandomArray(buffers[idx], sizes[idx]); } } } void showArray(int* buffer, int dataSize) { for (int counter = 0; counter < dataSize; counter++) { printf("%d ", buffer[counter]); if ((counter + 1) % NUM_OF_LINE == 0) { printf("\n"); } } printf("\n"); } void showBuffers(int** buffers, int* sizes, int validSize) { printf("Buffers:\n"); for (int idx = 0; idx < validSize; idx++) { printf("Buffer::%d\n", idx); showArray(buffers[idx], sizes[idx]); } printf("\n"); } void freeBuffers(int** buffers) { for (int idx = 0; idx < BF_SIZE; idx++) { if (buffers[idx] != NULL) { free(buffers[idx]); } } } #endif
C
#include <stdio.h> #include <stdlib.h> struct node { int val; struct node* next; }; /* constructs a new node */ struct node* new_node(int val, struct node *next) { struct node* new_node = (struct node*) malloc(sizeof(struct node)); new_node->val = val; new_node->next = next; return new_node; } /* returns pointer to next field and frees memory for passed node */ struct node* delete_node(struct node* to_free) { struct node *to_return = to_free->next; free(to_free); return to_return; } int next_in_chain(int n) { int sum = 0; int squares[10] = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}; while(n > 0) { sum += squares[n%10]; n /= 10; } return sum; } int euler_92(int cap) { /* index array so that numbers[1] corresponds to 1 instead of 2 * max possible number in chain (730 for integers) must fit in the array */ int* numbers = (int*) malloc((cap > 1000?cap:1000) * sizeof(int)); int index = 1; int temp_index = 1; int count = 0; struct node *num_list = NULL; /* initilize numbers to 0 */ for (temp_index = 0; temp_index < cap; temp_index++) { numbers[temp_index] = 0; } numbers[1] = 1; numbers[89] = 89; for (index = 1; index < cap; index++) { for (temp_index = index; numbers[temp_index] == 0; temp_index = next_in_chain(temp_index)) { /* build up linked list structure containing a list of numbers */ num_list = new_node(temp_index, num_list); } /* traverse the linked list, so that numbers[val] = numbers[temp_index]; * free nodes of the list as traverse them */ for (;num_list != NULL; num_list = delete_node(num_list)) { if (num_list->val < cap) { numbers[num_list->val] = numbers[temp_index]; } } } /* traverse numbers and count how many are 89 */ for (temp_index = 1; temp_index < cap; temp_index++) { if (numbers[temp_index] == 89){ count++; } } return count; } int main() { int cap = 10000000; int count = euler_92(cap); printf("%d starting numbers below %d arrive at 89\n", count, cap); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ealbert <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/11/16 22:08:57 by ealbert #+# #+# */ /* Updated: 2016/11/19 19:34:04 by ealbert ### ########.fr */ /* */ /* ************************************************************************** */ #include "fdf.h" void draw_line4(unsigned char *px, t_line l, t_env *v) { l.i = 1; l.e = 2 * l.dx - l.dy; l.inc1 = 2 * (l.dx - l.dy); l.inc2 = 2 * l.dx; while (l.i < l.dy) { if (l.e >= 0) { l.x += l.xinc; l.e += l.inc1; } else l.e += l.inc2; l.y += l.yinc; ft_pixel_put(px, l.x, l.y, v); l.i++; } } void draw_line3(unsigned char *px, t_line l, t_env *v) { l.i = 1; l.e = 2 * l.dy - l.dx; l.inc1 = 2 * (l.dy - l.dx); l.inc2 = 2 * l.dy; while (l.i < l.dx) { if (l.e >= 0) { l.y += l.yinc; l.e += l.inc1; } else l.e += l.inc2; l.x += l.xinc; ft_pixel_put(px, l.x, l.y, v); l.i++; } } static t_line init_line(t_line l, t_pts **pts, int i, int j) { l.x1 = pts[i][j].x; l.y1 = pts[i][j].y; l.x2 = (l.i == 1) ? pts[i][j + 1].x : pts[i + 1][j].x; l.y2 = (l.i == 1) ? pts[i][j + 1].y : pts[i + 1][j].y; l.dx = abs(l.x2 - l.x1); l.dy = abs(l.y2 - l.y1); l.xinc = (l.x2 < l.x1) ? -1 : 1; l.yinc = (l.y2 < l.y1) ? -1 : 1; l.x = l.x1; l.y = l.y1; return (l); } void draw_line2(t_pts **pts, t_env *v) { int i; int j; unsigned char *px; px = v->data; j = -1; while (++j < v->nb) { i = -1; while (++i < v->lines - 1) { v->color = (!v->p[i][j].z && !v->p[i + 1][j].z) ? C_RED : C_GREEN; v->l.i = 2; v->l = init_line(v->l, pts, i, j); if (v->l.dx > v->l.dy) draw_line3(px, v->l, v); else draw_line4(px, v->l, v); } } } void draw_line1(t_pts **pts, t_env *v) { int i; int j; unsigned char *px; px = v->data; i = -1; while (++i < v->lines) { j = -1; while (++j < v->nb - 1) { v->color = (!v->p[i][j].z && !v->p[i][j + 1].z) ? C_RED : C_GREEN; v->l.i = 1; v->l = init_line(v->l, pts, i, j); if (v->l.dx > v->l.dy) draw_line3(px, v->l, v); else draw_line4(px, v->l, v); } } draw_line2(pts, v); }
C
#include <stdio.h> #include <stdbool.h> bool mx_islower(int c); bool mx_isupper(int c); int mx_tolower(int c); int mx_toupper(int c); void mx_reverse_case(char *s); void mx_reverse_case(char *s) { char tmp[100]; for (int i = 0; s[i]; i++) { if (mx_islower(s[i])) { tmp[i] = s[i]; tmp[i] = mx_toupper(tmp[i]); } else if (mx_isupper(s[i])) { tmp[i] = s[i]; tmp[i] = mx_tolower(tmp[i]); } else { tmp[i] = s[i]; } } s = tmp; }
C
#include <stdio.h> unsigned int reverseBits(unsigned int n) { unsigned int i, result = 0; for(i = 0; i < 32; i ++) { int tmp1 = (n >> i) << 31 >> i; //int tmp2 = n >> (i+1); //int tmp3 = (tmp1 | tmp2) >> i; result = result | tmp1; } return result; } int main() { printf("%ud\n", reverseBits(43261596)); return 0; }
C
#include <pthread.h> #include <stdlib.h> #include <unistd.h> #include <stdio.h> pthread_mutex_t mojmuteks=PTHREAD_MUTEX_INITIALIZER; int buf[512]; void *prod(void *arg) { int i = 0; while(true) { pthread_mutex_lock(&mojmuteks); buf[i % 512] = i; printf("prod umiescil %d na pozycji %d\n",i, buf[i % 512]); fflush(stdout); i++; pthread_mutex_unlock(&mojmuteks); sleep(2); } return NULL; } int main(void) { pthread_t mojwatek, mojwatek2; int j = 0; if ( pthread_create( &mojwatek, NULL, prod, NULL) ) { printf("blad przy tworzeniu watka."); abort(); } while(true) { pthread_mutex_lock(&mojmuteks); int pobranie = buf[j % 512]; printf("kons pobral %d z pozycji %d",j, buf[j % 512]); fflush(stdout); j++; pthread_mutex_unlock(&mojmuteks); sleep(3); } if ( pthread_join ( mojwatek, NULL ) ) { printf("blad przy koczeniu watka."); abort(); } exit(0); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_printf_print_arg.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: bopopovi <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/06/26 18:44:17 by bopopovi #+# #+# */ /* Updated: 2019/06/18 21:43:31 by bopopovi ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" /* ** Used to print the 'S' argument in regard to wchar_t handling rules ** Function prints no more than n bytes */ void ft_printf_print_wcs(t_ptf *ptf, wchar_t *input, int n) { unsigned char bytes[4]; int total_b; int len; int i; total_b = 0; i = 0; len = 0; while (input[i] != L'\0') { ft_bzero(bytes, 4); len = ft_wctomb(bytes, input[i]); total_b += len; if (total_b <= n) { ft_printf_buff_cat(ptf, (char*)bytes, (u_int64_t)len); if (total_b == n) break ; } else break ; i++; } } /* ** Dump parsed part of the format string ** Decides wether width should be space or zero ** Then proceeds to print formated arg and its computed prefix and or suffix ** If the specifier is 'S' or 'r' args are send to their dedicated functions */ void ft_printf_print(t_ptf *ptf, char *prfx, char *input, int n) { char *width; ft_printf_dump_fmt(ptf); width = " "; if (ft_strchr(ptf->flags, '0')) width = ptf->precision < 0 || ft_strchr("rsScC", ptf->spec) ? "0" : " "; if (ft_strlen(prfx) && *width == '0') ft_printf_buff_cat(ptf, prfx, (u_int64_t)ft_strlen(prfx)); if (!ft_strchr(ptf->flags, '-') && ptf->width > 0) ft_printf_buff_catn(ptf, width, (u_int64_t)ptf->width); if (ft_strlen(prfx) && *width == ' ') ft_printf_buff_cat(ptf, prfx, (u_int64_t)ft_strlen(prfx)); if (ft_strchr("BDIOUXP", ft_toupper(ptf->spec)) && ptf->precision > 0) ft_printf_buff_catn(ptf, "0", (u_int64_t)ptf->precision); if (ptf->spec == 'S') ft_printf_print_wcs(ptf, (wchar_t*)input, n); else if (ptf->spec == 'r') ft_printf_buff_cat_npr(ptf, input, (u_int64_t)n); else if (ptf->spec != 'S') ft_printf_buff_cat(ptf, input, (u_int64_t)n); if (ft_strchr("AEF", ft_toupper(ptf->spec)) && ptf->precision > 0) ft_printf_buff_catn(ptf, "0", (u_int64_t)ptf->precision); if (ft_strchr(ptf->flags, '-') && (int)ptf->width > 0) ft_printf_buff_catn(ptf, " ", (u_int64_t)ptf->width); }
C
#include <stdio.h> #include <string.h> #include <unistd.h> char buf[416]; char out[65536 + 4096] = "1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\n"; int main(int argc, char **argv) { const int o[16] = { 4, 7, 2, 11, 2, 7, 12, 2, 12, 7, 2, 11, 2, 7, 12, 2 }; char *t = out + 30; unsigned long long i = 1, j = 1; for (int l = 1; l < 20; l++) { int n = sprintf(buf, "Buzz\n%llu1\nFizz\n%llu3\n%llu4\nFizzBuzz\n%llu6\n%llu7\nFizz\n%llu9\nBuzz\nFizz\n%llu2\n%llu3\nFizz\nBuzz\n%llu6\nFizz\n%llu8\n%llu9\nFizzBuzz\n%llu1\n%llu2\nFizz\n%llu4\nBuzz\nFizz\n%llu7\n%llu8\nFizz\n", i, i, i, i, i, i, i + 1, i + 1, i + 1, i + 1, i + 1, i + 2, i + 2, i + 2, i + 2, i + 2); i *= 10; while (j < i) { memcpy(t, buf, n); t += n; if (t >= &out[65536]) { char *u = out; do { int w = write(1, u, &out[65536] - u); if (w > 0) u += w; } while (u < &out[65536]); memcpy(out, out + 65536, t - &out[65536]); t -= 65536; } char *q = buf; for (int k = 0; k < 16; k++) { char *p = q += o[k] + l; if (*p < '7') *p += 3; else { *p-- -= 7; while (*p == '9') *p-- = '0'; ++*p; } } j += 3; } } }
C
#include<stdio.h> int main() {//ABSOLUTE VALUE OF A NUMBER int n; printf("ABSOLUTE VALUE OF A NUMBER\nEnter number="); scanf("%d",&n); if(n<0) n=n*-1; printf("%d",n); }
C
//square of 12 is 144. 21 which is a reverse of 12 has a square 441 which is same as 144 reversed //there are few numbers which have this property //Program to find out whether any more such number exist in the range 10 to 100. #include<stdio.h> int getreverse(int n); int main() { int num,revnum,sqrnum,revsqrnum; for(num=10; num<=100; num++) { sqrnum=num*num; revnum=getreverse(num); revsqrnum=getreverse(sqrnum); if(revsqrnum==revnum*revnum) printf("%d %d %d %d\n",num,sqrnum,revnum,revsqrnum); } } int getreverse(int n) { int d1,d2,d3,d4,d5,rnum; d5=n%10; n=n/10; d4=n%10; n=n/10; d3=n%10; n=n/10; d2=n%10; n=n/10; d1=n%10; n=n/10; rnum=d5*10000+d4*1000+d3*100+d2*10+d1; while(rnum%10==0) rnum=rnum/10; return (rnum); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> int main() { printf("Process ID of current process= %d\n",getpid()); printf("Process ID of parent process= %d\n",getppid()); printf("Real user ID of current process= %d\n",getuid()); printf("Effective user ID of current process= %d\n",geteuid()); printf("Real group ID of current process= %d\n",getgid()); printf("Effective group ID of current process= %d\n",getegid()); for(;;){sleep(1);} return 0; }
C
#include "bigint_internal.h" #include <string.h> #include <stdlib.h> #include <assert.h> // calculates the largest multiple of b that fits into a, returns the quotient // and subtracts the appropriate amount from the remainder. static WordType simpleDiv(size_t rlen, WordType* rbuf, size_t blen, const WordType* bbuf) { WordType q = 0; size_t shf = rlen; while(rbuf[shf - 1] == 0) { shf--; } shf *= YABI_WORD_BIT_SIZE; while(cmpBuffers(rlen, rbuf, blen, bbuf, 0) >= 0) { size_t shfWords, shfAmt; WordType holder; // calculate the maximum power of two we can divide by while(1) { // number of words to shift right shfWords = shf / YABI_WORD_BIT_SIZE; shfAmt = shf % YABI_WORD_BIT_SIZE; while(shfWords >= rlen) { shfWords--; } // temporary variable for shifted out bits holder = rbuf[shfWords] & (((WordType)1 << shfAmt) - 1); // can we divide by this number rshiftBuffers(rlen - shfWords, rbuf + shfWords, shfAmt, rlen - shfWords, rbuf + shfWords, 0); if(cmpBuffers(rlen - shfWords, rbuf + shfWords, blen, bbuf, 0) >= 0) { break; } // no, reset and try the next power of two assert(shfWords != 0 || shfAmt != 0); lshiftBuffers(rlen - shfWords, rbuf + shfWords, shfAmt, rlen - shfWords, rbuf + shfWords); rbuf[shfWords] |= holder; shf = shfWords * YABI_WORD_BIT_SIZE + shfAmt - 1; } // calculate (2^shf * (r / 2^shf - d)) // rbuf[shfWords:] has already been divided out addBuffers(rlen - shfWords, rbuf + shfWords, blen, bbuf, 1, rlen - shfWords, rbuf + shfWords); lshiftBuffers(rlen - shfWords, rbuf + shfWords, shfAmt, rlen - shfWords, rbuf + shfWords); rbuf[shfWords] |= holder; q += (WordType)1 << shf; shf--; } return q; } /** * Divides two unsigned BigInts. b != 0. */ static ydiv_t divUnsigned(const BigInt* a, const BigInt* b, size_t qlen, WordType* qbuffer, size_t rlen, WordType* rbuffer) { // long division memset(qbuffer, 0, qlen * sizeof(WordType)); memset(rbuffer, 0, rlen * sizeof(WordType)); for(size_t i = a->data[a->len - 1] ? a->len : a->len - 1; i > 0; i--) { // shift r up by 1 word memmove(rbuffer + 1, rbuffer, (rlen - 1) * sizeof(WordType)); // set LSW to current word of a rbuffer[0] = a->data[i - 1]; // set next digit of q to r / d and subtract qd from r // if r < d, sets the current word of q to 0 and leaves r unchanged WordType w = simpleDiv(rlen, rbuffer, b->len, b->data); if(i <= qlen) { qbuffer[i - 1] = w; } } ydiv_t res; // find quotient and remainder length res.qlen = qlen; res.rlen = rlen; while(res.qlen > 1 && qbuffer[res.qlen - 1] == 0) { res.qlen--; } while(res.rlen > 1 && rbuffer[res.rlen - 1] == 0) { res.rlen--; } return res; } static void negateInPlace(size_t len, WordType* buf) { // quick negation algorithm: // find the lowest 1 bit. Flip all the bits // above the lowest 1 bit. // e.g. -0b110100 = 0b001100 // - (-12) = 12 size_t i; for(i = 0; i < (len - 1) && buf[i] == 0; i++); buf[i] = ~buf[i] + 1; for(i++; i < len; i++) { buf[i] = ~buf[i]; } } ydiv_t yabi_divToBuf(const BigInt* a, const BigInt* b, size_t qlen, WordType* qbuffer, size_t rlen, WordType* rbuffer) { // cannot divide by zero if(b->len == 1 && b->data[0] == 0) { return (ydiv_t) { .qlen = 0, .rlen = 0 }; } const BigInt* num; const BigInt* denom; size_t rrlen; WordType* rbuf; int qnegative = 0; int rnegative = 0; // change negative numbers to positive if(HI_BIT(a->data[a->len - 1])) { num = yabi_negate(a); qnegative ^= 1; rnegative = 1; } else { num = a; } if(HI_BIT(b->data[b->len - 1])) { denom = yabi_negate(b); qnegative ^= 1; } else { denom = b; } // make sure the remainder can hold partial results // (rlen > b->len) if(rlen <= b->len) { rrlen = b->len + 1; rbuf = YABI_MALLOC(rrlen * sizeof(WordType)); } else { rrlen = rlen; rbuf = rbuffer; } // quotient does not have to be expanded in long division // ; // do unsigned division ydiv_t result = divUnsigned(num, denom, qlen, qbuffer, rrlen, rbuf); // negate the quotient if either operand was negative if(qnegative) { negateInPlace(qlen, qbuffer); } // negate the remainder if the numerator was negative if(rnegative) { negateInPlace(rrlen, rbuf); } // copy and free dynamic storage if(num != a) { YABI_FREE((void*)num); } if(denom != b) { YABI_FREE((void*)denom); } if(rbuf != rbuffer) { memcpy(rbuffer, rbuf, rlen * sizeof(WordType)); YABI_FREE(rbuf); } // fix overflow if(result.qlen < qlen && HI_BIT(qbuffer[result.qlen - 1]) != qnegative) { // only if nonzero if(result.qlen != 1 || qbuffer[0] != 0) { result.qlen++; } } if(result.rlen < rlen && HI_BIT(rbuffer[result.rlen - 1]) != rnegative) { // only if nonzero if(result.rlen != 1 || rbuffer[0] != 0) { result.rlen++; } } // return return result; } ydiv_t yabi_div(const BigInt* a, const BigInt* b) { size_t qlen = a->len + 1; size_t rlen = b->len + 1; BigInt* q = YABI_NEW_BIGINT(qlen); q->refCount = 0; q->len = qlen; BigInt* r = YABI_NEW_BIGINT(rlen); r->refCount = 0; r->len = rlen; ydiv_t res = yabi_divToBuf(a, b, qlen, q->data, rlen, r->data); if(res.qlen != qlen) { YABI_RESIZE_BIGINT(q, res.qlen); } if(res.rlen != rlen) { YABI_RESIZE_BIGINT(r, res.rlen); } res.quo = q; res.rem = r; return res; }
C
#include <stdio.h> int main(void) { double Year_Second = 3.156e+7; printf("One year have %lf seconds.\n", Year_Second); int ages; printf("Enter your age: "); scanf("%d", &ages); printf("The age have %lf seconds.\n", ages * Year_Second); return 0; }
C
/* ** put_fd.c for perfection in /home/skyrise/Work/Repositories/Epitech/IA/dante/generation/perfection/srcs/misc/ ** ** Made by Buyumad Anas ** Login <[email protected]@epitech.eu> ** ** Started on Tue Apr 26 15:49:22 2016 Buyumad Anas ** Last update Tue Apr 26 16:08:36 2016 Buyumad Anas */ #include <unistd.h> #include "perfection.h" int put_fd(int fd, char *string) { if (string == NULL) return (ERROR); write(fd, string, str_len(string)); if (fd == 2) return (ERROR); return (SUCCESS); }
C
// RadioFilter.cpp : Defines the entry point for the console application. // #include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> char *FindGoodPart(char *compPart); int main(int argc, char *argv[]) { printf("main ==>\n"); char currData[BUFSIZ]; char prevData[BUFSIZ]; size_t index = 0; prevData[0] = '\0'; // forever while (1) { // Get the next character from stdin char buffer[1]; read(0, buffer, sizeof(buffer)); // printf("%c", buffer[0]); // If there was no more data, we be done if (buffer[0] == EOF) break; // If the characer is not a carriage return or line feed if (buffer[0]!= '\n' && buffer[0] != '\r') { // If there is room in the array, add the character. if (index < BUFSIZ) { currData[index++] = buffer[0]; currData[index] = '\0'; } } // We got the carriage return or line feed else { // Do we care about that record? char *goodPart = FindGoodPart(currData); if (goodPart) { // printf("============================\n"); // printf("Good part: [%s]\n", goodPart); // printf("Prev data: [%s]\n", prevData); // printf("============================\n\n"); // We do, because it is not a 1179998 // address, but is a 11xxxxx address. // Is it the same as the last data printed? if (strcmp(goodPart, prevData) != 0) { // No, it isn't, so show it printf("%s\n", goodPart); printf("\n"); // Now, make a copy of what was just printed strcpy(prevData, goodPart); } } // Reset to read the next record index = 0; currData[index] = '\0'; } } printf("main <==\n"); return 0; } char *FindGoodPart(char *record) { char *goodPart = NULL; if (record) { // printf("Record: [%s]\n", record); char *address = strstr(record, "Address"); if (address) { address += 9; char *interestingData = strdup(address); if (interestingData) { // printf("Interesting data: [%s]\n", interestingData); char *token = strtok(interestingData, " "); // printf("token [%s]\n", token); if (strcmp(token, "1179998") != 0 && strcmp(token, "0") != 0) { if (token[0] == '1' && token[1] == '1') { char *oTri = strchr(address, '<'); char *cTri = strchr(address, '>'); if (oTri && cTri) { oTri[0] = '\0'; } char *alpha = strstr(address, "Alpha: "); if (alpha) { goodPart = alpha + 9; // printf("Good part: [%s]\n", goodPart); } } } free(interestingData); } } } return goodPart; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* builtin_unset.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mli <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/08/21 10:07:47 by mli #+# #+# */ /* Updated: 2020/09/28 09:43:35 by mli ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" /* ** this file is a subset of the builtin_root.c file. ** It takes care of the unset builtin. */ /* ** note: the unset can take more than one argument, therefore we will loop ** over each of them. ** ** note: we assume that we do call the function with the argv[0] as being ** the builtin name. so we start with arg argv[1]. ** ** note: set the exit_status to 0 if everytihng ok, or 1 if at least one of ** the unset identifiers was wrong, starting by a forbidden character. ** ** RETURN: 1 always. because no fatal error possible. */ int unset_builtin(t_list **env_head, char **argv, t_control *control) { int i; i = 1; while (argv[i]) { if (!is_identifier_valid(argv[i], "unset")) unset_in_env_list(env_head, argv[i]); else control->exit_status = 1; i++; } return (1); } /* ** note: this function will try to find a matching label in the linked list ** and remove it. ** note: if the link is found, note: that we use *ptr (and not ptr) to ** really afect the list (*ptr = (*ptr)->next). And we free the link ** and set it to NULL. Terefore if it is the last link, the head of ** the list is set to NULL. */ void unset_in_env_list(t_list **env_head, char *str) { t_list **ptr; t_list *extra; ptr = env_head; while (*ptr) { if (!ft_strncmp(str, ((t_env*)((*ptr)->content))->label, \ ft_strlen(str) + 1)) { extra = *ptr; *ptr = (*ptr)->next; env_del_struct(extra->content); free(extra); return ; } ptr = &(*ptr)->next; } } /* ** note: this function will check that the identifer is ok, when passed to ** unset or export builtin command. ** ** note: the message is displayed on the standard error when the first char ** of the identifier is either: ** @, ~, %, ^, *, +, =, \, /, ?, ',' or '.' ** ** input: - command: command name to display in case of error message ** - the identifier string. ** ** RETURN: 0 OK ** 1 KO therefore we can assign the returned value directly in the ** control->exit_status variable. */ int is_identifier_valid(char *identifier, char *command) { if (!identifier[0] || ft_stristr(identifier, "@~%^*+=\\/?,.") == 0) { ft_perror(command, identifier, "not a valid identifier"); return (1); } return (0); }
C
#include<stdio.h> int main() { int b,c[50]; scanf("%d",&n); int b,max; for(b=0;b<n;b++) { scanf("%d",&c[b]); } max=a[0]; for(b=0;b<n;b++) { if(max<c[b]) { max=c[b]; break; } } printf("%d",max); return 0; }
C
//Single threaded test case to test error conditions //Key not found, data request for more than 4KB #include <stdio.h> #include <stdlib.h> #include <sys/syscall.h> #include <time.h> #include <keyvalue.h> #include <fcntl.h> #include <assert.h> int main(int argc, char *argv[]) { int i = 0, number_of_threads = 1, number_of_keys = 1024, number_of_transactions = 65536; int k, j; int a; int tid; int test = 1; __u64 check_size; char * data = (char *)malloc(8092); char * check_data = (char *)malloc(8092); int devfd; //keyvalue device file descriptor if(argc < 3) { fprintf(stderr, "Usage: %s number_of_keys number_of_transactions\n", argv[0]); exit(1); } number_of_keys = atoi(argv[1]); number_of_transactions = atoi(argv[2]); __u64 size[1000]; __u64 keys[1000]; devfd = open("/dev/keyvalue", O_RDWR); if(devfd < 0) { fprintf(stderr, "Device open failed"); exit(1); } srand((int)time(NULL)+(int)getpid()); //1. Test for key not found for(i=0; i<8092; i++) { data[i] = rand() % 256; } //Put keys and values into key_value store for(i=0; i<100; i++) { size[i] = rand() % 4096; tid = kv_set(devfd, i, size[i], (void *)data); assert(tid != -1); fprintf(stderr, "SET\t%d\t%d\t%d\n", tid, i, size[i]); } for(i=0; i<100; i++) { a = (rand() % 100) + 101; tid = kv_get(devfd, a, &check_size, (void *)check_data); if(tid != -1) { fprintf(stderr, "ERROR - Key found at %d!!\n", a); } } //2.Test for trying to put data more than 4KB tid = kv_set(devfd, 100, 5000, (void *)data); if(tid != -1) { fprintf(stderr, "ERROR - Data size!!\n"); } tid = kv_set(devfd, 102, 4800, (void *)data); if(tid != -1) { fprintf(stderr, "ERROR - Data size!!\n"); } //3.Test for hashmap collision - Map size = 128 size[126] = rand() % 4096; tid = kv_set(devfd, 126, size[126], (void *)data); assert(tid != -1); size[254] = rand() % 4096; tid = kv_set(devfd, 254, size[254], (void *)data); assert(tid != -1); size[382] = rand() % 4096; tid = kv_set(devfd, 382, size[382], (void *)data); assert(tid != -1); tid = kv_get(devfd, 254, &check_size, (void *)check_data); if(tid == -1) { printf("ERORR!!\n"); } else { if(check_size != size[254]) { printf("ERROR in size!!\n"); test = 0; } else { for(j=0; j<check_size; j++) { if(check_data[j] != data[j]) { printf("ERROR in data!!\n"); test = 0; break; } } } } tid = kv_get(devfd, 382, &check_size, (void *)check_data); if(tid == -1) printf("ERORR!!\n"); else { if(check_size != size[382]) { printf("ERROR in size!!\n"); test = 0; } else { for(j=0; j<check_size; j++) { if(check_data[j] != data[j]) { printf("ERROR in data!!\n"); test = 0; break; } } } } tid = kv_get(devfd, 126, &check_size, (void *)check_data); if(tid == -1) printf("ERORR!!\n"); else { if(check_size != size[126]) { printf("ERROR in size!!\n"); test = 0; } else { for(j=0; j<check_size; j++) { if(check_data[j] != data[j]) { printf("ERROR in data!!\n"); test = 0; break; } } } } tid = kv_delete(devfd, 254); if(tid == -1) { printf("ERROR in delete!\n"); test = 0; } tid = kv_get(devfd, 254, &check_size, (void *)check_data); if(tid != -1) { printf("ERORR!!\n"); test = 0; } tid = kv_get(devfd, 382, &check_size, (void *)check_data); if(tid == -1) printf("ERORR!!\n"); else { if(check_size != size[382]) { printf("ERROR in size!!\n"); test = 0; } else { for(j=0; j<check_size; j++) { if(check_data[j] != data[j]) { printf("ERROR in data!!\n"); test = 0; break; } } } } if(test == 1) printf("Test passed!!\n"); else printf("Test failed!!\n"); return 1; }
C
/* By: Aijaz Ahmad Wani email :[email protected] IMCA (SEM-2) subject: DATA STRUCTURES PROGARM:(a) : CALCULATE THE NUMBER OF STUDENTS WHO GET MORE THAN 60 MARKS (b) : PRINT NAME AND MARKS OF STUDENTS WHO GET MORE THAN 60 MARKS*/ #include <stdio.h> #include <stdlib.h> struct student{ char name[10]; int marks; }stu[5]; int main() { int i,count=0; for(i=0;i<5;i++){ printf("enter student name and marks of %dth student: ",i); scanf("%s",&stu[i].name); scanf("%d",&stu[i].marks); } printf("\n\nstudents who obtained more than 60 marks "); for(i=0;i<5;i++) { if(stu[i].marks>60){ count++; printf("%s",stu[i].name); printf(" %d",stu[i].marks); printf("\n"); } } printf("\ntotal no. of students who got more than 60 marks = %d",count); getch(); }
C
#include<stdio.h> int main() { while(1) { float fahrenheit = 0; scanf("%f", &fahrenheit); if (fahrenheit == 0) break; float centigrade = ((fahrenheit - 32) / 9)*5; printf("%f\n", centigrade); } return 0; }
C
/*Inversion Count (n^2) * * @Prerna(1910990964) * * Assignment_7-SortingAlgorithms * */ #include<stdio.h> int main() { int n; scanf("%d",&n); int arr[n]; for(int i = 0; i < n; i++) { scanf("%d",&arr[i]); } int inversions = 0; for(int i = 0;i < n; i++) { for(int j = i + 1; j < n; j++) { if(arr[i] > arr[j]) { inversions++; } } } printf("inversions : %d",inversions); }
C
#include <stdio.h> #include <stdlib.h> #include "listadinordcab.h" struct no{ int info; struct no * prox; }; Lista cria_lista() { Lista cab; cab = (Lista) malloc(sizeof(struct no)); if (cab != NULL) { cab->prox = NULL; cab->info = 0; } return cab; } int lista_vazia(Lista lst) { if (lst->prox== NULL) return 1; // Lista vazia else return 0; // Lista NÃO vazia } void print_lista(Lista lst){ Lista aux; aux = lst->prox; printf("{"); while(aux!=NULL){ printf(" %d ",aux->info); aux = aux->prox; } printf("}"); } int insere_ord(Lista *lst, int elem) { Lista N = (Lista) malloc(sizeof(struct no)); if (N == NULL) { return 0; } N->info = elem; Lista aux = *lst; while (aux->prox != NULL && aux->prox->info < elem) aux = aux->prox; N->prox = aux->prox; aux->prox = N; (*lst)->info++; return 1; } int remove_ord (Lista *lst, int elem) { if (lista_vazia(*lst) == 1) return 0; Lista aux = *lst; while (aux->prox != NULL && aux->prox->info < elem) aux = aux->prox; if (aux->prox == NULL || aux->prox->info > elem) return 0; Lista aux2 = aux->prox; aux->prox = aux2->prox; free(aux2); (*lst)->info--; return 1; } Lista intercala_ord(Lista lst1, Lista lst2){ Lista lst3; lst3 = cria_lista(); int elem; lst1 = lst1->prox; lst2 = lst2->prox; while (lst1 != NULL){ elem = lst1->info; insere_ord(&lst3,elem); lst1 = lst1->prox; } while (lst2 != NULL){ elem = lst2->info; insere_ord(&lst3,elem); lst2 = lst2->prox; } return lst3; } int remove_impares(Lista *lst){ if(lista_vazia(*lst)==1){ return NULL; } Lista aux2 = (*lst)->prox; while (aux2 != NULL){ if(aux2->info%2!=0){remove_ord(&(*lst),aux2->info);} aux2 = aux2->prox; } return 1; } int menor(Lista lst){ if(lista_vazia(lst)==1) return NULL; Lista aux = lst; int menor; menor = lst->prox->info; while (aux->prox != NULL){ aux = aux->prox; if(aux->info<=menor) menor = aux->info; } return menor; } int tamanho(Lista lst){ return lst->info; } int iguais(Lista lst,Lista lst2){ if(lista_vazia(lst)==1 && lista_vazia(lst2)==1) return 1; int cont=0; Lista aux = lst->prox; Lista aux2 = lst2->prox; if(tamanho(lst)!=tamanho(lst2)) return 0; while(aux != NULL){ if(aux->info!=aux2->info)break; aux = aux->prox; aux2 = aux2->prox; } if(aux==NULL){return 1;} else{return 0;} }
C
/* ============================================================================ Name : ex31.c Author : Jonathan Geva - 304861347 Version : Copyright : MINE ALL MINE!!! Description : Server side - chomp game ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/types.h> #include <sys/fcntl.h> #include <sys/sem.h> //function: convert string to int int convertTOint(char* s) { int i=0,sum=0; while((s[i] >= '0') && (s[i] <= '9')) { sum = (sum*10) + (s[i]-'0'); i++; } return sum; } //function: checks if there is a ',' char in string int checkPsik(char* s) { int i=1; while(s[i]!=',') { i=i+1; } return i; } int main(void) { int fd; int shm_id; char* sm; key_t srvkey = ftok("Ex31.c",'j'); // creating a key shm_id = shmget(srvkey, 1024, IPC_CREAT | 0666); // gets shared memory id sm = (char*)shmat(shm_id,NULL,0); if(shm_id == -1) // checks if shared memory wasnt created { perror("failed to create shared memory\n"); exit(0); } char buffer[100] = {'\0'}; pid_t pid1,pid2; int m,n; mkfifo("fifo_clientTOserver",0777); //opening fifo write(1,"opened fifo\n",sizeof("opened fifo\n")); write(1,"Waiting for client request\n",sizeof("waiting for client request\n")); fd = open("fifo_clientTOserver",O_RDONLY); if(fd == -1) { write(1,"failed to create fifo\n",strlen("failed to create fifo\n")); exit(0); } //Waiting for client 1 int r = read(fd,&pid1,100*sizeof(char)); while(r==0) { r = read(fd,&pid1,100*sizeof(char)); } write(1,"Waiting for client request\n",sizeof("waiting for client request\n")); //Waiting for client 2 r = read(fd,&pid2,100*sizeof(char)); while(r==0) { r = read(fd,&pid2,100*sizeof(char)); } close(fd); unlink("fifo_clientTOserver"); //User is entering number of rows & columns in order to create the board write(1,"Enter number of rows\n",sizeof("Enter number of rows\n")); scanf("%d",&m); write(1,"Enter number of columns\n",sizeof("Enter number of columns\n")); scanf("%d",&n); sprintf(buffer,"p%d,%d,%d",pid1,m,n); strcpy(sm, buffer); while(1) { int row = convertTOint(sm+1); int psik = checkPsik(sm+1); int column = convertTOint(sm+psik+2); if ((row == m-1) && (column == n-1) && ((sm[0] == '1') || (sm[0] == '2'))) { break; } } sleep(1); write(1,"GAME OVER\n",strlen("GAME OVER\n")); shmdt(sm); shmctl(shm_id,IPC_RMID,NULL); return EXIT_SUCCESS; }
C
#include <stdio.h> #include <string.h> int convert(char x) { return(x - 32); } int main() { char letra; scanf("%c", &letra); printf("%c\n", convert(letra)); return(0); }
C
/* ** EPITECH PROJECT, 2020 ** str isprintable ** File description: ** project */ int my_str_isprintable(char const *str) { int i = 0; int j = 0; if (str[i] == '\0') { return (1); } for ( ; str[i] != '\0' ; i++) { if (str[i] > 31 && str[i] < 126) { j++; } else { return (0); } } if (j > 0) { return (1); } }
C
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <time.h> #include <string.h> #include "sort.h" int* create_array(char category, size_t n); int* create_array(char category, size_t n) { int *arr = NULL; arr = (int *) malloc(n*sizeof(int)); //assert(arr != NULL); if(category == 's') { for(unsigned long int i=0; i<n; i++) { arr[i] = i; } } else if(category == 'v') { for (unsigned long int j=n-1; j>0; j--) { arr[j] = j; } arr[0] = 0; } else if(category == 'r') { srand(time(NULL)); for (unsigned long int k=0; k<n; k++) { arr[k] = rand() % 500000; } } else { free(arr); return NULL; } return arr; } int main(int argc, char const *argv[]) { // time command is not an argument :P size_t size = atoi(argv[3]); int *a = create_array(*argv[2], size); for (unsigned long int i = 0; i < size; i++) { printf("%i ", a[i]); } printf("\n"); if(strcmp(argv[1], "select") == 0) { SelectionSort(a, size); } else if(strcmp(argv[1], "insert") == 0) { InsertionSort(a, size); } for (unsigned long int i = 0; i < size; i++) { printf("%i ", a[i]); } printf("\n"); free(a); return 0; } //gcc SelectionSort.o InsertionSort.o sorting.c -o sorting -Wall -W -std=c99 //Bobby said it was OK to use header files // *****TESTING******* /*int main(int argc, char const *argv[]) { int arr[] = {4, -2, 4, -5, 2, 12}; size_t size = sizeof(arr)/sizeof(arr[0]); SelectionSort(arr, size); for(unsigned int i=0; i<size; i++) { printf("%i ", arr[i]); } return 0; }*/
C
#include <math.h> #include <string.h> #include "mex.h" #include "flowlib.h" void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* Matrices for inputs, temp variable, and output. */ double *Img1, *Img2, *Dx, *Dy; // Dx, Dy return values and Img1 and Img2 /* Sizes */ mwSignedIndex nY, nX; /* Arguments */ int nLevel, nWarp, nIter, nDuals, errNo, nFields, iFields; /* Parameters */ double sFactor, lambda; /* More sizes */ mwSize nElems; mxArray *field; const char *fieldName; /* Set default values for all parameters. */ nLevel = 1000; sFactor = 0.9; nWarp = 1; nIter = 50; lambda = 50.0; nDuals = 6; /* Check for proper number of arguments. */ if ( nrhs != 3 ) { mexErrMsgIdAndTxt("MATLAB:estimateFlow:rhs", "This function requires 3 input arguments."); } if ( nlhs != 2) { mexErrMsgIdAndTxt("MATLAB:imresize:lhs", "This function requires 2 output argument."); } Img1 = mxGetPr(prhs[0]); Img2 = mxGetPr(prhs[1]); nY = (mwSignedIndex) mxGetM(prhs[0]); nX = (mwSignedIndex) mxGetN(prhs[0]); // Ensure that both Img1 and Img2 are 2D. if ( mxGetNumberOfDimensions(prhs[0]) != 2 || mxGetNumberOfDimensions(prhs[1]) != 2) { mexErrMsgIdAndTxt("MATLAB:estimateFlow2", "Img1/2 must be 2D matrices!"); } // Ensure that Img1 and Img2 have the same dimensions. if ( nY != (mwSignedIndex) mxGetM(prhs[1]) || nX != (mwSignedIndex) mxGetN(prhs[0]) ) { mexErrMsgIdAndTxt("MATLAB:estimateFlow2", "Img1/2 must have the same size."); } // Ensure that the 3rd input is a structure. if (!mxIsStruct(prhs[2])) { mexErrMsgIdAndTxt("MATLAB:estimateFlow2", "Third input must be a structure."); } nFields = mxGetNumberOfFields(prhs[2]); nElems = (mwSize) mxGetNumberOfElements(prhs[2]); // Assume that there is only one element for each field. if (nElems != 1) { mexErrMsgIdAndTxt("MATLAB:estimateFlow2", "Passed in multiple values for a field."); } // Ensure that fields are present and have the correct type. for (iFields = 0; iFields < nFields; ++iFields) { field = mxGetFieldByNumber(prhs[2], 0, iFields); if (field == NULL) { mexPrintf("%s%d\t%s%d\n", "Field number ", iFields+1, " and structure index ", 1); mexErrMsgIdAndTxt("MATLAB:estimateFlow", "Field is empty!"); } if( !mxIsChar(field) && !mxIsNumeric(field) ) { mexPrintf("%s%d\t%s%d\n", "Field number ", iFields+1, " and structure index ", 1); mexErrMsgIdAndTxt("MATLAB:estimateFlow", "Field must be either a string or a numeric value!"); } } // Pull the field values. for (iFields = 0; iFields < nFields; ++iFields) { fieldName = mxGetFieldNameByNumber(prhs[2], iFields); field = mxGetFieldByNumber(prhs[2], 0, iFields); //mexPrintf("Found field %s.\n", fieldName); if (strcmp("nLevel", fieldName) == 0) { nLevel = (int) mxGetScalar(field); } else if (strcmp("sFactor", fieldName) == 0) { sFactor = (double) mxGetScalar(field); } else if (strcmp("nWarp", fieldName) == 0) { nWarp = (int) mxGetScalar(field); } else if (strcmp("nIter", fieldName) == 0) { nIter = (int) mxGetScalar(field); } else if (strcmp("lambda", fieldName) == 0) { lambda = (double) mxGetScalar(field); } else { mexPrintf("Warning: Unknown field name %s.\n", fieldName); } } //mexPrintf("Info: Running estimateFlow with the parameters.\n"); //mexPrintf("nY = %d, nX = %d, nLevel = %d, sFactor = %2.2f, nWarp = %d, nIter = %d, lambda = %2.2f.\n", // nY, nX, nLevel, sFactor, nWarp, nIter, lambda); // Create space for the return values Dx, Dy. plhs[0] = mxCreateNumericMatrix(nY, nX, mxDOUBLE_CLASS, mxREAL); plhs[1] = mxCreateNumericMatrix(nY, nX, mxDOUBLE_CLASS, mxREAL); Dx = mxGetPr(plhs[0]); Dy = mxGetPr(plhs[1]); // 1 2 3 4 5 6 7 8 9 10 11 errNo = estimateFlow2(Dx, Dy, Img1, Img2, nX, nY, nLevel, sFactor, nWarp, nIter, lambda); if (errNo != 0) { mexPrintf("The error code is %d\n", errNo); mexErrMsgIdAndTxt("MATLAB:estimateFlow2", "Too small input size of the imags."); } }
C
/// \file /// \brief Реализация функций из ArchipelagoCollection.h /// \details Реализация функций из ArchipelagoCollection.h. #include <malloc.h> #include <assert.h> #include <string.h> #include "ArchipelagoCollection.h" ArchipelagoCollection* ArchipelagoCollectionCreate() { ArchipelagoCollection* pCollection = (ArchipelagoCollection*) malloc(sizeof(ArchipelagoCollection)); assert(pCollection); pCollection->pList = LinkedListCreate(); assert(pCollection->pList); return pCollection; } void ArchipelagoCollectionDestroy(ArchipelagoCollection* pCollection) { LinkedListDestroy(pCollection->pList); free(pCollection); } void ArchipelagoCollectionDestroyArchipelagos(ArchipelagoCollection* pCollection) { for (LinkedListNode* pIterator = ArchipelagoCollectionGetIterator(pCollection); pIterator != NULL; ArchipelagoCollectionIteratorNext(&pIterator)) { Archipelago* pArchipelago = ArchipelagoCollectionGetByIterator(pIterator); ArchipelagoDestroy(pArchipelago); } } void ArchipelagoCollectionAdd(ArchipelagoCollection* pCollection, Archipelago* pArchipelago) { LinkedListAppendElement(pCollection->pList, pArchipelago); } void ArchipelagoCollectionRemove(ArchipelagoCollection* pCollection, Archipelago* pArchipelago) { LinkedListRemoveElement(pCollection->pList, pArchipelago); } Archipelago* ArchipelagoCollectionFindByName( ArchipelagoCollection* pCollection, char* name) { for (LinkedListNode* pIterator = ArchipelagoCollectionGetIterator(pCollection); pIterator != NULL; ArchipelagoCollectionIteratorNext(&pIterator)) { Archipelago* pArchipelago = ArchipelagoCollectionGetByIterator(pIterator); if (strcmp(pArchipelago->Name, name) == 0) { return pArchipelago; } } return NULL; } Archipelago* ArchipelagoCollectionGetFirst( ArchipelagoCollection* pCollection) { return (Archipelago*) LinkedListGetFirstElement(pCollection->pList); } LinkedListNode* ArchipelagoCollectionGetIterator( ArchipelagoCollection* pCollection) { return LinkedListGetFirstNode(pCollection->pList); } Archipelago* ArchipelagoCollectionIteratorNext( LinkedListNode** ppArchipelagoIterator) { return ArchipelagoCollectionGetByIterator( LinkedListIteratorNext(ppArchipelagoIterator)); } Archipelago* ArchipelagoCollectionGetByIterator( LinkedListNode* pArchipelagoIterator) { return (Archipelago*) pArchipelagoIterator->pElement; }