language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* Collection of functions over a CFG boars structure that are not related to actual state changes nor tactical evaluation; though they may still be useful. */ #include "config.h" #include <stdlib.h> #include <string.h> #include <assert.h> #include "alloc.h" #include "board.h" #include "cfg_board.h" #include "flog.h" #include "move.h" #include "types.h" extern u8 out_neighbors8[TOTAL_BOARD_SIZ]; extern u8 out_neighbors4[TOTAL_BOARD_SIZ]; extern move_seq neighbors_side[TOTAL_BOARD_SIZ]; extern move_seq neighbors_diag[TOTAL_BOARD_SIZ]; extern move_seq neighbors_3x3[TOTAL_BOARD_SIZ]; extern bool border_left[TOTAL_BOARD_SIZ]; extern bool border_right[TOTAL_BOARD_SIZ]; extern bool border_top[TOTAL_BOARD_SIZ]; extern bool border_bottom[TOTAL_BOARD_SIZ]; extern u8 active_bits_in_byte[256]; /* Returns the first liberty found of the group (in no particular order). RETURNS a liberty of the group */ move get_1st_liberty( const group * g ) { assert(g->liberties > 0); for (u8 i = 0; i < LIB_BITMAP_SIZ; ++i) { if (g->ls[i]) { u8 j; for (j = 0; j < 7; ++j) { if (g->ls[i] & (1 << j)) { break; } } return i * 8 + j; } } flog_crit("cfg", "CFG group has no liberties"); exit(EXIT_FAILURE); /* this is unnecessary but mutes erroneous complaints */ } /* Returns a liberty of the group after the specified point. If the group has no more liberties then NONE is returned instead. RETURNS a liberty of the group */ move get_next_liberty( const group * g, move start /* exclusive */ ) { ++start; for (move m = start; m < TOTAL_BOARD_SIZ; ++m) { u8 mask = (1 << (m % 8)); if (g->ls[m / 8] & mask) { return m; } } return NONE; } /* Get closest group in the 3x3 neighborhood of a point. RETURNS group pointer or NULL */ group * get_closest_group( const cfg_board * cb, move m ) { for (u8 k = 0; k < neighbors_3x3[m].count; ++k) { move n = neighbors_3x3[m].coord[k]; if (cb->g[n] != NULL) { return cb->g[n]; } } return NULL; } /* Return the minimum amount of liberties of groups with stones adjacent to an intersection. RETURNS minimum number of liberties found, or NONE */ u16 min_neighbor_libs( const cfg_board * cb, move m, u8 stone ) { assert(is_board_move(m)); u16 ret = NONE; if (!border_left[m] && cb->p[m + LEFT] == stone) { ret = cb->g[m + LEFT]->liberties; } if (!border_right[m] && cb->p[m + RIGHT] == stone && cb->g[m + RIGHT]->liberties < ret) { ret = cb->g[m + RIGHT]->liberties; } if (!border_top[m] && cb->p[m + TOP] == stone && cb->g[m + TOP]->liberties < ret) { ret = cb->g[m + TOP]->liberties; } if (!border_bottom[m] && cb->p[m + BOTTOM] == stone && cb->g[m + BOTTOM]->liberties < ret) { ret = cb->g[m + BOTTOM]->liberties; } return ret; } /* Return the maximum amount of liberties of groups with stones adjacent to an intersection. RETURNS maximum number of liberties found, or 0 */ u8 max_neighbor_libs( const cfg_board * cb, move m, u8 stone ) { assert(is_board_move(m)); u8 ret = 0; if (!border_left[m] && cb->p[m + LEFT] == stone) { ret = cb->g[m + LEFT]->liberties; } if (!border_right[m] && cb->p[m + RIGHT] == stone && cb->g[m + RIGHT]->liberties > ret) { ret = cb->g[m + RIGHT]->liberties; } if (!border_top[m] && cb->p[m + TOP] == stone && cb->g[m + TOP]->liberties > ret) { ret = cb->g[m + TOP]->liberties; } if (!border_bottom[m] && cb->p[m + BOTTOM] == stone && cb->g[m + BOTTOM]->liberties > ret) { ret = cb->g[m + BOTTOM]->liberties; } return ret; } /* Tests whether a neighbor group of stone type stone has two liberties. RETURNS true if neighbor group is put in atari */ bool puts_neighbor_in_atari( const cfg_board * cb, move m, u8 stone ) { if (!border_left[m] && cb->p[m + LEFT] == stone && cb->g[m + LEFT]->liberties == 2) { return true; } if (!border_right[m] && cb->p[m + RIGHT] == stone && cb->g[m + RIGHT]->liberties == 2) { return true; } if (!border_top[m] && cb->p[m + TOP] == stone && cb->g[m + TOP]->liberties == 2) { return true; } return (!border_bottom[m] && cb->p[m + BOTTOM] == stone && cb->g[m + BOTTOM]->liberties == 2); } /* Return the maximum number of stones of a group of stones of value stone; adjacent to the intersection m. RETURNS maximum number of stones of a group, or 0 */ u16 max_neighbor_group_stones( const cfg_board * cb, move m, u8 stone ) { assert(is_board_move(m)); u16 ret = 0; if (!border_left[m] && cb->p[m + LEFT] == stone) { ret = cb->g[m + LEFT]->stones.count; } if (!border_right[m] && cb->p[m + RIGHT] == stone && cb->g[m + RIGHT]->stones.count > ret) { ret = cb->g[m + RIGHT]->stones.count; } if (!border_top[m] && cb->p[m + TOP] == stone && cb->g[m + TOP]->stones.count > ret) { ret = cb->g[m + TOP]->stones.count; } if (!border_bottom[m] && cb->p[m + BOTTOM] == stone && cb->g[m + BOTTOM]->stones.count > ret) { ret = cb->g[m + BOTTOM]->stones.count; } return ret; } /* Tests whether two groups have exactly the same liberties. RETURNS true if the groups have the exact same liberties */ bool groups_same_liberties( const group * restrict g1, const group * restrict g2 ) { return memcmp(g1->ls, g2->ls, LIB_BITMAP_SIZ) == 0; } /* Tests whether two groups share at least one liberty. RETURNS true if the groups share at least one liberty */ bool groups_share_liberties( const group * restrict g1, const group * restrict g2 ) { for (u8 i = 0; i < LIB_BITMAP_SIZ; ++i) { if ((g1->ls[i] & g2->ls[i]) > 0) { return true; } } return false; } /* Counts the number of shared liberties between two groups. RETURNS number of shared liberties */ u8 groups_shared_liberties( const group * restrict g1, const group * restrict g2 ) { u8 ret = 0; for (u8 i = 0; i < LIB_BITMAP_SIZ; ++i) { ret += active_bits_in_byte[g1->ls[i] & g2->ls[i]]; } return ret; }
C
// autor: Ana Luisa // autor: Gabriel Sylar // arquivo: L5211.c // atividade: 2.1.1 #include <stdio.h> #include <pthread.h> #include <unistd.h> pthread_mutex_t mutex; pthread_mutexattr_t attr; void bar() { printf("Tentando pegar o lock de novo.\n"); pthread_mutex_lock(&mutex); printf("Estou com duplo acesso?\n"); pthread_mutex_unlock(&mutex); } void *foo(void *empty) { pthread_mutex_lock(&mutex); printf("Acesso a região crı́tica.\n"); bar(); pthread_mutex_unlock(&mutex); } int main() { pthread_t t; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&mutex, &attr); pthread_create(&t, NULL, foo, NULL); pthread_join(t, NULL); pthread_mutex_destroy(&mutex); return 0; }
C
#include<stdio.h> int main() { int i,j,n; //double a; scanf("%d",&n); double a[n]; for(i=0;i<n;i++) { scanf("%lf",&a[i]); } int max = a[0]; for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(a[i]>a[j]) { int temp; temp = a[i]; a[i] = a[j]; a[j] = temp; } } } for(i=0;i<n;i++) { prinf("%lf",a[i]); } return 0; }
C
#include <stdio.h> #include "cuboid.h" double getLength() { double l; printf("Enter the length of the cuboid: "); scanf("%lf", &l); return l; } double getWidth() { double w; printf("Enter the width of the cuboid: "); scanf("%lf", &w); return w; } double getHeight() { double h; printf("Enter the height of the cuboid: "); scanf("%lf", &h); return h; } void showResults(Cuboid c) { printf("V=%.2f SA=%.2f", getVolume(c), getSurArea(&c)); printf(" (Cuboid: L=%.2f W=%.2f H=%.2f)\n", c.l, c.w, c.h); }
C
#include <string.h> #include "utils.h" int ymax(int a, int b) { return a < b ? b : a; } int wstrsize(wchar_t *szStr) { return (wcslen(szStr)+1) * sizeof(wchar_t) / sizeof(char); }
C
/* * Description: This sets up a generic timer that you can register. * Use TimerGetValue(<timer instance>) to get the certain timer instance value. * You can test the return value to see if the value is >= to a certain value * * * */ #include "LSP.h" #ifdef USE_MTIMERS #include "main.h" #include "mTimers.h" #include "main.h" #include "mTimers.h" #define MAX_TIMERS 16 // increase if more timers are needed volatile uint32_t genericTimer[MAX_TIMERS] = {0}; // array that holds timer values for each timer instance volatile uint8_t timerInstance = 0; // timer instance /* function: Declare an uint8_t variable in your code and save the pointer value called from this function. This variable will be used to GetTimer or SetTimer e.g. uint8_t myTimer = TimerRegister(); Note: Currently there is no function to unregister a timer. input: none output: the new timer instance pointer */ uint8_t TimerRegister(void) { if(timerInstance == MAX_TIMERS) { printf("Maximum timers reached!"); return 0; // added return 0; 10-10-17 } ++timerInstance; genericTimer[timerInstance] = 0;// clear the timer return timerInstance; } /* function: Call this function from SysTick_Handler() in stm32f1xx_it.c input: none output: none */ void TimerSYSTICK(void) { uint8_t i; if(timerInstance == 0) return; // no timers create so return for(i = 1; i < timerInstance + 1; i++) { // increment all timer instances genericTimer[i]++; } } /* function: Call this function to return the timer value input: The timer instance output: none */ uint32_t TimerGetValue(uint8_t timer) { return genericTimer[timer]; } /* function: Set the timer instance to a value, usually you would reset the value to zero. input: none output: none */ void TimerSetValue(uint8_t timer, uint32_t value) { genericTimer[timer] = value; } #endif // USE_MTIMERS
C
#pragma once struct Position { int x; int y; unsigned int tileID; Position() = default; Position(unsigned int tileID, int x, int y) : tileID{ tileID }, x { x }, y{ y } {}; void move(int dx, int dy); }; bool operator==(Position& position1, Position& position2); bool operator!=(Position& position1, Position& position2);
C
/** * helpers.c * * Helper functions for Problem Set 3. */ #define SWAP(A, B) { int t = A; A = B; B = t; } #include <cs50.h> #include <math.h> #include "helpers.h" /** * Returns true if value is in array of n values, else false. */ bool search(int value, int values[], int n) { if (n < 0) { return false; } int index = n/2; int temp = 2; while (values[index] != value){ if (round((float) n/(temp)) == 1){ return false; } if (values[index] > value){ index -= round((float) n/(2*temp)); } else { index += round((float) n/(2*temp)); } temp *= 2; } return true; } /** * Sorts array of n values. */ void sort(int values[], int n) { for (int i = 0; i < n - 1; i++){ for (int j = i + 1; j < n; j++){ if (values[i] > values[j]){ SWAP(values[i], values[j]); } } } }
C
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/ip.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <errno.h> #include <stdlib.h> #include <assert.h> #include <pthread.h> #include <fcntl.h> #include <poll.h> #define DX 5e-10 struct arg { double from; double to; double res; int num; }; int handleInt(const char *str, int *num); int setup_connection(); void *threadRoutine(void *args); int main(int argc, char **argv) { if (argc == 1) { printf("Missing argument\n"); return 1; } int n = 0; if (handleInt(argv[1], &n)) { return 1; } int conn = setup_connection(); send(conn, &n, sizeof(int), 0); struct arg *args = calloc(n, sizeof(struct arg)); pthread_t *threads = calloc(n, sizeof(pthread_t)); int running = 0; char tmp = 0; do { if (recv(conn, &tmp, sizeof(char), MSG_PEEK) == 0) break; running = 0; for (int i = 0; i < n; i++) { if (recv(conn, &tmp, sizeof(char), MSG_PEEK | MSG_DONTWAIT) < 0) break; recv(conn, &(args[i].num), sizeof(int), 0); recv(conn, &(args[i].from), sizeof(double), 0); recv(conn, &(args[i].to), sizeof(double), 0); // printf("%d:%g, %g\n", args[i].num, args[i].from, args[i].to); if (pthread_create(&(threads[i]), NULL, threadRoutine, (void *)(args + i)) != 0) { printf("Failed to create threads\n"); exit(1); } running++; } // exit(1); for (int i = 0; i < running; i++) { if (pthread_join(threads[i], NULL) != 0) { printf("Failed to join threads\n"); return 1; } send(conn, &(args[i].res), sizeof(double), 0); send(conn, &(args[i].num), sizeof(int), 0); // printf("%d:%g\n", args[i].num, args[i].res); // exit(1); } } while (recv(conn, &tmp, sizeof(char), MSG_PEEK | MSG_DONTWAIT) != 0); free(threads); free(args); close(conn); } int handleInt(const char *str, int *num) { errno = 0; char *endp = NULL; *num = strtol(str, &endp, 10); if (errno == ERANGE) { printf("You've entered too big number. Unable to comply\n"); return 1; } if (*num < 0) { printf("You've entered negative number. Unable to comply\n"); return 1; } if (endp == str) { printf("You've entered nothing like number. Unable to comply\n"); return 1; } if (*num == 0) { printf("You've entered 0. So?"); return 1; } return 0; } int setup_connection() { struct sockaddr_in server_addr = { .sin_family = AF_INET, .sin_port = htons(9009), .sin_addr.s_addr = INADDR_ANY }; int udp = socket(AF_INET, SOCK_DGRAM, 0); int broadcast = 1; if (setsockopt(udp, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast))) { perror("Failed to make broadcast socket"); exit(1); } if (bind(udp, (struct sockaddr *) &server_addr, sizeof(server_addr))) { perror("Error binding"); exit(1); } socklen_t len = sizeof(struct sockaddr_in); char buf[50] = ""; int buflen = 50; struct sockaddr_in client_addr = {}; recvfrom(udp, buf, buflen, 0, (struct sockaddr *) &client_addr, &len); if (strcmp(buf, "Request") != 0) exit(0); char response[] = "Response"; sendto(udp, response, strlen(response) + 1, 0, (struct sockaddr *) &client_addr, sizeof(client_addr)); close(udp); int tcp = socket(AF_INET, SOCK_STREAM, 0); int option = 1; setsockopt(tcp, SOL_SOCKET, SO_REUSEPORT, &option, sizeof(int)); fcntl(tcp, F_SETFL, O_NONBLOCK); if (bind(tcp, (struct sockaddr *) &server_addr, sizeof(server_addr))) { perror("Error binding"); exit(1); } listen(tcp, 256); struct pollfd tcp_poll = { .fd = tcp, .events = POLLIN }; if (poll(&tcp_poll, 1, 2000) == 0) { printf("Peer died\n"); exit(1); } int conn = accept(tcp, (struct sockaddr *) &client_addr, &len); if (conn < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) { printf("Peer died\n"); exit(1); } close(tcp); return conn; } double f(double x) { return x; } void *threadRoutine(void *args) { assert(args); struct arg *arg = (struct arg *) args; double from = arg->from; double to = arg->to; double sum = 0; double fcur = f(from); double fprev = 0; for (double x = from; x <= to; x += DX) { fprev = fcur; fcur = f(x); sum += (fprev + fcur) / 2 * DX; } arg->res = sum; return NULL; }
C
/* * Author: Nikhil Jagdale * Description: This program provides dummy GPS co-odrindates generated ramdomly * along with the current system date and time. Information is packed * in a struct for the client to further process * * Copyright (c) 2015 Nikhil Jagdale */ #include "GPS.h" static int GetRandomLatitide(){ srand(time(NULL)); return rand()%90; } static int GetRandomLongitude(){ //srand(time(NULL)); return rand()%180; } void GetGPSInfo(gps_info* data){ time_t rawtime; time(&rawtime); data->latitude = GetRandomLatitide(); data->longitude = GetRandomLongitude(); data->timeinfo = localtime(&rawtime); }
C
#include "common.h" #include "vga.h" extern char get_char(); int str2int(char *b, int i); int read_int(char *prompt) { // display prompt draw_string(prompt); // read char buffer[20]; int i = 0; char c; while( (c = get_char()) != '\n' ) { buffer[i ++] = c; } buffer[i] = '\0'; return str2int(buffer, --i); } int str2int(char *str, int m) { int n = 0; //for (int i = m; i >= 0; i --) { for (int i = 0; i <= m; i ++) { n = n * 10 + ( (str[i]) - '0' ); } return n; } char read_char() { char c = get_char(); return c; }
C
#include "hash_tables.h" /** *hash_table_delete - deletes a hash table *@ht: hashtable used * * Return: void */ void hash_table_delete(hash_table_t *ht) { hash_node_t *temp, *ptr; unsigned long int count; if (!ht) return; for (count = 0; count < ht->size; count++) { ptr = ht->array[count]; while (ptr) { temp = ptr->next; free(ptr->key); free(ptr->value); free(ptr); ptr = temp; } } free(ht->array); free(ht); }
C
/*Lee un maximo de caracteres del teclado y lo guarda en el puntero dado. Si hay * mas caracteres de los que se pueden leer estos son descartados * ARGUMENTOS: * cadena: Un array o puntero de tamano maximo+1 (debe haber espacio para * el NULL final) en donde se va a guardar la lectura del teclado * tamano: El tamano del array, vamos a leer (tamano-1) caracteres del * teclado*/ void leer_teclado(char *cadena, int tamano); /*Verifica si la cadena (DEBE TERMINAR EN NULL) contiene solo numeros. * Se puede usar sscanf para convertir a int los numeros en la cadena una * vez que se haya comprobado que son numeros * ARGUMENTOS: * cadena: Un string a verificar que contenga solo numeros * tamano: El tamano del string a verificar * RETORNO: 1 si es un numero, 0 si no es un numero lo que contiene * */ int revisar_numero(char *cadena, int tamano); /*Saca todos los caracteres que no han sido leidos del teclado del buffer*/ void limpiar_buffer();
C
// // Created by puzankova 30.05.18 // #include "priority_queue.h" #define ALLOCATE(t, n) (t *) malloc((n) * sizeof(t)) struct Node { double value; int key; struct Node* next; struct Node* prev; }; int capacity = 0; struct Node *highest = NULL; void restore_props() { struct Node *cur = highest; while(cur->prev != NULL && cur->key > cur->prev->key) { struct Node *max = cur; struct Node *min = cur->prev; if (max->next != NULL) min->next = max->next; else min->next = NULL; max->prev = min->prev; max->next = min; min->prev = max; if (cur == highest) highest = min; else min->next->prev = min; cur = max; } } int insert(double value, int key) { // return the exit code: // 0 - success // 1 - not enough free space in the queue // 2 - other // the queue size is 100 elements if (capacity < 100) { struct Node *temp = ALLOCATE(struct Node, 1); if (temp == NULL) { return 1; } temp->key = key; temp->value = value; temp->prev = highest; temp->next = NULL; if (highest != NULL) highest->next = temp; highest = temp; restore_props(); capacity++; return 0; } else return 1; } double extract_min() { // returns the min value and delete it from queue // if queue is empty returns -infinity and print error message to the screen struct Node *temp = highest; if (highest != NULL) { highest = highest->prev; if (highest != NULL) { highest->next = NULL; } restore_props(); capacity--; return temp->value; } else { printf("What the hack are you doing with my queue???"); return INT64_MIN; } }
C
#include <stdio.h> #include <stdlib.h> typedef unsigned char Byte; typedef unsigned short USHORT; typedef struct h_tree{ Byte symbol; int frequency; struct h_tree *left; struct h_tree *right; } Node; typedef Node* NODE; NODE create_node(){ NODE htree = (NODE) malloc(sizeof(Node)); htree->left = NULL; htree->right = NULL; htree->frequency = 0; return htree; } NODE buildTree(NODE root, Byte *tree, int *index, int treeSize) { NODE node = create_node(); if(tree[*index] == '*')//nó interno { node -> symbol = '*'; ++(*index); node -> left = buildTree(node,tree,index,treeSize); ++(*index); node -> right = buildTree(node, tree,index, treeSize); } else // é folha { if(tree[*index] == '\\')// se a folha começar com '\' existem duas possibilidades para o próximo char na leitura { if(tree[++(*index)] == '\\' && (*index)<treeSize) // a folha é do tipo '\\' { node -> symbol = '\\'; return node; } if(tree[++(*index)] == '*' && (*index)<treeSize)// a folha é do tipo '\*' { node -> symbol = '*'; return node; } } else if(!(*index)<treeSize){ //Caso não tenha '\' , a folha será qualquer outro caractere node -> symbol = tree[*index]; return node; } } } void preOrder_tree(NODE node) { if(node == NULL) { return; } printf("%c",node->symbol); preOrder_tree(node->left); preOrder_tree(node->right); } int is_bit_i_set(USHORT b, int i){ USHORT mask = 1 << i; return mask & b; } void print_bits_byte(USHORT b, int go_to_next_line) { int i; for(i = 0; i < 16; i++) { if(is_bit_i_set(b,i)) { printf("%d", 1); } else { printf("%d", 0); } } if (go_to_next_line) { printf("\n"); } } int read_Header(FILE *file, Byte *tree_array, Byte *trash) { USHORT sizeTree = 0; Byte first_byte, second_byte,tree_byte; first_byte = fgetc(file); // Pega o primeiro Byte do arquivo second_byte = fgetc(file); // Pega o segundo Byte do arquivo (*trash) = first_byte >> 5; // Shift bit pra esquerda para obter apenas os 3 bits do lixo, ex: 10100000 ~ (>>5) ~ 00000101 first_byte = first_byte << 3; // Shift bit pra esquerda para retirar o lixo, ex: 11000001 ~ 00001000 first_byte = first_byte >> 3; // Shift bit pra direita para voltr ao lugar (já sem o lixo): 00001000 ~ 00000001 sizeTree = first_byte; //atribui o Byte "first_byte" modificado ao USHORT sizeTree sizeTree = sizeTree << 8; // Shift bit para a esquerda para deixar as oito primeiro posições livres para o second_byte sizeTree |= second_byte; // concatena USHORT com Byte (através do operador "OU") // printf("trash = %d sizeTree = %d\n", *trash, sizeTree); // print apenas para teste int i; for(i = 0; i < sizeTree; i++) // lê a árvore e coloca no array { tree_byte = fgetc(file); tree_array[i] = tree_byte; } return sizeTree; //retorna o tamanho para ser usado na função BuildTree } int main() { int i = 0; Byte input[256]; // Array que recebe o nome do arquivo a ser descompactado Byte tree_array[256] = {0}; // Array que receberá a arvore lida no cabeçalho Byte trash = 0; // Lixo que será passado como ponteiro para a função de leitura do cabeçalho /* scanf("%s", input); // Ler o nome do arquivo a ser descomprimidio FILE *file = fopen(input,"rb"); //Forma Final para ler qualquer arquivo */ FILE *file = fopen("new.txt","rb"); // Para teste com o arquivo test.txt int sizeTree = read_Header(file,tree_array,&trash); // Ler o Cabeçalho e retorna o tamanho da árvore NODE root = buildTree(NULL,tree_array,&i,sizeTree); //Montar a árvore e retorna o nó raíz // preOrder_tree(root); // Apenas para teste: Printa a árvore em pré ordem puts(""); fclose(file); return 0; }
C
#include <stdlib.h> #include <stdio.h> int main(int argc, char * argv[]) { if (argc < 3) fprintf(stdout, "Il faut donner un mot et une phrase en arguments sur la ligne de commande.\n"); else { int taille = 0; while(argv[1][taille]!= '\0'){ taille++; } char * mot_a_trouver = malloc(sizeof(char)*(taille+1)); taille = 0; while(argv[1][taille]!='\0'){ mot_a_trouver[taille] = argv[1][taille]; taille++; } mot_a_trouver[taille]='\0'; taille = 0; int nb_mots = 1; while(argv[2][taille]!='\0'){ if((argv[2][taille] == ' ') || (argv[2][taille] == '\'')) nb_mots++; taille++; } char ** phrase = malloc(sizeof(char*)*(nb_mots)); taille = 0; nb_mots = 0; int nb_lettres = 0; while(argv[2][taille]!='\0'){ if(argv[2][taille] == ' ' || argv[2][taille] =='\''){ if(argv[2][taille] == '\'') nb_lettres++; phrase[nb_mots] = malloc(sizeof(char)*(nb_lettres + 1)); nb_mots++; nb_lettres = 0; } else nb_lettres++; taille++; } phrase[nb_mots] = malloc(sizeof(char)*(nb_lettres + 1)); taille = 0; nb_mots = 0; nb_lettres = 0; while(argv[2][taille]!='\0'){ if(argv[2][taille] == ' ' || argv[2][taille] =='\''){ if (argv[2][taille] == '\''){ phrase[nb_mots][nb_lettres] = '\''; nb_lettres++; } phrase[nb_mots][nb_lettres] = '\0'; nb_mots++; nb_lettres = 0; } else { phrase[nb_mots][nb_lettres] = argv[2][taille]; nb_lettres++; } taille++; } phrase[nb_mots][nb_lettres] = '\0'; char ** phrase_sans_ponctuation = malloc(sizeof(char*)*(nb_mots+1)); for(int i = 0 ; i < nb_mots+1 ; i++){ taille = 0; int j = 0; while(phrase[i][j] != '\0'){ switch(phrase[i][j]){ case 'a' : taille++; break; case 'b' : taille++; break; case 'c' : taille++; break; case 'd' : taille++; break; case 'e' : taille++; break; case 'f' : taille++; break; case 'g' : taille++; break; case 'h' : taille++; break; case 'i' : taille++; break; case 'j' : taille++; break; case 'k' : taille++; break; case 'l' : taille++; break; case 'm' : taille++; break; case 'n' : taille++; break; case 'o' : taille++; break; case 'p' : taille++; break; case 'q' : taille++; break; case 'r' : taille++; break; case 's' : taille++; break; case 't' : taille++; break; case 'u' : taille++; break; case 'v' : taille++; break; case 'w' : taille++; break; case 'x' : taille++; break; case 'y' : taille++; break; case 'z' : taille++; break; case 'A' : taille++; break; case 'B' : taille++; break; case 'C' : taille++; break; case 'D' : taille++; break; case 'E' : taille++; break; case 'F' : taille++; break; case 'G' : taille++; break; case 'H' : taille++; break; case 'I' : taille++; break; case 'J' : taille++; break; case 'K' : taille++; break; case 'L' : taille++; break; case 'M' : taille++; break; case 'N' : taille++; break; case 'O' : taille++; break; case 'P' : taille++; break; case 'Q' : taille++; break; case 'R' : taille++; break; case 'S' : taille++; break; case 'T' : taille++; break; case 'U' : taille++; break; case 'V' : taille++; break; case 'W' : taille++; break; case 'X' : taille++; break; case 'Y' : taille++; break; case 'Z' : taille++; break; case '0' : taille++; break; case '1' : taille++; break; case '2' : taille++; break; case '3' : taille++; break; case '4' : taille++; break; case '5' : taille++; break; case '6' : taille++; break; case '7' : taille++; break; case '8' : taille++; break; case '9' : taille++; break; case '\'' : taille++; break; } j++; } phrase_sans_ponctuation[i] = malloc(sizeof(char) * (taille+1)); j=0; taille = 0; while(phrase[i][j] != '\0'){ switch(phrase[i][j]){ case 'a' : phrase_sans_ponctuation[i][taille] = 'a'; taille++; break; case 'b' : phrase_sans_ponctuation[i][taille]='b'; taille++; break; case 'c' : phrase_sans_ponctuation[i][taille]='c'; taille++; break; case 'd' : phrase_sans_ponctuation[i][taille]='d'; taille++; break; case 'e' : phrase_sans_ponctuation[i][taille]='e'; taille++; break; case 'f' : phrase_sans_ponctuation[i][taille]='f'; taille++; break; case 'g' : phrase_sans_ponctuation[i][taille]='g'; taille++; break; case 'h' : phrase_sans_ponctuation[i][taille]='h'; taille++; break; case 'i' : phrase_sans_ponctuation[i][taille]='i'; taille++; break; case 'j' : phrase_sans_ponctuation[i][taille]='j'; taille++; break; case 'k' : phrase_sans_ponctuation[i][taille]='k'; taille++; break; case 'l' : phrase_sans_ponctuation[i][taille]='l'; taille++; break; case 'm' : phrase_sans_ponctuation[i][taille]='m'; taille++; break; case 'n' : phrase_sans_ponctuation[i][taille]='n'; taille++; break; case 'o' : phrase_sans_ponctuation[i][taille]='o'; taille++; break; case 'p' : phrase_sans_ponctuation[i][taille]='p'; taille++; break; case 'q' : phrase_sans_ponctuation[i][taille]='q'; taille++; break; case 'r' : phrase_sans_ponctuation[i][taille]='r'; taille++; break; case 's' : phrase_sans_ponctuation[i][taille]='s'; taille++; break; case 't' : phrase_sans_ponctuation[i][taille]='t'; taille++; break; case 'u' : phrase_sans_ponctuation[i][taille]='u'; taille++; break; case 'v' : phrase_sans_ponctuation[i][taille]='v'; taille++; break; case 'w' : phrase_sans_ponctuation[i][taille]='w'; taille++; break; case 'x' : phrase_sans_ponctuation[i][taille]='x'; taille++; break; case 'y' : phrase_sans_ponctuation[i][taille]='y'; taille++; break; case 'z' : phrase_sans_ponctuation[i][taille]='z'; taille++; break; case 'A' : phrase_sans_ponctuation[i][taille]='A'; taille++; break; case 'B' : phrase_sans_ponctuation[i][taille]='B'; taille++; break; case 'C' : phrase_sans_ponctuation[i][taille]='C'; taille++; break; case 'D' : phrase_sans_ponctuation[i][taille]='D'; taille++; break; case 'E' : phrase_sans_ponctuation[i][taille]='E'; taille++; break; case 'F' : phrase_sans_ponctuation[i][taille]='F'; taille++; break; case 'G' : phrase_sans_ponctuation[i][taille]='G'; taille++; break; case 'H' : phrase_sans_ponctuation[i][taille]='H'; taille++; break; case 'I' : phrase_sans_ponctuation[i][taille]='I'; taille++; break; case 'J' : phrase_sans_ponctuation[i][taille]='J'; taille++; break; case 'K' : phrase_sans_ponctuation[i][taille]='K'; taille++; break; case 'L' : phrase_sans_ponctuation[i][taille]='L'; taille++; break; case 'M' : phrase_sans_ponctuation[i][taille]='M'; taille++; break; case 'N' : phrase_sans_ponctuation[i][taille]='N'; taille++; break; case 'O' : phrase_sans_ponctuation[i][taille]='O'; taille++; break; case 'P' : phrase_sans_ponctuation[i][taille]='P'; taille++; break; case 'Q' : phrase_sans_ponctuation[i][taille]='Q'; taille++; break; case 'R' : phrase_sans_ponctuation[i][taille]='R'; taille++; break; case 'S' : phrase_sans_ponctuation[i][taille]='S'; taille++; break; case 'T' : phrase_sans_ponctuation[i][taille]='T'; taille++; break; case 'U' : phrase_sans_ponctuation[i][taille]='U'; taille++; break; case 'V' : phrase_sans_ponctuation[i][taille]='V'; taille++; break; case 'W' : phrase_sans_ponctuation[i][taille]='W'; taille++; break; case 'X' : phrase_sans_ponctuation[i][taille]='X'; taille++; break; case 'Y' : phrase_sans_ponctuation[i][taille]='Y'; taille++; break; case 'Z' : phrase_sans_ponctuation[i][taille]='Z'; taille++; break; case '0' : phrase_sans_ponctuation[i][taille]='0'; taille++; break; case '1' : phrase_sans_ponctuation[i][taille]='1'; taille++; break; case '2' : phrase_sans_ponctuation[i][taille]='2'; taille++; break; case '3' : phrase_sans_ponctuation[i][taille]='3'; taille++; break; case '4' : phrase_sans_ponctuation[i][taille]='4'; taille++; break; case '5' : phrase_sans_ponctuation[i][taille]='5'; taille++; break; case '6' : phrase_sans_ponctuation[i][taille]='6'; taille++; break; case '7' : phrase_sans_ponctuation[i][taille]='7'; taille++; break; case '8' : phrase_sans_ponctuation[i][taille]='8'; taille++; break; case '9' : phrase_sans_ponctuation[i][taille]='9'; taille++; break; case '\'' : phrase_sans_ponctuation[i][taille]='\''; taille++; break; } j++; phrase_sans_ponctuation[i][taille]='\0'; } } int found = 0; int j = 0; while(j < nb_mots+1 && !found){ int res = 0; int end = 0; int i = 0; while(!end){ end = (mot_a_trouver[i] == '\0') || (phrase_sans_ponctuation[j][i] == '\0') || (mot_a_trouver[i] != phrase_sans_ponctuation[j][i]); if (mot_a_trouver[i] == phrase_sans_ponctuation[j][i]) res = 1; else res = 0; i++; } j++; found = found || res; } if(found) printf("VRAI.\n"); else printf("FAUX.\n"); } return 1; }
C
/* This program initializes 3 (3x4) 2D arrays. It then multiplies the elements of the 1st and 2nd array and stores the answer of each in the elements of the 3rd array. Author: Robert Eviston Date: 18th November 2013 */ #include <stdio.h> #define ROW 3 #define COL 4 main() { int matrix1[ROW][COL]; int matrix2[ROW][COL]; int matrix3[ROW][COL]; int i; int j; printf("Please enter 24 values into the following array\n\n"); for (i=0;i<ROW;i++) { for (j=0;j<COL;j++) { scanf("%d", &matrix1[i][j]); }// End second for () }// End outter for () for (i=0;i<ROW;i++) { for (j=0;j<COL;j++) { scanf("%d", &matrix2[i][j]); flushall(); }// End second for () }// End outter for () for (i=0;i<ROW;i++) { for (j=0;j<COL;j++) { matrix3[i][j] = (matrix1[i][j] * matrix2[i][j]); }// End second for () }// End outter for () for (i=0;i<ROW;i++) { for (j=0;j<COL;j++) { printf("%d, ", matrix3[i][j]); }// End second for () }// End outter for () getchar(); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* error.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ale-goff <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/05/16 14:00:30 by anjansse #+# #+# */ /* Updated: 2019/06/02 15:22:44 by anjansse ### ########.fr */ /* */ /* ************************************************************************** */ #include <lem_in.h> static int elem_in_array(char **array) { int i; i = -1; while (array[++i]) ; return (i); } static void check_coord(char **array) { if (*array) { array++; while (*array) { if (!(ft_isdigit(**array))) send_error(); array++; } } } void send_error(void) { ft_putstr_fd("\x1b[91mERROR\n", 2); exit(1); } int check_error(char *str) { char **split; char **split2; if (str[0] == 'L') return (1); split = ft_strsplit(str, ' '); split2 = ft_strsplit(str, '-'); check_coord(split); if (str[0] != '#' && (elem_in_array(split) != 3 && \ elem_in_array(split2) != 2)) send_error(); if (split) { if (split[0] && split[1] && split[2]) free(split[2]); ft_freemap(split, 2); } if (split2) ft_freemap(split2, 2); return (0); }
C
/** ****************************************************************************** * @file crc.c * @author SE4 Sistemi Embedded Team (Di Fiore Giovanni, Iannucci Federico, Miranda Salvatore) * @version V1.0 * @date 05/lug/2015 * @brief TODO: brief for crc.c ****************************************************************************** */ /* Includes ********************************************************************/ #include "utils/crc.h" #include "stm32f4xx_hal.h" /** * @addtogroup CAL_Module * @{ */ /** * @addtogroup CAL_UTILS CAL Utils * @brief Moduli di utilità utilizzati da CAL * @{ */ /** * @addtogroup CAL_UTILS_CRC CRC Module * @brief Fornisce le funzione per l'accesso all'hardware per il calcolo di un CRC-32. * @{ */ /* Private Constants ***********************************************************/ /* Private Macros **************************************************************/ /* Private Types ***************************************************************/ /** * @defgroup CAL_UTILS_CRC_Private_Types Private Types * @brief Tipi privati * @{ */ CRC_HandleTypeDef CrcHandle; /**< Handle della periferica CRC */ /** * @} */ /* Private Variables ***********************************************************/ /* Private Functions ***********************************************************/ /* Exported Constants **********************************************************/ /* Exported Macros *************************************************************/ /* Exported Types **************************************************************/ /* Exported Variables **********************************************************/ /* Exported Functions **********************************************************/ /** * @addtogroup CAL_UTILS_CRC_Exported_Functions Exported Functions * @brief Funzioni esportate * @{ */ /** * @brief Inizializza il CRC-Calculator * @retval none */ uint8_t crcInit() { CrcHandle.Instance = CRC; if (HAL_CRC_Init(&CrcHandle) == HAL_OK) { return 1; } return 0; } /** * @brief De-inizializza il CRC-Calculator * @retval none */ uint8_t crcDeInit() { if (HAL_CRC_DeInit(&CrcHandle) == HAL_OK) { return 1; } return 0; } uint8_t crcCheckState() { return HAL_CRC_GetState(&CrcHandle) == HAL_CRC_STATE_READY; } /** * @brief Calcola un CRC-32 bit * @param in data Dati su cui calcolarlo * @param in length Lunghezza dei dati * @retval CRC-32 */ uint32_t crcCalculate(uint32_t* data, uint32_t length) { return HAL_CRC_Calculate(&CrcHandle, data, length); } /** * @} */ /* HAL Dependant ****************************************************************/ /** * @defgroup CAL_UTILS_CRC_HAL_Dependant Hardware Dependant Functions * @brief Funzioni per la configurazione dell'hardware sottostante. * @{ */ /** * @brief CRC MSP Initialization * This function configures the hardware resources used in this example: * - Peripheral's clock enable * @param hcrc: CRC handle pointer * @retval None */ void HAL_CRC_MspInit(CRC_HandleTypeDef *hcrc) { (void)hcrc; /* CRC Peripheral clock enable */ __HAL_RCC_CRC_CLK_ENABLE(); } /** * @brief CRC MSP De-Initialization * This function freeze the hardware resources used in this example: * - Disable the Peripheral's clock * @param hcrc: CRC handle pointer * @retval None */ void HAL_CRC_MspDeInit(CRC_HandleTypeDef *hcrc) { (void)hcrc; /* Enable CRC reset state */ __HAL_RCC_CRC_FORCE_RESET(); /* Release CRC from reset state */ __HAL_RCC_CRC_RELEASE_RESET(); } /** * @} */ /** * @} */ /** * @} */ /** * @} */ /** * @} */
C
#include <stdio.h> #include <stdlib.h> #include <math.h> int main () { float N1, N2, M; printf("Informe a nota 1: "); scanf("%f", &N1); printf("Informe a nota 2: "); scanf("%f", &N2); if(N1>=0 || N2>=0) { M = (N1+N2)/2; if(M<4) { printf("Reprovado"); } else { if(M>7) { printf("Aprovado!"); } else { printf("Esta em prova final!"); } } } else { printf("informe valores vlidos!"); } return 0; }
C
#ifndef __M_SERIAL_H_ #define __M_SERIAL_H_ #include<windows.h> /** * @brief serial_exists * * Check if a serial port exist * * @param[in] port number of port: 7 for "COM7" * * @return TRUE if serial port found, FALSE when not found */ BOOL serial_exist( int port); /** * @brief serial_open * * Open a serial port by name, like "\\.\COM9" or "COM1" * * @return a Handle on Serial port opened, on error return NULL */ HANDLE serial_open( char *serialPort); /** * @brief serial_config * * Configure an opened serial port * * @param[in] hComm Handle to opened serial port * @param[in] speed baudrate, use CBR_9600,CBR_115200 like value * @param[in] parity use NOPARITY, EVENPARITY, MARKPARITY ... * @return FALSE on error */ BOOL serial_config(HANDLE hComm, int speed, int parity); /** * @brief serial_write * * @param[in] hComm Handle to opened serial port * @param[in] lpBuffer buffer to data to write * @param[in] dNoOFBytestoWrite byte count to write on serial port from lpBuffer * @param[out] dNoOfBytesWritten byte count really written after the call * @return FALSE on error */ BOOL serial_write(HANDLE hComm, char *lpBuffer, DWORD dNoOFBytestoWrite, DWORD *dNoOfBytesWritten); /** * @brief serial_read * * @param[in] hComm Handle to opened serial port * @param[out] ReadBuffer buffer to retrieve data, shall be allocated by caller * @param[in] dNoOfBytesToRead byte count to read from serial port to ReadBuffer * @param[out] dNoOfBytesReallyRead byte count really read after the call * @return FALSE on error */ BOOL serial_read(HANDLE hComm, char *ReadBuffer,DWORD dNoOfBytesToRead, DWORD *dNoOfBytesReallyRead); /** * @brief serial_flush * * Flush serial port (only RX ?) * * @param[in] hComm Handle to opened serial port */ void serial_flush(HANDLE hComm); /** * @brief serial_check_error * * Get error status and FIFO status * This function flush all buffer RX+TX on error (design choice) * * @param[in] hComm Handle to opened serial port * @param[out] inqueue return current input queue size in bytes, can be NULL if not needed * @param[out] outqueue return current output queue size in bytes, can be NULL if not needed * @param[out] error return current error when case, 0 when ok, can be NULL if not needed * @return FALSE on error * @return TRUE when OK */ BOOL serial_check_error(HANDLE hComm, DWORD *inqueue, DWORD *outqueue, DWORD *error); /** * @brief serial_close * @param[in] hComm Handle to opened serial port */ void serial_close(HANDLE hComm); #endif /* __M_SERIAL_H_ */
C
//选择排序 void SelectSort(int *array, int size) { for (int i = 0; i < size - 1; i++) { int MaxPos = 0; for (int j = 1; j < size-i; j++) { if (array[j]>array[MaxPos]) { MaxPos = j; } } if (MaxPos != size - i - 1) { Swap(&array[MaxPos], &array[size - 1 - i]); } } } void SelectSortOP(int *array, int size) { int begin = 0; int end = size - 1; while (begin<=end) { int Maxpos = begin;//标记最大数 int Minpos = begin;//标记最小数 for (int i = begin; i <= end; i++) { if (array[i] > array[Maxpos]) Maxpos = i; if (array[i] < array[Minpos]) Minpos = i; } Swap(&array[begin], &array[Minpos]); //if (Maxpos == begin) //{ // Maxpos = Minpos; //} Swap(&array[end], &array[Maxpos]); begin++; end--; } }
C
#include <stdio.h> int main() {//Вывести все различные элементы последовательности, упорядоченные по возрастанию. int N, a=0, b=0, i=0; scanf ("%d", &N); for (i; i<N; i++) { a=b; scanf ("%d", &b); if (b!=a) printf ("%d ", b); } return 0; }
C
//IEEE Giresun SB //Bubble Sort Algorithm #include <stdio.h> #include <stdlib.h> //rand() ve srand() için stdlib kütüphanesi ekleniyor #define BOYUT 100000 //BOYUT ismindi dizi boyutu için sabit tanımlanıyor int main(void) { int dizi[BOYUT] = {0}; //Dizinin her ekemanına sıfır atanıyor size_t i, gecis; //Gerekli sayaçlar int swap; //Elemanların dizide yerlerini değiştirmek için kullanılacak değişken srand(time(NULL)); //DİZİYİ EKRANA YAZDIR. for(i = 0; i < BOYUT; i++) { dizi[i] = rand() % 100; printf("%d ", dizi[i]); } puts(""); //=printf("\n"); for(gecis = 0; gecis < BOYUT; gecis++) { //Yer değiştimelerin hepsini yapmak için gerekli döngü for(i = 0; i < BOYUT - 1; i++) { //Dizideki tüm ikili elemanların karşılaştırlılması için gerekli döngü if(dizi[i] > dizi[i + 1]) { //Eğer soldaki sayı sağdakinden büyük ise yerlerini değiştir // printf("Swap\tDizi[%d]\tDizi[%d]\n", i, i+1); // printf("%d\t%d\t%d\n", swap, dizi[i], dizi[i + 1]); swap = dizi[i]; // printf("%d\t%d\t%d\n", swap, dizi[i], dizi[i + 1]); dizi[i] = dizi[i + 1]; // printf("%d\t%d\t%d\n", swap, dizi[i], dizi[i + 1]); dizi[i + 1] = swap; // printf("%d\t%d\t%d\n", swap, dizi[i], dizi[i + 1]); } } } //Sıralanmış dizi ekran yazdırılıyor for(i = 0; i < BOYUT; i++) { printf("%d ", dizi[i]); } return 0; }
C
#include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <pthread.h> #include <netinet/in.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/types.h> int main(int argc, const char * argv[]) { setbuf(stdout, 0); int sock_fd = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in sock; inet_aton(argv[1], &(sock.sin_addr)); sock.sin_port = htons(atoi(argv[2])); sock.sin_family = AF_INET; connect(sock_fd, (struct sockaddr*)&sock, sizeof(sock)); int file_fd = open(argv[3], O_RDONLY); struct stat entryInfo; lstat(argv[3], &entryInfo); char* text = (char*)mmap(NULL, entryInfo.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, file_fd, 0); char* strToSend = strtok (text,"\n\0"); char* strToCheck = strtok(NULL, "\n\0"); char* input = (char*)malloc(1<<10*sizeof(char)); ssize_t strLen = 0, currentPos = 0, partLen; int strNum = 0; while (strToSend != NULL){ //отправляем полностью "первую" строку strLen = strlen(strToSend); while (currentPos < strLen){ partLen = send(sock_fd, strToSend + currentPos, strLen, 0); currentPos += partLen; if (partLen == -1) break; } strLen = strlen(strToCheck); //теперь считываем "вторую" currentPos = 0; input[0] = 'a'; while (input[currentPos] != '\n'){ partLen = recv(sock_fd, input + currentPos, strLen, 0); currentPos += partLen; if (partLen == -1) break; if (currentPos > strLen){ exit(EXIT_FAILURE); } } //сравниваем ++strNum; if (strcmp(input, strToCheck) != 0) exit(EXIT_FAILURE); else printf("\n%d", strNum); strToSend = strtok (NULL, "\n\0"); strToCheck = strtok(NULL, "\n\0"); } return 0; }
C
#include <stdio.h> int main() { char* p1 = "anything"; char* p2 = "anything"; printf("p1=%x, p2=%x\n", p1, p2); return 0; }
C
#ifndef SPLAYTREE_H #define SPLAYTREE_H #include <cstdlib> #include <cstdio> #include <cmath> #include "chem_global.h" #include <climits> #include <cfloat> #include <algorithm> #include "defines.h" #define KEYTYP int #define VALTYP double /* floor function for negative values */ #define NEGFLR(x) ( ((x)<0) ? ( ((int) (x))-1) : ( ((int) (x)) ) ) /* STRUCTURES */ /* splayTree : main splaytree structure */ /* Contains T, the root and the information header */ /* and nil node */ /* treeNode : Holds the key, value and left and right pointers */ struct treeNode { KEYTYP * key; /* list of key values used by the search algorithm */ VALTYP * val; /* values for the given key */ int min_key; /* mineral combination kode */ struct treeNode *left, *right; /* pointer to the left- and right-hand nodes (ST) */ }; struct splayTree { /* size : number of tree nodes * num_while : use to test the efficiency */ long int size, num_while; /* Special splay tree nodes */ struct treeNode *t, *nil_node, *header, *new_node; /* val_scale_log : rescale factor for the logarithim binned values * val_scale_log_inv : factor for scaling logarithmic binned key values * val_scale_lin : rescale factor for the linear binned values * val_scale_lin_inv : factor for scaling linear binned key values * key_to_val : used to translate 'key values' to physical values */ VALTYP * val_scale_log, * val_scale_log_inv, * val_scale_lin, * val_scale_lin_inv, * key_to_val; VALTYP * val_log, * val_lin; /* a : logarithmic bin width factor (physcical value) * log_a_inv : invers of the logartihm (base 10) of 'a' * b : linear intevall length */ VALTYP a, log_a_inv, b; KEYTYP * new_key; /* num_val : number of return values * num_val_log : number of logarithmic binned key values * num_val_lin : number of lineare binned key values * num_key : total number of key values (num_val_log + num_val_lin) */ int num_val, num_val_log, num_val_lin, num_key; /*** chemistry relevant paramters *** * Vchem_key : holds the vchem structure for the given mineral combination * min_key : mineral key. Binary representation of the mineral combination */ struct BasVec * Vchem_key; int min_key; }; /* FUNCTIONS */ void SetNewVal(struct treeNode *, struct splayTree *, real * ctot, real * ctot_min, int ctot_min_size); void CopyKey(KEYTYP *dest, KEYTYP *orig, struct splayTree * st); int CompKey(KEYTYP * k1, KEYTYP * k2, struct splayTree * st); void FreeTreeNode(struct treeNode *tn); struct splayTree * InitializeSplayTree(int num_val, int num_val_log, int num_val_lin, int num_interval_log, double interval_lin, VALTYP * val_scale, VALTYP * val_scale_lin); void Splay(KEYTYP * key, struct splayTree * st); struct treeNode * FindInsert(VALTYP * val_log, VALTYP * val_lin, struct splayTree *st, real * ctot_min, int ctot_min_size); struct treeNode * FindInsertNoInterp(VALTYP * val_log, VALTYP * val_lin, struct splayTree *st, real * ctot_min, int ctot_min_size); struct treeNode * MakeNewNode(struct splayTree *); void DeleteKey(KEYTYP * key, struct splayTree *st); void EmptySplayTree(struct splayTree *st); void FreeSplayTree(struct splayTree *st); void SetNewKey(KEYTYP *key, VALTYP * val_log, VALTYP * val_lin, struct splayTree * st); #endif
C
#include <stdio.h> #include <stdlib.h> #include <pthread.h> struct foo { int a , b, c, d ; }; void printfoo(char * s , struct foo * fp); void * thr_fun1(void * arg); void * thr_fun2(void * arg); int main() { int err ; pthread_t tid1 ; pthread_t tid2 ; struct foo * fp ; err = pthread_create(&tid1,NULL,thr_fun1,NULL); if( err != 0) { printf(" tid1 could not created \n"); } err = pthread_join(tid1,(void*)&fp); if( err != 0) printf("join 1 could not done \n"); sleep(1); printf("parent starting second thread \n"); err = pthread_create(&tid2,NULL,thr_fun2,NULL); if( err != 0 ) printf("tid2 could not created \n"); pthread_join(tid2,(void*)&fp); sleep(1); printfoo("parent : \n",fp); exit(0); } void *thr_fun1(void * arg) { struct foo f = { 1,2,3,4}; printfoo("thread 1 : \n",&f); pthread_exit((void *)&f); } void * thr_fun2(void * arg) { printf("thread 2 : id %d\n",pthread_self()); struct foo f = {4,3,2,1}; printfoo("this is thread 2 ",&f); pthread_exit((void *)&f); } void printfoo(char * s , struct foo * fp) { printf(s); printf("Structure at 0x%x \n",(unsigned)fp); printf("foo.a %d \n",fp->a); printf("foo.b %d \n",fp->b); printf("foo.c %d \n",fp->c); printf("foo.d %d \n ",fp->d); }
C
/* * ===================================================================================== * * Filename: main.c * * Description: * * Version: 1.0 * Created: 08/16/2015 01:52:04 PM * Revision: none * Compiler: gcc * * Author: Jiang JiaJi (@.@), [email protected] * Company: Xilinx XUP * * ===================================================================================== */ #include <stdio.h> #include "../xlib/xil_dma.h" #include<sys/time.h> #define DEVICE_NAME "/dev/xdma" #define DMA_CH 1 int main() { const int LENGTH = 1024 * 1024; int i; uint32_t *src; uint32_t *dst; printf("max image is %d for nom!\n", LENGTH); printf("DMA Channel is %d\n", DMA_CH); xil_dma *mydma = XilDMACreate(DEVICE_NAME); /***************************dma load data**********************************/ src = (uint32_t *)mydma->setupAlloc(mydma, LENGTH, sizeof(uint32_t)); dst = (uint32_t *)mydma->setupAlloc(mydma, LENGTH, sizeof(uint32_t)); for (i = 0; i < LENGTH; i++) { src[i] = 'z'; } src[LENGTH-1] = '\n'; for (i = 0; i < LENGTH; i++) { dst[i] = 'd'; } dst[LENGTH-1] = '\n'; printf("test: dst buffer before transmit:\n"); for (i = 0; i < 10; i++) { printf("%c\t", (char)dst[i]); } printf("\n"); /****************dma Transfer****************************/ struct timeval tv; struct timezone tz; gettimeofday(&tv,&tz); long start = tv.tv_sec * 1000000 + tv.tv_usec; if (0 < mydma->getDevNum(mydma)) { mydma->performTransfer(mydma, DMA_CH, XDMA_WAIT_NONE, src, LENGTH, XDMA_MEM_TO_DEV); mydma->performTransfer(mydma, DMA_CH, XDMA_WAIT_NONE, dst, LENGTH, XDMA_DEV_TO_MEM); } while(dst[LENGTH - 2] != src[LENGTH - 2]); gettimeofday(&tv,&tz); long now = tv.tv_sec * 1000000 + tv.tv_usec - start - 72; printf("running time is %ld us\n", now); int count; for (i = 0; i < LENGTH; i++) { if((char)dst[i] != 'z') { count = i; break; } if(i >= LENGTH - 10) { printf("%c\t", (char)dst[i]); } } printf("\n count is %d\n", count); XilDMADestory(mydma); return 0; }
C
/* * Bootstrap Scheme - a quick and very dirty Scheme interpreter. * Copyright (C) 2010 Peter Michaux (http://peter.michaux.ca/) * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public * License version 3 as published by the Free Software Foundation. * * 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 Affero General Public License version 3 for more details. * * You should have received a copy of the GNU Affero General Public * License version 3 along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <stdlib.h> #include <stdio.h> #include <string.h> /**************************** MODEL ******************************/ typedef enum {THE_EMPTY_LIST, BOOLEAN, SYMBOL, FIXNUM, CHARACTER, STRING, PAIR, PRIMITIVE_PROC, COMPOUND_PROC, INPUT_PORT, OUTPUT_PORT, EOF_OBJECT} object_type; typedef struct object { object_type type; union { struct { char value; } boolean; struct { char *value; } symbol; struct { long value; } fixnum; struct { char value; } character; struct { char *value; } string; struct { struct object *car; struct object *cdr; } pair; struct { struct object *(*fn)(struct object *arguments); } primitive_proc; struct { struct object *parameters; struct object *body; struct object *env; } compound_proc; struct { FILE *stream; } input_port; struct { FILE *stream; } output_port; } data; } object; /* no GC so truely "unlimited extent" */ object *alloc_object(void) { object *obj; obj = malloc(sizeof(object)); if (obj == NULL) { fprintf(stderr, "out of memory\n"); exit(1); } return obj; } object *the_empty_list; object *false; object *true; object *symbol_table; object *quote_symbol; object *define_symbol; object *set_symbol; object *ok_symbol; object *if_symbol; object *lambda_symbol; object *begin_symbol; object *cond_symbol; object *else_symbol; object *let_symbol; object *and_symbol; object *or_symbol; object *eof_object; object *the_empty_environment; object *the_global_environment; object *cons(object *car, object *cdr); object *car(object *pair); object *cdr(object *pair); char is_the_empty_list(object *obj) { return obj == the_empty_list; } char is_boolean(object *obj) { return obj->type == BOOLEAN; } char is_false(object *obj) { return obj == false; } char is_true(object *obj) { return !is_false(obj); } object *make_symbol(char *value) { object *obj; object *element; /* search for they symbol in the symbol table */ element = symbol_table; while (!is_the_empty_list(element)) { if (strcmp(car(element)->data.symbol.value, value) == 0) { return car(element); } element = cdr(element); }; /* create the symbol and add it to the symbol table */ obj = alloc_object(); obj->type = SYMBOL; obj->data.symbol.value = malloc(strlen(value) + 1); if (obj->data.symbol.value == NULL) { fprintf(stderr, "out of memory\n"); exit(1); } strcpy(obj->data.symbol.value, value); symbol_table = cons(obj, symbol_table); return obj; } char is_symbol(object *obj) { return obj->type == SYMBOL; } object *make_fixnum(long value) { object *obj; obj = alloc_object(); obj->type = FIXNUM; obj->data.fixnum.value = value; return obj; } char is_fixnum(object *obj) { return obj->type == FIXNUM; } object *make_character(char value) { object *obj; obj = alloc_object(); obj->type = CHARACTER; obj->data.character.value = value; return obj; } char is_character(object *obj) { return obj->type == CHARACTER; } object *make_string(char *value) { object *obj; obj = alloc_object(); obj->type = STRING; obj->data.string.value = malloc(strlen(value) + 1); if (obj->data.string.value == NULL) { fprintf(stderr, "out of memory\n"); exit(1); } strcpy(obj->data.string.value, value); return obj; } char is_string(object *obj) { return obj->type == STRING; } object *cons(object *car, object *cdr) { object *obj; obj = alloc_object(); obj->type = PAIR; obj->data.pair.car = car; obj->data.pair.cdr = cdr; return obj; } char is_pair(object *obj) { return obj->type == PAIR; } object *car(object *pair) { return pair->data.pair.car; } void set_car(object *obj, object* value) { obj->data.pair.car = value; } object *cdr(object *pair) { return pair->data.pair.cdr; } void set_cdr(object *obj, object* value) { obj->data.pair.cdr = value; } #define caar(obj) car(car(obj)) #define cadr(obj) car(cdr(obj)) #define cdar(obj) cdr(car(obj)) #define cddr(obj) cdr(cdr(obj)) #define caaar(obj) car(car(car(obj))) #define caadr(obj) car(car(cdr(obj))) #define cadar(obj) car(cdr(car(obj))) #define caddr(obj) car(cdr(cdr(obj))) #define cdaar(obj) cdr(car(car(obj))) #define cdadr(obj) cdr(car(cdr(obj))) #define cddar(obj) cdr(cdr(car(obj))) #define cdddr(obj) cdr(cdr(cdr(obj))) #define caaaar(obj) car(car(car(car(obj)))) #define caaadr(obj) car(car(car(cdr(obj)))) #define caadar(obj) car(car(cdr(car(obj)))) #define caaddr(obj) car(car(cdr(cdr(obj)))) #define cadaar(obj) car(cdr(car(car(obj)))) #define cadadr(obj) car(cdr(car(cdr(obj)))) #define caddar(obj) car(cdr(cdr(car(obj)))) #define cadddr(obj) car(cdr(cdr(cdr(obj)))) #define cdaaar(obj) cdr(car(car(car(obj)))) #define cdaadr(obj) cdr(car(car(cdr(obj)))) #define cdadar(obj) cdr(car(cdr(car(obj)))) #define cdaddr(obj) cdr(car(cdr(cdr(obj)))) #define cddaar(obj) cdr(cdr(car(car(obj)))) #define cddadr(obj) cdr(cdr(car(cdr(obj)))) #define cdddar(obj) cdr(cdr(cdr(car(obj)))) #define cddddr(obj) cdr(cdr(cdr(cdr(obj)))) object *make_primitive_proc( object *(*fn)(struct object *arguments)) { object *obj; obj = alloc_object(); obj->type = PRIMITIVE_PROC; obj->data.primitive_proc.fn = fn; return obj; } char is_primitive_proc(object *obj) { return obj->type == PRIMITIVE_PROC; } object *is_null_proc(object *arguments) { return is_the_empty_list(car(arguments)) ? true : false; } object *is_boolean_proc(object *arguments) { return is_boolean(car(arguments)) ? true : false; } object *is_symbol_proc(object *arguments) { return is_symbol(car(arguments)) ? true : false; } object *is_integer_proc(object *arguments) { return is_fixnum(car(arguments)) ? true : false; } object *is_char_proc(object *arguments) { return is_character(car(arguments)) ? true : false; } object *is_string_proc(object *arguments) { return is_string(car(arguments)) ? true : false; } object *is_pair_proc(object *arguments) { return is_pair(car(arguments)) ? true : false; } char is_compound_proc(object *obj); object *is_procedure_proc(object *arguments) { object *obj; obj = car(arguments); return (is_primitive_proc(obj) || is_compound_proc(obj)) ? true : false; } object *char_to_integer_proc(object *arguments) { return make_fixnum((car(arguments))->data.character.value); } object *integer_to_char_proc(object *arguments) { return make_character((car(arguments))->data.fixnum.value); } object *number_to_string_proc(object *arguments) { char buffer[100]; sprintf(buffer, "%d", (car(arguments))->data.fixnum.value); return make_string(buffer); } object *string_to_number_proc(object *arguments) { return make_fixnum(atoi((car(arguments))->data.string.value)); } object *symbol_to_string_proc(object *arguments) { return make_string((car(arguments))->data.symbol.value); } object *string_to_symbol_proc(object *arguments) { return make_symbol((car(arguments))->data.string.value); } object *add_proc(object *arguments) { long result = 0; while (!is_the_empty_list(arguments)) { result += (car(arguments))->data.fixnum.value; arguments = cdr(arguments); } return make_fixnum(result); } object *sub_proc(object *arguments) { long result; result = (car(arguments))->data.fixnum.value; while (!is_the_empty_list(arguments = cdr(arguments))) { result -= (car(arguments))->data.fixnum.value; } return make_fixnum(result); } object *mul_proc(object *arguments) { long result = 1; while (!is_the_empty_list(arguments)) { result *= (car(arguments))->data.fixnum.value; arguments = cdr(arguments); } return make_fixnum(result); } object *quotient_proc(object *arguments) { return make_fixnum( ((car(arguments) )->data.fixnum.value)/ ((cadr(arguments))->data.fixnum.value)); } object *remainder_proc(object *arguments) { return make_fixnum( ((car(arguments) )->data.fixnum.value)% ((cadr(arguments))->data.fixnum.value)); } object *is_number_equal_proc(object *arguments) { long value; value = (car(arguments))->data.fixnum.value; while (!is_the_empty_list(arguments = cdr(arguments))) { if (value != ((car(arguments))->data.fixnum.value)) { return false; } } return true; } object *is_less_than_proc(object *arguments) { long previous; long next; previous = (car(arguments))->data.fixnum.value; while (!is_the_empty_list(arguments = cdr(arguments))) { next = (car(arguments))->data.fixnum.value; if (previous < next) { previous = next; } else { return false; } } return true; } object *is_greater_than_proc(object *arguments) { long previous; long next; previous = (car(arguments))->data.fixnum.value; while (!is_the_empty_list(arguments = cdr(arguments))) { next = (car(arguments))->data.fixnum.value; if (previous > next) { previous = next; } else { return false; } } return true; } object *cons_proc(object *arguments) { return cons(car(arguments), cadr(arguments)); } object *car_proc(object *arguments) { return caar(arguments); } object *cdr_proc(object *arguments) { return cdar(arguments); } object *set_car_proc(object *arguments) { set_car(car(arguments), cadr(arguments)); return ok_symbol; } object *set_cdr_proc(object *arguments) { set_cdr(car(arguments), cadr(arguments)); return ok_symbol; } object *list_proc(object *arguments) { return arguments; } object *is_eq_proc(object *arguments) { object *obj1; object *obj2; obj1 = car(arguments); obj2 = cadr(arguments); if (obj1->type != obj2->type) { return false; } switch (obj1->type) { case FIXNUM: return (obj1->data.fixnum.value == obj2->data.fixnum.value) ? true : false; break; case CHARACTER: return (obj1->data.character.value == obj2->data.character.value) ? true : false; break; case STRING: return (strcmp(obj1->data.string.value, obj2->data.string.value) == 0) ? true : false; break; default: return (obj1 == obj2) ? true : false; } } object *apply_proc(object *arguments) { fprintf(stderr, "illegal state: The body of the apply " "primitive procedure should not execute.\n"); exit(1); } object *interaction_environment_proc(object *arguments) { return the_global_environment; } object *setup_environment(void); object *null_environment_proc(object *arguments) { return setup_environment(); } object *make_environment(void); object *environment_proc(object *arguments) { return make_environment(); } object *eval_proc(object *arguments) { fprintf(stderr, "illegal state: The body of the eval " "primitive procedure should not execute.\n"); exit(1); } object *read(FILE *in); object *eval(object *exp, object *env); object *load_proc(object *arguments) { char *filename; FILE *in; object *exp; object *result; filename = car(arguments)->data.string.value; in = fopen(filename, "r"); if (in == NULL) { fprintf(stderr, "could not load file \"%s\"", filename); exit(1); } while ((exp = read(in)) != NULL) { result = eval(exp, the_global_environment); } fclose(in); return result; } object *make_input_port(FILE *in); object *open_input_port_proc(object *arguments) { char *filename; FILE *in; filename = car(arguments)->data.string.value; in = fopen(filename, "r"); if (in == NULL) { fprintf(stderr, "could not open file \"%s\"\n", filename); exit(1); } return make_input_port(in); } object *close_input_port_proc(object *arguments) { int result; result = fclose(car(arguments)->data.input_port.stream); if (result == EOF) { fprintf(stderr, "could not close input port\n"); exit(1); } return ok_symbol; } char is_input_port(object *obj); object *is_input_port_proc(object *arguments) { return is_input_port(car(arguments)) ? true : false; } object *read_proc(object *arguments) { FILE *in; object *result; in = is_the_empty_list(arguments) ? stdin : car(arguments)->data.input_port.stream; result = read(in); return (result == NULL) ? eof_object : result; } object *read_char_proc(object *arguments) { FILE *in; int result; in = is_the_empty_list(arguments) ? stdin : car(arguments)->data.input_port.stream; result = getc(in); return (result == EOF) ? eof_object : make_character(result); } int peek(FILE *in); object *peek_char_proc(object *arguments) { FILE *in; int result; in = is_the_empty_list(arguments) ? stdin : car(arguments)->data.input_port.stream; result = peek(in); return (result == EOF) ? eof_object : make_character(result); } char is_eof_object(object *obj); object *is_eof_object_proc(object *arguments) { return is_eof_object(car(arguments)) ? true : false; } object *make_output_port(FILE *in); object *open_output_port_proc(object *arguments) { char *filename; FILE *out; filename = car(arguments)->data.string.value; out = fopen(filename, "w"); if (out == NULL) { fprintf(stderr, "could not open file \"%s\"\n", filename); exit(1); } return make_output_port(out); } object *close_output_port_proc(object *arguments) { int result; result = fclose(car(arguments)->data.output_port.stream); if (result == EOF) { fprintf(stderr, "could not close output port\n"); exit(1); } return ok_symbol; } char is_output_port(object *obj); object *is_output_port_proc(object *arguments) { return is_output_port(car(arguments)) ? true : false; } object *write_char_proc(object *arguments) { object *character; FILE *out; character = car(arguments); arguments = cdr(arguments); out = is_the_empty_list(arguments) ? stdout : car(arguments)->data.output_port.stream; putc(character->data.character.value, out); fflush(out); return ok_symbol; } void write(FILE *out, object *obj); object *write_proc(object *arguments) { object *exp; FILE *out; exp = car(arguments); arguments = cdr(arguments); out = is_the_empty_list(arguments) ? stdout : car(arguments)->data.output_port.stream; write(out, exp); fflush(out); return ok_symbol; } object *error_proc(object *arguments) { while (!is_the_empty_list(arguments)) { write(stderr, car(arguments)); fprintf(stderr, " "); arguments = cdr(arguments); }; printf("\nexiting\n"); exit(1); } object *make_compound_proc(object *parameters, object *body, object* env) { object *obj; obj = alloc_object(); obj->type = COMPOUND_PROC; obj->data.compound_proc.parameters = parameters; obj->data.compound_proc.body = body; obj->data.compound_proc.env = env; return obj; } char is_compound_proc(object *obj) { return obj->type == COMPOUND_PROC; } object *make_input_port(FILE *stream) { object *obj; obj = alloc_object(); obj->type = INPUT_PORT; obj->data.input_port.stream = stream; return obj; } char is_input_port(object *obj) { return obj->type == INPUT_PORT; } object *make_output_port(FILE *stream) { object *obj; obj = alloc_object(); obj->type = OUTPUT_PORT; obj->data.output_port.stream = stream; return obj; } char is_output_port(object *obj) { return obj->type == OUTPUT_PORT; } char is_eof_object(object *obj) { return obj == eof_object; } object *enclosing_environment(object *env) { return cdr(env); } object *first_frame(object *env) { return car(env); } object *make_frame(object *variables, object *values) { return cons(variables, values); } object *frame_variables(object *frame) { return car(frame); } object *frame_values(object *frame) { return cdr(frame); } void add_binding_to_frame(object *var, object *val, object *frame) { set_car(frame, cons(var, car(frame))); set_cdr(frame, cons(val, cdr(frame))); } object *extend_environment(object *vars, object *vals, object *base_env) { return cons(make_frame(vars, vals), base_env); } object *lookup_variable_value(object *var, object *env) { object *frame; object *vars; object *vals; while (!is_the_empty_list(env)) { frame = first_frame(env); vars = frame_variables(frame); vals = frame_values(frame); while (!is_the_empty_list(vars)) { if (var == car(vars)) { return car(vals); } vars = cdr(vars); vals = cdr(vals); } env = enclosing_environment(env); } fprintf(stderr, "unbound variable, %s\n", var->data.symbol.value); exit(1); } void set_variable_value(object *var, object *val, object *env) { object *frame; object *vars; object *vals; while (!is_the_empty_list(env)) { frame = first_frame(env); vars = frame_variables(frame); vals = frame_values(frame); while (!is_the_empty_list(vars)) { if (var == car(vars)) { set_car(vals, val); return; } vars = cdr(vars); vals = cdr(vals); } env = enclosing_environment(env); } fprintf(stderr, "unbound variable, %s\n", var->data.symbol.value); exit(1); } void define_variable(object *var, object *val, object *env) { object *frame; object *vars; object *vals; frame = first_frame(env); vars = frame_variables(frame); vals = frame_values(frame); while (!is_the_empty_list(vars)) { if (var == car(vars)) { set_car(vals, val); return; } vars = cdr(vars); vals = cdr(vals); } add_binding_to_frame(var, val, frame); } object *setup_environment(void) { object *initial_env; initial_env = extend_environment( the_empty_list, the_empty_list, the_empty_environment); return initial_env; } void populate_environment(object *env) { #define add_procedure(scheme_name, c_name) \ define_variable(make_symbol(scheme_name), \ make_primitive_proc(c_name), \ env); add_procedure("null?" , is_null_proc); add_procedure("boolean?" , is_boolean_proc); add_procedure("symbol?" , is_symbol_proc); add_procedure("integer?" , is_integer_proc); add_procedure("char?" , is_char_proc); add_procedure("string?" , is_string_proc); add_procedure("pair?" , is_pair_proc); add_procedure("procedure?" , is_procedure_proc); add_procedure("char->integer" , char_to_integer_proc); add_procedure("integer->char" , integer_to_char_proc); add_procedure("number->string", number_to_string_proc); add_procedure("string->number", string_to_number_proc); add_procedure("symbol->string", symbol_to_string_proc); add_procedure("string->symbol", string_to_symbol_proc); add_procedure("+" , add_proc); add_procedure("-" , sub_proc); add_procedure("*" , mul_proc); add_procedure("quotient" , quotient_proc); add_procedure("remainder", remainder_proc); add_procedure("=" , is_number_equal_proc); add_procedure("<" , is_less_than_proc); add_procedure(">" , is_greater_than_proc); add_procedure("cons" , cons_proc); add_procedure("car" , car_proc); add_procedure("cdr" , cdr_proc); add_procedure("set-car!", set_car_proc); add_procedure("set-cdr!", set_cdr_proc); add_procedure("list" , list_proc); add_procedure("eq?", is_eq_proc); add_procedure("apply", apply_proc); add_procedure("interaction-environment", interaction_environment_proc); add_procedure("null-environment", null_environment_proc); add_procedure("environment" , environment_proc); add_procedure("eval" , eval_proc); add_procedure("load" , load_proc); add_procedure("open-input-port" , open_input_port_proc); add_procedure("close-input-port" , close_input_port_proc); add_procedure("input-port?" , is_input_port_proc); add_procedure("read" , read_proc); add_procedure("read-char" , read_char_proc); add_procedure("peek-char" , peek_char_proc); add_procedure("eof-object?" , is_eof_object_proc); add_procedure("open-output-port" , open_output_port_proc); add_procedure("close-output-port", close_output_port_proc); add_procedure("output-port?" , is_output_port_proc); add_procedure("write-char" , write_char_proc); add_procedure("write" , write_proc); add_procedure("error", error_proc); } object *make_environment(void) { object *env; env = setup_environment(); populate_environment(env); return env; } void init(void) { the_empty_list = alloc_object(); the_empty_list->type = THE_EMPTY_LIST; false = alloc_object(); false->type = BOOLEAN; false->data.boolean.value = 0; true = alloc_object(); true->type = BOOLEAN; true->data.boolean.value = 1; symbol_table = the_empty_list; quote_symbol = make_symbol("quote"); define_symbol = make_symbol("define"); set_symbol = make_symbol("set!"); ok_symbol = make_symbol("ok"); if_symbol = make_symbol("if"); lambda_symbol = make_symbol("lambda"); begin_symbol = make_symbol("begin"); cond_symbol = make_symbol("cond"); else_symbol = make_symbol("else"); let_symbol = make_symbol("let"); and_symbol = make_symbol("and"); or_symbol = make_symbol("or"); eof_object = alloc_object(); eof_object->type = EOF_OBJECT; the_empty_environment = the_empty_list; the_global_environment = make_environment(); } /***************************** READ ******************************/ char is_delimiter(int c) { return isspace(c) || c == EOF || c == '(' || c == ')' || c == '"' || c == ';'; } char is_initial(int c) { return isalpha(c) || c == '*' || c == '/' || c == '>' || c == '<' || c == '=' || c == '?' || c == '!'; } int peek(FILE *in) { int c; c = getc(in); ungetc(c, in); return c; } void eat_whitespace(FILE *in) { int c; while ((c = getc(in)) != EOF) { if (isspace(c)) { continue; } else if (c == ';') { /* comments are whitespace also */ while (((c = getc(in)) != EOF) && (c != '\n')); continue; } ungetc(c, in); break; } } void eat_expected_string(FILE *in, char *str) { int c; while (*str != '\0') { c = getc(in); if (c != *str) { fprintf(stderr, "unexpected character '%c'\n", c); exit(1); } str++; } } void peek_expected_delimiter(FILE *in) { if (!is_delimiter(peek(in))) { fprintf(stderr, "character not followed by delimiter\n"); exit(1); } } object *read_character(FILE *in) { int c; c = getc(in); switch (c) { case EOF: fprintf(stderr, "incomplete character literal\n"); exit(1); case 's': if (peek(in) == 'p') { eat_expected_string(in, "pace"); peek_expected_delimiter(in); return make_character(' '); } break; case 'n': if (peek(in) == 'e') { eat_expected_string(in, "ewline"); peek_expected_delimiter(in); return make_character('\n'); } break; } peek_expected_delimiter(in); return make_character(c); } object *read_pair(FILE *in) { int c; object *car_obj; object *cdr_obj; eat_whitespace(in); c = getc(in); if (c == ')') { /* read the empty list */ return the_empty_list; } ungetc(c, in); car_obj = read(in); eat_whitespace(in); c = getc(in); if (c == '.') { /* read improper list */ c = peek(in); if (!is_delimiter(c)) { fprintf(stderr, "dot not followed by delimiter\n"); exit(1); } cdr_obj = read(in); eat_whitespace(in); c = getc(in); if (c != ')') { fprintf(stderr, "where was the trailing right paren?\n"); exit(1); } return cons(car_obj, cdr_obj); } else { /* read list */ ungetc(c, in); cdr_obj = read_pair(in); return cons(car_obj, cdr_obj); } } object *read(FILE *in) { int c; short sign = 1; int i; long num = 0; #define BUFFER_MAX 1000 char buffer[BUFFER_MAX]; eat_whitespace(in); c = getc(in); if (c == '#') { /* read a boolean or character */ c = getc(in); switch (c) { case 't': return true; case 'f': return false; case '\\': return read_character(in); default: fprintf(stderr, "unknown boolean or character literal\n"); exit(1); } } else if (isdigit(c) || (c == '-' && (isdigit(peek(in))))) { /* read a fixnum */ if (c == '-') { sign = -1; } else { ungetc(c, in); } while (isdigit(c = getc(in))) { num = (num * 10) + (c - '0'); } num *= sign; if (is_delimiter(c)) { ungetc(c, in); return make_fixnum(num); } else { fprintf(stderr, "number not followed by delimiter\n"); exit(1); } } else if (is_initial(c) || ((c == '+' || c == '-') && is_delimiter(peek(in)))) { /* read a symbol */ i = 0; while (is_initial(c) || isdigit(c) || c == '+' || c == '-') { /* subtract 1 to save space for '\0' terminator */ if (i < BUFFER_MAX - 1) { buffer[i++] = c; } else { fprintf(stderr, "symbol too long. " "Maximum length is %d\n", BUFFER_MAX); exit(1); } c = getc(in); } if (is_delimiter(c)) { buffer[i] = '\0'; ungetc(c, in); return make_symbol(buffer); } else { fprintf(stderr, "symbol not followed by delimiter. " "Found '%c'\n", c); exit(1); } } else if (c == '"') { /* read a string */ i = 0; while ((c = getc(in)) != '"') { if (c == '\\') { c = getc(in); if (c == 'n') { c = '\n'; } } if (c == EOF) { fprintf(stderr, "non-terminated string literal\n"); exit(1); } /* subtract 1 to save space for '\0' terminator */ if (i < BUFFER_MAX - 1) { buffer[i++] = c; } else { fprintf(stderr, "string too long. Maximum length is %d\n", BUFFER_MAX); exit(1); } } buffer[i] = '\0'; return make_string(buffer); } else if (c == '(') { /* read the empty list or pair */ return read_pair(in); } else if (c == '\'') { /* read quoted expression */ return cons(quote_symbol, cons(read(in), the_empty_list)); } else if (c == EOF) { return NULL; } else { fprintf(stderr, "bad input. Unexpected '%c'\n", c); exit(1); } fprintf(stderr, "read illegal state\n"); exit(1); } /*************************** EVALUATE ****************************/ char is_self_evaluating(object *exp) { return is_boolean(exp) || is_fixnum(exp) || is_character(exp) || is_string(exp); } char is_variable(object *expression) { return is_symbol(expression); } char is_tagged_list(object *expression, object *tag) { object *the_car; if (is_pair(expression)) { the_car = car(expression); return is_symbol(the_car) && (the_car == tag); } return 0; } char is_quoted(object *expression) { return is_tagged_list(expression, quote_symbol); } object *text_of_quotation(object *exp) { return cadr(exp); } char is_assignment(object *exp) { return is_tagged_list(exp, set_symbol); } object *assignment_variable(object *exp) { return car(cdr(exp)); } object *assignment_value(object *exp) { return car(cdr(cdr(exp))); } char is_definition(object *exp) { return is_tagged_list(exp, define_symbol); } object *definition_variable(object *exp) { if (is_symbol(cadr(exp))) { return cadr(exp); } else { return caadr(exp); } } object *make_lambda(object *parameters, object *body); object *definition_value(object *exp) { if (is_symbol(cadr(exp))) { return caddr(exp); } else { return make_lambda(cdadr(exp), cddr(exp)); } } object *make_if(object *predicate, object *consequent, object *alternative) { return cons(if_symbol, cons(predicate, cons(consequent, cons(alternative, the_empty_list)))); } char is_if(object *expression) { return is_tagged_list(expression, if_symbol); } object *if_predicate(object *exp) { return cadr(exp); } object *if_consequent(object *exp) { return caddr(exp); } object *if_alternative(object *exp) { if (is_the_empty_list(cdddr(exp))) { return false; } else { return cadddr(exp); } } object *make_lambda(object *parameters, object *body) { return cons(lambda_symbol, cons(parameters, body)); } char is_lambda(object *exp) { return is_tagged_list(exp, lambda_symbol); } object *lambda_parameters(object *exp) { return cadr(exp); } object *lambda_body(object *exp) { return cddr(exp); } object *make_begin(object *seq) { return cons(begin_symbol, seq); } char is_begin(object *exp) { return is_tagged_list(exp, begin_symbol); } object *begin_actions(object *exp) { return cdr(exp); } char is_last_exp(object *seq) { return is_the_empty_list(cdr(seq)); } object *first_exp(object *seq) { return car(seq); } object *rest_exps(object *seq) { return cdr(seq); } char is_cond(object *exp) { return is_tagged_list(exp, cond_symbol); } object *cond_clauses(object *exp) { return cdr(exp); } object *cond_predicate(object *clause) { return car(clause); } object *cond_actions(object *clause) { return cdr(clause); } char is_cond_else_clause(object *clause) { return cond_predicate(clause) == else_symbol; } object *sequence_to_exp(object *seq) { if (is_the_empty_list(seq)) { return seq; } else if (is_last_exp(seq)) { return first_exp(seq); } else { return make_begin(seq); } } object *expand_clauses(object *clauses) { object *first; object *rest; if (is_the_empty_list(clauses)) { return false; } else { first = car(clauses); rest = cdr(clauses); if (is_cond_else_clause(first)) { if (is_the_empty_list(rest)) { return sequence_to_exp(cond_actions(first)); } else { fprintf(stderr, "else clause isn't last cond->if"); exit(1); } } else { return make_if(cond_predicate(first), sequence_to_exp(cond_actions(first)), expand_clauses(rest)); } } } object *cond_to_if(object *exp) { return expand_clauses(cond_clauses(exp)); } object *make_application(object *operator, object *operands) { return cons(operator, operands); } char is_application(object *exp) { return is_pair(exp); } object *operator(object *exp) { return car(exp); } object *operands(object *exp) { return cdr(exp); } char is_no_operands(object *ops) { return is_the_empty_list(ops); } object *first_operand(object *ops) { return car(ops); } object *rest_operands(object *ops) { return cdr(ops); } char is_let(object *exp) { return is_tagged_list(exp, let_symbol); } object *let_bindings(object *exp) { return cadr(exp); } object *let_body(object *exp) { return cddr(exp); } object *binding_parameter(object *binding) { return car(binding); } object *binding_argument(object *binding) { return cadr(binding); } object *bindings_parameters(object *bindings) { return is_the_empty_list(bindings) ? the_empty_list : cons(binding_parameter(car(bindings)), bindings_parameters(cdr(bindings))); } object *bindings_arguments(object *bindings) { return is_the_empty_list(bindings) ? the_empty_list : cons(binding_argument(car(bindings)), bindings_arguments(cdr(bindings))); } object *let_parameters(object *exp) { return bindings_parameters(let_bindings(exp)); } object *let_arguments(object *exp) { return bindings_arguments(let_bindings(exp)); } object *let_to_application(object *exp) { return make_application( make_lambda(let_parameters(exp), let_body(exp)), let_arguments(exp)); } char is_and(object *exp) { return is_tagged_list(exp, and_symbol); } object *and_tests(object *exp) { return cdr(exp); } char is_or(object *exp) { return is_tagged_list(exp, or_symbol); } object *or_tests(object *exp) { return cdr(exp); } object *apply_operator(object *arguments) { return car(arguments); } object *prepare_apply_operands(object *arguments) { if (is_the_empty_list(cdr(arguments))) { return car(arguments); } else { return cons(car(arguments), prepare_apply_operands(cdr(arguments))); } } object *apply_operands(object *arguments) { return prepare_apply_operands(cdr(arguments)); } object *eval_expression(object *arguments) { return car(arguments); } object *eval_environment(object *arguments) { return cadr(arguments); } object *list_of_values(object *exps, object *env) { if (is_no_operands(exps)) { return the_empty_list; } else { return cons(eval(first_operand(exps), env), list_of_values(rest_operands(exps), env)); } } object *eval_assignment(object *exp, object *env) { set_variable_value(assignment_variable(exp), eval(assignment_value(exp), env), env); return ok_symbol; } object *eval_definition(object *exp, object *env) { define_variable(definition_variable(exp), eval(definition_value(exp), env), env); return ok_symbol; } object *eval(object *exp, object *env) { object *procedure; object *arguments; object *result; tailcall: if (is_self_evaluating(exp)) { return exp; } else if (is_variable(exp)) { return lookup_variable_value(exp, env); } else if (is_quoted(exp)) { return text_of_quotation(exp); } else if (is_assignment(exp)) { return eval_assignment(exp, env); } else if (is_definition(exp)) { return eval_definition(exp, env); } else if (is_if(exp)) { exp = is_true(eval(if_predicate(exp), env)) ? if_consequent(exp) : if_alternative(exp); goto tailcall; } else if (is_lambda(exp)) { return make_compound_proc(lambda_parameters(exp), lambda_body(exp), env); } else if (is_begin(exp)) { exp = begin_actions(exp); while (!is_last_exp(exp)) { eval(first_exp(exp), env); exp = rest_exps(exp); } exp = first_exp(exp); goto tailcall; } else if (is_cond(exp)) { exp = cond_to_if(exp); goto tailcall; } else if (is_let(exp)) { exp = let_to_application(exp); goto tailcall; } else if (is_and(exp)) { exp = and_tests(exp); if (is_the_empty_list(exp)) { return true; } while (!is_last_exp(exp)) { result = eval(first_exp(exp), env); if (is_false(result)) { return result; } exp = rest_exps(exp); } exp = first_exp(exp); goto tailcall; } else if (is_or(exp)) { exp = or_tests(exp); if (is_the_empty_list(exp)) { return false; } while (!is_last_exp(exp)) { result = eval(first_exp(exp), env); if (is_true(result)) { return result; } exp = rest_exps(exp); } exp = first_exp(exp); goto tailcall; } else if (is_application(exp)) { procedure = eval(operator(exp), env); arguments = list_of_values(operands(exp), env); /* handle eval specially for tail call requirement */ if (is_primitive_proc(procedure) && procedure->data.primitive_proc.fn == eval_proc) { exp = eval_expression(arguments); env = eval_environment(arguments); goto tailcall; } /* handle apply specially for tail call requirement */ if (is_primitive_proc(procedure) && procedure->data.primitive_proc.fn == apply_proc) { procedure = apply_operator(arguments); arguments = apply_operands(arguments); } if (is_primitive_proc(procedure)) { return (procedure->data.primitive_proc.fn)(arguments); } else if (is_compound_proc(procedure)) { env = extend_environment( procedure->data.compound_proc.parameters, arguments, procedure->data.compound_proc.env); exp = make_begin(procedure->data.compound_proc.body); goto tailcall; } else { fprintf(stderr, "unknown procedure type\n"); exit(1); } } else { fprintf(stderr, "cannot eval unknown expression type\n"); exit(1); } fprintf(stderr, "eval illegal state\n"); exit(1); } /**************************** PRINT ******************************/ void write_pair(FILE *out, object *pair) { object *car_obj; object *cdr_obj; car_obj = car(pair); cdr_obj = cdr(pair); write(out, car_obj); if (cdr_obj->type == PAIR) { fprintf(out, " "); write_pair(out, cdr_obj); } else if (cdr_obj->type == THE_EMPTY_LIST) { return; } else { fprintf(out, " . "); write(out, cdr_obj); } } void write(FILE *out, object *obj) { char c; char *str; switch (obj->type) { case THE_EMPTY_LIST: fprintf(out, "()"); break; case BOOLEAN: fprintf(out, "#%c", is_false(obj) ? 'f' : 't'); break; case SYMBOL: fprintf(out, "%s", obj->data.symbol.value); break; case FIXNUM: fprintf(out, "%d", obj->data.fixnum.value); break; case CHARACTER: c = obj->data.character.value; fprintf(out, "#\\"); switch (c) { case '\n': fprintf(out, "newline"); break; case ' ': fprintf(out, "space"); break; default: putc(c, out); } break; case STRING: str = obj->data.string.value; putchar('"'); while (*str != '\0') { switch (*str) { case '\n': fprintf(out, "\\n"); break; case '\\': fprintf(out, "\\\\"); break; case '"': fprintf(out, "\\\""); break; default: putc(*str, out); } str++; } putchar('"'); break; case PAIR: fprintf(out, "("); write_pair(out, obj); fprintf(out, ")"); break; case PRIMITIVE_PROC: fprintf(out, "#<primitive-procedure>"); break; case COMPOUND_PROC: fprintf(out, "#<compound-procedure>"); break; case INPUT_PORT: fprintf(out, "#<input-port>"); break; case OUTPUT_PORT: fprintf(out, "#<output-port>"); break; case EOF_OBJECT: fprintf(out, "#<eof>"); break; default: fprintf(stderr, "cannot write unknown type\n"); exit(1); } } /***************************** REPL ******************************/ int main(int argc, char* argv[]) { object *exp; init(); if(argc == 1) { printf("Welcome to Bootstrap Scheme. " "Use ctrl-c to exit.\n"); while (1) { printf("> "); exp = read(stdin); if (exp == NULL) { break; } printf("ans: "); write(stdout, eval(exp, the_global_environment)); printf("\n"); } printf("Goodbye\n"); } else { /* exec a file */ FILE* fp = fopen(argv[1], "r"); if(fp == 0) { printf("no such file: %s\n", argv[1]); return -1; } while((exp = read(fp)) != NULL) { write(stdout, eval(exp, the_global_environment)); printf("\n"); } } return 0; } /**************************** MUSIC ******************************* Slipknot, Neil Young, Pearl Jam, The Dead Weather, Dave Matthews Band, Alice in Chains, White Zombie, Blind Melon, Priestess, Puscifer, Bob Dylan, Them Crooked Vultures, Black Sabbath, Pantera, Tool, ZZ Top, Queens of the Stone Age, Raised Fist, Rage Against the Machine, Primus, Black Label Society, The Offspring, Nickelback, Metallica, Jeff Beck, M.I.R.V., The Tragically Hip, Willie Nelson, Highwaymen */
C
#include<stdio.h> #include<mpi.h> #define MASTERTAG 1 #define SLAVETAG 4 int processNumber, numOfProcesses, lowerBound, upperBound, allocatedPortion, i, j, k; double matrixA[100][100], matrixB[100][100], matrixC[100][100]; MPI_Status status; MPI_Request request; void initializeAB() { for (i = 0; i < 100; i++) { for (j = 0; j < 100; j++) { matrixA[i][j] = j; } } for (i = 0; i < 100; i++) { for (j = 0; j < 100; j++) { matrixB[i][j] = j; } } } void printArray() { for (i = 0; i < 100; i++) { printf("\n"); for (j = 0; j < 100; j++) printf("%8.2f ", matrixA[i][j]); } printf("\n\n\n"); for (i = 0; i < 100; i++) { printf("\n"); for (j = 0; j < 100; j++) printf("%8.2f ", matrixB[i][j]); } printf("\n\n\n"); for (i = 0; i < 100; i++) { printf("\n"); for (j = 0; j < 100; j++) printf("%8.2f ", matrixC[i][j]); } printf("\n\n"); } int main(int argc, char *argv[]) { MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &processNumber); MPI_Comm_size(MPI_COMM_WORLD, &numOfProcesses); //master process if (processNumber == 0) { initializeAB(); for (i = 1; i < numOfProcesses; i++) { allocatedPortion = (100 / (numOfProcesses - 1)); lowerBound = (i - 1) * allocatedPortion; if (((i + 1) == numOfProcesses) && ((100 % (numOfProcesses - 1)) != 0)) { upperBound = 100; } else { upperBound = lowerBound + allocatedPortion; } MPI_Isend(&lowerBound, 1, MPI_INT, i, MASTERTAG, MPI_COMM_WORLD, &request); MPI_Isend(&upperBound, 1, MPI_INT, i, MASTERTAG + 1, MPI_COMM_WORLD, &request); MPI_Isend(&matrixA[lowerBound][0], (upperBound - lowerBound) * 100, MPI_DOUBLE, i, MASTERTAG + 2, MPI_COMM_WORLD, &request); } } //broadcast matrixB to all the slaves MPI_Bcast(&matrixB, 100*100, MPI_DOUBLE, 0, MPI_COMM_WORLD); //slave processes if (processNumber > 0) { MPI_Recv(&lowerBound, 1, MPI_INT, 0, MASTERTAG, MPI_COMM_WORLD, &status); MPI_Recv(&upperBound, 1, MPI_INT, 0, MASTERTAG + 1, MPI_COMM_WORLD, &status); MPI_Recv(&matrixA[lowerBound][0], (upperBound - lowerBound) * 100, MPI_DOUBLE, 0, MASTERTAG + 2, MPI_COMM_WORLD, &status); for (i = lowerBound; i < upperBound; i++) { for (j = 0; j < 100; j++) { for (k = 0; k < 100; k++) { matrixC[i][j] += (matrixA[i][k] * matrixB[k][j]); } } } MPI_Isend(&lowerBound, 1, MPI_INT, 0, SLAVETAG, MPI_COMM_WORLD, &request); MPI_Isend(&upperBound, 1, MPI_INT, 0, SLAVETAG + 1, MPI_COMM_WORLD, &request); MPI_Isend(&matrixC[lowerBound][0], (upperBound - lowerBound) * 100, MPI_DOUBLE, 0, SLAVETAG + 2, MPI_COMM_WORLD, &request); } //master process if (processNumber == 0) { for (i = 1; i < numOfProcesses; i++) {// untill all slaves have handed back the processed data MPI_Recv(&lowerBound, 1, MPI_INT, i, SLAVETAG, MPI_COMM_WORLD, &status); MPI_Recv(&upperBound, 1, MPI_INT, i, SLAVETAG + 1, MPI_COMM_WORLD, &status); MPI_Recv(&matrixC[lowerBound][0], (upperBound - lowerBound) * 100, MPI_DOUBLE, i, SLAVETAG + 2, MPI_COMM_WORLD, &status); } printArray(); } MPI_Finalize(); return 0; }
C
#include <OWL/Optimized3d/tensor/tensorf32.h> //Return a^n static size_t powint(unsigned int a, unsigned int n) { size_t res = 1; size_t p = a; for(unsigned int n_ = n ; n_ != 0 ; n_ >>= 1u) { if((n_ & 1u) != 0) { res *= p; } p *= p; } return res; } // static size_t tensor_index(owl_Tensorp8f32 const* T, unsigned int const* index_list) { size_t k = 0; for(unsigned int m = 0 ; m < T->dim ; m++) { k = (size_t)T->vector_dim * k + (size_t)index_list[m]; } return k; } //Creates a new Tensorp8 and sets all data to 0 // // owl_Tensorp8f32* owl_Tensorp8f32_Create(unsigned int vector_dim, unsigned int stored_dim) { owl_Tensorp8f32* T = malloc(sizeof(*T)); if(T != NULL) { T->vector_dim = vector_dim; T->stored_dim = stored_dim; T->dim = stored_dim; T->data = NULL; if(vector_dim > 0 && stored_dim > 0) { T->data = owl_v8f32_array_alloc(powint(vector_dim, stored_dim)); if(T->data != NULL) { owl_Tensorp8f32_Zero(T); } else { owl_Tensorp8f32_Destroy(T); T = NULL; } } else { owl_Tensorp8f32_Destroy(T); T = NULL; } } return T; } //Destroy a Tensorp8 // // void owl_Tensorp8f32_Destroy(owl_Tensorp8f32* T) { if(T != NULL) { owl_v8f32_array_free(T->data); free(T); } } //T = 0 // // owl_Tensorp8f32* owl_Tensorp8f32_Zero(owl_Tensorp8f32* T) { owl_v8f32 zero = owl_v8f32_zero(); size_t n = powint(T->vector_dim, T->dim); for(size_t k = 0 ; k < n ; k++) { owl_v8f32_store8(T->data + 8*k, zero); } return T; } //T = T1 + T2 // // owl_Tensorp8f32* owl_Tensorp8f32_Add(owl_Tensorp8f32* T, owl_Tensorp8f32 const* T1, owl_Tensorp8f32 const* T2) { size_t n = powint(T->vector_dim, T->dim); for(size_t k = 0 ; k < n ; k++) { owl_v8f32_store8( T->data + 8*k, owl_v8f32_add( owl_v8f32_load8(T1->data + 8*k), owl_v8f32_load8(T2->data + 8*k) ) ); } return T; } //T = T1 - T2 // // owl_Tensorp8f32* owl_Tensorp8f32_Sub(owl_Tensorp8f32* T, owl_Tensorp8f32 const* T1, owl_Tensorp8f32 const* T2) { size_t n = powint(T->vector_dim, T->dim); for(size_t k = 0 ; k < n ; k++) { owl_v8f32_store8( T->data + 8*k, owl_v8f32_sub( owl_v8f32_load8(T1->data + 8*k), owl_v8f32_load8(T2->data + 8*k) ) ); } return T; } //T = a * T1 // // owl_Tensorp8f32* owl_Tensorp8f32_ScalarMul(owl_Tensorp8f32* T, owl_Tensorp8f32 const* T1, float a) { size_t n = powint(T->vector_dim, T->dim); for(size_t k = 0 ; k < n ; k++) { owl_v8f32_store8( T->data + 8*k, owl_v8f32_scalar_mul(owl_v8f32_load8(T1->data + 8*k), a) ); } return T; } //T = T1 // // owl_Tensorp8f32* owl_Tensorp8f32_Copy(owl_Tensorp8f32* T, owl_Tensorp8f32 const* T1) { size_t n = powint(T->vector_dim, T->dim); for(size_t k = 0 ; k < n ; k++) { owl_v8f32_store8( T->data + 8*k, owl_v8f32_load8(T1->data + 8*k) ); } return T; } //T = T1 + a*T2 // // owl_Tensorp8f32* owl_Tensorp8f32_AddScalarMul(owl_Tensorp8f32* T, owl_Tensorp8f32 const* T1, owl_Tensorp8f32 const* T2, float a) { size_t n = powint(T->vector_dim, T->dim); for(size_t k = 0 ; k < n ; k++) { owl_v8f32_store8( T->data + 8*k, owl_v8f32_add_scalar_mul( owl_v8f32_load8(T1->data + 8*k), owl_v8f32_load8(T2->data + 8*k), a ) ); } return T; } //T[i0,i1,...] // // owl_v8f32 owl_Tensorp8f32_GetComp(owl_Tensorp8f32 const* T, unsigned int const* index_list) { return owl_v8f32_load8(T->data + 8 * tensor_index(T, index_list)); } //T[i0,i1,...] = f // // owl_Tensorp8f32* OWL_VECTORCALL owl_Tensorp8f32_SetComp(owl_Tensorp8f32* T, unsigned int const* index_list, owl_v8f32 f) { owl_v8f32_store8(T->data + 8 * tensor_index(T, index_list), f); return T; } // // // owl_Tensorp8f32* owl_Tensorp8f32_Contraction(owl_Tensorp8f32* T, owl_Tensorp8f32 const* T1, unsigned int contraction_index, owl_v8f32 const* v) { unsigned int dim_T = T->dim; size_t n = powint(T->vector_dim, dim_T); size_t c_pow = powint(T->vector_dim, dim_T - contraction_index); for(size_t k = 0 ; k < n ; k++) { size_t low_order = k % c_pow; size_t high_order = k - low_order; owl_v8f32 f = owl_v8f32_zero(); for(unsigned int m = 0 ; m < T->vector_dim ; m++) { size_t low_order_i = low_order + c_pow * m; f = owl_v8f32_addmul( f, owl_v8f32_load8(T1->data + 8*(low_order_i + c_pow * T->vector_dim * high_order)), v[m] ); } owl_v8f32_store8(T->data + 8*k, f); } return T; }
C
#pragma once #include <stdint.h> #ifndef UINT32_MAX #include <limits.h> #define UINT32_MAX ULONG_MAX #endif uint32_t xor128(void) { static uint32_t x = 123456789; static uint32_t y = 362436069; static uint32_t z = 521288629; static uint32_t w = 88675123; uint32_t t; t = x ^ (x << 11); x = y; y = z; z = w; return w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); } double rng() { return (xor128() % UINT32_MAX)*1. / UINT32_MAX; }
C
/* Beat Hirsbrunner and Fulvio Frapolli, University of Fribourg, January 2008 */ #include <stdio.h> int main(int argc, char *argv[]) { FILE *f; unsigned long pos; /* position to read from */ if (argc != 2) { printf("Usage: %s input_file\n", argv[0]); return -1; } f = fopen(argv[1], "r"); printf("\n%s\n\n", "loop forever (quit with ctrl-C)"); while (1) { printf("> Insert pos: "); scanf("%lu", &pos); fseek(f, pos, 0); // new seek position // printf("%lu ", ftell(f)); // current value of the file position printf("%c", fgetc(f)); // value pointed by the current file position // printf(" %lu", ftell(f)); printf("\n"); } fclose(f); }
C
#include<stdio.h> #include<conio.h> #include<stdlib.h> struct NODE { int info; struct NODE *next; struct NODE *pre; }; typedef struct NODE *cdnode; cdnode insertl(cdnode ,int); cdnode insertb(cdnode ,int); cdnode insertsp(cdnode ,int,int); cdnode createnode(cdnode,int); cdnode deletel(cdnode); cdnode deleteb(cdnode ); cdnode deletesp(cdnode,int); int lsize(cdnode); void displayf(cdnode); void displayb(cdnode); void main() { cdnode start=NULL; int a,b,c,x,e,n ; clrscr(); do { printf("enter the choice \n 1: insert from begin\n 2:insert to last\n 3:insert at specified position\n 4:delete from first\n 5:delete at last\n 6: delete from specified position\n 7:display\n 8:display backward\n 9:size\n"); scanf("%d",&c); switch(c) { case 1: printf("enter a no"); scanf("%d",&x); start =insertb(start,x); break; case 2: printf("enter a no"); scanf("%d",&x); start=insertl(start,x); break; case 3: printf("enter a no"); scanf("%d",&x); printf("enter the position"); scanf("%d",&a); start=insertsp(start,x,a); break; case 4: start=deleteb(start) ; break; case 5: start=deletel(start); break; case 6: printf("enter a position"); scanf("%d",&e); start=deletesp(start,e); break; case 7: displayf(start); break; case 8: displayb(start); break; case 9:printf("length is =%d",lsize(start)); break; default:printf("wrong choice"); } printf("if u want to continue press 1 "); scanf("%d",&b); }while(b==1); getch(); } void displayb(cdnode f) { cdnode t,l; int i; if(f==NULL) printf("underflow"); else { l=f->pre; t=l; do { printf("%d\n",t->info); t=t->pre; }while(t!=l); } } void displayf(cdnode f) { cdnode t; int i; if(f==NULL) printf("underflow"); else { t=f; do { printf("%d\n",t->info); t=t->next; }while(t!=f); } } cdnode insertb(cdnode f, int x) { cdnode temp,t; temp=createnode(temp,x); if(f==NULL) { f=temp; temp->next=f; temp->pre=f; return f; } else { (f->pre)->next=temp; temp->pre=f->pre; f->pre=temp; temp->next=f; f=temp; return (f); } } cdnode insertl(cdnode f, int x) { int i; cdnode temp,t,l; temp=createnode(temp,x); if(f==NULL) { f=temp; temp->next=f; temp->pre=f; return f; } else { l=f->pre; l->next=temp; temp->pre=l; temp->next=f; f->pre=temp; return f; } } cdnode createnode(cdnode f,int x) { f=(cdnode)malloc(sizeof(struct NODE)); f->info=x; f->pre=NULL; f->next=NULL; return f; } cdnode insertsp(cdnode f, int x,int pos) { int i,j; cdnode temp,t; temp=createnode(temp,x); i=lsize(f); if(pos==1) { f=insertb(f,x); return f; } else if(pos==i+1) { f=insertl(f,x); return f; } else if(pos>(i+1)) { printf("insertion at this position not possible"); return f; } else if(pos<=i) { cdnode t1; temp=createnode(temp,x); for(t=f,j=1;j<(pos-1);j++,t=t->next); temp->next=t->next; (t->next)->pre=temp; t->next=temp; temp->pre=t; return f; } } int lsize(cdnode f) { int i; cdnode t; for(i=0,t=f;t->next!=f;t=t->next,i++); return i+1; } cdnode deleteb(cdnode f) { cdnode t,t1,l; if(f==NULL) { printf("underflow"); return f; } else if(f->next==f) { t=f; printf("deleted item=%d",t->info); f=NULL; free(t); return f; } else { l=f->pre; t=f; f=f->next; l->next=f; f->pre=l; printf("deleted item=%d",t->info); free(t); return f; } } cdnode deletel(cdnode f) { cdnode t,t1,l; if(f==NULL) { printf("underflow"); return f; } else if(f->next==f) { t=f; f=NULL; printf("deleted item=%d",t->info); free(t); return f; } else { l=f->pre; t1=l->pre; t1->next=f; f->pre=t1; printf("deleted item=%d",l->info); free(l); return f; } } cdnode deletesp(cdnode f,int pos) { cdnode t,t1; int i,j; if(f==NULL) { printf("not posssible"); return f; } i=lsize(f); if(pos==1) { f=deleteb(f); return f; } if(pos==i) { f=deletel(f); return f; } if(pos>i) { printf("not possible"); return f; } if(pos>1 && pos <i) { for(t=f,j=1;j<(pos);j++,t=t->next); t1=t->pre; t1->next=t->next; (t->next)->pre=t1; printf("%d\n ",t->info); free(t); return f; } }
C
#include <stdio.h> #include <string.h> #include "strutil.h" int main() { char buffer[128]; char buffer2[128]; strcpy( buffer, "Esto ES UNA prueba" ); printf( "Cadena original: '%s'\n", buffer ); strtolower( buffer ); printf( "Cadena: '%s'\n", buffer ); strtoupper( buffer ); printf( "Cadena: '%s'\n", buffer ); strsubstring( buffer, buffer2, 0, 4 ); printf( "Subcadena: '%s'\n", buffer2 ); printf( "Posición de '%s' en '%s': %d\n", buffer2, buffer, strpos( buffer, buffer2 ) ); printf( "Posición de 'ES' en '%s': %d\n", buffer, strpos( buffer, " ES " ) ); printf( "Posición de '%s' en '%s': %d\n", buffer, buffer2, strpos( buffer2, buffer ) ); printf( "Posición de NULL en '%s': %d\n", buffer, strpos( buffer, NULL ) ); strinsert( "NO ", buffer, 5 ); printf( "Insertando NO queda: '%s'\n", buffer ); strsubstring( buffer, buffer2, 100, 4 ); printf( "Subcadena: '%s'\n", buffer2 ); strsubstring( buffer, buffer2, 5, 2 ); printf( "Subcadena: '%s'\n", buffer2 ); strsubstring( buffer, buffer2, 5, 200 ); printf( "Subcadena: '%s'\n", buffer2 ); printf( "Buffer es '%s'\n", buffer ); strdel( buffer, 4, 3 ); printf( "Quitando 3 de 4, queda '%s'\n", buffer ); strreplace( buffer, "S", "Z" ); printf( "Reemplazando S por Z, queda '%s'\n", buffer ); strreplace( buffer, "UNA", "OTRA" ); printf( "Reemplazando UNA por OTRA, queda '%s'\n", buffer ); strclear( buffer2 ); int i = 0; for(; i < strlen( buffer ); ++i) { strconcatchar( buffer2, buffer[ i ] ); printf( "%s\n", buffer2 ); } return 0; }
C
#include <stdio.h> #include <sys/fcntl.h> #include <stdlib.h> #include <unistd.h> typedef struct record { int num; char *name; } rec; int main(int argc, char *argv[]) { int fd = open(argv[1], O_RDWR); if (fd == -1) { printf("Unable to open the file\n"); exit(1); } printf("Enter the record number you wish to lock(from 1 to 3)\n"); int num; scanf("%d", &num); getchar(); //for clearing buffer struct flock flk; //memset(&flk, 0, sizeof(flk)); flk.l_type = F_RDLCK; flk.l_whence = SEEK_SET; flk.l_start = sizeof(rec) * (num - 1); flk.l_len = sizeof(rec); flk.l_pid = getpid(); printf("Before locking...\n"); int ret = fcntl(fd, F_SETLK, &flk); if (ret == -1) { printf("Attempt to read lock failed\n"); exit(1); } else { printf("Read locked with lock type %d : ... hit Enter to unlock\n", flk.l_type); getchar(); flk.l_type = F_UNLCK; fcntl(fd, F_SETLK, &flk); } printf("Unlocked\n"); //printf("Lock type : %d\n", flk.l_type); return 0; }
C
#include <stdio.h> #include <sys/types.h> #include <fcntl.h> #include <sys/ioctl.h> #ifdef OLD_FBIO_H_LOC #include <sun/fbio.h> #else /*OLD_FBIO_H_LOC*/ #include <sys/fbio.h> #endif /*OLD_FBIO_H_LOC*/ static char* typename(); void main( argc, argv ) int argc; char* argv[]; { int fd; struct fbgattr attr; struct fbtype type; fd = open( "/dev/fb", O_RDWR ); if ( fd < 0 ) { perror( "/dev/fb" ); exit( 1 ); } if ( ioctl( fd, FBIOGATTR, &attr ) == 0 ) printf( "FBIOGATTR says fbtype is %d (%s)\n", attr.fbtype.fb_type, typename( attr.fbtype.fb_type ) ); else perror( "FBIOGATTR failed" ); if ( ioctl( fd, FBIOGTYPE, &type ) == 0 ) printf( "FBIOGTYPE says fbtype is %d (%s)\n", type.fb_type, typename( type.fb_type ) ); else perror( "FBIOGTYPE failed" ); exit( 0 ); } static char* typename( type ) int type; { switch ( type ) { case FBTYPE_SUN1BW: return "FBTYPE_SUN1BW"; case FBTYPE_SUN1COLOR: return "FBTYPE_SUN1COLOR"; case FBTYPE_SUN2BW: return "FBTYPE_SUN2BW"; case FBTYPE_SUN2COLOR: return "FBTYPE_SUN2COLOR"; case FBTYPE_SUN2GP: return "FBTYPE_SUN2GP"; #ifdef FBTYPE_SUN5COLOR case FBTYPE_SUN5COLOR: return "FBTYPE_SUN5COLOR"; #endif /*FBTYPE_SUN5COLOR*/ case FBTYPE_SUN3COLOR: return "FBTYPE_SUN3COLOR"; #ifdef FBTYPE_MEMCOLOR case FBTYPE_MEMCOLOR: return "FBTYPE_MEMCOLOR"; #endif /*FBTYPE_MEMCOLOR*/ case FBTYPE_SUN4COLOR: return "FBTYPE_SUN4COLOR"; #ifdef FBTYPE_SUNFAST_COLOR case FBTYPE_SUNFAST_COLOR: return "FBTYPE_SUNFAST_COLOR"; #endif /*FBTYPE_SUNFAST_COLOR*/ #ifdef FBTYPE_SUNROP_COLOR case FBTYPE_SUNROP_COLOR: return "FBTYPE_SUNROP_COLOR"; #endif /*FBTYPE_SUNROP_COLOR*/ #ifdef FBTYPE_SUNFB_VIDEO case FBTYPE_SUNFB_VIDEO: return "FBTYPE_SUNFB_VIDEO"; #endif /*FBTYPE_SUNFB_VIDEO*/ #ifdef FBTYPE_SUNGIFB case FBTYPE_SUNGIFB: return "FBTYPE_SUNGIFB"; #endif /*FBTYPE_SUNGIFB*/ #ifdef FBTYPE_SUNGPLAS case FBTYPE_SUNGPLAS: return "FBTYPE_SUNGPLAS"; #endif /*FBTYPE_SUNGPLAS*/ #ifdef FBTYPE_SUNGP3 case FBTYPE_SUNGP3: return "FBTYPE_SUNGP3"; #endif /*FBTYPE_SUNGP3*/ #ifdef FBTYPE_SUNGT case FBTYPE_SUNGT: return "FBTYPE_SUNGT"; #endif /*FBTYPE_SUNGT*/ default: return "unknown"; } }
C
#include<stdio.h> int main() { int i=0,j=0; for(i=0;i<10;i++) { j=i; while(1) { if(j==5) break; printf("%d\n",j); j++; } } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* errors_handler.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ekiriche <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/04/23 13:08:01 by ekiriche #+# #+# */ /* Updated: 2018/04/23 13:08:10 by ekiriche ### ########.fr */ /* */ /* ************************************************************************** */ #include "push_swap.h" void error(void) { write(2, "Error\n", 6); exit(0); } void check_for_intmax_intmin(int argc, int i, char **argv) { char *wut; wut = ft_itoa(ft_atoi(argv[argc - i])); if (ft_strcmp(wut, argv[argc - i]) != 0 && ft_strcmp(argv[argc - i], "0") != 0 && ft_strcmp(argv[argc - i], "-v") != 0 && ft_strcmp(argv[argc - i], "-c") != 0 && ft_strcmp(argv[argc - i], "-i") != 0) { ft_memdel((void**)&wut); error(); } ft_memdel((void**)&wut); } void check_for_digit(char **argv, int argc, int i) { if (ft_atoi(argv[argc - i]) == 0 && ft_strcmp(argv[argc - i], "0") != 0 && ft_strcmp(argv[argc - i], "-v") != 0 && ft_strcmp(argv[argc - i], "-c") != 0 && ft_strcmp(argv[argc - i], "-i") != 0) error(); } void look_for_errors(int argc, char **argv) { int i; int l; i = 1; while (argc - i > 0) { l = 1; check_for_digit(argv, argc, i); check_for_intmax_intmin(argc, i, argv); while (argc - i - l > 0) { if (ft_atoi(argv[argc - i]) == ft_atoi(argv[argc - i - l]) && ft_strcmp(argv[argc - i], "-v") != 0 && ft_strcmp(argv[argc - i], "-c") != 0 && ft_strcmp(argv[argc - i], "-i") != 0) error(); l++; } i++; } } void check_for_error(char *str) { char *wut; wut = ft_itoa(ft_atoi(str)); if (ft_strcmp(wut, str) != 0 && ft_strcmp(str, "-v") != 0 && ft_strcmp(str, "-c") != 0 && ft_strcmp(str, "-i") != 0) { ft_memdel((void**)&wut); error(); } ft_memdel((void**)&wut); }
C
///String function strlen,strcpy,strcat,strcmp. #include<stdio.h> #include<string.h> int main() { char s[100],s1[100]; int i,ln,ck; gets(s); //scanf("%s%s",s,s1); //strcpy(s,s1); ///strcat(s," "); ///strcat(s,s1); ///ln=strlen(s); ///ck=strcmp(s,s1); strrev(s); printf("%s",s); } /*#include<stdio.h> #include<string.h> int main() { int i,ck; char N[100],N1[100]; while(scanf("%s%s",N,N1)!=EOF){ ck=strcmp(N,N1); if(strlen(N)>strlen(N1)) printf("N big\n"); else if(strlen(N)<strlen(N1)) printf("N1 big\n"); else if(ck==0) printf("Same\n"); else if(ck==1) printf("N big\n"); else if(ck==-1) printf("N1 Big\n"); } } */
C
#include <stdio.h> #include "Tokeniser.c" int main(){ char* value = "if 'hello' == 1 {"; Tokeniser tokeniser; Tokeniser_create(&tokeniser, value); /* Token tok; Token_create(&tok, STRING_TOKEN, "hello world"); Tokeniser_add(&tokeniser, &tok); //printf("%s", tokeniser.tokens[0]->value); */ Tokeniser_tokenise(&tokeniser); return 0; };
C
#include <iostream> #include <algorithm> using namespace std; int main() { int n; cin >> n; string t[n]; for (int i = 0; i < n; i++) cin >> t[i]; sort( t, t + n); for (int i = 0; i < n; i++) cout << t[i] << '\n'; }
C
#include <stdio.h> #include <stdlib.h> int Recur_Bin(int, int); int Itera_Bin(int, int); int main(void) { int input_1,input_2; printf("JCWUW:"); scanf("%d", &input_1); printf("JCWUU:"); scanf("%d", &input_2); printf("Recur:\n __\n"); printf(" / \\ %d\n", input_1); printf("x %d\n", Recur_Bin(input_1,input_2)); printf(" \\ / %d\n", input_2); printf(" \n\n"); printf("Itera:\n __\n"); printf(" / \\ %d\n", input_1); printf("x %d\n", Itera_Bin(input_1,input_2)); printf(" \\ / %d\n", input_2); printf(" \n"); return 0; } int Recur_Bin(int input_1, int input_2) { if(input_1 == input_2 || input_2 == 0) return 1; else return Recur_Bin(input_1 - 1,input_2) + Recur_Bin(input_1 - 1,input_2 - 1); } int Itera_Bin(int input_1, int input_2) { int i, c = 1; if(input_1 == input_2 || input_2 == 0) return 1; else { for(i = 0; i<input_2; i++) { c = c * input_1 / (i + 1); input_1--; } return c; } }
C
int test(float x, double y) { return x + y; } int main() { printf("%d (expected 15)\n", test(7.753f, 8.222)); return 0; }
C
#include "gpio_driver.h" int mem_fd; void *gpio_map; volatile unsigned *gpio; unsigned char gpio_bus[GPIO_BUS_SIZE] = {24, 4, 17, 22, 9, 25, 18, 23}; unsigned char clock_pin = 8; unsigned char key_pin = 10; unsigned char bus_dir_pin = 21; unsigned initialized = 0x00; unsigned char debug_flag = 0x01; void set_debug_flag(unsigned char v) { debug_flag = v; } // Set up a memory regions to access GPIO void setup_io() { /* open /dev/mem */ if ((mem_fd = open("/dev/mem", O_RDWR|O_SYNC) ) < 0) { printf("can't open /dev/mem \n"); exit(-1); } /* mmap GPIO */ gpio_map = mmap( NULL, //Any adddress in our space will do BLOCK_SIZE, //Map length PROT_READ|PROT_WRITE,// Enable reading & writting to mapped memory MAP_SHARED, //Shared with other processes mem_fd, //File to map GPIO_BASE //Offset to GPIO peripheral ); close(mem_fd); //No need to keep mem_fd open after mmap if (gpio_map == MAP_FAILED) { printf("mmap error %d\n", (int)gpio_map);//errno also set! exit(-1); } // Always use volatile pointer! gpio = (volatile unsigned *)gpio_map; initialized = 0x01; } // setup_io void send_key_byte(unsigned char value) { int i = 0; if (0x00 == initialized) { init(); } GPIO_CLR = 1 << clock_pin; GPIO_SET = 1 << bus_dir_pin; GPIO_SET = 1 << key_pin; for(i = 0; i < GPIO_BUS_SIZE; i++) { INP_GPIO(gpio_bus[i]); OUT_GPIO(gpio_bus[i]); if (0x01 == ((value >> i) & 0x01)) { GPIO_SET = 1 << gpio_bus[i]; } else { GPIO_CLR = 1 << gpio_bus[i]; } } usleep(CLK_DELAY); GPIO_SET = 1 << clock_pin; usleep(CLK_DELAY); GPIO_CLR = 1 << clock_pin; GPIO_CLR = 1 << bus_dir_pin; GPIO_CLR = 1 << key_pin; usleep(CLK_DELAY); if (debug_flag) { printf("Out: \t%c,\t%x\n", value, value); } } void send_data_byte(unsigned char value) { int i = 0; if (0x00 == initialized) { init(); } GPIO_CLR = 1 << clock_pin; GPIO_SET = 1 << bus_dir_pin; usleep(CLK_DELAY); for(i = 0; i < GPIO_BUS_SIZE; i++) { INP_GPIO(gpio_bus[i]); OUT_GPIO(gpio_bus[i]); if (0x01 == ((value >> i) & 0x01)) { GPIO_SET = 1 << gpio_bus[i]; } else { GPIO_CLR = 1 << gpio_bus[i]; } } usleep(CLK_DELAY); GPIO_SET = 1 << clock_pin; usleep(CLK_DELAY); GPIO_CLR = 1 << clock_pin; usleep(CLK_DELAY); GPIO_CLR = 1 << bus_dir_pin; usleep(CLK_DELAY); if (debug_flag) { printf("Out: \t%c,\t%x\n", value, value); } } unsigned char get_byte() { unsigned char value = 0x00; int i = 0; if (0x00 == initialized) { init(); } GPIO_CLR = 1 << bus_dir_pin; GPIO_SET = 1 << clock_pin; usleep(CLK_DELAY); for(i = 0; i < GPIO_BUS_SIZE; i++) { INP_GPIO(gpio_bus[i]); if (GET_GPIO(gpio_bus[i])) { value |= 1 << i; } } GPIO_CLR = 1 << clock_pin; usleep(CLK_DELAY); if (debug_flag) { printf("In: \t%c,\t%x\n", value, value); } return value; } void init(){ setup_io(); INP_GPIO(clock_pin); OUT_GPIO(clock_pin); INP_GPIO(key_pin); OUT_GPIO(key_pin); INP_GPIO(bus_dir_pin); OUT_GPIO(bus_dir_pin); printf("Driver initialized\n"); }
C
//Henry Plaskonos //ex7.3 //8 Oct 2018 //Numerically integrates a function with simpsons. #include <stdio.h> #include <math.h> #include "comphys.h" #include "comphys.c" double f(double n); double simpson(double a, double b, int points, double (*func)(double)); int main() { int ni; int points; double y; double a = 1; double b = 2; printf("Please enter the amount of points to evaluate the integral > "); ni = scanf("%d", &points); y = simpson(a, b, points, f); printf("area = %lf\n", y); return(0); } double f(double n) { return sin(n) * n; } double simpson(double a, double b, int points, double (*func)(double)) { double x1; int i; double sum = 0; double h = (b - a) / ((double)points - 1); //I casted, per recommendation sum = 0.33333333333 * h * ((*func)(a) + (*func)(b)); x1 = a + h; for (i = 2; i < points; i++) { if (i % 2 == 0) { sum += h * 1.3333333333 * (*func)(x1); } else { sum += h * 0.66666666666666 * (*func)(x1); } x1 += h; } return sum; }
C
#include <stdio.h> #define SIZE 10 int sum(int *start, int *end); int main(void){ int marbles[SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; printf("the total of numbers is %d", sum(marbles, marbles+SIZE)); return 0; } int sum(int *start, int *end){ int total = 0; while(start < end){ total += *start; start++; } return total; }
C
#ifndef GRAPH_H #define GRAPH_H #include "maplocation.h" #define MAX_GRAPH_EDGES 32 typedef MapLocation GraphVertex; typedef char Direction; typedef struct GraphEdge { GraphVertex start; Direction direction; GraphVertex end; } GraphEdge; typedef struct Graph { GraphEdge edges[MAX_GRAPH_EDGES]; int edge_count; } Graph; void GraphCreateEmpty(Graph *graph); void GraphAddEdge(Graph *graph, GraphEdge edge); #endif
C
/** Square Tone Generator */ /* @section I N C L U D E S */ #include "at89c5131.h" #include "stdio.h" #include "math.h" unsigned char sendMSB [] = {0x77, 0x7a, 0x7b, 0x7d, 0x7e, 0x7f, 0x7f, 0x7f, 0x7e,0x7d, 0x7b, 0x7a, 0x77, 0x75,0x74,0x72,0x71,0x70,0x70, 0x70,0x71,0x72,0x74,0x75}; unsigned char sendLSB [] = {0xff, 0x11, 0xff, 0xa7, 0xed, 0xb9, 0xff, 0xb9, 0xed, 0xa7, 0xff, 0x11, 0xff, 0xed,0x00,0x58,0x12,0x46,0x00, 0x46,0x12,0x58,0x00,0xed}; void SPI_Init(); void sdelay(int delay); unsigned char datasend8bit; unsigned char serial_data; sbit CS_BAR = P1^4; // Chip Select for the DAC sbit ldac = P3^0; bit transmit_completed= 0; // To check if spi data transmit is complete int iter = 12; unsigned int serial; void it_SPI(void) interrupt 9 /* interrupt address is 0x004B */ { switch ( SPSTA ) /* read and clear spi status register */ { case 0x80: serial_data=SPDAT; /* read receive data */ transmit_completed=1;/* set software flag */ break; case 0x10: /* put here for mode fault tasking */ break; case 0x40: /* put here for overrun tasking */ break; } } /** * FUNCTION_INPUTS: P1.5(MISO) serial input * FUNCTION_OUTPUTS: P1.7(MOSI) serial output * P1.4(SSbar) P1.6(SCK) */ void SPI_Init() { CS_BAR = 1; // DISABLE ADC SLAVE SELECT-CS SPCON |= 0x20; // P1.1(SSBAR) is available as standard I/O pin SPCON |= 0x01; // Fclk Periph/4 AND Fclk Periph=12MHz ,HENCE SCK IE. BAUD RATE=3000KHz SPCON |= 0x10; // Master mode SPCON &= ~0x08; // CPOL=0; transmit mode example|| SCK is 0 at idle state SPCON |= 0x04; // CPHA=1; transmit mode example IEN1 |= 0x04; // enable spi interrupt EA=1; // enable interrupts SPCON |= 0x40; // run spi;ENABLE SPI INTERFACE SPEN= 1 } void main(){ SPI_Init(); iter = 0; while (1){ if(iter == 24) { iter = 0;} CS_BAR = 0; // enable DAC as slave ldac = 1; SPDAT= sendMSB[iter]; //SPDAT = 0x7b; // Write start bit to start ADC while(!transmit_completed); transmit_completed = 0; SPDAT = sendLSB[iter]; //SPDAT = 0xf0; while(!transmit_completed); transmit_completed = 0; CS_BAR = 1; ldac = 0; iter++; } }
C
#include "game.h" void print_game_rules(void) { printf("\nA player rolls two dice. Each die has six faces. \nThese faces contain 1, 2, 3, 4, 5, and 6 spots. \nAfter the dice have come to rest, the sum of the spots on the two upward faces is calculated. \nIf the sum is 7 or 11 on the first throw, the player wins. \nIf the sum is 2, 3, or 12 on the first throw (called 'craps'), the player loses (i.e. the 'house' wins). \nIf the sum is 4, 5, 6, 8, 9, or 10 on the first throw, then the sum becomes the player's 'point.' \nTo win, you must continue rolling the dice until you 'make your point.' \nThe player loses by rolling a 7 before making the point.\n\n"); } int runmenu(void) { int option = 0; printf("\nMAIN MENU\n"); printf("\n1. Rules for game of craps\n"); printf("2. Play New Game \n"); printf("3. Continue playing game (If game has already been started) \n"); printf("4. Exit \n"); scanf("%d", &option); return option; } double get_bank_balance(void) { double balance = 0.0; printf("Enter initial bank balance from which wages will be added or subtracted from\n"); scanf("%lf", &balance); return balance; } double get_wager_amount(void) { double wager = 0.0; printf("Enter in wager for this roll\n"); scanf("%lf", &wager); return wager; } double check_wager_amount(double wager, double bankbalance) { int checkwager = 0; double overdraft = 0.0; overdraft = bankbalance - wager; while (overdraft < 0) { printf("That wager exceeds the balance in your bank account\n"); wager = get_wager_amount(); overdraft = bankbalance - wager; } return wager; } //int get_new_wager(int checkwager, double wager, double bankbalance) //{ // // while (checkwager == 0) // { // // wager = get_wager_amount(); // checkwager = check_wager_amount(wager, bankbalance); // } // return wager; //} int roll_die(void) { int die = 0, chance = 0, bob = 0, bob1 = 0, bob2 =0; srand((unsigned int)time(NULL)); /* bob1 = rand(); srand((unsigned int)time(NULL)); bob2 = rand(); bob = bob1 * bob2;*/ //chance = rand() % 2 + 1; //if (chance == 0) die = rand() % 6 + 1; /* else die = rand() % 6 + 1;*/ return die; } int calculate_sum_dice(int die1_value, int die2_value) { int sum = 0; sum = die1_value + die2_value; return sum; } int is_win_loss_or_point(int sum_dice) { if (sum_dice == 7 || sum_dice == 11) return 1; //player wins else if (sum_dice == 2 || sum_dice == 3 || sum_dice == 12) return 0; //player loses else if (sum_dice <= 12 && sum_dice >= 2) return -1; //player point return 99; //error checking } void random(unsigned int milliseconds) { Sleep(milliseconds); } int is_point_loss_or_neither(int sum_dice, int point_value) { if (sum_dice == point_value) return 1; //player win else if (sum_dice == 7) return 0; //player lost else return -1; //need to roll again (not condition 1 or 2) } double adjust_bank_balance(double bank_balance, double wager_amount, int add_or_subtract) { if (add_or_subtract == 1) // If they won, add wager bank_balance += wager_amount; else if (add_or_subtract == 0) //IF they lost, take away wager bank_balance -= wager_amount; return bank_balance; } void chatter_messages(int number_rolls, int win_loss_neither, double initial_bank_balance, double current_bank_balance, double wager) { /*if (win_loss_neither == 0) printf("Sorry, you busted!"); else if (win_loss_neither == 1) printf("nice roll");*/ if (initial_bank_balance > 1000) { printf("\nDeep pockets eh?\n\n"); } else if (current_bank_balance < 50) printf("\nOh, you're going for broke, huh?\n\n"); else if (wager<10) printf("\nAw cmon, take a chance!\n\n"); else if (current_bank_balance > 10000) { printf("\nYou're up big, now's the time to cash in your chips!\n\n"); } else if (number_rolls >= 16) { printf("\nLong game ain't it!\n\n"); } } int yourbroke(double bankbalance, int *newgame) { int continueplaying = 0; if (bankbalance <= 0) { printf("You have gone broke!\n"); //*newgame = 1; return 2; } if (bankbalance > 0) { continueplaying = wanttocontinue(); return continueplaying; } } int wanttocontinue(void) { int continueplaying = 0; printf("\nWould you like to play again?\n"); printf("If yes, please enter a 0, if you would like to view the menu again, enter a 1\n"); printf("If you would like to exit, please enter any other number."); scanf("%d", &continueplaying); return continueplaying; }
C
#include <stdio.h> void strCpy(char *s, char *t); int main() { char str1[] = "hello, world"; char str2[16]; strCpy(str2, str1); printf("now the str2 is: %s\n", str2); } /* 字符串复制(指针进阶版)*/ void strCpy(char *s, char *t) { while ((*s++ = *t++) != '\0') ; }
C
#ifndef STATIC_HASH_TABLE_H_INCLUDED_ #define STATIC_HASH_TABLE_H_INCLUDED_ #define STATIC_HASH_TABLE_SIZE 10 #include <stdlib.h> #include <stdio.h> #include <stdbool.h> typedef struct bucket_ { char* key; int value; struct bucket_* next_bucket; struct bucket_* prev_bucket; } bucket; typedef struct static_hash_table_ { bucket* store[STATIC_HASH_TABLE_SIZE]; unsigned int size; unsigned int capacity; } static_hash_table; static_hash_table* static_hash_table_create(); static_hash_table* static_hash_table_put(static_hash_table*, char*, int); void static_hash_table_clear(static_hash_table*); void static_hash_table_drop_table(static_hash_table*); void static_hash_table_print(static_hash_table*); int static_hash_table_get(static_hash_table*, char*, int*); bool static_hash_table_remove(static_hash_table*, char*); int calculate_hash(char*, int); #endif
C
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <dirent.h> #include <getopt.h> static const char SHORT_USAGE[] = "Usage: walk [OPTION...] [DIRECTORY...]\n"; static const char HELP[] = "Recursively walk the specified directories (or current directory, if none is\n" "specified.\n\n" " -0, --null separate filenames by a null character\n" " --help display this help and exit\n"; static const char ASK_FOR_HELP[] = "Try 'walk --help' for more information.\n"; static const char *const JUST_CURRENT_DIRECTORY[] = {".", NULL}; // Like readdir(3), but resets errno(3) before the call to make it easy to // check. static struct dirent *readdir2(DIR *const dirp) { errno = 0; return readdir(dirp); } // Like realloc(3), but exits the binary in an out-of-memory situation. static void *xrealloc(void *ptr, const size_t size) { if (!(ptr = realloc(ptr, size))) { perror("realloc"); exit(EXIT_FAILURE); } return ptr; } static void strcpy3(char *dest, const char *s1, const char *s2, const char *s3) { stpcpy(stpcpy(stpcpy(dest, s1), s2), s3); } static void put_filename(const char *filename, bool null_terminate) { if (null_terminate) { fputs(filename, stdout); fputc(0, stdout); } else { puts(filename); } } // Walks the directory named dirname, printing the names of all files it // contains (but not the name of the directory itself). Returns 2 if dirname is // not a directory and 1 if another error occurs. static int walk(const char dirname[], bool null_terminate) { DIR *const dir = opendir(dirname); if (!dir) { if (errno != ENOTDIR) { perror(dirname); return 1; } return 2; } int r = 0; char *filename = NULL; for (const struct dirent *f = readdir2(dir); f; f = readdir2(dir)) { if (strcmp(f->d_name, ".") == 0 || strcmp(f->d_name, "..") == 0) continue; filename = xrealloc( filename, strlen(dirname) + 1 + strlen(f->d_name) + 1); strcpy3(filename, dirname, "/", f->d_name); // TODO([email protected]): Emulate Plan 9's cleanname(3). put_filename(filename, null_terminate); // Walk the file if we can successfully open it as a directory. // Don't worry about it if it's not one (walk(filename) == 2). if ((f->d_type == DT_DIR || f->d_type == DT_UNKNOWN) && walk(filename, null_terminate) == 1) r = 1; } if (errno) { // from readdir perror(dirname); r = 1; } free(filename); if (closedir(dir)) { perror(dirname); r = 1; } return r; } int main(const int argc, char *const argv[]) { static const struct option long_options[] = { {"help", no_argument, NULL, 'h'}, {"null", no_argument, NULL, '0'}, {NULL, 0, NULL, 0}, }; bool null_terminate = false; while (true) { const int c = getopt_long(argc, argv, "0", long_options, NULL); if (c == -1) break; switch (c) { case 'h': fputs(SHORT_USAGE, stdout); fputs(HELP, stdout); return 0; case '0': null_terminate = true; break; case '?': fputs(ASK_FOR_HELP, stderr); return 1; default: fputs("Internal error; please report.\n", stderr); return 1; } } int r = 0; const char *const *const dirs = argc == optind ? JUST_CURRENT_DIRECTORY : (const char *const *)argv + optind; for (int i = 0; dirs[i]; ++i) { put_filename(dirs[i], null_terminate); r |= walk(dirs[i], null_terminate); } return r; }
C
#include <stdio.h> #include <math.h> #include <malloc.h> float Determinante(int n, float **m){ int sinal = 1; int i, j, k; float det = 0; float **A; if(n == 1){ return m[0][0]; } else { A =(float**) malloc((n-1)*sizeof(float*)); for (i=0;i<n;i++) { A[i] = (float*) malloc((n-1)*sizeof(float)); } for(k=0;k<n;k++){ for (j=0;j<k;j++){ for(i=1;i<n;i++){ A[i-1][j] = m[i][j]; } } for (j=k+1;j<n;j++){ for(i=1;i<n;i++){ A[i-1][j-1] = m[i][j]; } } det += sinal*(m[0][k]*Determinante(n-1, A)); sinal *= -1; } } return det; } void SistemaTriangularInferior(int ordem, float **matriz, float *termos, float **solucao) { int i, j; float s = 0; for(i = 0; i < ordem; i++) { s = termos[i]; for(j = 0; j < i; j++) { s = s - (matriz[i][j] * (*solucao)[j]); } (*solucao)[i] = s/matriz[i][i]; } } void SistemaTriangularSuperior(int ordem, float **matriz, float *termos, float **solucao) { int i, j; float s = 0; for(i = ordem - 1; i >= 0; i--) { s = termos[i]; for(j = ordem - 1; j > i; j--) { s = s - (matriz[i][j] * (*solucao)[j]); } (*solucao)[i] = s/matriz[i][i]; } } void DecomposicaoLU(int ordem, float **matriz, float *termos, float **solucao) { int i, j, linha, coluna, uc, lc, uf, lf, k, n, o = 0; float **m, **l, **u, *y, soma; for(i = ordem; i >= 1; i--) { if(Determinante(i, matriz) == 0) { printf("\nSistema nao converge!\n"); o = 1; break; } } if(o == 0) { u = (float**) malloc(ordem * sizeof(float*)); for(i = 0; i < ordem; i++) { u[i] = (float*) malloc(ordem * sizeof(float)); for(j = 0; j < ordem; j++) { u[i][j] = 0; } } l = (float**) malloc(ordem * sizeof(float*)); for(i = 0; i < ordem; i++) { l[i] = (float*) malloc(ordem * sizeof(float)); for(j = 0; j < ordem; j++) { l[i][j] = 0; } } soma = 0; uc = 0; lc = 0; linha = 0; coluna = 0; for(n = 0; n < ordem; n++) { for(j = uc; j < ordem; j++) { for(k = 0; k <= linha - 1; k++) { soma = soma + l[linha][k] * u[k][j]; } u[linha][j] = matriz[linha][j] - soma; soma = 0; } linha = linha + 1; uc = uc + 1; for(i = lc; i < ordem; i++) { for(k = 0; k <= coluna - 1; k++) { soma = soma + l[i][k] * u[k][coluna]; } l[i][coluna] = (matriz[i][coluna] - soma) / u[coluna][coluna]; soma = 0; } coluna = coluna + 1; lc = lc + 1; } y = (float*) malloc(ordem * sizeof(float)); SistemaTriangularInferior(ordem, l, termos, &y); SistemaTriangularSuperior(ordem, u, y, solucao); } } void GaussCompacto(int ordem, float **matriz, float **termos, float **solucao) { int i, j, o = 0, n, uc, lc, k, linha, coluna; float **a, **u, **l, soma; for(i = ordem; i >= 1; i--) { if(Determinante(i, matriz) == 0) { printf("\nSistema nao converge!\n"); o = 1; break; } } if(o == 0) { a = (float**) malloc(ordem * sizeof(float*)); for(i = 0; i < ordem; i++) { a[i] = (float*) malloc((ordem + 1) * sizeof(float)); for(j = 0; j < ordem; j++) { a[i][j] = matriz[i][j]; } a[i][ordem] = (*termos)[i]; } u = (float**) malloc(ordem * sizeof(float*)); for(i = 0; i < ordem; i++) { u[i] = (float*) malloc((ordem + 1) * sizeof(float)); for(j = 0; j < ordem + 1; j++) { u[i][j] = 0; } } l = (float**) malloc(ordem * sizeof(float*)); for(i = 0; i < ordem; i++) { l[i] = (float*) malloc(ordem * sizeof(float)); for(j = 0; j < ordem; j++) { l[i][j] = 0; } } soma = 0; uc = 0; lc = 1; for(n = 0; n < ordem; n++) { for(j = uc; j < ordem + 1; j++) { for(k = 0; k <= n - 1; k++) { soma = soma + l[n][k] * u[k][j]; } u[n][j] = a[n][j] - soma; soma = 0; } uc = uc + 1; for(i = lc; i < ordem; i++) { for(k = 0; k <= n - 1; k++) { soma = soma + l[i][k] * u[k][n]; } l[i][n] = (a[i][n] - soma) / u[n][n]; soma = 0; } lc = lc + 1; } for(i = 0; i < ordem; i++) { (*termos)[i] = u[i][ordem]; } SistemaTriangularSuperior(ordem, u, *termos, solucao); } } void GaussSeidel(int ordem, float **matriz, float *termos, float e, float *inicial, int maximo, float **solucao, int *iteracoes) { float soma, a, d, max, *b, *x, numerador, denominador, erro, *anterior; int i, j, o = 0, k; soma = 0; for(i = 0; i < ordem; i++) { if(matriz[i][i] == 0) { printf("\nSistema nao converge!\n"); o = 1; break; } } if(o == 0) { d = Determinante(ordem, matriz); if(d == 0) { printf("\nSistema nao converge!\n"); o = 1; } if(o == 0) { for(i = 0; i < ordem; i++) { for(j = 0; j < ordem; j++) { if(j != i) { a = (matriz[i][j] / matriz[i][j]); if(a < 0) { a = a * (-1); } soma = soma + a; } } if(i == 0) { max = soma; } else { if(soma > max) { max = soma; } } soma = 0; } if(max >= 1) { o = 2; } } if(o == 2) { b = (float*) malloc(ordem * sizeof(float)); for(i = 0; i < ordem; i++) { soma = 0; for(j = 0; j < i - 1; j++) { a = matriz[i][j] / matriz[i][i]; if(a < 0) { a = a * (-1); } soma = soma + a * b[j]; } for(j = i + 1; j < ordem; j++) { a = matriz[i][j] / matriz[i][i]; if(a < 0) { a = a * (-1); } soma = soma + a; } b[i] = soma; if(i == 0) { max = b[i]; } else { if(b[i] > max) { max = b[i]; } } } if(max < 1) { o = 0; } free(b); } if(o == 0) { x = inicial; k = 0; erro = e; max = -1; anterior = (float*) malloc(ordem * sizeof(float)); do { for(i = 0; i < ordem; i++) { x[i] = termos[i]; for(j = 0; j < i; j++) { x[i] = x[i] - (matriz[i][j]) * x[j]; } for(j = i + 1; j < ordem; j++) { x[i] = x[i] - (matriz[i][j]) * x[j]; } x[i] = x[i] / matriz[i][i]; } if(k > 0) { for(i = 0; i < ordem; i++) { numerador = x[i] - anterior[i]; if(numerador < 0) { numerador = numerador * (-1); } if(numerador > max) { max = numerador; } } numerador = max; max = -1; for(i = 0; i < ordem; i++) { denominador = x[i]; if(denominador < 0) { denominador = denominador * (-1); } if(denominador > max) { max = denominador; } } denominador = max; max = -1; erro = numerador/denominador; } k++; for(i = 0; i < ordem; i++) { anterior[i] = x[i]; } } while((erro >= e)&&(k + 1 <= maximo)); (*solucao) = x; (*iteracoes) = k; } } } int main() { int i; int ordem; float **matriz; float *termos; float *solucao; float determinante; float *inicial; int iteracoes; ordem = 3; matriz = (float**)malloc(ordem*sizeof(int)); for(i = 0; i < ordem; i++) { matriz[i] = (float*) malloc(ordem * sizeof(float)); } matriz[0][0] = 5; matriz[0][1] = 1; matriz[0][2] = 1; matriz[1][0] = 3; matriz[1][1] = 4; matriz[1][2] = 1; matriz[2][0] = 3; matriz[2][1] = 3; matriz[2][2] = 6; solucao = (float*) malloc(ordem*sizeof(float)); termos = (float*) malloc(ordem*sizeof(float)); termos[0] = 5; termos[1] = 6; termos[2] = 0; inicial = (float*) malloc(ordem * sizeof(float)); inicial[0] = 0; inicial[1] = 0; inicial[2] = 0; //DecomposicaoLU(ordem, matriz, termos, &solucao); //GaussCompacto(ordem, matriz, &termos, &solucao); GaussSeidel(ordem, matriz, termos, 0.01, inicial, 5, &solucao, &iteracoes); for(i = 0; i < ordem; i++) { printf("%f ", solucao[i]); } printf("Iteracoes = ", iteracoes); return (0); }
C
// Copyright 2007-2009 Russ Cox. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include <stdio.h> #include <stdlib.h> #include "reos_pattern.h" #include "unicode_inst.h" #include "unicode_tree.h" #include "unicode/uchar.h" #include "unicode/ustdio.h" #include "unicode/utypes.h" TreeNode* new_unicode_tree_node(int type, TreeNode *left, TreeNode *right) { TreeNode *node = malloc(sizeof(TreeNode)); if (type == NodeUnicodeChar || type == NodeUnicodeRange) node->args = malloc(sizeof(UnicodeTreeNodeArgs)); else node->args = 0; node->type = type; node->left = left; node->right = right; node->x = 0; node->y = 0; return node; } void free_unicode_tree_node(TreeNode *node) { if (node) { if (node->type == NodeUnicodeChar || node->type == NodeUnicodeRange) { free(node->args); free_unicode_tree_node(node->left); free_unicode_tree_node(node->right); free(node); } else free_standard_tree_node(node, free_unicode_tree_node); } } int unicode_tree_node_compile(ReOS_Pattern *pattern, int index, TreeNode *node, ReOS_InstFactoryFunc inst_factory) { switch (node->type) { case NodeUnicodeChar: { ReOS_Inst *lit = inst_factory(OpUnicodeChar); ((UnicodeInstArgs *)lit->args)->c1 = ((UnicodeTreeNodeArgs *)node->args)->c1; pattern->set_inst(pattern, lit, index); return index+1; } case NodeUnicodeRange: { ReOS_Inst *range = inst_factory(OpUnicodeRange); UnicodeInstArgs *inst_args = range->args; UnicodeTreeNodeArgs *node_args = node->args; inst_args->c1 = node_args->c1; inst_args->c2 = node_args->c2; pattern->set_inst(pattern, range, index); return index+1; } default: return standard_tree_node_compile(pattern, index, node, inst_factory, unicode_tree_node_compile); } } void print_unicode_tree(TreeNode *node) { UnicodeTreeNodeArgs *args = (UnicodeTreeNodeArgs *)node->args; switch (node->type) { case NodeUnicodeChar: { printf("Token("); if (u_isgraph(args->c1)) { printf("'"); UFILE *u_stdout = u_finit(stdout, 0, 0); u_fputc(args->c1, u_stdout); u_fclose(u_stdout); printf("'"); } else printf("0x%x", args->c1); printf(")"); break; } case NodeUnicodeRange: { printf("Range("); UFILE *u_stdout = u_finit(stdout, 0, 0); if (u_isgraph(args->c1)) { printf("'"); u_fputc(args->c1, u_stdout); printf("'"); } else printf("0x%x", args->c1); printf("-"); if (u_isgraph(args->c2)) { printf("'"); u_fputc(args->c2, u_stdout); printf("'"); } else printf("0x%x", args->c2); u_fclose(u_stdout); printf(")"); break; } default: print_standard_tree(node, print_unicode_tree); } }
C
#include<stdlib.h> #include<limits.h> #include "shedl_utils.c" void srtf(struct Proc* procs, int n){ sort_procs(procs, n); print_procs(procs,n); int c=0/*keep track of finished process*/, time=0; int shortest = INT_MAX/*a high fucking value*/; int index = -1/* assume that we have not found our smallest reamainig time process*/; // itereate while until all process are completed while(c<n){ for(int i=0;i<n;i++){ // choose the process with the smallest remaining time. if(procs[i].rt /*if process is not completed*/ && time >= procs[i].at /*and the process has arrived*/ ){ if(procs[i].rt < shortest){ /*choose i as the process to be executed if remaining time of i is the samllest In case of equat remaining time fifo will be taken as the process are sorted by the arrival time */ index = i; shortest = procs[i].rt; } } } if(index == -1){ // if no process is found printf("No process to run at : %dms\n",time); time ++; continue; } // if a process is found: printf("Running process P(%d)\n" ,procs[index].pid); procs[index].rt -= 1; time +=1; if(procs[index].rt == 0) { // the process has completed printf("Process P(%d) completed at : %dms\n",procs[index].pid,time); procs[index].tat = time - procs[index].at; procs[index].wt = procs[index].tat - procs[index].bt; shortest = INT_MAX; index = -1; c++; } } } int main(){ int n,i; printf("Enter the number of processes: "); scanf("%d",&n); struct Proc procs[n]; for(i =0 ;i<n; i++){ printf("Enter the arrival time of process %d: ",i); scanf("%d",& procs[i].at); procs[i].pid = i; procs[i].wt = 0; procs[i].tat = 0; } for(i=0; i<n; i++){ printf("Enter the burst time of process %d: ",i); scanf("%d",& procs[i].bt); procs[i].rt = procs[i].bt; } print_procs(procs,n); srtf(procs,n); gant_chart(procs,n); return 0; }
C
#include "generator.h" #include <stdio.h> static PyObject* generator_new(PyTypeObject* type, PyObject* args, PyObject* kwargs) { // Parse arguments (iterator: set of dicts) PyObject *sequence; if (!PyArg_ParseTuple(args, "O", &sequence)) { return NULL; } // Check arguments if (!PySequence_Check(sequence)) { PyErr_SetString(PyExc_TypeError, "First parameter should be Iterable"); return NULL; } Py_ssize_t len = PySequence_Length(sequence); if (len == -1) { return NULL; } // Create new GeneratorState and initialize its state GeneratorState* gen = (GeneratorState*)type->tp_alloc(type, 0); if (gen == NULL) { return NULL; } // Initialize generator Py_INCREF(sequence); gen->sequence = sequence; gen->seq_index = 0; return (PyObject*)gen; } static void generator_dealloc(GeneratorState* gen) { // We need `XDECREF` here because when the generator is exhausted, `gen->sequence` is cleared // with `Py_CLEAR` which sets it to NULL Py_XDECREF(gen->sequence); Py_TYPE(gen)->tp_free(gen); } static PyObject* generator_next(GeneratorState* gen) { PyObject* elem = PySequence_GetItem(gen->sequence, gen->seq_index); if (elem) { gen->seq_index++; return elem; } // The reference to the sequence is cleared in the first generator call after its exhaustion // (after the call that returned the last element). Py_CLEAR will be harmless for subsequent // calls since it's idempotent on NULL if (PyErr_ExceptionMatches(PyExc_IndexError) || PyErr_ExceptionMatches(PyExc_StopIteration)) { PyErr_Clear(); gen->seq_index = -1; Py_CLEAR(gen->sequence); } return NULL; } PyTypeObject PyGenerator_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "generator", // tp_name sizeof(GeneratorState), // tp_basicsize 0, // tp_itemsize (destructor)generator_dealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_reserved 0, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags 0, // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset PyObject_SelfIter, // tp_iter (iternextfunc)generator_next, // tp_iternext 0, // tp_methods 0, // tp_members 0, // tp_getset 0, // tp_base 0, // tp_dict 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset 0, // tp_init PyType_GenericAlloc, // tp_alloc generator_new, // tp_new };
C
#define STACK_MIN_SIZE 1 #define EMPTY_STACK -1 typedef struct stack_record *Stack; struct stack_record{ int capacity; int stack_top; stack_elem_t *elements; }; Stack create_stack(int size); void dispose_stack(Stack S); void push(stack_elem_t element, Stack S); int is_full(Stack S); int is_empty(Stack S); Stack create_stack(int size){ Stack S; if (size < STACK_MIN_SIZE){ printf("Stack size too small\n"); exit(1); } S = (Stack)malloc(sizeof(struct stack_record) * size); if (S == NULL){ printf("Out of space while creating a stack\n"); exit(1); } S->capacity = size; S->elements = (stack_elem_t *)malloc(sizeof(stack_elem_t) * size); if (S->elements == NULL){ printf("Out of space while creating the stack array\n"); exit(1); } S->stack_top = EMPTY_STACK; return S; } void dispose_stack(Stack S){ if (S != NULL){ free(S->elements); free(S); } } void push(stack_elem_t element, Stack S){ if (is_full(S)){ printf("Push to a full stack\n"); exit(1); } S->elements[++S->stack_top] = element; } stack_elem_t pop(Stack S){ stack_elem_t element; if (is_empty(S)){ printf("Pop from an empty stack\n"); exit(1); } element = S->elements[S->stack_top--]; return element; } stack_elem_t top(Stack S){ if (is_empty(S)){ printf("Trying to get the top of an empty stack\n"); exit(1); } return S->elements[S->stack_top]; } int is_full(Stack S){ return S->stack_top + 1 == S->capacity; } int is_empty(Stack S){ return S->stack_top == EMPTY_STACK; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> /* use the second bit to store result, keep first bit to calculate neighbors DIE2DIE: 00 LIVE2DIE: 01 DIE2LIVE: 10 LIVE2LIVE: 11 */ enum { DIE2DIE = 0, LIVE2DIE = 1, DIE2LIVE = 2, LIVE2LIVE = 3 }; int neighbors(int **board, int boardRowSize, int boardColSize, int i, int j) { int n = 0; if (i - 1 >= 0) n += board[i - 1][j] & 0x01; /* N */ if (i - 1 >= 0 && j + 1 < boardColSize) n += board[i - 1][j + 1] & 0x01; /* NE */ if (j + 1 < boardColSize) n += board[i][j + 1] & 0x01; /* E */ if (i + 1 < boardRowSize && j + 1 < boardColSize) n += board[i + 1][j + 1] & 0x01; /* SE */ if (i + 1 < boardRowSize) n += board[i + 1][j] & 0x01; /* S */ if (i + 1 < boardRowSize && j - 1 >= 0) n += board[i + 1][j - 1] & 0x01; /* SW */ if (j - 1 >= 0) n += board[i][j - 1] & 0x01; /* W */ if (i - 1 >= 0 && j - 1 >= 0) n += board[i - 1][j - 1] & 0x01; /* NW */ return n; } void gameOfLife(int** board, int boardRowSize, int boardColSize) { int i, j; for (i = 0; i < boardRowSize; i++) { for (j = 0; j < boardColSize; j++) { int n = neighbors(board, boardRowSize, boardColSize, i, j); if (board[i][j] == 1) {/* live cell */ if (n < 2 || n > 3) { /* die */ board[i][j] = LIVE2DIE; } else { /* 2 or 3, lives on the next generation */ board[i][j] = LIVE2LIVE; } } else if (board[i][j] == 0) {/* dead cell */ if (n == 3) { /* becomes live */ board[i][j] = DIE2LIVE; } else { board[i][j] = DIE2DIE; } } } } for (i = 0; i < boardRowSize; i++) { for (j = 0; j < boardColSize; j++) { board[i][j] >>= 1; /* translate result */ } } } /* Helper functions */ void print(int **board, int boardRowSize, int boardColSize) { int i, j; for (i = 0; i < boardRowSize; i++ ){ for (j = 0; j < boardColSize; j++) { printf("%d ", board[i][j]); } printf("\n"); } printf("\n"); } int ** generateBoard(char **board_ch, int boardRowSize, int boardColSize) { int **board_i = (int **)malloc(boardRowSize * sizeof(int *)); int i, j; for (i = 0; i < boardRowSize; i++) { board_i[i] = (int *)malloc(boardColSize * sizeof(int)); for (j = 0; j < boardColSize; j++) { board_i[i][j] = board_ch[i][j] - '0'; } } return board_i; } int main() { char *strs[] = { "1001", "0110", "1101", "0110" }; int rows = sizeof(strs) / sizeof(strs[0]); int cols = strlen(strs[0]); int **board = generateBoard(strs, rows, cols); printf("Board:\n"); print(board, rows, cols); gameOfLife(board, rows, cols); printf("Result:\n"); print(board, rows, cols); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* l3d_ray_hit_utils2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ohakola <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/30 16:49:21 by ohakola #+# #+# */ /* Updated: 2021/05/03 15:20:37 by ohakola ### ########.fr */ /* */ /* ************************************************************************** */ #include "lib3d.h" /* ** Get closest hit whether triangle or not (aabb might be the other) */ void l3d_get_closest_hit(t_hits *hits, t_hit **closest) { t_hits *head; t_hit *hit; head = hits; *closest = NULL; while (head) { hit = (t_hit *)head->content; if (*closest == NULL) *closest = hit; if (*closest && hit != NULL && hit->t <= (*closest)->t) *closest = hit; head = head->next; } } /* ** Get closest triangle hit within range `range` */ void l3d_get_closest_triangle_hit_at_range(t_hits *hits, t_hit **closest, uint32_t ignore_id, float range) { t_hits *head; t_hit *hit; head = hits; *closest = NULL; while (head) { hit = (t_hit *)head->content; if (*closest == NULL && hit->t > 0.0 && hit->t <= range && hit->triangle->parent->id != ignore_id) *closest = hit; if (*closest && hit && hit->t > 0.0 && hit->t <= range && hit->triangle->parent->id != ignore_id && hit->t <= (*closest)->t) *closest = hit; head = head->next; } if (*closest && !(*closest)->triangle) *closest = NULL; } /* ** Get closest triangle hit from hits that is facing dir */ void l3d_get_closest_facing_triangle_hit(t_hits *hits, t_hit **closest, t_vec3 dir, uint32_t ignore_id) { t_hits *head; t_hit *hit; head = hits; *closest = NULL; while (head) { hit = (t_hit *)head->content; if (*closest == NULL && hit->t > 0.0 && hit->triangle->parent->id != ignore_id && ml_vector3_dot(hit->normal, dir) < 0) *closest = hit; if (*closest && hit && hit->t > 0.0 && hit->triangle->parent->id != ignore_id && hit->t <= (*closest)->t && ml_vector3_dot(hit->normal, dir) < 0) *closest = hit; head = head->next; } if (*closest && !(*closest)->triangle) *closest = NULL; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* output_h.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gfielder <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/18 15:32:35 by gfielder #+# #+# */ /* Updated: 2019/04/23 18:31:25 by gfielder ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> #include <sys/ioctl.h> #include "libft.h" #include "ls.h" static uint16_t g_num_entries = 0; static uint16_t g_col_size = 8; static uint16_t g_num_rows; static uint16_t g_num_cols; static uint16_t g_current_column; static uint16_t g_current_row; void ftls_out_h(t_file *f, t_ls_options *options) { (void)options; ftls_outh_new_entry(); ft_putstr(f->name); } void ftls_note_entry(t_file *f, uint16_t len) { (void)f; g_col_size = tty_note_length(len); g_num_entries++; } void ftls_end_column_output(t_file *f, t_ls_options *options) { (void)f; (void)options; g_col_size = 8; if (!g_num_entries) return ; g_num_entries = 0; tty_end_columns(); } void ftls_begin_column_output(t_file *f, t_ls_options *options) { uint16_t ws; uint16_t i; (void)f; (void)options; if (!g_num_entries) return ; ws = tty_get_window_width(); g_num_cols = ws / g_col_size; if (g_num_cols == 0) g_num_cols = 1; g_num_rows = (g_num_entries / g_num_cols) + 1; if (g_num_entries / g_num_rows + 1 < g_num_cols) { g_num_cols = g_num_entries / g_num_rows + 1; g_col_size = tty_note_length(ws / g_num_cols); } g_current_column = -1; g_current_row = 65535; i = 0; while (i++ < g_num_rows) write(1, "\n", 1); write(1, "\x1B[", 2); ft_putnbr((int)g_num_rows); write(1, "A", 1); } void ftls_outh_new_entry(void) { if (g_current_row >= g_num_rows) { g_current_row = 1; tty_begin_column(++g_current_column); } else { tty_next_row(); g_current_row++; } }
C
#include<stdio.h> void toh(int,char,char,char); int main() { int num; printf("Enter the number of the disk:"); scanf("%d",&num); printf("\nThe sequence of moves in the tower of hanoi are:"); toh(num,'A','C','B'); return 0; } void toh(int num,char frompeg,char topeg,char auxpeg) { if(num==1) { printf("\nmove 1 disk from %c peg to %c peg\n",frompeg,topeg); return; } toh(num-1,frompeg,auxpeg,topeg); printf("Move %d disk from %c peg to %c peg",num,frompeg,topeg); toh(num-1,auxpeg,topeg,frompeg); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* algo.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tle-meur <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/02/04 20:16:15 by tle-meur #+# #+# */ /* Updated: 2016/02/11 16:33:52 by tle-meur ### ########.fr */ /* */ /* ************************************************************************** */ #include <limits.h> #include "filler.h" #include "libft/libft.h" static void find_way(t_filler *f) { int i; int j; int minx; int miny; i = -1; minx = INT_MAX / 2; miny = INT_MAX / 2; while (++i < f->grid.hig && (j = -1)) while (++j < f->grid.wid) if (f->grid.g[i][j] == f->itschars[0] || f->grid.g[i][j] == f->itschars[1]) if (FT_ABS(f->y - i) + FT_ABS(f->x - j) < FT_ABS(miny - i) + FT_ABS(minx - j) && ((minx = j) || 1)) miny = i; if (minx == INT_MAX / 2) f->way = LEFT | UP; else if (minx <= f->x && miny <= f->x) f->way = LEFT | UP; else if (minx <= f->x) f->way = LEFT | DOWN; else if (miny <= f->x) f->way = RIGHT | UP; else f->way = RIGHT | DOWN; } static int put_form(t_filler *f, t_grid *g, int y, int x) { int i; int j; t_grid *p; p = &f->form; i = -1; while (++i < p->hig && (j = -1)) while (++j < p->wid) if (p->g[i][j] == '*' && ((f->y - y + i < 0 || f->y - y + i >= g->hig || f->x - x + j < 0 || f->x - x + j >= g->wid) || (!(i == y && j == x) && g->g[f->y - y + i][f->x - x + j] != '.'))) return (0); return (1); } static int test_form(t_filler *f, t_grid *g, int *x, int *y) { int i; int j; t_grid *p; int im; int jm; p = &f->form; i = (f->way | UP) ? p->hig : -1; im = (f->way | UP) ? -1 : p->hig; jm = (f->way | LEFT) ? -1 : p->wid; while ((i = (f->way | UP) ? i - 1 : i + 1) != im && ((j = (f->way | LEFT) ? p->wid : -1) || 1)) while ((j = (f->way | LEFT) ? j - 1 : j + 1) != jm) if (p->g[i][j] == '*' && put_form(f, g, i, j) && ((*x = f->x - j) || 1) && ((*y = f->y - i) || 1) && ((i = (f->way | UP) ? -1 : p->hig) || 1) && ((im = (f->way | UP) ? p->hig : -1) || 1) && ((jm = (f->way | LEFT) ? p->wid : -1) || 1)) while ((i = (f->way | UP) ? i + 1 : i - 1) != im && ((j = (f->way | LEFT) ? -1 : p->wid) || 1)) while ((j = (f->way | LEFT) ? j + 1 : j - 1) != jm) if (p->g[i][j] == '*' && ((f->x = *x + j) || 1)) return ((f->y = *y + i) || 1); return (0); } static int find_next_case(t_filler *f, t_grid *g) { int xy[4]; int xymax[2]; xy[0] = (f->way | UP) ? 0 : g->hig - 1; xy[1] = (f->way | LEFT) ? 0 : g->wid - 1; xy[2] = (f->way | UP) ? 1 : -1; xy[3] = (f->way | LEFT) ? 1 : -1; xymax[0] = f->y; xymax[1] = f->x; if (my_find(f, g, xy, xymax)) return (1); if (find_next_case2(f, g, xy, xymax)) return (1); xy[0] = f->y; xy[1] = f->x; xymax[0] = (f->way | UP) ? g->hig : -1; xymax[1] = (f->way | LEFT) ? g->wid : -1; return (my_find(f, g, xy, xymax)); } int my_compute(t_filler *f) { int x; int y; y = -1; while (++y < f->grid.hig && (x = -1)) while (++x < f->grid.wid) if (f->grid.g[y][x] == f->mychars[0]) f->grid.g[y][x] = f->mychars[1]; while (1) { find_way(f); if (test_form(f, &f->grid, &x, &y)) break ; f->grid.g[f->y][f->x] = f->mychars[0]; if (!find_next_case(f, &f->grid)) return (0); } ft_printf("%d %d\n", y, x); return (1); }
C
#include<stdio.h> unsigned long int numberOfZeros(unsigned long ); int main(){ unsigned long int result; unsigned long int number; int testcases; scanf("%d",&testcases); while(testcases-- > 0){ scanf("%lu",&number); result= numberOfZeros(number); printf("%lu\n",result); } getch(); return 0; } unsigned long int numberOfZeros(unsigned long number){ unsigned long int j; unsigned long int count=0; if(number==5) return 1; else{ for(j=5;number/j>=1;j=j*5) count+=number/j; return count; } }
C
#include <stdio.h> #include <stdlib.h> typedef struct treenode //树的节点 { char data ; treenode * leftchild, * rightchild ; }TreeNode; typedef TreeNode * StackElemType ; //定义栈包含的数据类型 typedef struct stacknode //栈的节点 { StackElemType data ; stacknode * next ; }StackNode; typedef TreeNode * QueueElemType ; //定义队列包含的数据类型 typedef struct queuenode //定义队列节点 { QueueElemType data ; struct queuenode * next ; }QueueNode; typedef struct queuehead //定义队列的头节点 { QueueNode * front, * rear ; }QueueHead; //stack的有关声明 StackNode * InitStack(StackNode * S) ; void StackPush(StackNode * S, StackElemType data) ; void StackPop(StackNode * S, StackElemType & data) ; int StackEmpty(StackNode * S) ; int StackGetTop(StackNode * S, StackElemType & data) ; //queue的有关声明 QueueHead * InitQueue(QueueHead * Q) ; void QueuePush(QueueHead * Q, QueueElemType data) ; void QueuePop(QueueHead * Q, QueueElemType & data) ; int QueueEmpty(QueueHead * Q) ; //TreeTraverse的有关声明 TreeNode * InitTree(TreeNode * T) ; void PreTraverseTree1(TreeNode * T) ; void PreTraverseTree2(TreeNode * T) ; void InOrderTraverseTree1(TreeNode * T) ; void InOrderTraverseTree2(TreeNode * T) ; void LastTraverseTree1(TreeNode * T) ; void LastTraverseTree2(TreeNode * T) ; void LevelTraverseTree(TreeNode * T) ; //栈的函数定义 StackNode * InitStack(StackNode * S) { S = (StackNode *)malloc(sizeof(StackNode)) ; if(NULL == S) { printf("Not enough memory!\n") ; exit(0) ; } S->next = NULL ; return(S) ; } void StackPush(StackNode * S, StackElemType data) { StackNode * q ; q = (StackNode *)malloc(sizeof(StackNode)) ; if(NULL == q) { printf("Not enough memory!\n") ; exit(0) ; } q->data = data ; q->next = S->next ; S->next = q ; } void StackPop(StackNode * S, StackElemType & data) { StackNode * q ; if(NULL == S->next) { printf("Empty Stack!\n") ; } q = S->next ; data = q->data ; S->next = q->next ; free(q) ; } int StackEmpty(StackNode * S) { if(NULL == S->next) { return(1) ; } return(0) ; } int StackGetTop(StackNode * S, StackElemType & data) { if(NULL != S->next) { data = S->next->data ; return(1) ; } else { //data = NULL ; return(0) ; } } //队列函数的定义 QueueHead * InitQueue(QueueHead * Q) { QueueNode * q ; Q = (QueueHead *)malloc(sizeof(QueueHead)) ; if(NULL == Q) { printf("Not enough memory!\n") ; exit(0) ; } q = (QueueNode *)malloc(sizeof(QueueNode)) ; if(NULL == q) { printf("Not enough memory!\n") ; exit(0) ; } q->next = NULL ; Q->front = q ; Q->rear = q ; return(Q) ; } void QueuePush(QueueHead * Q, QueueElemType data) { QueueNode * q ; q = (QueueNode *)malloc(sizeof(QueueNode)) ; if(NULL == q) { printf("Not enough memory!\n") ; exit(0) ; } q->data = data ; q->next = Q->rear->next ; Q->rear->next = q ; Q->rear = q ; } void QueuePop(QueueHead * Q, QueueElemType & data) { QueueNode * q ; if(Q->front == Q->rear) { printf("Null Queue!\n") ; return ; } q = Q->front->next ; data = q->data ; Q->front->next = q->next ; if(Q->rear == q) Q->rear = Q->front ; free(q) ; } int QueueEmpty(QueueHead * Q) { if(Q->front == Q->rear) return(1) ; else return(0) ; } //树的各种遍历函数定义 /*建立一棵二叉树*/ TreeNode * InitTree(TreeNode * T) { char data ; scanf("%c", &data) ; if('#' == data) { T = NULL ; } else { T = (TreeNode *)malloc(sizeof(TreeNode)) ; T->data = data ; T->leftchild = InitTree(T->leftchild) ; T->rightchild = InitTree(T->rightchild) ; } return(T) ; } /*二叉树递归先序遍历*/ void PreTraverseTree1(TreeNode * T) { if(T) { printf("%c ", T->data) ; PreTraverseTree1(T->leftchild) ; PreTraverseTree1(T->rightchild) ; } } /*二叉树的非递归先序遍历*/ void PreTraverseTree2(TreeNode * T) { StackNode * S ; TreeNode * p ; S = NULL ; p = T ; S = InitStack(S) ; if(NULL == p) { printf("NULL!\n") ; return ; } while(p || !StackEmpty(S)) { if(p) { StackPush(S, p) ; printf("%c ", p->data) ; p = p->leftchild ; } else { StackPop(S, p) ; p = p->rightchild ; } } free(S) ; } /*二叉树递归中序遍历*/ void InOrderTraverseTree1(TreeNode * T) { if(T) { InOrderTraverseTree1(T->leftchild) ; printf("%c ", T->data) ; InOrderTraverseTree1(T->rightchild) ; } } /*二叉树的非递归中序遍历*/ void InOrderTraverseTree2(TreeNode * T) { StackNode * S ; TreeNode * p ; S = NULL ; p = T ; S = InitStack(S) ; if(NULL == p) { printf("NULL!\n") ; return ; } while(p || !StackEmpty(S)) { if(p) { StackPush(S, p) ; p = p->leftchild ; } else { StackPop(S, p) ; printf("%c ", p->data) ; p = p->rightchild ; } } free(S) ; } /*二叉树递归后序遍历*/ void LastTraverseTree1(TreeNode * T) { if(T) { LastTraverseTree1(T->leftchild) ; LastTraverseTree1(T->rightchild) ; printf("%c ", T->data) ; } } /*二叉树非递归后序遍历*/ void LastTraverseTree2(TreeNode * T) { StackNode * S ; TreeNode * cur, * pre ; S = NULL ; S = InitStack(S) ; if(NULL == T) { printf("NULL!\n") ; return ; } pre = NULL ; cur = NULL ; StackPush(S,T) ; while(!StackEmpty(S)) { cur = NULL ; StackGetTop(S,cur) ; if((cur->leftchild == NULL && cur->rightchild == NULL) || (pre != NULL && (pre == cur->leftchild ||pre == cur->rightchild))) { printf("%c ", cur->data) ; pre = cur ; StackPop(S,cur) ; } else { if(cur->rightchild != NULL) { StackPush(S,cur->rightchild) ; } if(cur->leftchild != NULL) { StackPush(S,cur->leftchild) ; } } } free(S) ; } /*二叉树层次遍历*/ void LevelTraverseTree(TreeNode * T) { QueueHead * Q ; TreeNode * p ; Q = NULL ; p = T ; Q = InitQueue(Q) ; if(NULL == p) { printf("NULL!\n") ; return ; } QueuePush(Q,p) ; while(!QueueEmpty(Q)) { p = NULL ; QueuePop(Q,p) ; if(NULL != p->leftchild) QueuePush(Q,p->leftchild) ; if(NULL != p->rightchild) QueuePush(Q,p->rightchild) ; printf("%c ", p->data) ; } } //主函数的定义 void Tips() { printf("********************************************************************************\n\n"); printf(" BiTree traversal! \n\n"); printf(" Bitree is constructed according to PreOrder, '#' represents Null node! \n\n") ; printf("********************************************************************************\n\n"); printf("Please input the BiTree:") ; } int main() { TreeNode * T ; T = NULL ; Tips() ; T = InitTree(T) ; printf("Recursive preOrder traversal...\n") ; PreTraverseTree1(T) ; printf("\n\n") ; printf("Non-recursive preOrder traversal...\n") ; PreTraverseTree2(T) ; printf("\n\n") ; printf("Recursive InOrder traversal...\n") ; InOrderTraverseTree1(T) ; printf("\n\n") ; printf("Non-recursive InOrder traversal...\n") ; InOrderTraverseTree2(T) ; printf("\n\n") ; printf("Recursive PostOrder traversal...\n") ; LastTraverseTree1(T) ; printf("\n\n") ; printf("Non-recursive PostOrder traversal...\n") ; LastTraverseTree2(T) ; printf("\n\n") ; printf("Hierarchical traversal...\n") ; LevelTraverseTree(T) ; printf("\n\n") ; return 0 ; }
C
#include <string.h> size_t my_strlen(char *s) { return ((s) ? (strlen(s)) : (0)); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <security/pam_appl.h> #include <security/pam_ext.h> #include <security/pam_modules.h> #include <security/pam_modutil.h> /* expected hook */ PAM_EXTERN int pam_sm_setcred( pam_handle_t *pamh, int flags, int argc, const char **argv ) { return PAM_SUCCESS; } PAM_EXTERN int pam_sm_acct_mgmt(pam_handle_t *pamh, int flags, int argc, const char **argv) { printf("Acct mgmt\n"); return PAM_SUCCESS; } PAM_EXTERN int pam_sm_open_session(pam_handle_t *pamh, int flags, int argc, const char **argv) { printf("Sessing open\n"); const char* pUsername; int retval = pam_get_user(pamh, &pUsername, "Username: "); if (retval != PAM_SUCCESS) return retval; struct passwd *user_entry = NULL; user_entry = pam_modutil_getpwnam (pamh, pUsername); PAM_MODUTIL_DEF_PRIVS(privs); if (pam_modutil_drop_priv(pamh, &privs, user_entry)) { return PAM_SESSION_ERR; } char envvar[2048]; memset(&envvar, 0, sizeof(envvar)); sprintf(envvar, "PAM_USERNAME=%s", pUsername); retval = pam_putenv(pamh, envvar); if (retval != PAM_SUCCESS) { return retval; } if (pam_modutil_regain_priv(pamh, &privs)) retval = PAM_SESSION_ERR; return PAM_SUCCESS; } /* expected hook, this is where custom stuff happens */ PAM_EXTERN int pam_sm_authenticate( pam_handle_t *pamh, int flags,int argc, const char **argv ) { int retval; int fd[2]; // NB - PAM specifically proscribes free()'ing memory returned from pam_* util funcs, // so these pointers are intentionally not cleaned up. const char* pUsername; const char* pAuthTok; //sleep(30); retval = pam_get_user(pamh, &pUsername, "Username: "); if (retval != PAM_SUCCESS) return retval; retval = pam_get_authtok(pamh, PAM_AUTHTOK, &pAuthTok, "Halt! What's the password?: "); if (retval != PAM_SUCCESS) return retval; // Fork and execute our PAM auth extension, in this case, a simple shell script. pipe(fd); pid_t cpid = fork(); if (cpid == -1) { printf("Encountered error processing PAM authen (err 1)"); return PAM_AUTH_ERR; } if (cpid == 0) { // Child execution path // Attach stdout of process we exec to write end of our pipe, hence // redirecting PAM auth extension output back to parent. close(1); dup(fd[1]); // TO DO - parameterize the location & name of the PAM auth extension. int rc = execlp("/usr/local/sbin/do_pam_auth.sh", "do_pam_auth.sh", pUsername, pAuthTok, NULL); } else { // Parent execution path char buff[1024]; memset(buff, 0, sizeof(buff)); int cnt = read(fd[0], buff, sizeof(buff)); close(fd[0]); if (strcmp(buff, "accepted") != 0) { return PAM_AUTH_ERR; } } printf("Welcome %s\n", pUsername); return PAM_SUCCESS; }
C
#include<stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char **argv[]){ int n = atoi(argv[1]); if(n>0 && n<11){ for (int i = 1; i <= n; ++i) { printf("%d\n", i); } } if (n==0) { return 0; } for (int i = 0; argv[i]!='\0'; ++i) { if (argv[i]>= 'A' && argv[i]<= 'Z') { return 0; } else if (argv[i] >= 'a' && argv[i]<= 'z') { return 0; } } /*if(argc<2) { for(int i=1; i<=10;i++) { printf("%d\n", i); return 0; } } else { if(n>0 && n<11) { for (int i = 1; i < n; ++i) { printf("%d\n", i ); return 0; } } if (n==NULL) { printf("probleme\n"); } } */ } /* { int val; val = atoi(*argv[1]); if(argc==1) { for(int i = 0; i<=10; i++) { printf("%d\n", i); } } if(val==0){ printf("nul \n"); return 0; } if (val>=1 && val<11) { for(int i=1; i<=val; i++){ printf("%d\n",i ); return 0; } } return 0; } argv[1]= a; if(a==0){ return 0; } if(a>30 && a<39){ for(int i=1; i<a; i++){ printf("%d\n",i ); return 0; } } */
C
#include <dispatch/dispatch.h> #include <stdio.h> // Pure GCD cat-like program (used to test the overhead of OCaml's runtime) dispatch_group_t cat(dispatch_fd_t fd) { dispatch_group_t group = dispatch_group_create(); dispatch_queue_t queue = dispatch_queue_create("ocaml.rw.queue", DISPATCH_QUEUE_SERIAL); dispatch_io_t in_io = dispatch_io_create(DISPATCH_IO_STREAM, fd, queue, ^(int err){ return; }); dispatch_io_t out_io = dispatch_io_create(DISPATCH_IO_STREAM, STDOUT_FILENO, queue, ^(int err){ return; }); dispatch_io_set_high_water(in_io, 1024 * 64); dispatch_group_enter(group); dispatch_io_read(in_io, 0, SIZE_MAX, queue, ^(bool done, dispatch_data_t data, int error) { size_t data_size; if (error) { printf("Somethings gone wrong!"); return; } if (done) { dispatch_group_leave(group); } if (data) { // data_size = dispatch_data_get_size(data); // if (data_size > 0) { dispatch_group_enter(group); dispatch_io_write(out_io, 0, data, queue, ^(bool done, dispatch_data_t data, int error) { if (error) { printf("Something's gone wrong!"); return; } if (done) { dispatch_group_leave(group); } } ); // } } } ); return group; } int main(int argc, char *argv[]) { if (argc > 1) { int fd = open(argv[1], O_RDONLY); dispatch_group_wait(cat(fd), DISPATCH_TIME_FOREVER); } else { dispatch_group_wait(cat(STDIN_FILENO), DISPATCH_TIME_FOREVER); } }
C
#include "../Headers/ShiftAnd.h" int * FazMascara(char * P,int m){ //Realiza o alocamento e preenchimento da mascara do padrao int * M; M = (int *)calloc(256, sizeof(int)); //128 for(int i=0;i < m; i++){ M[P[i]] = M[P[i]] | 1 << (m-i-1); } return M; } void ShiftAnd(char * P, char * T,int m,int n){ //Algoritmo ShiftAnd int R; int i; int * M; M =FazMascara(P,m); //Inicialmente é chamado metodo para criar mascara para o padrao R = 0; for(i = 0; i < n; i++){ //Em seguida busca ShiftAnd é realizada R = (((R >> 1) | (1 << (m-1)) ) & M[T[i]]); if((R & 1) != 0){ printf("\t--> Casamento na posicao: %3d <--\n", i - m + 2); } } free(M); }
C
/** * @author: Ashish A Gaikwad <[email protected]> * Shell Sort Algorithm (modified Insertion sort) in C */ #include <stdio.h> #define MAX 30 int main() { int total, kira, series[MAX]; printf("Enter Number Of Elements:\n"); scanf("%d", &total); for(int i=0; i<total; i++) { printf("Number %d: ", i+1); scanf("%d", &series[i]); } for (int i = total/2; i>0; --i) { // Let the Partial Insertion sort begin for(int z = i; z<total; z++) { for (int j = z-1; j>=0; j -= i) { if(series[j] > series[j+i]) { kira = series[j]; series[j] = series[j+i]; series[j+i] = kira; } else break; } } } // Show sorted elements :) printf("The Shell Sorted Result:\n"); for (int i = 0; i < total; ++i) { printf("%d ", series[i]); } printf("\n"); return 0; }
C
#include "lexos/kprint.h" #include "lexos/panic.h" #include "lexos/arch/apic.h" /* Local variable */ static volatile uint32_t *lapic = NULL; static volatile uint32_t *ioapic = NULL; void apic_find(acpi_madt_s *madt) { if (!madt) { panic(NULL, "MADT POINTER IS NULL.\n"); } lapic = (uint32_t *)((uintptr_t)madt->plapic); acpi_madt_rec_s *cur = &madt->records; while (((uintptr_t)cur - (uintptr_t)madt) < madt->header.len && cur->len != 0) /* Prevent infinite loop */ { acpi_madt_plapic_s *cur_plapic; acpi_madt_ioapic_s *cur_ioapic; acpi_madt_lapicaddr_s *cur_lapicaddr; switch (cur->type) { case ACPI_MADT_REC_PLAPIC: cur_plapic = (acpi_madt_plapic_s *)cur; kprint("Processor LAPIC (cpu : %u, apic_id : %u, flags : 0x%x)\n", cur_plapic->proc_id, cur_plapic->apic_id, cur_plapic->flags); break; case ACPI_MADT_REC_IOAPIC: cur_ioapic = (acpi_madt_ioapic_s *)cur; kprint("I/O APIC (id : %u, addr : 0x%x)\n", cur_ioapic->ioapic_id, cur_ioapic->pioapic); ioapic = (uint32_t *)((uintptr_t)cur_ioapic->pioapic); break; case ACPI_MADT_REC_LAPICADDR: cur_lapicaddr = (acpi_madt_lapicaddr_s *)cur; kprint("LAPIC override address : 0x%x\n", cur_lapicaddr->plapic); lapic = cur_lapicaddr->plapic; break; case ACPI_MADT_REC_ISO: case ACPI_MADT_REC_NMI: /* Nothing to do */ break; default: kprint("Unreconized madt rec entry type (type : %u)\n", cur->type); break; } cur = (void *)cur + cur->len; } return; }
C
/* Name: Zaynab Ghazi * File: music.h * Desc: * Header corresponding to "music.c" */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "ArrayList.h" //create s ong struct: struct song{ char* title; char* artist; char* duration; char* release; char* fade_out_t0; char* tempo; char* terms; char* year; }; //signatures of fucntions in c_file: void print_song(struct song * c_song); int comp_1(const void* p,const void* q); int comp_2(const void* p,const void* q); int comp_3(const void* p,const void* q); int comp_4(const void* p,const void* q); int comp_5(const void* p,const void* q); int comp_6(const void* p,const void* q); int comp_7(const void* p,const void* q); int comp_8(const void* p,const void* q); struct song* binary_search(ArrayList* list, struct song * target, int min_ind, int max_ind, int (*comp )(const void*,const void*)); char* string_copy(char* original);
C
/* --------------------------------------------------------- */ /* --------------- A Very Short Example -------------------- */ /* --------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> /* free() */ #include <stddef.h> /* NULL */ #include "cmaes_interface.h" double fitfun(double const *x, int dim); /* the objective (fitness) function to be minimized */ double fitfun(double const *x, int N) { /* function "cigtab" */ int i; double sum = 1e4*x[0]*x[0] + 1e-4*x[1]*x[1]; for(i = 2; i < N; ++i) sum += x[i]*x[i]; return sum; } /* the optimization loop */ int main(int argn, char **args) { cmaes_t evo; /* an CMA-ES type struct or "object" */ double *arFunvals, *const*pop, *xfinal; int i; /* Initialize everything into the struct evo, 0 means default */ arFunvals = cmaes_init(&evo, 0, NULL, NULL, 0, 0, "cmaes_initials.par"); printf("%s\n", cmaes_SayHello(&evo)); cmaes_ReadSignals(&evo, "cmaes_signals.par"); /* write header and initial values */ /* Iterate until stop criterion holds */ while(!cmaes_TestForTermination(&evo)) { /* generate lambda new search points, sample population */ pop = cmaes_SamplePopulation(&evo); /* do not change content of pop */ /* Here we may resample each solution point pop[i] until it becomes feasible. function is_feasible(...) needs to be user-defined. Assumptions: the feasible domain is convex, the optimum is not on (or very close to) the domain boundary, initialX is feasible and initialStandardDeviations are sufficiently small to prevent quasi-infinite looping. */ /* for (i = 0; i < cmaes_Get(&evo, "popsize"); ++i) while (!is_feasible(pop[i])) cmaes_ReSampleSingle(&evo, i); */ /* evaluate the new search points using fitfun */ for (i = 0; i < cmaes_Get(&evo, "lambda"); ++i) { arFunvals[i] = fitfun(pop[i], (int) cmaes_Get(&evo, "dim")); } /* update the search distribution used for cmaes_SamplePopulation() */ cmaes_UpdateDistribution(&evo, arFunvals); /* read instructions for printing output or changing termination conditions */ cmaes_ReadSignals(&evo, "cmaes_signals.par"); fflush(stdout); /* useful in MinGW */ } printf("Stop:\n%s\n", cmaes_TestForTermination(&evo)); /* print termination reason */ cmaes_WriteToFile(&evo, "all", "allcmaes.dat"); /* write final results */ /* get best estimator for the optimum, xmean */ xfinal = cmaes_GetNew(&evo, "xmean"); /* "xbestever" might be used as well */ cmaes_exit(&evo); /* release memory */ /* do something with final solution and finally release memory */ free(xfinal); return 0; }
C
#include <stdio.h> #include <math.h> int main(){ double b=3.14,f=(9*b/5-b/5)/10,x=b/5,result1=0; for(;x<9*b/5;x+=f) { result1=-log(fabs(2*sin(x/2))); double result2=0,result3=0; for(int n=1;n<41;n++) { double el; el=cos(n*x)/n; result2+=el; } int n=1; double el; do { el=cos(n*x)/n; result3+=el; n++; }while(fabs(el)>0.0001); printf("Result1: %lf |",result1); printf("Result2: %lf |",result2); printf("Result3: %lf\n",result3); } }
C
// Program name: Required Exercise 2.0B // // Author: Ashley Bruce // Date: 09-11-19 // Course: Computer Science 217 // // // Description: Modifying the program to calculate the course effeciency at Cuesta // #include <stdio.h> #include <stdlib.h> int main (void) { printf ("This program calculates a Cuesta class efficiency factor \n where 15 and above is considered eficient \n\n"); #define OPTIMUM_EFFICIENCY 15 #define TRUE 1 #define FALSE 0 float lec_hours, lab_hours; int student_number, repeat; char quit; TOP: repeat = TRUE; printf ("Enter the number of weekly lecture hours > "); scanf ("\n%f", &lec_hours); printf ("Enter the number of weekly lab hours > "); scanf ("%f", &lab_hours); printf ("Enter the number of students in the class > "); scanf ("%i", &student_number); if (lec_hours + lab_hours == 0) { printf ("Lecture hours and lab hours can't add to 0 \n\n"); goto TOP; } printf ("\n\n"); float efficiency_coefficient_numerator, efficiency_coefficient_denominator, efficiency_coefficient; efficiency_coefficient_numerator = (1.0/2.0)*lec_hours + (2.0/3.0)*lab_hours; efficiency_coefficient_denominator = lec_hours + lab_hours; efficiency_coefficient = efficiency_coefficient_numerator / efficiency_coefficient_denominator; printf ("Course Efficiency Coefficient = %.2f \n", efficiency_coefficient); float efficiency_factor; efficiency_factor = efficiency_coefficient * student_number; printf ("Course Efficiency Factor = %.2f \n", efficiency_factor); float percent_efficiency; percent_efficiency = (efficiency_factor / OPTIMUM_EFFICIENCY )* 100; printf ("Course Percent Efficiency = %.2f \n\n", percent_efficiency); printf ("To quit enter Y > "); scanf ("\n%c", &quit); if (tolower(quit) == 'y') { repeat = FALSE; } if (repeat == TRUE) { goto TOP; } system ("PAUSE"); return 0; }
C
/* ** EPITECH PROJECT, 2020 ** af ** File description: ** * */ #include "my.h" int get_ch(char str) { if (str == '1') return 1; if (str == '2') return 2; if (str == '3') return 3; if (str == '4') return 4; if (str == '5') return 5; if (str == '6') return 6; if (str == '7') return 7; if (str == '8') return 8; return 0; }
C
#include <stdio.h> #include <string.h> #include <locale.h> int main(){ char s[11]; char a[] = " / / "; printf("Ange datum i svenskt format ÅÅÅÅ-MM-DD: "); scanf("%s", s); strncpy(a, s+5, 2); // Månad strncpy(a+3, s+8, 2); // Dag strncpy(a+6, s+2, 2); // År printf("I amerika skriver dem: %s\n", a); }
C
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/wait.h> #include <netinet/in.h> #include <unistd.h> #include <fcntl.h> #include <signal.h> #include <stdbool.h> #include <sys/ipc.h> #include <sys/shm.h> #include "handler.h" enum { MAX_CONNECTIONS_COUNT = 50 }; volatile int socket_fd; volatile int connect_fd; volatile int shm_id; void main_handle_sigint(int signum) { while (wait(NULL) != -1) {} close(socket_fd); shmctl(shm_id, IPC_RMID, NULL); exit(EXIT_SUCCESS); } void child_handle_sigint(int signum) { close(connect_fd); recv(connect_fd, NULL, 0, 0); exit(EXIT_SUCCESS); } int main(int argc, char **argv) { if (argc < 2) { fputs("No port", stdout); exit(EXIT_FAILURE); } shm_id = shmget(IPC_PRIVATE, sizeof(int), 0666 | IPC_CREAT); int port; sscanf(argv[1], "%d", &port); socket_fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if (socket_fd == -1) { perror("Creating socket error"); exit(EXIT_FAILURE); } int opt = 1; if (setsockopt (socket_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof (opt)) == -1) { perror("Socket option error"); } struct sockaddr_in addr = { .sin_family = PF_INET, .sin_port = htons(port), .sin_addr.s_addr = htonl(INADDR_ANY), }; if (bind(socket_fd, (struct sockaddr*) &addr, sizeof(addr)) == -1) { perror("Binding error"); close(socket_fd); exit(EXIT_FAILURE); } if (listen(socket_fd, MAX_CONNECTIONS_COUNT) == -1) { perror("Listening error"); close(socket_fd); exit(EXIT_FAILURE); } sigset_t sigset; sigemptyset(&sigset); sigaddset(&sigset, SIGINT); struct sigaction sa = { .sa_mask = sigset, .sa_handler = main_handle_sigint, }; sigaction(SIGINT, &sa, NULL); while (1) { while (waitpid(0, NULL, WNOHANG) != -1) {} connect_fd = accept(socket_fd, NULL, NULL); sigprocmask(SIG_BLOCK, &sigset, NULL); if (connect_fd == -1) { break; } if (fork() == 0) { sa.sa_handler = child_handle_sigint; sigaction(SIGINT, &sa, NULL); sigprocmask(SIG_UNBLOCK, &sigset, NULL); handle_connection(connect_fd, shm_id); close(connect_fd); exit(EXIT_SUCCESS); } close(connect_fd); sigprocmask(SIG_UNBLOCK, &sigset, NULL); } close(socket_fd); while (wait(NULL) != -1) {} return EXIT_SUCCESS; }
C
#include "Stack.h" void * stack_new(size_t element_size) { pStack ptr = (pStack)calloc(1, sizeof(Stack)); if (NULL == ptr){ fprintf(stderr, "stack allocate error\n"); } ptr->element_size = element_size; ptr->data = NULL; ptr->size = 0; ptr->capacity = 0; /* Initialize method */ ptr->top = &stack_top; ptr->pop = &stack_pop; ptr->push = &stack_push; ptr->free = &stack_free; return ptr; } void stack_free(pStack ptr) { free(ptr->data); ptr->size = 0; free(ptr); } bool stack_push(pStack ptr, void * value) { if (ptr->data == NULL) { ptr->data = calloc(1, ptr->element_size); if (ptr->data == NULL) { exit(EXIT_FAILURE); } memcpy(ptr->data, (char*)value, ptr->element_size); ptr->size = 1; } else { if (ptr->capacity <= ptr->size){ ptr->data = realloc(ptr->data, ptr->size * ptr->element_size + ptr->element_size); memcpy(ptr->data + ptr->element_size * ptr->size, (char *)value, ptr->element_size); ptr->size += 1; ptr->capacity += 1; } else { memcpy(ptr->data + ptr->element_size * ptr->size, (char *)value, ptr->element_size); ptr->size += 1; } } return true; } void stack_pop(pStack ptr) { ptr->size -= 1; } void * stack_top(pStack ptr) { return ptr->data + ((ptr->size - 1) * ptr->element_size); } size_t stack_size(pStack ptr) { return ptr->size; } /** * Test */ typedef struct _stu { int no; char name[20]; char *addr; }Student, *pStudent; #if 1 int main(void) { int value = 10, v = 11, i; Student s1 = {12, "student1", "addr1"},s2 = {13, "student2","a1"}, s3 = {15, "stu3", "address3"}, *sptr; pStack ps = stack_new(sizeof(Student) + 20); pStack p = stack_new(sizeof(int)); stack_push(p, &value); stack_push(p, &v); printf("%d\n", *((int*)stack_top(p))); stack_pop(p); printf("%d\n", *((int*)stack_top(p))); stack_push(ps, &s1); ps->push(ps, &s2); sptr = (pStudent)ps->top(ps); printf("no: %d, name: %s\n", sptr->no, sptr->addr); ps->pop(ps); stack_push(ps, &s3); sptr = (pStudent)stack_top(ps); printf("no: %d, name: %s\n", sptr->no, sptr->addr); ps->free(ps); for (i = 0; i < 100; i++) { stack_push(p, &i); } for (i = 0; i < 100; i++) { printf("%d ", *((int*)stack_top(p))); stack_pop(p); } printf("\nStack size: %ld\n", sizeof(Stack)); stack_free(p); exit(EXIT_SUCCESS); } #endif
C
#include <fstream> #include <iostream> #include <string> #include <iomanip> using namespace std; enum RelationType {LESS, EQUAL, GREATER}; class ItemType { public: void WriteItemToFile (ofstream& outFile) ; RelationType ComparedTo(ItemType& item) const; // Purpose: To compare to items of the same type. // Input: info. // Pre: both Objects are constructed, and all values are assigned a value. // Output: RelationType. // Post: Items are compared and a bool is returned. // Note: none void setStudent(int inStudentID, char inGrade, char inMajor, char inGender); void setID(int id); int idis() const; char gradeis() const; char majoris() const; char genderis() const; protected: int studId; char grade, major, gender; };
C
// Interface to the Student DB ADT // !!! DO NOT MODIFY THIS FILE !!! #ifndef STUDENT_DB_H #define STUDENT_DB_H #include "List.h" #include "Record.h" typedef struct studentDb *StudentDb; /** * Creates a new student DB */ StudentDb DbNew(void); /** * Frees all memory allocated to the given student DB */ void DbFree(StudentDb db); /** * Inserts a student record into the given DB if there is not already * a record with the same zid. If inserted successfully, this function * takes ownership of the given record (so the caller should not modify * or free it). Returns true if the record was successfully inserted, * and false if the DB already contained a record with the same zid. */ bool DbInsertRecord(StudentDb db, Record r); /** * Deletes a student record with the given zid from the DB. Returns true * if the record was successfully deleted, and false if there was no * record with that zid. */ bool DbDeleteByZid(StudentDb db, int zid); /** * Searches for a record with the given zid. Returns the record if it * was found, or NULL otherwise. The returned record should not be * modified or freed. */ Record DbFindByZid(StudentDb db, int zid); /** * Searches for all records with the same family name and given name as * the provided family name and given name, and returns them all in a * list in increasing order of zid. Returns an empty list if there are * no such records. The records in the returned list should not be * freed, but it is the caller's responsibility to free the list itself. */ List DbFindByName(StudentDb db, char *familyName, char *givenName); /** * Displays all records in order of zid, one per line. */ void DbListByZid(StudentDb db); /** * Displays all records in order of name (family name first), one per * line. Records with the same name are ordered by zid. */ void DbListByName(StudentDb db); #endif
C
/*x = achar o ponto médio y = fórmula x1,x2 são os intervalos */ #include<stdio.h> #include<stdlib.h> #include<math.h> int main(){ float x1,x2,x,y,e= 0.0001,calc,calc1; x1= 0; x2= 2; calc= pow(x1,3)-x1-1; calc1= pow(x2,3)-x2-1; if(calc>calc1){ printf("decrescente\n"); }else printf("crescente\n"); do{ x= (x1+x2)/2; y= pow(x,3)-x-1; if(y > e){ x2 = x; }else if(y < -e){ x1=x; } }while(y > e || y < -e); printf("Letra a: %.4f\n",x); printf("============================================="); x1= 0.1; x2=1; calc= x1 + log(x1) ; calc1= x2 + log(x2); if(calc>calc1){ printf("\ndecrescente\n"); }else printf("\ncrescente\n"); do{ x = (x1+x2)/2; y = x + log(x); if(y > e){ x2=x; }else if(y < -e){ x1=x; } }while(y > e || y < -e); printf("\nLetra b: %.4f\n",x); printf("============================================="); x1 = 0; x2 = 2; calc= 5*sin(x1)-5+x1; calc1= 5*sin(x2)-5+x2; if(calc>calc1){ printf("\ndecrescente\n"); }else printf("\ncrescente\n"); do{ x=(x1+x2)/2; y = 5*sin(x)-5+x; if(y>e){ x2=x; }else if(y<-e){ x1=x; } }while(y>e || y<-e); printf("\nLetra c: %.4f\n",x); printf("============================================="); x1 = 1; x2 = 2.5; calc= pow(x1,3)-3*x1-2; calc1= pow(x2,3)-3*x2-2; if(calc>calc1){ printf("\ndecrescente\n"); }else printf("\ncrescente\n"); do{ x=(x1+x2)/2; y = pow(x,3)-3*x-2; if(y>e){ x2=x; }else if(y<-e){ x1=x; } }while(y>e || y<-e); printf("\nLetra d: %.0f\n",x); printf("============================================="); x1 = -1.5; x2 = -0.5; calc= pow(x1,3)-2*pow(x1,2)-13*x1-10; calc1= pow(x2,3)-2*pow(x2,2)-13*x2-10; if(calc>calc1){ printf("\ndecrescente\n"); }else printf("\ncrescente\n"); do{ x=(x1+x2)/2; y = pow(x,3)-2*pow(x,2)-13*x-10; if(y>e){ x2=x; }else if(y<-e){ x1=x; } }while(y>e || y<-e); printf("\nLetra e: %.0f\n",x); printf("============================================="); return 0; }
C
/******************************************************************** * * @Arxiu : command.c * @Finalitat : Funcions que conformen el TAD comanda. * @Autors : Esteve Genovard Ferriol - ls30742 & Sergi Simó Bosquet - ls30685 * @Data Creació: 12 de Desembre del 2016 * ******************************************************************** */ #include "../HEADERS/command.h" void COMMAND_create(Command command) { bzero(command, COMMAND_SIZE); } void COMMAND_setType(Command command, char * type) { int i; for (i = 0; i < COMMAND_TYPE_MAX && type[i] != '\0'; i++) { command[i] = type[i]; } } void COMMAND_setInfo(Command command, char * info) { int i, j = 0; for (i = COMMAND_TYPE_MAX; i < COMMAND_INFO_MAX && info[j] != '\0'; i++) { command[i] = info[j]; j++; } } void COMMAND_setData(Command command, char * data, int firstPosition) { int i = 0; while (data[i] != '\0') { command[firstPosition] = data[i]; i++; firstPosition++; } } CommandType COMMAND_getType(Command command) { char type[6]; CommandType commandType; int i = 0; while (command[i] != '\0' && i < 5) { type[i] = command[i]; i++; } type[i] = '\0'; if (!strcmp(type, COMMAND_TYPE_RICK_MATCH)) commandType = RickMatch; else if (!strcmp(type, COMMAND_TYPE_RICK_CONNECTION)) commandType = RickConnection; else if (!strcmp(type, COMMAND_TYPE_RICK_DISCONNECTION)) commandType = RickDisconnection; else if (!strcmp(type, COMMAND_TYPE_RICK_NEXT)) commandType = RickNewMorty; else if (!strcmp(type, COMMAND_TYPE_RICK_LIKE)) commandType = RickLike; else if (!strcmp(type, COMMAND_TYPE_MORTY_XAT)) commandType = MortyXat; return commandType; } CommandInfo COMMAND_getInfo(Command command) { char info[10]; CommandInfo commandInfo; int i = 5, j = 0; while (command[i] != '\0' && j < 10) { info[j] = command[i]; i++; j++; } info[j] = '\0'; if (!strcmp(info, COMMAND_INFO_RICK_CONNECTION_OK)) commandInfo = RickConnectionOK; else if (!strcmp(info, COMMAND_INFO_RICK_CONNECTION_KO)) commandInfo = RickConnectionKO; else if (!strcmp(info, COMMAND_INFO_RICK_DISCONNECTION_OK)) commandInfo = RickDisconnectionOK; else if (!strcmp(info, COMMAND_INFO_RICK_DISCONNECTION_KO)) commandInfo = RickDisconnectionKO; else if (!strcmp(info, COMMAND_INFO_RICK_NEXT)) commandInfo = RickNewMortyInfo; else if (!strcmp(info, COMMAND_INFO_RICK_NEXT_NO)) commandInfo = RickNoMortyInfo; else if (!strcmp(info, COMMAND_INFO_RICK_LIKE)) commandInfo = RickLikeInfo; else if (!strcmp(info, COMMAND_INFO_MORTY_XAT_EXIT)) commandInfo = MortyXatExit; return commandInfo; } int COMMAND_getPort(Command command) { char info[10]; int i = 5, j = 0; while (command[i] != '\0' && j < 10) { info[j] = command[i]; i++; j++; } info[j] = '\0'; return atoi(info); } char * COMMAND_getData(Command command, int start, int final) { char * destination; int i, j = 0; destination = (char *) malloc(sizeof(char)*(final-start+2)); if (destination == NULL) SINGNALS_programExit(-1, SIGNALS_MEMORY_ERROR); //Control d'errors else { for (i = start; i <= final && command[i] != '\0'; i++) { destination[j] = command[i]; j++; } destination[j] = '\0'; } if (strlen(destination) != 0 ) { destination = realloc(destination, sizeof(char)*strlen(destination)); if (destination == NULL) SINGNALS_programExit(-1, SIGNALS_MEMORY_ERROR); } return destination; }
C
#include <stdio.h> #include <string.h> #include <capstone/capstone.h> #include "lib.h" typedef char *(trans_insn_fn_t)(cs_insn *insn); trans_insn_fn_t trans_mov; trans_insn_fn_t trans_movz; trans_insn_fn_t trans_adr; trans_insn_fn_t trans_svc; static trans_insn_fn_t *trans_insn_fn_table[] = { trans_mov, trans_movz, trans_adr, trans_svc }; static char* insn_table[] = { "mov", "movz", "adr", "svc" }; void translate_from_arm64_to_x64(cs_insn *insn) { char t_insn[64]; unsigned int reg; int i; for (i=0; i<4; ++i) { if (strcmp(insn->mnemonic, insn_table[i]) == 0) break; } if (i == 4) return; printf("\tTranslated : %s\n", trans_insn_fn_table[i](insn)); } /* convert_reg_from_arm64_to_x64(){ } */ char *trans_mov(cs_insn *insn) { return "movq"; } char *trans_movz(cs_insn *insn) { return "movq"; } char *trans_adr(cs_insn *insn) { return "movq"; } char *trans_svc(cs_insn *insn) { return "syscall"; } void print_cs_arm64_detail(csh handle, cs_detail *detail) { if (detail->regs_read_count > 0) { printf("\tImplicit registers read: "); for (int n = 0; n < detail->regs_read_count; n++) { printf("%s ", cs_reg_name(handle, detail->regs_read[n])); } printf("\n"); } if (detail->regs_write_count > 0) { printf("\tImplicit registers write: "); for (int n = 0; n < detail->regs_write_count; n++) { printf("%s ", cs_reg_name(handle, detail->regs_write[n])); } printf("\n"); } if (detail->arm64.op_count) printf("\tNumber of operands: %u\n", detail->arm64.op_count); for (int n = 0; n < detail->arm64.op_count; n++) { cs_arm64_op *op = &(detail->arm64.operands[n]); switch(op->type) { case ARM64_OP_REG: printf("\t\toperands[%u].type: REG = %s (%u)\n", n, cs_reg_name(handle, op->reg), op->reg); break; case ARM64_OP_IMM: printf("\t\toperands[%u].type: IMM = 0x%x\n", n, op->imm); break; case ARM64_OP_FP: printf("\t\toperands[%u].type: FP = %f\n", n, op->fp); break; case ARM64_OP_MEM: printf("\t\toperands[%u].type: MEM\n", n); if (op->mem.base != ARM64_REG_INVALID) printf("\t\t\toperands[%u].mem.base: REG = %s\n", n, cs_reg_name(handle, op->mem.base)); if (op->mem.index != ARM64_REG_INVALID) printf("\t\t\toperands[%u].mem.index: REG = %s\n", n, cs_reg_name(handle, op->mem.index)); if (op->mem.disp != 0) printf("\t\t\toperands[%u].mem.disp: 0x%x\n", n, op->mem.disp); break; case ARM64_OP_CIMM: printf("\t\toperands[%u].type: C-IMM = %u\n", n, op->imm); break; } if (op->shift.type != ARM64_SFT_INVALID && op->shift.value) printf("\t\t\tShift: type = %u, value = %u\n", op->shift.type, op->shift.value); if (op->ext != ARM64_EXT_INVALID) printf("\t\t\tExt: %u\n", op->ext); } if (detail->arm64.cc != ARM64_CC_INVALID) printf("\tCode condition: %u\n", detail->arm64.cc); if (detail->arm64.update_flags) printf("\tUpdate-flags: True\n"); if (detail->arm64.writeback) printf("\tWrite-back: True\n"); }
C
#include "core/time.h" #include "platform/timer.h" #include "math/math.h" // -------------------------------------------------------------------------------- // Time, DeltaTime, FrameCount engine_time_t engine_time = { 0, 0, 0, 0, 1, 1 }; // Time, CosTime, SinTime, DeltaTime vec4_t engine_shader_time = { .vec = { 0, 1, 0, 0 } }; // The tick count for when the engine is initialized. static uint64_t start = 0; static uint64_t previous = 0; // -------------------------------------------------------------------------------- void time_initialize(void) { start = timer_get_ticks(); previous = start; // Set initial delta time to a non-zero value to avoid division by zero. engine_time.delta_time = 1 / 60.0f; engine_time.real_delta_time = 1 / 60.0f; engine_shader_time.w = 1 / 60.0f; } void time_tick(void) { // TODO: Use high precision clock! uint64_t now = timer_get_ticks(); uint64_t elapsed = now - start; float real_time = 0.001f * elapsed; float delta = 0.001f * (now - previous); float real_delta = 0.001f * (now - previous); // Update engine time. engine_time.delta_time = engine_time.scale * delta; engine_time.real_delta_time = real_delta; engine_time.time += engine_time.delta_time; engine_time.real_time = real_time; engine_time.frame_count++; // Update shader time. engine_shader_time.x = engine_time.time; engine_shader_time.w = engine_time.delta_time; math_sincos(engine_time.time, &engine_shader_time.z, &engine_shader_time.y); previous = now; } void time_set_scale(float scale) { if (scale < 0) { return; } engine_time.scale = scale; }
C
//*BFS*// //*Prasansha Satpathy*// //*02- C2*// #include <stdio.h> int rear = 0 , front = -1; int queue[100]; int color[100], dist[100], graph[100][100]; int nodes, edges; int WHITE = 0; int GRAY = 1; int BLACK = 2; void enqueue(int root_node) { queue[rear] = root_node; rear = rear + 1; } int empty() { if(front == rear-1) return 0; else return 1; } int dequeue() { front = front + 1; return queue[front]; } void bfs() { int x, y, i, t, j,src; for(i=1 ; i<= nodes; i++){ for(j=1 ; j<=nodes ; j++){ graph[i][j] == 0; } } printf("Enter the src:"); scanf("%d", &src); for (i = 0; i < edges; i++) { printf("Edge %d: ", i); scanf("%d %d", &x, &y); graph[x][y] = 1; graph[y][x] = 1; } for(i=0; i< nodes ; i++){ for(j=0; j<nodes ;j++){ printf("%d\t", graph[i][j]); } printf("\n"); } enqueue(src); color[src] = GRAY; dist[src] = 0; do { int u = dequeue(); for (i = 0; i < nodes; i++) { if ((graph[u][i] == 1) && (color[i] == WHITE)) { enqueue(i); color[i] = GRAY; dist[i] = dist[u] + 1; } } color[u] = BLACK; }while(empty()); } void main() { int i; printf("Nodes, edges\n"); scanf("%d %d", &nodes, &edges); for(i=0;i<nodes;i++) color[i] = WHITE; bfs(); for(i =0 ; i< nodes; i++){ printf("\n The distance of node %d : %d",i, dist[i]); } }
C
#include <sys/queue.h> #include "utils.h" struct buffer{ char *buf; int size; LIST_ENTRY(buffer) next; }; static LIST_HEAD(buffer_chain, buffer) buffer_chain_head; int buffer_total_size = 0; static void clear_buffer_chain(){ while(buffer_chain_head.lh_first != NULL){ struct buffer *tmp = buffer_chain_head.lh_first; LIST_REMOVE(buffer_chain_head.lh_first, next); free(tmp->buf); free(tmp); } buffer_total_size = 0; } static char *buffer_chain_enlarge(int size){ struct buffer *buf = malloc(sizeof(struct buffer)); buf->buf = malloc(size); buf->size = size; LIST_INSERT_HEAD(&buffer_chain_head, buf, next); buffer_total_size += size; return buf->buf; } static void buffer_chain_store(char **str){ int position = buffer_total_size; *str = malloc(buffer_total_size); struct buffer *bent; LIST_FOREACH(bent, &buffer_chain_head, next){ position -= bent->size; memcpy(str+position, bent->buf, bent->size); } } void *zmalloc(size_t size){ void *tmp = malloc(size); memset(tmp, 0, size); return tmp; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> /** * Auto-generated code below aims at helping you parse * the standard input according to the problem statement. **/ int char_to_strbinary(char *in, char * out){ for(int i=0; i<strlen(in) -1; i++){ char c=in[i]; c<<=1; for(int j=0; j<7; j++){ *out++= '0' + ((c & 0b10000000)/0b10000000); c<<=1; } } return 0; } int main() { char MESSAGE[100]; fgets(MESSAGE,100,stdin); char T[800]; memset(T,0,sizeof(T)); char_to_strbinary(MESSAGE, T); for (int i=0; i<strlen(T);){ if(T[i++]=='1'){ printf("0 0"); while(T[i]=='1'&& i<strlen(T)){ printf("0"); i++; } } else{ printf("00 0"); while(T[i]=='0' && i<strlen(T)) { printf("0"); i++; } } if(i<strlen(T)) printf(" "); } // Write an action using printf(). DON'T FORGET THE TRAILING \n // To debug: fprintf(stderr, "Debug messages...\n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> int f[1001][8193] = {{0}}, w[1001], v[1001]; char b[1001][8193]; int T = 0, R[1001]; void printKnaspItem(int i, int W) { if (i == 0 || W == 0) return; if (b[i][W] == '<') { printKnaspItem(i - 1, W - w[i]); ++T; R[T] = i; } else printKnaspItem(i - 1, W); } int main() { int weight, number; int i, j; scanf ("%d%d", &number, &weight); for (i = 1; i <= number; ++i) scanf("%d", &w[i]); for (i = 1; i <= number; ++i) scanf("%d", &v[i]); for (i = 1; i <= number; ++i) { for (j = 1; j <= weight; ++j) { if (w[i] > j) { f[i][j] = f[i - 1][j]; b[i][j] = '>'; } else { if (v[i] + f[i - 1][j - w[i]] > f[i - 1][j]) { f[i][j] = v[i] + f[i - 1][j - w[i]]; b[i][j] = '<'; } else { f[i][j] = f[i - 1][j]; b[i][j] = '>'; } } } } printKnaspItem(number, weight); printf("%d\n", T); for (i = 1; i < T; ++i) printf("%d ", R[i]); printf("%d", R[i]); return 0; }
C
/* * dsa-verify.c * * Created on: Oct 31, 2019, 12:58:33 PM * Author: Joshua Fehrenbach */ #include "dsa.h" #include "dsa-hash.h" int dsa_verify(const struct dsa_params *params, mpz_srcptr y, const uint8_t *digest, size_t digest_size, struct dsa_signature *sig) { mpz_t w, v, tmp; int res; /* Check that r and s are in the proper range */ if (mpz_sgn(sig->r) <= 0 || mpz_cmp(sig->r, params->q) >= 0) { return 0; } if (mpz_sgn(sig->s) <= 0 || mpz_cmp(sig->s, params->q) >= 0) { return 0; } /* Compute w = s^-1 (mod q) */ mpz_init(w); if (!mpz_invert(w, sig->s, params->q)) { mpz_clear(w); return 0; } mpz_init(v); mpz_init(tmp); /* Compute hash */ _dsa_hash(tmp, mpz_sizeinbase(params->q, 2), digest, digest_size); /* v = g^{w*h (mod q)} (mod p) */ mpz_mul(tmp, tmp, w); mpz_fdiv_r(tmp, tmp, params->q); mpz_powm(v, params->g, tmp, params->p); /* y^{w*r (mod q)} (mod p) */ mpz_mul(tmp, sig->r, w); mpz_fdiv_r(tmp, tmp, params->q); mpz_powm(tmp, y, tmp, params->p); /* v = ( g^{w*h} * y^{w*r} (mod p) ) (mod q) */ mpz_mul(v, v, tmp); mpz_fdiv_r(v, v, params->p); mpz_fdiv_r(v, v, params->q); res = !mpz_cmp(v, sig->r); mpz_clear(tmp); mpz_clear(v); mpz_clear(w); return res; }
C
/* * ===================================================================================== * * Filename: fork_sig_sync.c * * Description: * * Version: 1.0 * Created: 09/20/2014 10:43:47 AM * Revision: none * Compiler: gcc * * Author: Kevin (###), [email protected] * Organization: * * ===================================================================================== */ #include <signal.h> #include "../lib/curr_time.h" #include "../lib/tlpi_hdr.h" #define SYNC_SIG SIGUSR1 static void handler(int sig) { } int main(int argc, char *argv[]) { pid_t childPid; sigset_t blockMask, origMask, emptyMask; struct sigaction sa; setbuf(stdout, NULL); sigemptyset(&blockMask); sigaddset(&blockMask, SYNC_SIG); if (sigprocmask(SIG_BLOCK, &blockMask, &origMask) == -1) { errExit("sigprocmask"); } sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; sa.sa_handler = handler; if (sigaction(SYNC_SIG, &sa, NULL) == -1) errExit("sigaction"); switch (childPid = fork()) { case -1: errExit("fork"); case 0: /* Child */ printf("[%s %ld] Child started - doing some work\n", currTime("%T"), (long) getpid()); sleep(2); printf("[%s %ld] Child about to signal parent\n", currTime("%T"), (long) getpid()); if (kill(getppid(), SYNC_SIG) == -1) errExit("kill"); _exit(EXIT_SUCCESS); default : printf("[%s %ld] Parent about to wait for signal\n", currTime("%T"), (long) getpid()); sigemptyset(&emptyMask); if (sigsuspend(&emptyMask) == -1 && errno != EINTR) errExit("sigsuspeng"); printf("[%s %ld] Parent got signal\n", currTime("T"), (long) getpid()); if (sigprocmask(SIG_SETMASK, &origMask, NULL) == -1) errExit("sigprocmask"); exit(EXIT_SUCCESS); } }
C
#include "ee.h" #include "stm32f4xx.h" #include "joystick.h" /* Returns -1 if it's on the left, 1 on the right, 0 in the middle */ char get_x(uint32_t convertedVoltageADC){ if(convertedVoltageADC > 3000) //left return 1; if(convertedVoltageADC < 300) //right return -1; else return 0; } /* Returns -1 if it's on the bottom, 1 on the top, 0 in the middle */ char get_y(uint32_t convertedVoltageADC){ if(convertedVoltageADC < 300) //up return -1; if(convertedVoltageADC > 3000) //down return 1; else return 0; }
C
#include<stdio.h> int main() { int i,j,k; printf("Enter the value of i and j:"); scanf("%d%d",&i,&j); k=(--i)*2+2*(3j+5); printf("The output of expression \(--i\)\*2+2\*\(3j+5\) is %d",k); }
C
/************************************************************** Target MCU & clock speed: ATmega328P @ 8Mhz internal Name : LEDintr_WDT_328P.c Author : Insoo Kim ([email protected]) Date : Sun April 12, 2015 Description: Blink LED of PB0, using timer1 interrupt (T=1s) HEX size[Byte]: 218 out of 32K Ref: https://sites.google.com/site/qeewiki/books/avr-guide/timers-on-the-atmega328 Note: Strange stuff resolved!: Refer LEDintr_TMR0.c *****************************************************************/ //#include <stdio.h> #include <avr/io.h> #include <avr/interrupt.h> #include <avr/sleep.h> #include <avr/wdt.h> #include <util/delay.h> ISR(WDT_vect) { PORTB ^= 1<<PB0; } void check_wdt(void){ if(MCUSR & _BV(WDRF)){ // If a reset was caused by the Watchdog Timer... MCUSR &= ~_BV(WDRF); // Clear the WDT reset flag WDTCSR |= (_BV(WDCE) | _BV(WDE)); // Enable the WD Change Bit WDTCSR = 0x00; // Disable the WDT } } void setup_wdt(void){ // Set up Watch Dog Timer for Inactivity // Enable the WD Change Bit WDTCSR |= (_BV(WDCE) | _BV(WDE)); // Enable WDT interrupt // Set Timeout to ~1 seconds WDTCSR = _BV(WDIE) | _BV(WDP2) | _BV(WDP1); // Set Timeout to ~500 ms //WDTCSR = _BV(WDIE) | _BV(WDP2)| _BV(WDP0); } //call this routine to initialize all peripherals void init_devices(void){ //stop errant interrupts until set up cli(); //disable all interrupts //timer0_init(); MCUCR = 0x00; EICRA = 0x00; //extended ext ints EIMSK = 0x00; TIMSK0 = 0x02; //timer 0 interrupt sources PRR = 0x00; //power controller sei(); //re-enable interrupts //all peripherals are now initialized } //TIMER0 initialize - prescale:1024 // WGM: CTC // desired value: 10mSec // actual value: 10.048mSec (-0.5%) /* void timer0_init(void){ TCCR0B = 0x00; //stop TCNT0 = 0x00; //set count TCCR0A = 0x02; //CTC mode OCR0A = 0xFF; //OCR0A = 0x9C; TCCR0B = 0x05; //start timer } */ void init_io(void){ DDRB = 0xff; // use all pins on port B for output PORTB = 0x00; // (LED's low & off) } int main(void) { init_io(); cli(); check_wdt(); setup_wdt(); sei(); // Enables interrupts /* //init I/O // Set up Port B pin 0 mode to output DDRB = 1<<DDB0; TIMSK0 = 0x02; //timer 0 interrupt sources //interrupt condition for Watch Dog Timer MCUSR &= ~_BV(WDRF); // temporarily prescale timer to 4s so we can measure current //WDTCSR |= (1<<WDP3); // (1<<WDP2) | (1<<WDP0); WDTCSR |= (1<<WDP2) | (1<<WDP1); // Enable watchdog timer interrupts WDTCSR |= (1<<WDIE);// | (1<<WDCE) | (1<<WDE); sei(); */ // Use the Power Down sleep mode set_sleep_mode(SLEEP_MODE_PWR_DOWN); while(1) { // let ISR handle the LED forever sleep_mode(); // go to sleep and wait for interrupt... } }
C
#include "holberton.h" /** * _strcat - appends strings * @dest: destination to append * @src: what to append * Return: pointer to dest */ char *_strcat(char *dest, char *src) { int tupapiesteban, j; for (tupapiesteban = 0; dest[tupapiesteban] != '\0'; tupapiesteban++) { } j = 0; while (src[j] != '\0') { dest[tupapiesteban] = src[j]; j++; tupapiesteban++; } tupapiesteban++; dest[tupapiesteban] = '\0'; return (dest); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <assert.h> #include <ctype.h> #include <string.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <unistd.h> int main(int argc, char *argv[]) { //Constants const int MAX_LINE = 1024; int batch_mode = 0; char error_message[30] = "An error has occurred\n"; FILE* target_stream; //Check should I run in batch mode? if(argc >= 3){ write(STDERR_FILENO, error_message, strlen(error_message)); exit(1); } else if(argc == 2){ //Do batch stuff target_stream = fopen(argv[1], "r"); if (target_stream == NULL) { write(STDERR_FILENO, error_message, strlen(error_message)); exit(1); } batch_mode = 1; } else { target_stream = stdin; } //Housekeeping int done = 1; while(done){ if(!batch_mode){ write(1, "mysh> ", 6); } //Read input variables int argsize; char in[MAX_LINE]; char* new_argv[512]; //Will not exceed 256 arguments int new_argc; int r; // Result for stuff char* arg; if(fgets(in, MAX_LINE, target_stream) == NULL){ if(feof(target_stream)){ //Read till the end of file for batch mode break; }else{ write(STDERR_FILENO, error_message, strlen(error_message)); } } if(batch_mode){ //Print stuff out if batch mode write(STDOUT_FILENO, in, strlen(in)); } if(strlen(in) > 513){ write(STDERR_FILENO, error_message, strlen(error_message)); continue; } if(strlen(in) == 1){ continue; //Just a return char } //Remove old stuff memset(&new_argv, 0, sizeof(new_argv)); strtok(in, "\n"); //Trick to remove new lines //Redirection detection int redirect_mode = 0; int bak, new; //File discriptor variables strtok(in, ">"); arg = strtok (NULL, ">"); if(arg != NULL) { if(strstr(arg, ">") != NULL){ //Found > chars write(STDERR_FILENO, error_message, strlen(error_message)); continue; }else{ //Switch stdout //Strip front whitespace while(arg[0] == ' '){ arg++; } char* path = strtok(arg, " "); //Trick to strip trailling whitespace if(strtok(NULL, " ") != NULL){ //Check for multiple redirection files write(STDERR_FILENO, error_message, strlen(error_message)); continue; } //Enable redirect mode redirect_mode = 1; fflush(stdout); bak = dup(1); new = open(arg, O_WRONLY|O_CREAT|O_TRUNC, S_IRWXU); if (new < 0) { write(STDERR_FILENO, error_message, strlen(error_message)); continue; } dup2(new, 1); close(new); } } new_argc = 0; arg = strtok (in, " "); while (arg != NULL) { new_argv[new_argc] = arg; new_argc++; arg = strtok (NULL, " "); } //Checking for builtin commands if(!strcmp(new_argv[0], "exit")){ if (new_argc != 1) { write(STDERR_FILENO, error_message, strlen(error_message)); } break; }else if(!strcmp(new_argv[0], "cd")){ //Code for cd char* target_dir; if(new_argv[1] == '\0'){ char * home_dir; home_dir = getenv ("HOME"); if (home_dir == NULL){ write(STDERR_FILENO, error_message, strlen(error_message)); continue; } target_dir = home_dir; }else{ target_dir = new_argv[1]; } if(chdir(target_dir) != 0){ write(STDERR_FILENO, error_message, strlen(error_message)); } continue; }else if(!strcmp(new_argv[0], "pwd")){ if (new_argc == 1) { //Code for pwd char cwd[1024]; if (getcwd(cwd, sizeof(cwd)) != NULL){ write(1, cwd, strlen(cwd)); write(1, "\n", 1); //Lazy hack to pass test }else{ write(STDERR_FILENO, error_message, strlen(error_message)); } }else{ write(STDERR_FILENO, error_message, strlen(error_message)); } continue; } //Forking here pid_t child_pid; pid_t gcc_pid; //Do fun feature, c compiler int fun_mode = 0; int arglength = strlen(new_argv[0]); if(new_argv[0][arglength - 1] == 'c' && new_argv[0][arglength - 2] == '.'){ char* gcc_argv[5]; gcc_argv[0] = "gcc"; gcc_argv[1] = "-o"; gcc_argv[2] = "/tmp/run"; gcc_argv[3] = new_argv[0]; gcc_argv[4] = NULL; //Replace running proggy new_argv[0] = "/tmp/run"; //Forking for gcc gcc_pid = fork(); //printf("%d\n", child_pid); if(gcc_pid == 0) { int x = execvp("gcc", gcc_argv); write(STDERR_FILENO, error_message, strlen(error_message)); exit(1); }else { wait(&gcc_pid); } } child_pid = fork(); if(child_pid == 0) { execvp(new_argv[0], new_argv); write(STDERR_FILENO, error_message, strlen(error_message)); exit(1); }else { wait(&child_pid); if(redirect_mode){ fflush(stdout); dup2(bak, 1); close(bak); } } } exit(0); }
C
/* fifobuffer.c *************************************************************** Contains functions for a FIFO-styled buffer that can be used as an intermediary storage when reading/writing data is unsynchron ized. The buffer is stoed in the heap. Use Mutex locks when rea ding/writing to the buffer. The implemented buffer is circular but does not overwrite old d ata. If the buffer is full it will throw an error message. 2020-11-26 Johannes Westman *************************************************************** */ #include<stdlib.h> #include"buffer.h" _FIFO_TYPE fifo_init(uint16_t l){ _FIFO_TYPE buf; buf.length = l; buf.base = (DATA_TYPE*)malloc(l); if(! buf.base) { buf.length = 0; } buf.head = buf.base; buf.tail = buf.base; buf.count = 0; return buf; } Buffer_Status fifo_check(_FIFO_TYPE* fbuf){ if(!fbuf || !(fbuf->head) || !(fbuf->tail) || !(fbuf->base)){ return LB_ERROR; } return LB_NO_ERROR; } Buffer_Status fifo_full_check(_FIFO_TYPE* fbuf) { Buffer_Status status = fifo_check(fbuf); if(status == LB_ERROR){ return LB_ERROR; } else if(fbuf->count == fbuf->length){ return LB_FULL; } else { return LB_NOT_FULL; } } Buffer_Status fifo_empty_check(_FIFO_TYPE* fbuf){ Buffer_Status status = fifo_check(fbuf); if(status == LB_ERROR){ return LB_ERROR; } else if(fbuf->count == 0){ return LB_EMPTY; } else{ return LB_NOT_EMPTY; } } Buffer_Status fifo_push(DATA_TYPE element, _FIFO_TYPE* fbuf){ Buffer_Status status = fifo_full_check(fbuf); if(status == LB_ERROR){ return LB_ERROR; } else if(status == LB_FULL){ return LB_FULL; } else { if(fbuf->head == (fbuf->base + fbuf->length)) { fbuf->head = fbuf->base; } else { fbuf->head ++; } } *(fbuf->head) = element; fbuf->count ++; return LB_NO_ERROR; } Buffer_Status fifo_pull(DATA_TYPE* element, _FIFO_TYPE* fbuf){ Buffer_Status status = fifo_empty_check(fbuf); if(status == LB_ERROR) { return LB_ERROR; } else if(status == LB_EMPTY){ return LB_EMPTY; } else { *element = *(fbuf->tail); fbuf->count --; if(fbuf->tail >= (fbuf->base + fbuf->length) ) { fbuf->tail = fbuf->base; } else { fbuf->tail ++; } return LB_NO_ERROR; } } void fifo_reset(_FIFO_TYPE* fbuf){ free((DATA_TYPE*)fbuf->base); }
C
#include <stdio.h> #include<conio.h> int main(void) { char a[50]; int i,n; scanf("%s %d",a,&n); int len; len=strlen(a); for(i=n;i<=len;i++) { printf("%c",a[i]); } getch(); }